mo commited on
Commit
e720a94
·
1 Parent(s): 179a76a

feat: desktop app packaging + engine/protocol/gateway packages, HTTP metrics pipeline

Browse files

- Restructure daemon into apps/desktop/ (bin, src, test, install.sh, package.json)
- New packages: engine (remote brain client), protocol (typed messages)
- New apps/gateway/ — local control-plane gateway for Docker platform
- Replace platform/ dir and packages/providers with monorepo layout
- Database: new initial schema migration + seeds, drop legacy mysql schema.sql
- scripts: keygen/setup updates + check-invariants
- .env.example template (no secrets); sqlite as default DB driver
- control.js: #httpStats() — POST metrics to /api/v1/agent/stats every 10s,
metrics start in connect() independent of WS; skip WS reconnect loop when
server can't upgrade (Sngine/Hostinger), keep HTTPS metrics running
- Tests: 26/26 pass

Files changed (49) hide show
  1. {bin → apps/desktop/bin}/mona-agent.js +0 -0
  2. install.sh → apps/desktop/install.sh +4 -2
  3. apps/desktop/package.json +17 -0
  4. {src → apps/desktop/src}/agent.js +0 -0
  5. {src → apps/desktop/src}/api.js +0 -0
  6. {src → apps/desktop/src}/cloud.js +0 -0
  7. {src → apps/desktop/src}/config.js +0 -0
  8. {src → apps/desktop/src}/control.js +45 -4
  9. {src → apps/desktop/src}/log.js +0 -0
  10. {src → apps/desktop/src}/tools/files.js +0 -0
  11. {src → apps/desktop/src}/tools/index.js +0 -0
  12. {src → apps/desktop/src}/tools/net.js +0 -0
  13. {src → apps/desktop/src}/tools/shell.js +0 -0
  14. {src → apps/desktop/src}/tools/sysinfo.js +0 -0
  15. {src → apps/desktop/src}/tui.js +0 -0
  16. {test → apps/desktop/test}/agent.test.mjs +0 -0
  17. {test → apps/desktop/test}/control.test.mjs +0 -0
  18. {test → apps/desktop/test}/docker-control.test.mjs +0 -0
  19. {test → apps/desktop/test}/render-harness.mjs +0 -0
  20. {test → apps/desktop/test}/tui-scroll.test.mjs +0 -0
  21. package.json +7 -6
  22. packages/engine/package.json +9 -0
  23. packages/engine/src/engine.mjs +136 -0
  24. packages/engine/src/index.mjs +16 -0
  25. packages/engine/src/simulated.mjs +95 -0
  26. packages/engine/src/sse.mjs +29 -0
  27. packages/protocol/package.json +9 -0
  28. packages/protocol/src/index.mjs +79 -0
  29. packages/providers/package.json +0 -1
  30. packages/providers/src/anthropic.mjs +0 -50
  31. packages/providers/src/google.mjs +0 -51
  32. packages/providers/src/index.mjs +0 -7
  33. packages/providers/src/ollama.mjs +0 -64
  34. packages/providers/src/openai.mjs +0 -65
  35. packages/providers/src/provider.mjs +0 -122
  36. packages/providers/src/router.mjs +0 -167
  37. packages/providers/src/simulated.mjs +0 -116
  38. platform/Dockerfile +0 -18
  39. platform/dashboard/app.js +0 -374
  40. platform/dashboard/index.html +0 -227
  41. platform/dashboard/style.css +0 -393
  42. platform/package.json +0 -26
  43. platform/src/agent-connection.js +0 -275
  44. platform/src/audit.js +0 -70
  45. platform/src/containers.js +0 -224
  46. platform/src/db.js +0 -167
  47. platform/src/llm-proxy.js +0 -203
  48. platform/src/server.js +0 -196
  49. platform/src/vault.js +0 -122
{bin → apps/desktop/bin}/mona-agent.js RENAMED
File without changes
install.sh → apps/desktop/install.sh RENAMED
@@ -61,7 +61,9 @@ echo -e " ${DIM}→ Installing dependencies${RESET}"
61
  rm -rf "$INSTALL_DIR/agent"
62
  mkdir -p "$INSTALL_DIR/agent"
63
  cp -R "$TMP_DIR"/. "$INSTALL_DIR/agent/"
64
- chmod +x "$INSTALL_DIR/agent/bin/mona-agent.js"
 
 
65
 
66
  # ── Symlink + PATH for the current shell ────────────────────────
67
  BIN_DIR="$HOME/.local/bin"
@@ -69,7 +71,7 @@ if ! mkdir -p "$BIN_DIR" 2>/dev/null; then
69
  BIN_DIR="$HOME/bin"
70
  mkdir -p "$BIN_DIR"
71
  fi
72
- ln -sf "$INSTALL_DIR/agent/bin/mona-agent.js" "$BIN_DIR/mona-agent"
73
  echo -e " Symlink: ${BOLD}$BIN_DIR/mona-agent${RESET}"
74
 
75
  case ":$PATH:" in
 
61
  rm -rf "$INSTALL_DIR/agent"
62
  mkdir -p "$INSTALL_DIR/agent"
63
  cp -R "$TMP_DIR"/. "$INSTALL_DIR/agent/"
64
+ chmod +x "$INSTALL_DIR/agent/apps/desktop/bin/mona-agent.js"
65
+ # agent entrypoint used by the mona-agent command
66
+ chmod +x "$INSTALL_DIR/agent/apps/desktop/src/config.js" 2>/dev/null || true
67
 
68
  # ── Symlink + PATH for the current shell ────────────────────────
69
  BIN_DIR="$HOME/.local/bin"
 
71
  BIN_DIR="$HOME/bin"
72
  mkdir -p "$BIN_DIR"
73
  fi
74
+ ln -sf "$INSTALL_DIR/agent/apps/desktop/bin/mona-agent.js" "$BIN_DIR/mona-agent"
75
  echo -e " Symlink: ${BOLD}$BIN_DIR/mona-agent${RESET}"
76
 
77
  case ":$PATH:" in
apps/desktop/package.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "mona-agent",
3
+ "version": "1.3.0",
4
+ "description": "mona.expert device agent — smart terminal, cloud brain. The only credential it holds is the mona.expert key.",
5
+ "type": "module",
6
+ "private": true,
7
+ "bin": {
8
+ "mona-agent": "./bin/mona-agent.js"
9
+ },
10
+ "dependencies": {
11
+ "ws": "^8.18.0"
12
+ },
13
+ "engines": {
14
+ "node": ">=20"
15
+ },
16
+ "license": "MIT"
17
+ }
{src → apps/desktop/src}/agent.js RENAMED
File without changes
{src → apps/desktop/src}/api.js RENAMED
File without changes
{src → apps/desktop/src}/cloud.js RENAMED
File without changes
{src → apps/desktop/src}/config.js RENAMED
File without changes
{src → apps/desktop/src}/control.js RENAMED
@@ -54,6 +54,7 @@ export class ControlChannel extends EventEmitter {
54
  #reconnectTimer = null;
55
  #closing = false;
56
  #stopped = false;
 
57
 
58
  constructor(apiKey, agentId, capabilities = null, { metricsIntervalMs } = {}) {
59
  super();
@@ -67,6 +68,11 @@ export class ControlChannel extends EventEmitter {
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') {
@@ -102,7 +108,6 @@ export class ControlChannel extends EventEmitter {
102
  });
103
  }
104
  this.#flush();
105
- this.#startMetrics();
106
  this.emit('connected');
107
  });
108
 
@@ -125,8 +130,9 @@ export class ControlChannel extends EventEmitter {
125
  });
126
 
127
  this.#ws.on('close', (code) => {
128
- this.#stopMetrics();
129
  if (this.#closing) return;
 
 
130
  // Terminal close: the credential itself was rejected — do not loop.
131
  if (TERMINAL_CLOSE_CODES.has(code)) {
132
  this.#stopped = true;
@@ -146,6 +152,16 @@ export class ControlChannel extends EventEmitter {
146
  });
147
 
148
  this.#ws.on('error', (err) => {
 
 
 
 
 
 
 
 
 
 
149
  log.error(`WebSocket error: ${err.message}`);
150
  this.emit('error', err);
151
  });
@@ -236,7 +252,8 @@ export class ControlChannel extends EventEmitter {
236
 
237
  // ── Device metrics stream ──────────────────────────────────────
238
  #startMetrics() {
239
- this.#metricsTimer = setInterval(async () => {
 
240
  const totalMem = os.totalmem(), freeMem = os.freemem();
241
  const cpus = os.cpus();
242
  const metrics = {
@@ -260,8 +277,32 @@ export class ControlChannel extends EventEmitter {
260
  } else {
261
  this.#send('device.metrics', metrics);
262
  }
 
 
 
263
  this.emit('metrics', metrics);
264
- }, this.#metricsIntervalMs);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  }
266
 
267
  #stopMetrics() {
 
54
  #reconnectTimer = null;
55
  #closing = false;
56
  #stopped = false;
57
+ #wsSkipped = false;
58
 
59
  constructor(apiKey, agentId, capabilities = null, { metricsIntervalMs } = {}) {
60
  super();
 
68
  connect() {
69
  if (this.#closing || this.#stopped) return this;
70
 
71
+ // Device metrics stream over HTTPS, independent of the WS link.
72
+ // This keeps the dashboard live even when the WS relay is down
73
+ // (shared hosting has no Node.js).
74
+ this.#startMetrics();
75
+
76
  let url = CLOUD.wsUrl;
77
  // Docker platform registers agents by agentId in the query string.
78
  if (CLOUD.platform === 'docker') {
 
108
  });
109
  }
110
  this.#flush();
 
111
  this.emit('connected');
112
  });
113
 
 
130
  });
131
 
132
  this.#ws.on('close', (code) => {
 
133
  if (this.#closing) return;
134
+ // WS relay absent (HTTP fallback active): no reconnect loop.
135
+ if (this.#wsSkipped) return;
136
  // Terminal close: the credential itself was rejected — do not loop.
137
  if (TERMINAL_CLOSE_CODES.has(code)) {
138
  this.#stopped = true;
 
152
  });
153
 
154
  this.#ws.on('error', (err) => {
155
+ // Shared hosting has no WS relay: LiteSpeed answers the upgrade
156
+ // with a normal HTTP response. Skip WS and keep the HTTPS
157
+ // metrics fallback — the dashboard stays live.
158
+ if (CLOUD.platform === 'sngine' && /unexpected server response/i.test(err.message)) {
159
+ if (!this.#wsSkipped) {
160
+ this.#wsSkipped = true;
161
+ log.info('WS relay unavailable on this control plane — device metrics stream via HTTPS');
162
+ }
163
+ return;
164
+ }
165
  log.error(`WebSocket error: ${err.message}`);
166
  this.emit('error', err);
167
  });
 
252
 
253
  // ── Device metrics stream ──────────────────────────────────────
254
  #startMetrics() {
255
+ if (this.#metricsTimer) return;
256
+ const tick = async () => {
257
  const totalMem = os.totalmem(), freeMem = os.freemem();
258
  const cpus = os.cpus();
259
  const metrics = {
 
277
  } else {
278
  this.#send('device.metrics', metrics);
279
  }
280
+ // HTTP fallback: shared hosting cannot run the Node WS relay,
281
+ // so also push metrics straight to the Sngine PHP API.
282
+ this.#httpStats(metrics);
283
  this.emit('metrics', metrics);
284
+ };
285
+ tick();
286
+ this.#metricsTimer = setInterval(tick, this.#metricsIntervalMs);
287
+ }
288
+
289
+ /** Push metrics + host info to the Sngine PHP API over HTTPS. */
290
+ #httpStats(payload) {
291
+ fetch(`${CLOUD.base}/api/v1/agent/stats`, {
292
+ method: 'POST',
293
+ headers: {
294
+ 'content-type': 'application/json',
295
+ 'authorization': `Bearer ${this.#apiKey}`,
296
+ },
297
+ body: JSON.stringify({
298
+ agentId: this.#agentId,
299
+ host: os.hostname(),
300
+ platform: os.platform(),
301
+ arch: os.arch(),
302
+ version: DEFAULTS.version,
303
+ ...payload,
304
+ }),
305
+ }).catch(() => {});
306
  }
307
 
308
  #stopMetrics() {
{src → apps/desktop/src}/log.js RENAMED
File without changes
{src → apps/desktop/src}/tools/files.js RENAMED
File without changes
{src → apps/desktop/src}/tools/index.js RENAMED
File without changes
{src → apps/desktop/src}/tools/net.js RENAMED
File without changes
{src → apps/desktop/src}/tools/shell.js RENAMED
File without changes
{src → apps/desktop/src}/tools/sysinfo.js RENAMED
File without changes
{src → apps/desktop/src}/tui.js RENAMED
File without changes
{test → apps/desktop/test}/agent.test.mjs RENAMED
File without changes
{test → apps/desktop/test}/control.test.mjs RENAMED
File without changes
{test → apps/desktop/test}/docker-control.test.mjs RENAMED
File without changes
{test → apps/desktop/test}/render-harness.mjs RENAMED
File without changes
{test → apps/desktop/test}/tui-scroll.test.mjs RENAMED
File without changes
package.json CHANGED
@@ -6,16 +6,17 @@
6
  "private": true,
7
  "workspaces": [
8
  "packages/*",
9
- "platform"
10
  ],
11
  "bin": {
12
- "mona-agent": "./bin/mona-agent.js"
13
  },
14
  "scripts": {
15
- "start": "node bin/mona-agent.js start",
16
- "gui": "node bin/mona-agent.js gui",
17
- "login": "node bin/mona-agent.js login",
18
- "test": "node --test test/agent.test.mjs test/control.test.mjs test/docker-control.test.mjs test/tui-scroll.test.mjs",
 
19
  "migrate": "node scripts/migrate.mjs",
20
  "setup": "node scripts/setup.mjs",
21
  "seed": "node scripts/seed.mjs",
 
6
  "private": true,
7
  "workspaces": [
8
  "packages/*",
9
+ "apps/*"
10
  ],
11
  "bin": {
12
+ "mona-agent": "./apps/desktop/bin/mona-agent.js"
13
  },
14
  "scripts": {
15
+ "start": "node apps/desktop/bin/mona-agent.js start",
16
+ "gui": "node apps/desktop/bin/mona-agent.js gui",
17
+ "login": "node apps/desktop/bin/mona-agent.js login",
18
+ "gateway": "node apps/gateway/src/index.mjs",
19
+ "test": "node --test test/*.test.mjs apps/desktop/test/agent.test.mjs apps/desktop/test/control.test.mjs apps/desktop/test/docker-control.test.mjs apps/desktop/test/tui-scroll.test.mjs",
20
  "migrate": "node scripts/migrate.mjs",
21
  "setup": "node scripts/setup.mjs",
22
  "seed": "node scripts/seed.mjs",
packages/engine/package.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@mona/engine",
3
+ "version": "1.0.0",
4
+ "description": "mona.expert AI engine client — the single brain. One key (the mona.expert key), one endpoint, no third-party models.",
5
+ "type": "module",
6
+ "private": true,
7
+ "main": "src/index.mjs",
8
+ "exports": { ".": "./src/index.mjs" }
9
+ }
packages/engine/src/engine.mjs ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { unavailable, providerError } from '@mona/core';
2
+ import { estimateTokens, readSse } from './sse.mjs';
3
+
4
+ /**
5
+ * mona.expert AI engine — the ONLY brain in this system.
6
+ *
7
+ * The engine decides everything: which model to use, what an agent is allowed
8
+ * to do, and what direction/execution commands to issue. The gateway sends it
9
+ * conversation context plus the device's capabilities; the engine answers with
10
+ * either text or tool_calls that the gateway relays to the device as commands.
11
+ *
12
+ * One credential exists for it — the mona.expert key — held server-side,
13
+ * encrypted by the keyring, never sent to a device, never logged.
14
+ *
15
+ * POST {base}/v1/think body: { messages, system?, tools?, stream? }
16
+ * Authorization: Bearer <mona.expert key>
17
+ *
18
+ * Stream chunks (same shape for remote and simulated engines):
19
+ * { type: 'delta', text }
20
+ * { type: 'tool_call', id, tool, args }
21
+ * { type: 'usage', usage: { inputTokens, outputTokens, model?, estimated? } }
22
+ * { type: 'done', finishReason, text }
23
+ */
24
+ export class EngineClient {
25
+ constructor({ url, key, timeoutMs = 120000, log = null }) {
26
+ this.url = String(url || '').replace(/\/$/, '');
27
+ this.key = key || '';
28
+ this.timeoutMs = timeoutMs;
29
+ this.log = log;
30
+ }
31
+
32
+ get mode() { return 'remote'; }
33
+ get name() { return 'mona.expert engine'; }
34
+
35
+ async authenticate(keyOverride) {
36
+ const key = keyOverride || this.key;
37
+ if (!key) return { ok: false, detail: 'No mona.expert key is stored. Add it under Settings → Engine key.' };
38
+ try {
39
+ await this.request('/v1/health', { key, timeoutMs: 10000 });
40
+ return { ok: true, detail: 'Engine reachable.' };
41
+ } catch (e) { return { ok: false, detail: e.message }; }
42
+ }
43
+
44
+ async request(path, { method = 'GET', body = null, signal = null, timeoutMs = this.timeoutMs, stream = false, key = null } = {}) {
45
+ if (!this.url) throw unavailable('The engine URL is not configured.');
46
+ const authKey = key ?? this.key;
47
+ const controller = new AbortController();
48
+ const timer = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
49
+ const onAbort = () => controller.abort(new Error('client aborted'));
50
+ signal?.addEventListener('abort', onAbort, { once: true });
51
+ try {
52
+ const res = await fetch(this.url + path, {
53
+ method,
54
+ headers: {
55
+ 'content-type': 'application/json',
56
+ 'user-agent': 'Mona.Expert-Gateway/2.0',
57
+ ...(authKey ? { authorization: `Bearer ${authKey}` } : {}),
58
+ },
59
+ body: body == null ? undefined : JSON.stringify(body),
60
+ signal: controller.signal,
61
+ });
62
+ if (!res.ok) {
63
+ const text = await res.text().catch(() => '');
64
+ throw this.mapError(res.status, text);
65
+ }
66
+ return stream ? res : await res.json();
67
+ } catch (e) {
68
+ if (e?.status) throw e;
69
+ if (String(e?.message).includes('timeout')) throw providerError('The mona.expert engine did not respond in time.');
70
+ if (String(e?.message).includes('aborted')) { const err = providerError('The request was cancelled.'); err.aborted = true; throw err; }
71
+ throw unavailable('The mona.expert engine could not be reached.', { internal: String(e?.message || e) });
72
+ } finally {
73
+ clearTimeout(timer);
74
+ signal?.removeEventListener('abort', onAbort);
75
+ }
76
+ }
77
+
78
+ mapError(status, rawBody) {
79
+ let detail = '';
80
+ try { const j = JSON.parse(rawBody); detail = j?.error?.message || j?.message || ''; } catch { detail = ''; }
81
+ const safe = detail.replace(/(mona_[A-Za-z0-9_-]{6,}|Bearer\s+\S+)/g, '[redacted]').slice(0, 240);
82
+ if (status === 401 || status === 403) return providerError(`The mona.expert engine rejected the stored key. ${safe}`);
83
+ if (status === 429) { const e = providerError('The mona.expert engine is rate limiting this account.'); e.status = 429; return e; }
84
+ if (status >= 500) return unavailable('The mona.expert engine is currently unavailable.', { internal: safe });
85
+ return providerError(`The engine rejected the request${safe ? `: ${safe}` : '.'}`);
86
+ }
87
+
88
+ async chat(req) {
89
+ const started = Date.now();
90
+ const data = await this.request('/v1/think', {
91
+ method: 'POST', body: this.body(req, false), signal: req.signal, key: req.credential,
92
+ });
93
+ return {
94
+ text: data.text ?? data.content ?? '',
95
+ finishReason: data.finish_reason || data.finishReason || 'stop',
96
+ usage: data.usage || { inputTokens: estimateTokens(JSON.stringify(req.messages)), outputTokens: estimateTokens(data.text ?? ''), estimated: true },
97
+ latencyMs: Date.now() - started,
98
+ model: data.model || 'engine',
99
+ toolCalls: data.tool_calls || data.toolCalls || null,
100
+ };
101
+ }
102
+
103
+ async *stream(req) {
104
+ const res = await this.request('/v1/think', {
105
+ method: 'POST', body: this.body(req, true), signal: req.signal, stream: true, key: req.credential,
106
+ });
107
+ let full = '', finish = 'stop';
108
+ for await (const evt of readSse(res)) {
109
+ if (evt.type === 'tool_call' || evt.tool_call) {
110
+ const tc = evt.type === 'tool_call' ? evt : evt.tool_call;
111
+ yield { type: 'tool_call', id: tc.id || String(Date.now()), tool: tc.tool, args: tc.args || tc.arguments || {} };
112
+ continue;
113
+ }
114
+ if (evt.type === 'delta' || typeof evt.delta === 'string') {
115
+ const text = evt.type === 'delta' ? evt.text : evt.delta;
116
+ full += text;
117
+ yield { type: 'delta', text };
118
+ continue;
119
+ }
120
+ if (evt.type === 'usage' || evt.usage) { yield { type: 'usage', usage: evt.usage }; continue; }
121
+ if (evt.type === 'done') { finish = evt.finishReason || finish; continue; }
122
+ if (typeof evt.done === 'boolean' && evt.done) { finish = evt.finish_reason || finish; continue; }
123
+ }
124
+ yield { type: 'done', finishReason: finish, text: full };
125
+ }
126
+
127
+ body({ messages, system, tools, stream, agentName, temperature, maxTokens }) {
128
+ const b = { messages, stream };
129
+ if (system) b.system = system;
130
+ if (tools?.length) b.tools = tools;
131
+ if (agentName) b.agent = agentName;
132
+ if (temperature != null) b.temperature = temperature;
133
+ if (maxTokens != null) b.max_tokens = maxTokens;
134
+ return b;
135
+ }
136
+ }
packages/engine/src/index.mjs ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export * from './sse.mjs';
2
+ export * from './engine.mjs';
3
+ export * from './simulated.mjs';
4
+
5
+ import { EngineClient } from './engine.mjs';
6
+ import { SimulatedEngine } from './simulated.mjs';
7
+
8
+ /**
9
+ * Engine factory. One brain, two modes:
10
+ * simulated — offline dev/CI (never allowed in production)
11
+ * remote — the real mona.expert engine (one key: the mona.expert key)
12
+ */
13
+ export function createEngine(cfg, { log = null } = {}) {
14
+ if (cfg.engine.mode === 'simulated') return new SimulatedEngine({ log });
15
+ return new EngineClient({ url: cfg.engine.url, key: cfg.engine.key, timeoutMs: cfg.engine.timeoutMs, log });
16
+ }
packages/engine/src/simulated.mjs ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { estimateTokens } from './sse.mjs';
2
+
3
+ /**
4
+ * Simulated engine — development and CI only, never production
5
+ * (assertProductionReady refuses SIMULATED_ENGINE_ENABLED=true in prod).
6
+ *
7
+ * It is NOT a language model. It exercises the full engine loop offline:
8
+ * gateway auth → conversation history → engine call → tool_calls → command →
9
+ * device → tool result → engine continuation → streaming → usage → audit.
10
+ *
11
+ * Tool-call trigger: a user message containing `tool: <name>` (e.g. `tool: sysinfo`)
12
+ * issues one tool_call for the named device tool; the tool result is echoed into
13
+ * the final answer. Everything else is a deterministic stand-in response.
14
+ */
15
+ const BANNER = '**Simulated engine response** — no language model was called. Auth, the command loop, streaming and usage accounting are real.';
16
+
17
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
18
+
19
+ function seedOf(text) {
20
+ let h = 2166136261;
21
+ for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 16777619); }
22
+ return (h >>> 0) / 4294967295;
23
+ }
24
+
25
+ const TOOL_RE = /(?:^|\s)tool:\s*([a-z][a-z0-9_.-]*)/i;
26
+
27
+ function compose({ messages, system, agentName }) {
28
+ const last = [...messages].reverse().find(m => m.role === 'user')?.content || '';
29
+ const words = last.trim().split(/\s+/).filter(Boolean);
30
+ const lines = [BANNER, ''];
31
+ lines.push(`Received ${words.length} words across ${messages.length} context messages.`);
32
+ lines.push(`Agent: **${agentName || 'unnamed'}** · system prompt: ${system ? `${system.length} chars` : 'none'}.`);
33
+ lines.push('');
34
+ lines.push(`The mona.expert engine would answer here and pick the model itself.`);
35
+ lines.push(`Echo for verification: *${words.slice(0, 12).join(' ')}${words.length > 12 ? '…' : ''}*`);
36
+ if (/hi|hello|hey/i.test(last)) {
37
+ lines.push('', 'Connected end to end: device → gateway → engine → back. Try `tool: sysinfo` to run a real command on the device.');
38
+ }
39
+ return lines.join('\n');
40
+ }
41
+
42
+ function composeToolFollowup({ toolResult, messages }) {
43
+ const lines = ['**Simulated engine** — tool executed on the device.', ''];
44
+ lines.push('```');
45
+ lines.push(String(toolResult).slice(0, 800));
46
+ lines.push('```');
47
+ return lines.join('\n');
48
+ }
49
+
50
+ export class SimulatedEngine {
51
+ constructor({ log = null } = {}) { this.log = log; }
52
+ get mode() { return 'simulated'; }
53
+ get name() { return 'Mona Simulator (dev only)'; }
54
+
55
+ async authenticate() { return { ok: true, detail: 'Simulated engine needs no key.' }; }
56
+
57
+ async chat(req) {
58
+ const started = Date.now();
59
+ const text = compose(req);
60
+ await sleep(80 + Math.floor(seedOf(text) * 200));
61
+ return {
62
+ text, finishReason: 'stop', model: 'mona-sim',
63
+ usage: { inputTokens: estimateTokens(JSON.stringify(req.messages)), outputTokens: estimateTokens(text), estimated: true },
64
+ latencyMs: Date.now() - started,
65
+ };
66
+ }
67
+
68
+ async *stream(req) {
69
+ // Tool-call turns: a "tool" role message means the engine is deciding what to do with a result.
70
+ const hasToolResult = req.messages?.some(m => m.role === 'tool');
71
+ const text = hasToolResult
72
+ ? composeToolFollowup({ toolResult: req.messages.at(-1)?.content ?? '', messages: req.messages })
73
+ : compose(req);
74
+
75
+ // Issue one tool_call when the user explicitly asks for a device tool.
76
+ if (!hasToolResult) {
77
+ const last = [...req.messages].reverse().find(m => m.role === 'user')?.content || '';
78
+ const m = TOOL_RE.exec(last);
79
+ if (m && req.tools?.some(t => (t.name || t) === m[1])) {
80
+ yield { type: 'tool_call', id: `sim-${Date.now()}`, tool: m[1], args: {} };
81
+ return;
82
+ }
83
+ }
84
+
85
+ await sleep(70 + Math.floor(seedOf(text) * 180));
86
+ const chunks = text.match(/\s*\S+|\s+/g) || [text];
87
+ for (const chunk of chunks) {
88
+ if (req.signal?.aborted) { yield { type: 'done', finishReason: 'stopped' }; return; }
89
+ await sleep(4);
90
+ yield { type: 'delta', text: chunk };
91
+ }
92
+ yield { type: 'usage', usage: { inputTokens: estimateTokens(JSON.stringify(req.messages) + (req.system || '')), outputTokens: estimateTokens(text), estimated: true, model: 'mona-sim' } };
93
+ yield { type: 'done', finishReason: 'stop', text };
94
+ }
95
+ }
packages/engine/src/sse.mjs ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** SSE utilities shared by engine adapters. */
2
+ export const estimateTokens = (text) => Math.max(1, Math.ceil(String(text || '').length / 3.8));
3
+
4
+ /** Line-oriented SSE reader. Yields parsed JSON objects and {__event} markers. */
5
+ export async function* readSse(response) {
6
+ const reader = response.body.getReader();
7
+ const decoder = new TextDecoder();
8
+ let buffer = '';
9
+ try {
10
+ while (true) {
11
+ const { done, value } = await reader.read();
12
+ if (done) break;
13
+ buffer += decoder.decode(value, { stream: true });
14
+ let idx;
15
+ while ((idx = buffer.indexOf('\n')) !== -1) {
16
+ const line = buffer.slice(0, idx).replace(/\r$/, '');
17
+ buffer = buffer.slice(idx + 1);
18
+ if (!line || line.startsWith(':')) continue;
19
+ if (line.startsWith('data:')) {
20
+ const data = line.slice(5).trim();
21
+ if (data === '[DONE]') return;
22
+ try { yield JSON.parse(data); } catch { /* keep-alive */ }
23
+ } else if (line.startsWith('event:')) {
24
+ yield { __event: line.slice(6).trim() };
25
+ }
26
+ }
27
+ }
28
+ } finally { try { await reader.cancel(); } catch {} }
29
+ }
packages/protocol/package.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@mona/protocol",
3
+ "version": "1.0.0",
4
+ "description": "mona.expert wire contract — WS envelopes, message types, close codes. The daemon and the gateway implement this.",
5
+ "type": "module",
6
+ "private": true,
7
+ "main": "src/index.mjs",
8
+ "exports": { ".": "./src/index.mjs" }
9
+ }
packages/protocol/src/index.mjs ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * mona.expert wire contract — the single source of truth for the device ↔ gateway
3
+ * WebSocket protocol. The daemon (apps/desktop) and the gateway (apps/gateway)
4
+ * implement this; `test/protocol.test.mjs` fails if they drift apart.
5
+ *
6
+ * Every frame is JSON: { v: 1, type, ts, agentId?, data }. `v` is the protocol
7
+ * version — always sent, always checked. Unknown versions are rejected at
8
+ * connect time, so an old device can never silently speak a broken dialect.
9
+ */
10
+
11
+ export const PROTOCOL_VERSION = 1;
12
+
13
+ /** Close codes the gateway uses to permanently reject a connection. */
14
+ export const CLOSE_CODES = Object.freeze({
15
+ UNAUTHORIZED: 4001, // bad / expired key — device must re-login
16
+ REVOKED: 4003, // device or agent revoked — terminal
17
+ PROTOCOL: 4002, // unsupported protocol version
18
+ });
19
+
20
+ export const isTerminalClose = (code) =>
21
+ code === CLOSE_CODES.UNAUTHORIZED || code === CLOSE_CODES.REVOKED || code === CLOSE_CODES.PROTOCOL;
22
+
23
+ /** Message types. `device →` frames are sent by the daemon; `gateway →` by the control plane. */
24
+ export const TYPES = Object.freeze({
25
+ /* handshake (device →) */
26
+ HELLO: 'hello',
27
+ HELLO_OK: 'hello.ok', // gateway → { heartbeatIntervalMs, permissions }
28
+ /* registration */
29
+ REGISTER: 'register', // device → device fingerprint / name
30
+ /* commands (gateway → device → gateway) */
31
+ COMMAND: 'command', // gateway → { id, tool, args, timeoutMs, requestId }
32
+ COMMAND_RESULT: 'command.result', // device → { id, ok, output, error, durationMs }
33
+ COMMAND_ERROR: 'command.error', // device → { id, error }
34
+ /* reasoning stream (device reports steps the engine asked it to take) */
35
+ AGENT_STEP: 'agent.step', // device → { runId, name, detail }
36
+ AGENT_TOKEN: 'agent.token', // device → { runId, text } (kept for TUI streaming)
37
+ AGENT_RESULT: 'agent.result', // device → { runId, ok, text, usage, error }
38
+ /* telemetry (device →) */
39
+ DEVICE_METRICS: 'device.metrics',
40
+ /* liveness */
41
+ PING: 'ping',
42
+ PONG: 'pong',
43
+ /* dashboard chat RPC (legacy docker-platform compatibility) */
44
+ CHAT: 'chat',
45
+ CHAT_RESPONSE: 'chat:response',
46
+ LLM_REQUEST: 'llm:request',
47
+ LLM_RESPONSE: 'llm:response',
48
+ LLM_ERROR: 'llm:error',
49
+ });
50
+
51
+ /** Device capability shape announced in `hello`. The gateway turns this into agent_permissions. */
52
+ export function capabilities({ tools = [], shell = null }) {
53
+ return { tools: [...tools], shell: shell ? { ...shell } : null };
54
+ }
55
+
56
+ /** Build a versioned envelope. */
57
+ export function envelope(type, data = {}, { agentId = null, ts = Date.now() } = {}) {
58
+ const msg = { v: PROTOCOL_VERSION, type, ts };
59
+ if (agentId != null) msg.agentId = agentId;
60
+ msg.data = data;
61
+ return msg;
62
+ }
63
+
64
+ /** Parse a raw frame; returns null for non-protocol JSON (keep-alives, garbage). */
65
+ export function parseFrame(raw) {
66
+ try {
67
+ const msg = JSON.parse(raw.toString());
68
+ if (typeof msg !== 'object' || msg === null || typeof msg.type !== 'string') return null;
69
+ return msg;
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
74
+
75
+ /** Validate the protocol version on a parsed frame. */
76
+ export function checkVersion(msg) {
77
+ if (msg.v === undefined) return false; // v1 tolerated as "implicit v1"? No: v is mandatory.
78
+ return Number(msg.v) === PROTOCOL_VERSION;
79
+ }
packages/providers/package.json DELETED
@@ -1 +0,0 @@
1
- { "name": "@mona/providers", "version": "1.0.0", "type": "module", "private": true, "main": "src/index.mjs", "exports": { ".": "./src/index.mjs" } }
 
 
packages/providers/src/anthropic.mjs DELETED
@@ -1,50 +0,0 @@
1
- import { Provider, estimateTokens } from './provider.mjs';
2
-
3
- export class AnthropicProvider extends Provider {
4
- constructor(meta = {}) {
5
- super({ slug: 'anthropic', name: 'Anthropic', kind: 'cloud', baseUrl: 'https://api.anthropic.com/v1', ...meta });
6
- }
7
- headers(credential) {
8
- return { 'x-api-key': credential, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' };
9
- }
10
- body({ model, messages, system, temperature, maxTokens, stream = false }) {
11
- return {
12
- model, max_tokens: maxTokens || 2048, temperature,
13
- ...(system ? { system } : {}),
14
- messages: messages.filter(m => m.role !== 'system').map(m => ({ role: m.role === 'assistant' ? 'assistant' : 'user', content: m.content })),
15
- stream,
16
- };
17
- }
18
- async authenticate(credential) { await this.listModels(credential); return { ok: true, detail: 'Key accepted.' }; }
19
- async listModels(credential) {
20
- const data = await this.request(`${this.baseUrl}/models`, { headers: this.headers(credential), timeoutMs: 15000 });
21
- return (data.data || []).map(m => ({ slug: m.id, displayName: m.display_name || m.id, family: 'Claude' }));
22
- }
23
- async chat(req) {
24
- const started = Date.now();
25
- const data = await this.request(`${this.baseUrl}/messages`, {
26
- method: 'POST', headers: this.headers(req.credential), body: this.body(req), signal: req.signal,
27
- });
28
- return {
29
- text: (data.content || []).filter(b => b.type === 'text').map(b => b.text).join(''),
30
- finishReason: data.stop_reason || 'end_turn',
31
- usage: { inputTokens: data.usage?.input_tokens ?? 0, outputTokens: data.usage?.output_tokens ?? 0 },
32
- latencyMs: Date.now() - started,
33
- model: data.model || req.model,
34
- };
35
- }
36
- async *stream(req) {
37
- const res = await this.request(`${this.baseUrl}/messages`, {
38
- method: 'POST', headers: this.headers(req.credential), body: this.body({ ...req, stream: true }), signal: req.signal, stream: true,
39
- });
40
- let inputTokens = 0, outputTokens = 0, finish = 'end_turn', out = '';
41
- for await (const evt of this.readSse(res)) {
42
- if (evt.type === 'message_start') inputTokens = evt.message?.usage?.input_tokens ?? 0;
43
- if (evt.type === 'content_block_delta' && evt.delta?.type === 'text_delta') { out += evt.delta.text; yield { type: 'delta', text: evt.delta.text }; }
44
- if (evt.type === 'message_delta') { outputTokens = evt.usage?.output_tokens ?? outputTokens; finish = evt.delta?.stop_reason || finish; }
45
- if (evt.type === 'error') yield { type: 'error', code: 'PROVIDER_ERROR', message: 'The provider ended the stream early.' };
46
- }
47
- yield { type: 'usage', usage: { inputTokens, outputTokens: outputTokens || estimateTokens(out), estimated: !outputTokens } };
48
- yield { type: 'done', finishReason: finish };
49
- }
50
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/providers/src/google.mjs DELETED
@@ -1,51 +0,0 @@
1
- import { Provider, estimateTokens } from './provider.mjs';
2
-
3
- export class GoogleProvider extends Provider {
4
- constructor(meta = {}) {
5
- super({ slug: 'google', name: 'Google AI', kind: 'cloud', baseUrl: 'https://generativelanguage.googleapis.com/v1beta', ...meta });
6
- }
7
- body({ messages, system, temperature, maxTokens }) {
8
- return {
9
- contents: messages.filter(m => m.role !== 'system').map(m => ({
10
- role: m.role === 'assistant' ? 'model' : 'user', parts: [{ text: m.content }],
11
- })),
12
- ...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}),
13
- generationConfig: { temperature, maxOutputTokens: maxTokens },
14
- };
15
- }
16
- async authenticate(credential) { await this.listModels(credential); return { ok: true, detail: 'Key accepted.' }; }
17
- async listModels(credential) {
18
- const data = await this.request(`${this.baseUrl}/models?key=${encodeURIComponent(credential)}`, { timeoutMs: 15000 });
19
- return (data.models || []).map(m => ({
20
- slug: String(m.name).replace(/^models\//, ''), displayName: m.displayName || m.name,
21
- family: 'Gemini', contextWindow: m.inputTokenLimit, maxOutput: m.outputTokenLimit,
22
- }));
23
- }
24
- async chat(req) {
25
- const started = Date.now();
26
- const url = `${this.baseUrl}/models/${encodeURIComponent(req.model)}:generateContent?key=${encodeURIComponent(req.credential)}`;
27
- const data = await this.request(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: this.body(req), signal: req.signal });
28
- const cand = data.candidates?.[0];
29
- return {
30
- text: (cand?.content?.parts || []).map(p => p.text || '').join(''),
31
- finishReason: (cand?.finishReason || 'STOP').toLowerCase(),
32
- usage: { inputTokens: data.usageMetadata?.promptTokenCount ?? 0, outputTokens: data.usageMetadata?.candidatesTokenCount ?? 0 },
33
- latencyMs: Date.now() - started,
34
- model: req.model,
35
- };
36
- }
37
- async *stream(req) {
38
- const url = `${this.baseUrl}/models/${encodeURIComponent(req.model)}:streamGenerateContent?alt=sse&key=${encodeURIComponent(req.credential)}`;
39
- const res = await this.request(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: this.body(req), signal: req.signal, stream: true });
40
- let usage = null, finish = 'stop', out = '';
41
- for await (const evt of this.readSse(res)) {
42
- const cand = evt.candidates?.[0];
43
- const text = (cand?.content?.parts || []).map(p => p.text || '').join('');
44
- if (text) { out += text; yield { type: 'delta', text }; }
45
- if (cand?.finishReason) finish = String(cand.finishReason).toLowerCase();
46
- if (evt.usageMetadata) usage = { inputTokens: evt.usageMetadata.promptTokenCount ?? 0, outputTokens: evt.usageMetadata.candidatesTokenCount ?? 0 };
47
- }
48
- yield { type: 'usage', usage: usage || { inputTokens: 0, outputTokens: estimateTokens(out), estimated: true } };
49
- yield { type: 'done', finishReason: finish };
50
- }
51
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/providers/src/index.mjs DELETED
@@ -1,7 +0,0 @@
1
- export * from './provider.mjs';
2
- export * from './openai.mjs';
3
- export * from './anthropic.mjs';
4
- export * from './google.mjs';
5
- export * from './ollama.mjs';
6
- export * from './simulated.mjs';
7
- export * from './router.mjs';
 
 
 
 
 
 
 
 
packages/providers/src/ollama.mjs DELETED
@@ -1,64 +0,0 @@
1
- import { Provider, estimateTokens } from './provider.mjs';
2
-
3
- /**
4
- * Local models. Modelled as an ordinary provider so a laptop GPU and a hosted
5
- * frontier model are the same kind of thing to routing, permissions and usage.
6
- * llama.cpp, vLLM and LM Studio all expose an OpenAI-shaped API — point
7
- * OpenAIProvider at their base URL and register it under a new slug.
8
- */
9
- export class OllamaProvider extends Provider {
10
- constructor(meta = {}) {
11
- super({ slug: 'ollama', name: 'Ollama (local)', kind: 'local', requiresCredential: false, baseUrl: 'http://127.0.0.1:11434', ...meta });
12
- }
13
- async authenticate() { await this.listModels(); return { ok: true, detail: 'Local runtime reachable.' }; }
14
- async listModels() {
15
- const data = await this.request(`${this.baseUrl}/api/tags`, { timeoutMs: 5000 });
16
- return (data.models || []).map(m => ({ slug: m.name, displayName: m.name, family: m.details?.family || 'local' }));
17
- }
18
- body({ model, messages, system, temperature, maxTokens, stream }) {
19
- return {
20
- model, stream,
21
- messages: system ? [{ role: 'system', content: system }, ...messages] : messages,
22
- options: { temperature, num_predict: maxTokens },
23
- };
24
- }
25
- async chat(req) {
26
- const started = Date.now();
27
- const data = await this.request(`${this.baseUrl}/api/chat`, {
28
- method: 'POST', headers: { 'content-type': 'application/json' }, body: this.body({ ...req, stream: false }), signal: req.signal,
29
- });
30
- return {
31
- text: data.message?.content || '',
32
- finishReason: data.done_reason || 'stop',
33
- usage: { inputTokens: data.prompt_eval_count ?? 0, outputTokens: data.eval_count ?? 0 },
34
- latencyMs: Date.now() - started,
35
- model: data.model || req.model,
36
- };
37
- }
38
- /** Ollama streams newline-delimited JSON rather than SSE. */
39
- async *stream(req) {
40
- const res = await this.request(`${this.baseUrl}/api/chat`, {
41
- method: 'POST', headers: { 'content-type': 'application/json' }, body: this.body({ ...req, stream: true }), signal: req.signal, stream: true,
42
- });
43
- const reader = res.body.getReader();
44
- const decoder = new TextDecoder();
45
- let buffer = '', out = '', usage = null, finish = 'stop';
46
- while (true) {
47
- const { done, value } = await reader.read();
48
- if (done) break;
49
- buffer += decoder.decode(value, { stream: true });
50
- let i;
51
- while ((i = buffer.indexOf('\n')) !== -1) {
52
- const line = buffer.slice(0, i).trim();
53
- buffer = buffer.slice(i + 1);
54
- if (!line) continue;
55
- let evt; try { evt = JSON.parse(line); } catch { continue; }
56
- const text = evt.message?.content;
57
- if (text) { out += text; yield { type: 'delta', text }; }
58
- if (evt.done) { finish = evt.done_reason || 'stop'; usage = { inputTokens: evt.prompt_eval_count ?? 0, outputTokens: evt.eval_count ?? 0 }; }
59
- }
60
- }
61
- yield { type: 'usage', usage: usage || { inputTokens: 0, outputTokens: estimateTokens(out), estimated: true } };
62
- yield { type: 'done', finishReason: finish };
63
- }
64
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/providers/src/openai.mjs DELETED
@@ -1,65 +0,0 @@
1
- import { Provider, estimateTokens } from './provider.mjs';
2
-
3
- /** OpenAI-compatible Chat Completions. Also the base for OpenRouter and any drop-in clone. */
4
- export class OpenAIProvider extends Provider {
5
- constructor(meta = {}) {
6
- super({ slug: 'openai', name: 'OpenAI', kind: 'cloud', baseUrl: 'https://api.openai.com/v1', ...meta });
7
- }
8
- headers(credential) {
9
- return { authorization: `Bearer ${credential}`, 'content-type': 'application/json', ...(this.extraHeaders || {}) };
10
- }
11
- body({ model, messages, system, temperature, maxTokens, stream = false }) {
12
- const msgs = system ? [{ role: 'system', content: system }, ...messages] : messages;
13
- return { model, messages: msgs, temperature, max_tokens: maxTokens, stream, ...(stream ? { stream_options: { include_usage: true } } : {}) };
14
- }
15
- async authenticate(credential) {
16
- await this.listModels(credential);
17
- return { ok: true, detail: 'Key accepted.' };
18
- }
19
- async listModels(credential) {
20
- const data = await this.request(`${this.baseUrl}/models`, { headers: this.headers(credential), timeoutMs: 15000 });
21
- return (data.data || []).map(m => ({ slug: m.id, displayName: m.id, family: (m.id.split('-')[0] || '').toUpperCase() }));
22
- }
23
- async chat(req) {
24
- const started = Date.now();
25
- const data = await this.request(`${this.baseUrl}/chat/completions`, {
26
- method: 'POST', headers: this.headers(req.credential), body: this.body(req), signal: req.signal,
27
- });
28
- const choice = data.choices?.[0] || {};
29
- return {
30
- text: choice.message?.content || '',
31
- finishReason: choice.finish_reason || 'stop',
32
- usage: { inputTokens: data.usage?.prompt_tokens ?? 0, outputTokens: data.usage?.completion_tokens ?? 0, estimated: !data.usage },
33
- latencyMs: Date.now() - started,
34
- model: data.model || req.model,
35
- };
36
- }
37
- async *stream(req) {
38
- const res = await this.request(`${this.baseUrl}/chat/completions`, {
39
- method: 'POST', headers: this.headers(req.credential), body: this.body({ ...req, stream: true }), signal: req.signal, stream: true,
40
- });
41
- let usage = null, finish = 'stop', out = '';
42
- for await (const evt of this.readSse(res)) {
43
- if (evt.usage) usage = { inputTokens: evt.usage.prompt_tokens ?? 0, outputTokens: evt.usage.completion_tokens ?? 0 };
44
- const d = evt.choices?.[0];
45
- if (d?.finish_reason) finish = d.finish_reason;
46
- const text = d?.delta?.content;
47
- if (text) { out += text; yield { type: 'delta', text }; }
48
- }
49
- yield { type: 'usage', usage: usage || { inputTokens: estimateTokens(JSON.stringify(req.messages)), outputTokens: estimateTokens(out), estimated: true } };
50
- yield { type: 'done', finishReason: finish };
51
- }
52
- async embeddings({ credential, model, input }) {
53
- const data = await this.request(`${this.baseUrl}/embeddings`, {
54
- method: 'POST', headers: this.headers(credential), body: { model, input },
55
- });
56
- return { vectors: (data.data || []).map(d => d.embedding), usage: { inputTokens: data.usage?.prompt_tokens ?? 0, outputTokens: 0 } };
57
- }
58
- }
59
-
60
- export class OpenRouterProvider extends OpenAIProvider {
61
- constructor() {
62
- super({ slug: 'openrouter', name: 'OpenRouter', baseUrl: 'https://openrouter.ai/api/v1' });
63
- this.extraHeaders = { 'http-referer': 'https://mona.expert', 'x-title': 'Mona.Expert' };
64
- }
65
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/providers/src/provider.mjs DELETED
@@ -1,122 +0,0 @@
1
- import { providerError, unavailable } from '@mona/core';
2
-
3
- /**
4
- * Provider contract.
5
- *
6
- * The gateway knows only this interface. Adding Mistral, Bedrock or a private
7
- * enterprise endpoint means writing one adapter file and one registry line —
8
- * no routing, auth or usage code changes.
9
- *
10
- * authenticate(credential) -> { ok, detail }
11
- * listModels(credential) -> ModelDescriptor[]
12
- * chat(request) -> ChatResult
13
- * stream(request) -> AsyncIterable<StreamChunk>
14
- * embeddings(request) -> { vectors, usage }
15
- * healthCheck(credential) -> { status, latencyMs }
16
- *
17
- * StreamChunk: { type: 'delta'|'usage'|'done'|'error', text?, usage?, finishReason?, code?, message? }
18
- */
19
- export class Provider {
20
- /** @param {{slug:string,name:string,kind:'cloud'|'local'|'simulated',baseUrl?:string,requiresCredential?:boolean,timeoutMs?:number}} meta */
21
- constructor(meta) {
22
- this.slug = meta.slug;
23
- this.name = meta.name;
24
- this.kind = meta.kind || 'cloud';
25
- this.baseUrl = meta.baseUrl || '';
26
- this.requiresCredential = meta.requiresCredential !== false;
27
- this.timeoutMs = meta.timeoutMs || 120000;
28
- }
29
- async authenticate() { throw new Error(`${this.slug}: authenticate() not implemented`); }
30
- async listModels() { throw new Error(`${this.slug}: listModels() not implemented`); }
31
- async chat() { throw new Error(`${this.slug}: chat() not implemented`); }
32
- async *stream() { throw new Error(`${this.slug}: stream() not implemented`); }
33
- async embeddings() { throw providerError(`${this.name} does not offer embeddings.`); }
34
- async healthCheck(credential) {
35
- const started = Date.now();
36
- try { await this.listModels(credential); return { status: 'operational', latencyMs: Date.now() - started }; }
37
- catch (e) { return { status: 'degraded', latencyMs: Date.now() - started, detail: e.message }; }
38
- }
39
-
40
- /** Shared fetch with timeout, no retries on non-idempotent calls, no secret logging. */
41
- async request(url, { method = 'GET', headers = {}, body = null, signal = null, timeoutMs = this.timeoutMs, stream = false } = {}) {
42
- const controller = new AbortController();
43
- const timer = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
44
- const onAbort = () => controller.abort(new Error('client aborted'));
45
- signal?.addEventListener('abort', onAbort, { once: true });
46
- try {
47
- const res = await fetch(url, {
48
- method,
49
- headers: { 'user-agent': 'Mona.Expert-Gateway/1.0', ...headers },
50
- body: body == null ? undefined : typeof body === 'string' ? body : JSON.stringify(body),
51
- signal: controller.signal,
52
- });
53
- if (!res.ok) {
54
- const text = await res.text().catch(() => '');
55
- throw this.mapError(res.status, text);
56
- }
57
- return stream ? res : await res.json();
58
- } catch (e) {
59
- if (e?.status) throw e;
60
- if (String(e?.message).includes('timeout')) throw providerError(`${this.name} did not respond in time.`);
61
- if (String(e?.message).includes('aborted')) { const err = providerError('The request was cancelled.'); err.aborted = true; throw err; }
62
- throw unavailable(`${this.name} could not be reached.`, { internal: String(e?.message || e) });
63
- } finally {
64
- clearTimeout(timer);
65
- signal?.removeEventListener('abort', onAbort);
66
- }
67
- }
68
-
69
- /** Upstream errors are translated, never forwarded verbatim — bodies can echo keys. */
70
- mapError(status, rawBody) {
71
- let detail = '';
72
- try { const j = JSON.parse(rawBody); detail = j?.error?.message || j?.message || ''; } catch { detail = ''; }
73
- const safe = detail.replace(/(sk-[A-Za-z0-9_-]{6,}|Bearer\s+\S+)/g, '[redacted]').slice(0, 240);
74
- if (status === 401 || status === 403) return providerError(`${this.name} rejected the stored credential. Check the API key in Security → Provider keys.`);
75
- if (status === 404) return providerError(`${this.name} does not recognise that model.`);
76
- if (status === 429) { const e = providerError(`${this.name} is rate limiting this key. Try again shortly.`); e.status = 429; e.code = 'PROVIDER_RATE_LIMITED'; return e; }
77
- if (status >= 500) return unavailable(`${this.name} is currently unavailable.`, { internal: safe });
78
- return providerError(`${this.name} rejected the request${safe ? `: ${safe}` : '.'}`);
79
- }
80
-
81
- /** Line-oriented SSE reader shared by every streaming adapter. */
82
- async *readSse(response) {
83
- const reader = response.body.getReader();
84
- const decoder = new TextDecoder();
85
- let buffer = '';
86
- try {
87
- while (true) {
88
- const { done, value } = await reader.read();
89
- if (done) break;
90
- buffer += decoder.decode(value, { stream: true });
91
- let idx;
92
- while ((idx = buffer.indexOf('\n')) !== -1) {
93
- const line = buffer.slice(0, idx).replace(/\r$/, '');
94
- buffer = buffer.slice(idx + 1);
95
- if (!line || line.startsWith(':')) continue;
96
- if (line.startsWith('data:')) {
97
- const data = line.slice(5).trim();
98
- if (data === '[DONE]') return;
99
- try { yield JSON.parse(data); } catch { /* skip non-JSON keep-alives */ }
100
- } else if (line.startsWith('event:')) {
101
- yield { __event: line.slice(6).trim() };
102
- }
103
- }
104
- }
105
- } finally { try { await reader.cancel(); } catch {} }
106
- }
107
- }
108
-
109
- export class ProviderRegistry {
110
- constructor() { this.map = new Map(); }
111
- register(provider) { this.map.set(provider.slug, provider); return this; }
112
- get(slug) {
113
- const p = this.map.get(slug);
114
- if (!p) throw providerError(`No adapter is registered for "${slug}".`);
115
- return p;
116
- }
117
- has(slug) { return this.map.has(slug); }
118
- list() { return [...this.map.values()]; }
119
- }
120
-
121
- /** Rough token estimate used only when a provider omits usage. Marked as estimated. */
122
- export const estimateTokens = (text) => Math.max(1, Math.ceil(String(text || '').length / 3.8));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/providers/src/router.mjs DELETED
@@ -1,167 +0,0 @@
1
- import { providerError, forbidden, notFound, dayKey } from '@mona/core';
2
-
3
- /**
4
- * Routing engine.
5
- *
6
- * This is the only place in the platform where a provider credential is decrypted,
7
- * and it is decrypted into a local variable that is passed to one adapter call and
8
- * then dropped. It is never attached to a request context, never returned, never
9
- * logged, and never crosses a serialisation boundary.
10
- */
11
- export class RoutingEngine {
12
- constructor({ registry, repos, keyring, config, log }) {
13
- this.registry = registry;
14
- this.repos = repos;
15
- this.keyring = keyring;
16
- this.config = config;
17
- this.log = log;
18
- }
19
-
20
- /** Resolve an agent's configured provider + model, honouring its routing policy. */
21
- async resolve(agent, { modelOverride = null } = {}) {
22
- const model = await this.repos.models.byId(modelOverride || agent.model_id);
23
- if (!model) throw notFound('That model is no longer available.');
24
- if (!model.enabled) throw providerError('That model has been disabled by an administrator.');
25
-
26
- const provider = await this.repos.providers.byId(model.provider_id);
27
- if (!provider) throw notFound('The provider for that model is no longer configured.');
28
- if (!provider.enabled) throw providerError(`${provider.name} is disabled on this platform.`);
29
- if (!this.registry.has(provider.slug)) throw providerError(`No adapter is loaded for ${provider.name}.`);
30
-
31
- // An override must still be a model the agent is allowed to use.
32
- if (modelOverride && modelOverride !== agent.model_id) {
33
- const allowed = await this.repos.db.get(
34
- 'SELECT 1 AS ok FROM agent_models WHERE agent_id = ? AND model_id = ?', [agent.id, modelOverride]);
35
- if (!allowed) throw forbidden('This agent is not permitted to use that model.');
36
- }
37
- return { provider, model, adapter: this.registry.get(provider.slug) };
38
- }
39
-
40
- /**
41
- * Fetch and decrypt the credential for one call.
42
- * @returns {Promise<{secret:string|null, credentialId:string|null}>}
43
- */
44
- async #credential(userId, provider) {
45
- const adapter = this.registry.get(provider.slug);
46
- if (!adapter.requiresCredential || !provider.requires_credential) return { secret: null, credentialId: null };
47
-
48
- const row = await this.repos.providerCredentials.activeSecretFor(userId, provider.id);
49
- if (!row) {
50
- throw forbidden(`No active ${provider.name} key is stored for this account. Add one under Security → Provider keys.`);
51
- }
52
- const secret = this.keyring.decrypt(row.secret_enc, { purpose: 'provider_credential', aad: `${userId}:${provider.id}` });
53
- return { secret, credentialId: row.id };
54
- }
55
-
56
- /** Cost in EUR from the model's per-million-token prices. Zero when unpriced. */
57
- static cost(model, usage) {
58
- const inPrice = Number(model.input_price_per_mtok || 0);
59
- const outPrice = Number(model.output_price_per_mtok || 0);
60
- return ((usage.inputTokens || 0) * inPrice + (usage.outputTokens || 0) * outPrice) / 1e6;
61
- }
62
-
63
- #buildRequest({ agent, model, messages, secret, signal, maxTokensOverride }) {
64
- return {
65
- model: model.slug,
66
- messages,
67
- system: agent.system_prompt || null,
68
- temperature: Number(agent.temperature),
69
- maxTokens: Math.min(maxTokensOverride || agent.max_tokens, model.max_output || agent.max_tokens),
70
- credential: secret,
71
- agentName: agent.name,
72
- signal,
73
- };
74
- }
75
-
76
- async chat({ agent, userId, messages, modelOverride = null, maxTokensOverride = null, signal = null }) {
77
- const { provider, model, adapter } = await this.resolve(agent, { modelOverride });
78
- const { secret, credentialId } = await this.#credential(userId, provider);
79
- const started = Date.now();
80
- try {
81
- const result = await adapter.chat(this.#buildRequest({ agent, model, messages, secret, signal, maxTokensOverride }));
82
- if (credentialId) await this.repos.providerCredentials.markUsed(credentialId);
83
- return { ...result, provider, model, cost: RoutingEngine.cost(model, result.usage), latencyMs: result.latencyMs ?? Date.now() - started };
84
- } catch (err) {
85
- await this.repos.providers.recordHealth(provider.id, err.status >= 500 ? 'degraded' : 'operational', Date.now() - started);
86
- throw err;
87
- }
88
- }
89
-
90
- /**
91
- * Streaming call. Yields adapter chunks unchanged plus a final `meta` chunk carrying
92
- * the resolved provider, model, usage and cost so the caller can persist one record.
93
- */
94
- async *stream({ agent, userId, messages, modelOverride = null, maxTokensOverride = null, signal = null }) {
95
- const { provider, model, adapter } = await this.resolve(agent, { modelOverride });
96
- const { secret, credentialId } = await this.#credential(userId, provider);
97
- const started = Date.now();
98
- let usage = { inputTokens: 0, outputTokens: 0 };
99
- let finishReason = 'stop';
100
- let firstTokenAt = null;
101
-
102
- try {
103
- for await (const chunk of adapter.stream(this.#buildRequest({ agent, model, messages, secret, signal, maxTokensOverride }))) {
104
- if (chunk.type === 'delta' && firstTokenAt === null) firstTokenAt = Date.now();
105
- if (chunk.type === 'usage') { usage = chunk.usage; continue; }
106
- if (chunk.type === 'done') { finishReason = chunk.finishReason || finishReason; continue; }
107
- yield chunk;
108
- }
109
- if (credentialId) await this.repos.providerCredentials.markUsed(credentialId);
110
- yield {
111
- type: 'meta',
112
- provider: provider.slug,
113
- providerName: provider.name,
114
- model: model.slug,
115
- modelId: model.id,
116
- simulated: provider.kind === 'simulated',
117
- usage,
118
- finishReason,
119
- latencyMs: Date.now() - started,
120
- firstTokenMs: firstTokenAt ? firstTokenAt - started : null,
121
- cost: RoutingEngine.cost(model, usage),
122
- };
123
- } catch (err) {
124
- await this.repos.providers.recordHealth(provider.id, err.status >= 500 ? 'degraded' : 'operational', Date.now() - started);
125
- throw err;
126
- }
127
- }
128
-
129
- /** Verify a user-supplied key against the live provider before it is stored. */
130
- async verifyCredential(providerSlug, secret) {
131
- const adapter = this.registry.get(providerSlug);
132
- if (!adapter.requiresCredential) return { ok: true, detail: `${adapter.name} does not use a key.` };
133
- try { return await adapter.authenticate(secret); }
134
- catch (e) { return { ok: false, detail: e.message }; }
135
- }
136
-
137
- async healthAll() {
138
- const rows = await this.repos.providers.all();
139
- const out = [];
140
- for (const p of rows) {
141
- if (!this.registry.has(p.slug)) { out.push({ slug: p.slug, status: 'not_configured', latencyMs: null }); continue; }
142
- const adapter = this.registry.get(p.slug);
143
- if (adapter.requiresCredential) { out.push({ slug: p.slug, status: p.status || 'unknown', latencyMs: p.latency_ms }); continue; }
144
- const h = await adapter.healthCheck();
145
- await this.repos.providers.recordHealth(p.id, h.status, h.latencyMs);
146
- out.push({ slug: p.slug, ...h });
147
- }
148
- return out;
149
- }
150
-
151
- /** One place to write everything a completed call produces. */
152
- async record({ requestId, userId, agentId, deviceId, route, status, latencyMs, usage, providerSlug, modelSlug, errorCode = null, ip = null, userAgent = null, cost = 0 }) {
153
- const tokens = (usage?.inputTokens || 0) + (usage?.outputTokens || 0);
154
- await this.repos.apiRequests.record({
155
- id: requestId, user_id: userId, agent_id: agentId, device_id: deviceId, method: 'POST', route,
156
- status, latency_ms: latencyMs, provider_slug: providerSlug, model_slug: modelSlug,
157
- input_tokens: usage?.inputTokens || 0, output_tokens: usage?.outputTokens || 0,
158
- error_code: errorCode, ip, user_agent: (userAgent || '').slice(0, 200),
159
- });
160
- await this.repos.usage.roll({
161
- userId, agentId, day: dayKey(), providerSlug, modelSlug,
162
- inputTokens: usage?.inputTokens || 0, outputTokens: usage?.outputTokens || 0,
163
- errors: status >= 400 ? 1 : 0, latencyMs, cost,
164
- });
165
- if (agentId) await this.repos.agents.recordTraffic(agentId, { tokens, errors: status >= 400 ? 1 : 0, latencyMs });
166
- }
167
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
packages/providers/src/simulated.mjs DELETED
@@ -1,116 +0,0 @@
1
- import { Provider, estimateTokens } from './provider.mjs';
2
-
3
- /**
4
- * Simulated provider — development and CI only.
5
- *
6
- * This is NOT a language model and never claims to be one. It exercises the full
7
- * gateway path (auth → policy → routing → streaming → usage → audit) without a
8
- * network or a paid key, so the platform can be tested end to end offline.
9
- *
10
- * Every response it produces is prefixed with a simulation banner, its models are
11
- * named "Simulated …", and `SIMULATED_PROVIDER_ENABLED=true` is refused at boot in
12
- * production (see assertProductionReady in @mona/core).
13
- */
14
- const BANNER = '**Simulated response** — no language model was called. Routing, authentication, streaming and usage accounting are real.';
15
-
16
- const MODELS = [
17
- { slug: 'mona-sim-fast', displayName: 'Simulated · Fast', family: 'Simulated', contextWindow: 32000, maxOutput: 4096, msPerToken: 6 },
18
- { slug: 'mona-sim-long', displayName: 'Simulated · Long context', family: 'Simulated', contextWindow: 200000, maxOutput: 8192, msPerToken: 14 },
19
- { slug: 'mona-sim-local', displayName: 'Simulated · On-device', family: 'Simulated', contextWindow: 8000, maxOutput: 2048, msPerToken: 22 },
20
- ];
21
-
22
- const sleep = (ms) => new Promise(r => setTimeout(r, ms));
23
-
24
- /** Deterministic per-prompt jitter so repeated runs are reproducible in CI. */
25
- function seedOf(text) {
26
- let h = 2166136261;
27
- for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 16777619); }
28
- return (h >>> 0) / 4294967295;
29
- }
30
-
31
- function compose({ messages, system, model, agentName }) {
32
- const last = [...messages].reverse().find(m => m.role === 'user')?.content || '';
33
- const turn = messages.filter(m => m.role === 'user').length;
34
- const words = last.trim().split(/\s+/).filter(Boolean);
35
- const seed = seedOf(last);
36
- const lines = [BANNER, ''];
37
-
38
- if (/```|\bfunction\b|\bclass\b|\bdef \b|\bimport \b|=>/.test(last) || /\bcode\b|\brefactor\b|\bbug\b/i.test(last)) {
39
- lines.push(`Reading the ${words.length}-word request as a code question. A real model would answer here; the simulator returns a structured stand-in so Markdown, fenced blocks and syntax highlighting are exercised in the client.`, '');
40
- lines.push('```js');
41
- lines.push('// Echo of the routing decision that produced this response');
42
- lines.push(`const route = {`);
43
- lines.push(` agent: ${JSON.stringify(agentName || 'unnamed')},`);
44
- lines.push(` model: ${JSON.stringify(model)},`);
45
- lines.push(` provider: 'simulated',`);
46
- lines.push(` systemPrompt: ${system ? `${system.length} chars` : 'none'},`);
47
- lines.push(` contextMessages: ${messages.length},`);
48
- lines.push('};');
49
- lines.push('```', '');
50
- lines.push('Set a provider key under **Security → Provider keys** and switch the agent to a live model to get a real answer.');
51
- } else if (/^\s*(hi|hello|hey|good (morning|evening))/i.test(last)) {
52
- lines.push(`Connected. This request travelled device → \`agent.mona.expert\` → policy check → provider adapter, and back over SSE.`, '');
53
- lines.push(`| Stage | Result |`, `| --- | --- |`, `| Agent credential | verified |`, `| Scope \`chat\` | granted |`, `| Provider | simulated |`, `| Model | \`${model}\` |`, '');
54
- lines.push('Ask something else, or run `/help` to see the command set.');
55
- } else if (/\?\s*$/.test(last.trim())) {
56
- lines.push(`That question reached turn ${turn} of this conversation with ${messages.length} messages in context.`, '');
57
- lines.push(`A live provider would answer it. The simulator confirms instead that:`, '');
58
- lines.push(`- the agent's credential passed verification`, `- the \`chat\` scope was granted`, `- \`${model}\` was selected by the routing policy`, `- usage for this request will appear on the dashboard within a second`);
59
- } else {
60
- lines.push(`Received ${words.length} words and ${last.length} characters across ${messages.length} context messages.`, '');
61
- lines.push(`Echoing the opening for verification: *${words.slice(0, 12).join(' ')}${words.length > 12 ? '…' : ''}*`, '');
62
- lines.push(`Latency for this response is synthetic (seed \`${seed.toFixed(4)}\`) so streaming behaviour looks realistic without a network call.`);
63
- }
64
- return lines.join('\n');
65
- }
66
-
67
- export class SimulatedProvider extends Provider {
68
- constructor() {
69
- super({ slug: 'simulated', name: 'Mona Simulator', kind: 'simulated', requiresCredential: false });
70
- }
71
- async authenticate() { return { ok: true, detail: 'Simulator needs no credential.' }; }
72
- async listModels() { return MODELS.map(({ msPerToken, ...m }) => m); }
73
- async healthCheck() { return { status: 'operational', latencyMs: 1 }; }
74
-
75
- async chat(req) {
76
- const started = Date.now();
77
- const text = compose(req);
78
- const spec = MODELS.find(m => m.slug === req.model) || MODELS[0];
79
- await sleep(120 + Math.floor(seedOf(text) * 260));
80
- return {
81
- text,
82
- finishReason: 'stop',
83
- usage: { inputTokens: estimateTokens(JSON.stringify(req.messages) + (req.system || '')), outputTokens: estimateTokens(text), estimated: true },
84
- latencyMs: Date.now() - started,
85
- model: spec.slug,
86
- simulated: true,
87
- };
88
- }
89
-
90
- async *stream(req) {
91
- const text = compose(req);
92
- const spec = MODELS.find(m => m.slug === req.model) || MODELS[0];
93
- await sleep(90 + Math.floor(seedOf(text) * 180)); // time-to-first-token
94
- const chunks = text.match(/\s*\S+|\s+/g) || [text];
95
- for (const chunk of chunks) {
96
- if (req.signal?.aborted) { yield { type: 'done', finishReason: 'stopped' }; return; }
97
- await sleep(spec.msPerToken);
98
- yield { type: 'delta', text: chunk };
99
- }
100
- yield { type: 'usage', usage: { inputTokens: estimateTokens(JSON.stringify(req.messages) + (req.system || '')), outputTokens: estimateTokens(text), estimated: true } };
101
- yield { type: 'done', finishReason: 'stop' };
102
- }
103
-
104
- async embeddings({ input }) {
105
- const items = Array.isArray(input) ? input : [input];
106
- return {
107
- vectors: items.map(text => {
108
- const s = seedOf(String(text));
109
- return Array.from({ length: 32 }, (_, i) => Math.sin((i + 1) * s * Math.PI) / 2);
110
- }),
111
- usage: { inputTokens: items.reduce((n, t) => n + estimateTokens(t), 0), outputTokens: 0 },
112
- };
113
- }
114
- }
115
-
116
- export const SIMULATED_MODELS = MODELS;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/Dockerfile DELETED
@@ -1,18 +0,0 @@
1
- FROM node:20-alpine
2
-
3
- WORKDIR /app
4
-
5
- COPY package.json package-lock.json* ./
6
- RUN npm ci --production
7
-
8
- COPY src/ ./src/
9
- COPY dashboard/ ./dashboard/
10
-
11
- RUN mkdir -p /data && chmod 755 /data
12
-
13
- EXPOSE 4300
14
-
15
- ENV PORT=4300
16
- ENV DATA_DIR=/data
17
-
18
- CMD ["node", "src/server.js"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/dashboard/app.js DELETED
@@ -1,374 +0,0 @@
1
- /**
2
- * mona.expert — Dashboard SPA
3
- *
4
- * Single brain. Single key.
5
- * All reasoning and direction comes from the mona.expert engine.
6
- * This UI never asks for or stores any provider key.
7
- */
8
-
9
- const API = '/api';
10
- let ws = null;
11
- let currentPage = 'dashboard';
12
- let chatAgentId = null;
13
-
14
- // ── Init ───────────────────────────────────────────────────────────
15
- document.addEventListener('DOMContentLoaded', () => {
16
- setupNavigation();
17
- setupForms();
18
- connectWS();
19
- loadPage('dashboard');
20
- });
21
-
22
- function setupNavigation() {
23
- document.querySelectorAll('.nav-item').forEach(item => {
24
- item.addEventListener('click', () => {
25
- const page = item.dataset.page;
26
- loadPage(page);
27
- });
28
- });
29
- }
30
-
31
- function setupForms() {
32
- document.getElementById('create-agent-form').addEventListener('submit', async (e) => {
33
- e.preventDefault();
34
- const form = e.target;
35
- const tools = Array.from(form.querySelectorAll('input[name="tools"]:checked')).map(cb => cb.value);
36
- const data = {
37
- name: form.name.value,
38
- model: form.model.value,
39
- systemPrompt: form.systemPrompt.value,
40
- tools
41
- };
42
-
43
- try {
44
- const res = await fetch(`${API}/agents`, {
45
- method: 'POST',
46
- headers: { 'Content-Type': 'application/json' },
47
- body: JSON.stringify(data)
48
- });
49
- if (!res.ok) throw new Error((await res.json()).error);
50
- hideCreateAgent();
51
- form.reset();
52
- loadAgents();
53
- } catch (err) {
54
- alert(`Failed to create agent: ${err.message}`);
55
- }
56
- });
57
- }
58
-
59
- // ── WebSocket ──────────────────────────────────────────────────────
60
- function connectWS() {
61
- const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
62
- const wsUrl = `${protocol}//${location.host}/ws?type=dashboard`;
63
-
64
- ws = new WebSocket(wsUrl);
65
-
66
- ws.onopen = () => updateStatus('connected', 'Connected');
67
- ws.onmessage = (event) => {
68
- try {
69
- handleWSMessage(JSON.parse(event.data));
70
- } catch (err) {
71
- console.error('WS parse error:', err);
72
- }
73
- };
74
- ws.onclose = () => {
75
- updateStatus('disconnected', 'Disconnected');
76
- setTimeout(connectWS, 3000);
77
- };
78
- ws.onerror = () => updateStatus('disconnected', 'Connection error');
79
- }
80
-
81
- function handleWSMessage(msg) {
82
- switch (msg.type) {
83
- case 'agent:log':
84
- if (currentPage === 'dashboard') loadDashboard();
85
- break;
86
- case 'agent:registered':
87
- case 'agent:disconnected':
88
- case 'agent:status':
89
- if (currentPage === 'dashboard') loadDashboard();
90
- if (currentPage === 'agents') loadAgents();
91
- break;
92
- case 'agent:chat':
93
- if (chatAgentId === msg.agentId) addChatMessage('agent', msg.message);
94
- break;
95
- case 'agent:error':
96
- if (chatAgentId === msg.agentId) addChatMessage('error', msg.error);
97
- break;
98
- }
99
- }
100
-
101
- function updateStatus(status, text) {
102
- document.getElementById('status-dot').className = 'status-dot ' + status;
103
- document.getElementById('status-text').textContent = text;
104
- }
105
-
106
- // ── Navigation ─────────────────────────────────────────────────────
107
- function loadPage(page) {
108
- currentPage = page;
109
- document.querySelectorAll('.nav-item').forEach(item => {
110
- item.classList.toggle('active', item.dataset.page === page);
111
- });
112
- document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
113
- const pageEl = document.getElementById(`page-${page}`);
114
- if (pageEl) pageEl.classList.add('active');
115
-
116
- switch (page) {
117
- case 'dashboard': loadDashboard(); break;
118
- case 'agents': loadAgents(); break;
119
- case 'audit': loadAudit(); break;
120
- case 'settings': loadSettings(); break;
121
- }
122
- }
123
-
124
- // ── Dashboard ──────────────────────────────────────────────────────
125
- async function loadDashboard() {
126
- try {
127
- const res = await fetch(`${API}/system`);
128
- const sys = await res.json();
129
-
130
- document.getElementById('stat-agents').textContent = sys.agentsRunning || 0;
131
- document.getElementById('stat-total').textContent = sys.agentsTotal || 0;
132
- document.getElementById('stat-uptime').textContent = sys.uptime ? formatUptime(sys.uptime) : '—';
133
-
134
- const auditRes = await fetch(`${API}/audit?limit=10`);
135
- const audit = await auditRes.json();
136
- const container = document.getElementById('recent-activity');
137
- const count = document.getElementById('activity-count');
138
- if (audit.length === 0) {
139
- container.innerHTML = '<p class="muted">No activity yet. Create an agent to get started.</p>';
140
- count.textContent = '';
141
- } else {
142
- count.textContent = `${audit.length} latest`;
143
- container.innerHTML = audit.map(entry => `
144
- <div class="activity-item">
145
- <span class="activity-icon">${eventIcon(entry.type)}</span>
146
- <span>${formatEvent(entry)}</span>
147
- <span class="activity-time">${timeAgo(entry.timestamp)}</span>
148
- </div>
149
- `).join('');
150
- }
151
- } catch (err) {
152
- console.error('Dashboard error:', err);
153
- }
154
- }
155
-
156
- // ── Agents ─────────────────────────────────────────────────────────
157
- async function loadAgents() {
158
- try {
159
- const res = await fetch(`${API}/agents`);
160
- const agents = await res.json();
161
- const container = document.getElementById('agents-list');
162
-
163
- if (agents.length === 0) {
164
- container.innerHTML = '<p class="muted">No agents yet. Create your first agent to get started.</p>';
165
- return;
166
- }
167
-
168
- container.innerHTML = agents.map(agent => `
169
- <div class="agent-card">
170
- <div class="agent-card-header">
171
- <div>
172
- <div class="agent-name">${esc(agent.name)}</div>
173
- <div class="agent-model">engine · ${esc(agent.model)}</div>
174
- </div>
175
- <span class="agent-status ${agent.status}">${agent.status}</span>
176
- </div>
177
- <div class="agent-tools">
178
- ${(agent.tools || []).map(t => `<span class="agent-tool-tag">${t}</span>`).join('')}
179
- </div>
180
- <div class="agent-actions">
181
- ${agent.status === 'stopped' || agent.status === 'created'
182
- ? `<button class="btn btn-success btn-sm" onclick="startAgent('${agent.id}')">▶ Start</button>`
183
- : `<button class="btn btn-secondary btn-sm" onclick="stopAgent('${agent.id}')">■ Stop</button>`
184
- }
185
- <button class="btn btn-primary btn-sm" onclick="openChat('${agent.id}', '${esc(agent.name)}')">💬 Chat</button>
186
- <button class="btn btn-danger btn-sm" onclick="deleteAgent('${agent.id}')">🗑</button>
187
- </div>
188
- </div>
189
- `).join('');
190
- } catch (err) {
191
- console.error('Agents error:', err);
192
- }
193
- }
194
-
195
- async function startAgent(id) {
196
- await fetch(`${API}/agents/${id}/start`, { method: 'POST' });
197
- loadAgents();
198
- }
199
-
200
- async function stopAgent(id) {
201
- await fetch(`${API}/agents/${id}/stop`, { method: 'POST' });
202
- loadAgents();
203
- }
204
-
205
- async function deleteAgent(id) {
206
- if (!confirm('Delete this agent? This cannot be undone.')) return;
207
- await fetch(`${API}/agents/${id}`, { method: 'DELETE' });
208
- loadAgents();
209
- }
210
-
211
- function showCreateAgent() {
212
- document.getElementById('create-agent-modal').classList.add('open');
213
- }
214
-
215
- function hideCreateAgent() {
216
- document.getElementById('create-agent-modal').classList.remove('open');
217
- }
218
-
219
- // ── Chat ───────────────────────────────────────────────────────────
220
- function openChat(agentId, name) {
221
- chatAgentId = agentId;
222
- document.getElementById('chat-title').textContent = name;
223
- document.getElementById('chat-messages').innerHTML = '<p class="muted chat-empty">Send a message to start talking with this agent.</p>';
224
- document.getElementById('chat-panel').classList.add('open');
225
- document.getElementById('chat-input').focus();
226
- }
227
-
228
- function closeChat() {
229
- chatAgentId = null;
230
- document.getElementById('chat-panel').classList.remove('open');
231
- }
232
-
233
- async function sendChat() {
234
- const input = document.getElementById('chat-input');
235
- const message = input.value.trim();
236
- if (!message || !chatAgentId) return;
237
-
238
- input.value = '';
239
- addChatMessage('user', message);
240
-
241
- try {
242
- const res = await fetch(`${API}/agents/${chatAgentId}/chat`, {
243
- method: 'POST',
244
- headers: { 'Content-Type': 'application/json' },
245
- body: JSON.stringify({ message })
246
- });
247
- const data = await res.json();
248
- if (data.error) addChatMessage('error', data.error);
249
- else if (data.reply) addChatMessage('agent', data.reply);
250
- } catch (err) {
251
- addChatMessage('error', `Connection error: ${err.message}`);
252
- }
253
- }
254
-
255
- function addChatMessage(role, text) {
256
- const container = document.getElementById('chat-messages');
257
- const empty = container.querySelector('.chat-empty');
258
- if (empty) empty.remove();
259
- const div = document.createElement('div');
260
- div.className = `chat-msg ${role}`;
261
- div.textContent = text;
262
- container.appendChild(div);
263
- container.scrollTop = container.scrollHeight;
264
- }
265
-
266
- // ── Audit ──────────────────────────────────────────────────────────
267
- async function loadAudit() {
268
- try {
269
- const type = document.getElementById('audit-filter-type').value;
270
- const url = type ? `${API}/audit?type=${encodeURIComponent(type)}&limit=100` : `${API}/audit?limit=100`;
271
- const res = await fetch(url);
272
- const entries = await res.json();
273
- const container = document.getElementById('audit-list');
274
-
275
- if (entries.length === 0) {
276
- container.innerHTML = '<p class="muted">No audit entries found.</p>';
277
- return;
278
- }
279
-
280
- container.innerHTML = entries.map(entry => `
281
- <div class="audit-entry">
282
- <span class="audit-ts">${entry.timestamp}</span>
283
- <span class="audit-type ${eventTypeClass(entry.type)}">${entry.type}</span>
284
- <span>${formatEvent(entry)}</span>
285
- </div>
286
- `).join('');
287
- } catch (err) {
288
- console.error('Audit error:', err);
289
- }
290
- }
291
-
292
- // ── Settings ───────────────────────────────────────────────────────
293
- async function loadSettings() {
294
- try {
295
- const res = await fetch(`${API}/system`);
296
- const sys = await res.json();
297
-
298
- document.getElementById('setting-docker').textContent = sys.docker?.available
299
- ? `Available (${sys.docker.containers || 0} containers)`
300
- : 'Not running — agents run as local processes';
301
-
302
- document.getElementById('setting-url').textContent = location.origin;
303
- document.getElementById('setting-data-dir').textContent = 'data/ (SQLite)';
304
- } catch (err) {
305
- console.error('Settings error:', err);
306
- }
307
- }
308
-
309
- // ── Helpers ────────────────────────────────────────────────────────
310
- function esc(str) {
311
- if (!str) return '';
312
- const div = document.createElement('div');
313
- div.textContent = str;
314
- return div.innerHTML;
315
- }
316
-
317
- function formatUptime(seconds) {
318
- const h = Math.floor(seconds / 3600);
319
- const m = Math.floor((seconds % 3600) / 60);
320
- if (h > 0) return `${h}h ${m}m`;
321
- if (m > 0) return `${m}m`;
322
- return `${Math.floor(seconds)}s`;
323
- }
324
-
325
- function timeAgo(ts) {
326
- const diff = (Date.now() - new Date(ts + 'Z').getTime()) / 1000;
327
- if (diff < 60) return 'just now';
328
- if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
329
- if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
330
- return `${Math.floor(diff / 86400)}d ago`;
331
- }
332
-
333
- function eventIcon(type) {
334
- if (type.startsWith('llm:')) return '◈';
335
- if (type.startsWith('agent:')) return '✦';
336
- if (type.startsWith('tool:')) return '🔧';
337
- return '≡';
338
- }
339
-
340
- function eventTypeClass(type) {
341
- if (type.startsWith('llm:')) return 'llm';
342
- if (type.startsWith('agent:')) return 'agent';
343
- if (type.startsWith('tool:')) return 'tool';
344
- if (type.includes('error')) return 'error';
345
- return '';
346
- }
347
-
348
- function formatEvent(entry) {
349
- const d = entry.data || {};
350
- switch (entry.type) {
351
- case 'llm:call':
352
- return `Engine call to ${d.model || 'brain'} — ${d.messageCount || 0} messages, ${d.tokenUsage?.total || 0} tokens`;
353
- case 'llm:proxy':
354
- return `Engine reasoning for agent ${d.agentId} — ${d.messageCount || 0} messages`;
355
- case 'llm:proxy:error':
356
- return `Engine error for ${d.agentId}: ${d.error}`;
357
- case 'agent:create':
358
- return `Agent "${d.name}" created`;
359
- case 'agent:start':
360
- return `Agent ${d.id} started`;
361
- case 'agent:stop':
362
- return `Agent ${d.id} stopped`;
363
- case 'agent:delete':
364
- return `Agent ${d.id} deleted`;
365
- case 'agent:log':
366
- return `[${d.level}] ${d.message}`;
367
- case 'agent:error':
368
- return `Error: ${d.error}`;
369
- case 'tool:executed':
370
- return `Tool "${d.tool}" executed`;
371
- default:
372
- return JSON.stringify(d).substring(0, 100);
373
- }
374
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/dashboard/index.html DELETED
@@ -1,227 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>mona.expert — Control Plane</title>
7
- <link rel="stylesheet" href="style.css">
8
- <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'><stop offset='0' stop-color='%237c5cff'/><stop offset='1' stop-color='%2322d3ee'/></linearGradient></defs><rect width='100' height='100' rx='24' fill='url(%23g)'/><text x='50' y='68' font-size='52' text-anchor='middle' fill='white' font-family='-apple-system,sans-serif' font-weight='700'>M</text></svg>">
9
- </head>
10
- <body>
11
- <div class="bg-glow bg-glow-1"></div>
12
- <div class="bg-glow bg-glow-2"></div>
13
- <div class="bg-grid"></div>
14
-
15
- <div id="app">
16
- <!-- Sidebar -->
17
- <nav id="sidebar">
18
- <div class="logo">
19
- <span class="logo-mark">M</span>
20
- <span class="logo-text">mona<span class="logo-dot">.</span>expert</span>
21
- </div>
22
-
23
- <ul class="nav-items">
24
- <li class="nav-item active" data-page="dashboard">
25
- <span class="nav-icon">◧</span><span class="nav-label">Dashboard</span>
26
- </li>
27
- <li class="nav-item" data-page="agents">
28
- <span class="nav-icon">✦</span><span class="nav-label">Agents</span>
29
- </li>
30
- <li class="nav-item" data-page="audit">
31
- <span class="nav-icon">≡</span><span class="nav-label">Audit Log</span>
32
- </li>
33
- <li class="nav-item" data-page="settings">
34
- <span class="nav-icon">⚙</span><span class="nav-label">Settings</span>
35
- </li>
36
- </ul>
37
-
38
- <div class="sidebar-footer">
39
- <span class="status-dot" id="status-dot"></span>
40
- <span id="status-text">Connecting…</span>
41
- </div>
42
- </nav>
43
-
44
- <!-- Main content -->
45
- <main id="content">
46
-
47
- <!-- Dashboard Page -->
48
- <div class="page active" id="page-dashboard">
49
- <div class="page-head">
50
- <div>
51
- <h1>Dashboard</h1>
52
- <p class="page-sub">Powered by the mona.expert engine</p>
53
- </div>
54
- <span class="live-badge"><span class="live-dot"></span> LIVE</span>
55
- </div>
56
-
57
- <div class="stats-grid" id="stats-grid">
58
- <div class="stat-card">
59
- <div class="stat-icon stat-icon-green">▶</div>
60
- <div class="stat-value" id="stat-agents">0</div>
61
- <div class="stat-label">Agents Running</div>
62
- </div>
63
- <div class="stat-card">
64
- <div class="stat-icon stat-icon-violet">✦</div>
65
- <div class="stat-value" id="stat-total">0</div>
66
- <div class="stat-label">Total Agents</div>
67
- </div>
68
- <div class="stat-card">
69
- <div class="stat-icon stat-icon-cyan">◈</div>
70
- <div class="stat-value stat-static">mona.expert</div>
71
- <div class="stat-label">AI Engine</div>
72
- </div>
73
- <div class="stat-card">
74
- <div class="stat-icon stat-icon-amber">◔</div>
75
- <div class="stat-value" id="stat-uptime">—</div>
76
- <div class="stat-label">Platform Uptime</div>
77
- </div>
78
- </div>
79
-
80
- <div class="card">
81
- <div class="card-head">
82
- <h3>Recent Activity</h3>
83
- <span class="card-hint" id="activity-count"></span>
84
- </div>
85
- <div id="recent-activity" class="activity-list">
86
- <p class="muted">Loading…</p>
87
- </div>
88
- </div>
89
- </div>
90
-
91
- <!-- Agents Page -->
92
- <div class="page" id="page-agents">
93
- <div class="page-head">
94
- <div>
95
- <h1>Agents</h1>
96
- <p class="page-sub">Directed by the mona.expert engine</p>
97
- </div>
98
- <button class="btn btn-primary" onclick="showCreateAgent()">+ New Agent</button>
99
- </div>
100
- <div id="agents-list" class="agents-grid">
101
- <p class="muted">Loading agents…</p>
102
- </div>
103
-
104
- <div class="modal" id="create-agent-modal">
105
- <div class="modal-backdrop" onclick="hideCreateAgent()"></div>
106
- <div class="modal-content">
107
- <div class="modal-head">
108
- <h3>Create New Agent</h3>
109
- <button class="btn-close" onclick="hideCreateAgent()">✕</button>
110
- </div>
111
- <form id="create-agent-form">
112
- <label>Name</label>
113
- <input type="text" name="name" placeholder="My Agent" required>
114
-
115
- <label>Brain</label>
116
- <div class="brain-note">mona.expert engine — model auto-assigned</div>
117
- <input type="hidden" name="model" value="openai/gpt-4o">
118
-
119
- <label>System Prompt <span class="opt">optional</span></label>
120
- <textarea name="systemPrompt" rows="3" placeholder="You are a helpful AI agent…"></textarea>
121
-
122
- <label>Tools</label>
123
- <div class="tools-checkboxes">
124
- <label class="checkbox-label"><input type="checkbox" name="tools" value="files" checked> Files</label>
125
- <label class="checkbox-label"><input type="checkbox" name="tools" value="web" checked> Web</label>
126
- <label class="checkbox-label"><input type="checkbox" name="tools" value="shell" checked> Shell</label>
127
- </div>
128
-
129
- <div class="modal-actions">
130
- <button type="button" class="btn btn-ghost" onclick="hideCreateAgent()">Cancel</button>
131
- <button type="submit" class="btn btn-primary">Create Agent</button>
132
- </div>
133
- </form>
134
- </div>
135
- </div>
136
- </div>
137
-
138
- <!-- Chat Panel -->
139
- <div class="chat-panel" id="chat-panel">
140
- <div class="chat-header">
141
- <div class="chat-title-wrap">
142
- <span class="chat-agent-avatar">✦</span>
143
- <h3 id="chat-title">Agent Chat</h3>
144
- </div>
145
- <button class="btn-close" onclick="closeChat()">✕</button>
146
- </div>
147
- <div class="chat-messages" id="chat-messages">
148
- <p class="muted chat-empty">Send a message to start talking with this agent.</p>
149
- </div>
150
- <div class="chat-input">
151
- <input type="text" id="chat-input" placeholder="Type a message…" autocomplete="off"
152
- onkeydown="if(event.key==='Enter')sendChat()">
153
- <button class="btn btn-primary send-btn" onclick="sendChat()">Send →</button>
154
- </div>
155
- </div>
156
-
157
- <!-- Audit Page -->
158
- <div class="page" id="page-audit">
159
- <div class="page-head">
160
- <div>
161
- <h1>Audit Log</h1>
162
- <p class="page-sub">Every command from the engine, every execution</p>
163
- </div>
164
- <select id="audit-filter-type" class="filter-select" onchange="loadAudit()">
165
- <option value="">All Events</option>
166
- <option value="llm:call">LLM Calls</option>
167
- <option value="llm:proxy">LLM Proxy</option>
168
- <option value="agent:create">Agent Created</option>
169
- <option value="agent:start">Agent Started</option>
170
- <option value="agent:stop">Agent Stopped</option>
171
- <option value="tool:executed">Tool Executed</option>
172
- <option value="agent:log">Agent Log</option>
173
- <option value="agent:error">Agent Error</option>
174
- </select>
175
- </div>
176
- <div id="audit-list" class="audit-list">
177
- <p class="muted">Loading audit log…</p>
178
- </div>
179
- </div>
180
-
181
- <!-- Settings Page -->
182
- <div class="page" id="page-settings">
183
- <div class="page-head">
184
- <div>
185
- <h1>Settings</h1>
186
- <p class="page-sub">Platform configuration</p>
187
- </div>
188
- </div>
189
- <div class="card">
190
- <div class="card-head"><h3>Platform</h3></div>
191
- <div class="setting-row">
192
- <span class="setting-label">Docker</span>
193
- <span id="setting-docker" class="setting-value">Checking…</span>
194
- </div>
195
- <div class="setting-row">
196
- <span class="setting-label">Platform URL</span>
197
- <span class="setting-value" id="setting-url">—</span>
198
- </div>
199
- <div class="setting-row">
200
- <span class="setting-label">Data Directory</span>
201
- <span class="setting-value" id="setting-data-dir">—</span>
202
- </div>
203
- </div>
204
- <div class="card">
205
- <div class="card-head"><h3>Security</h3></div>
206
- <div class="setting-row">
207
- <span class="setting-label">Device key</span>
208
- <span class="setting-value">mona.expert key only</span>
209
- </div>
210
- <div class="setting-row">
211
- <span class="setting-label">Provider keys</span>
212
- <span class="setting-value setting-good">none — engine handles everything</span>
213
- </div>
214
- </div>
215
- <div class="card">
216
- <div class="card-head"><h3>About</h3></div>
217
- <p>mona.expert control plane v1.0.0</p>
218
- <p class="muted">Open-source AI agent platform. MIT licensed.</p>
219
- <p class="muted">One key. One brain. mona.expert.</p>
220
- </div>
221
- </div>
222
- </main>
223
- </div>
224
-
225
- <script src="app.js"></script>
226
- </body>
227
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/dashboard/style.css DELETED
@@ -1,393 +0,0 @@
1
- /* ═══════════════════════════════════════════════════════════════
2
- mona.expert — Control Plane
3
- Dark glass theme · violet → cyan accents
4
- ═══════════════════════════════════════════════════════════════ */
5
-
6
- :root {
7
- --bg: #080b14;
8
- --bg-soft: #0c101d;
9
- --panel: rgba(255, 255, 255, 0.035);
10
- --panel-strong: rgba(255, 255, 255, 0.06);
11
- --border: rgba(255, 255, 255, 0.08);
12
- --border-strong: rgba(255, 255, 255, 0.14);
13
- --text: #e9edf8;
14
- --text-dim: #a7aec7;
15
- --muted: #6d7592;
16
- --accent-1: #7c5cff;
17
- --accent-2: #22d3ee;
18
- --grad: linear-gradient(135deg, var(--accent-1), var(--accent-2));
19
- --green: #34d399;
20
- --amber: #fbbf24;
21
- --red: #f87171;
22
- --cyan: #22d3ee;
23
- --violet: #a78bfa;
24
- --radius: 16px;
25
- --radius-sm: 10px;
26
- --shadow: 0 8px 30px rgba(0, 0, 0, 0.35);
27
- --font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
28
- --mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
29
- }
30
-
31
- * { margin: 0; padding: 0; box-sizing: border-box; }
32
-
33
- html, body { height: 100%; }
34
-
35
- body {
36
- font-family: var(--font);
37
- background: var(--bg);
38
- color: var(--text);
39
- font-size: 14px;
40
- line-height: 1.5;
41
- overflow: hidden;
42
- -webkit-font-smoothing: antialiased;
43
- }
44
-
45
- /* ── Ambient background ─────────────────────────────────────────── */
46
- .bg-glow { position: fixed; border-radius: 50%; filter: blur(120px); opacity: 0.35; pointer-events: none; z-index: 0; }
47
- .bg-glow-1 { width: 520px; height: 520px; top: -180px; right: -120px; background: radial-gradient(circle, rgba(124, 92, 255, 0.55), transparent 70%); }
48
- .bg-glow-2 { width: 460px; height: 460px; bottom: -160px; left: -100px; background: radial-gradient(circle, rgba(34, 211, 238, 0.4), transparent 70%); }
49
- .bg-grid {
50
- position: fixed; inset: 0; z-index: 0; pointer-events: none; opacity: 0.5;
51
- background-image:
52
- linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px),
53
- linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px);
54
- background-size: 44px 44px;
55
- mask-image: radial-gradient(ellipse 90% 70% at 50% 0%, black 40%, transparent 100%);
56
- }
57
-
58
- #app { display: flex; height: 100vh; position: relative; z-index: 1; }
59
-
60
- /* ── Sidebar ────────────────────────────────────────────────────── */
61
- #sidebar {
62
- width: 232px;
63
- flex-shrink: 0;
64
- display: flex;
65
- flex-direction: column;
66
- padding: 20px 14px 16px;
67
- background: rgba(10, 14, 26, 0.6);
68
- border-right: 1px solid var(--border);
69
- backdrop-filter: blur(14px);
70
- }
71
-
72
- .logo { display: flex; align-items: center; gap: 10px; padding: 2px 8px 18px; }
73
- .logo-mark {
74
- width: 34px; height: 34px; border-radius: 10px;
75
- background: var(--grad);
76
- color: white; font-weight: 800; font-size: 18px;
77
- display: grid; place-items: center;
78
- box-shadow: 0 4px 14px rgba(124, 92, 255, 0.45);
79
- }
80
- .logo-text { font-weight: 700; font-size: 15px; letter-spacing: -0.01em; }
81
- .logo-dot { color: var(--accent-2); }
82
-
83
- .nav-items { list-style: none; display: flex; flex-direction: column; gap: 4px; flex: 1; }
84
-
85
- .nav-item {
86
- display: flex; align-items: center; gap: 11px;
87
- padding: 10px 12px; border-radius: var(--radius-sm);
88
- color: var(--text-dim); cursor: pointer; user-select: none;
89
- transition: background 0.15s, color 0.15s;
90
- font-weight: 500;
91
- }
92
- .nav-item:hover { background: var(--panel); color: var(--text); }
93
- .nav-item.active {
94
- background: linear-gradient(135deg, rgba(124,92,255,0.16), rgba(34,211,238,0.10));
95
- color: white;
96
- box-shadow: inset 0 0 0 1px rgba(124,92,255,0.35);
97
- }
98
- .nav-icon { width: 20px; text-align: center; font-size: 15px; opacity: 0.9; }
99
- .nav-item.active .nav-icon { opacity: 1; }
100
-
101
- .sidebar-footer {
102
- display: flex; align-items: center; gap: 8px;
103
- padding: 12px 8px 4px; border-top: 1px solid var(--border);
104
- font-size: 12.5px; color: var(--muted);
105
- }
106
-
107
- .status-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--muted); flex-shrink: 0; }
108
- .status-dot.connected { background: var(--green); box-shadow: 0 0 8px rgba(52, 211, 153, 0.9); }
109
- .status-dot.disconnected { background: var(--red); box-shadow: 0 0 8px rgba(248, 113, 113, 0.8); }
110
-
111
- /* ── Main ───────────────────────────────────────────────────────── */
112
- #content { flex: 1; overflow-y: auto; padding: 28px 32px 40px; scrollbar-width: thin; scrollbar-color: var(--border-strong) transparent; }
113
- #content::-webkit-scrollbar { width: 8px; }
114
- #content::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 4px; }
115
-
116
- .page { display: none; animation: fadeUp 0.25s ease; }
117
- .page.active { display: block; }
118
-
119
- @keyframes fadeUp { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
120
-
121
- .page-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; margin-bottom: 22px; flex-wrap: wrap; }
122
- .page-head h1 { font-size: 24px; font-weight: 700; letter-spacing: -0.02em; }
123
- .page-sub { color: var(--muted); margin-top: 2px; font-size: 13px; }
124
-
125
- .live-badge {
126
- display: inline-flex; align-items: center; gap: 7px;
127
- font-size: 11px; font-weight: 700; letter-spacing: 0.12em;
128
- color: var(--green); padding: 6px 12px; border-radius: 999px;
129
- background: rgba(52, 211, 153, 0.08); border: 1px solid rgba(52, 211, 153, 0.25);
130
- }
131
- .live-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--green); animation: pulse 2s infinite; }
132
- @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
133
-
134
- /* ── Stat cards ─────────────────────────────────────────────────── */
135
- .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; margin-bottom: 20px; }
136
-
137
- .stat-card {
138
- background: var(--panel); border: 1px solid var(--border);
139
- border-radius: var(--radius); padding: 18px;
140
- position: relative; overflow: hidden;
141
- transition: transform 0.15s, border-color 0.15s, background 0.15s;
142
- }
143
- .stat-card:hover { transform: translateY(-2px); border-color: var(--border-strong); background: var(--panel-strong); }
144
- .stat-card::after {
145
- content: ""; position: absolute; top: 0; left: 0; right: 0; height: 2px;
146
- background: var(--grad); opacity: 0.55;
147
- }
148
- .stat-icon {
149
- width: 34px; height: 34px; border-radius: 9px; display: grid; place-items: center;
150
- font-size: 15px; margin-bottom: 12px;
151
- }
152
- .stat-icon-green { background: rgba(52,211,153,0.12); color: var(--green); }
153
- .stat-icon-violet { background: rgba(167,139,250,0.12); color: var(--violet); }
154
- .stat-icon-cyan { background: rgba(34,211,238,0.12); color: var(--cyan); }
155
- .stat-icon-amber { background: rgba(251,191,36,0.12); color: var(--amber); }
156
- .stat-value {
157
- font-size: 30px; font-weight: 800; letter-spacing: -0.03em; line-height: 1.1;
158
- background: var(--grad); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent;
159
- }
160
- .stat-label { color: var(--muted); font-size: 12px; margin-top: 4px; font-weight: 500; }
161
-
162
- /* ── Cards ──────────────────────────────────────────────────────── */
163
- .card {
164
- background: var(--panel); border: 1px solid var(--border);
165
- border-radius: var(--radius); padding: 20px; margin-bottom: 16px;
166
- }
167
- .card-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 14px; }
168
- .card-head h3 { font-size: 15px; font-weight: 600; }
169
- .card-hint { color: var(--muted); font-size: 12px; }
170
-
171
- /* ── Activity list ──────────────────────────────────────────────── */
172
- .activity-list { display: flex; flex-direction: column; }
173
- .activity-item {
174
- display: flex; align-items: center; gap: 12px;
175
- padding: 10px 8px; border-radius: var(--radius-sm);
176
- border-bottom: 1px solid var(--border);
177
- font-size: 13px;
178
- }
179
- .activity-item:last-child { border-bottom: none; }
180
- .activity-item:hover { background: var(--panel-strong); }
181
- .activity-icon {
182
- width: 28px; height: 28px; flex-shrink: 0; border-radius: 8px;
183
- display: grid; place-items: center; font-size: 13px;
184
- background: var(--panel-strong);
185
- }
186
- .activity-time { margin-left: auto; color: var(--muted); font-size: 11.5px; white-space: nowrap; }
187
-
188
- /* ── Buttons ────────────────────────────────────────────────────── */
189
- .btn {
190
- font-family: inherit; font-size: 13px; font-weight: 600;
191
- border: none; border-radius: var(--radius-sm);
192
- padding: 9px 16px; cursor: pointer; color: var(--text);
193
- transition: transform 0.12s, box-shadow 0.12s, filter 0.12s;
194
- }
195
- .btn:active { transform: scale(0.97); }
196
- .btn-primary { background: var(--grad); color: white; box-shadow: 0 4px 16px rgba(124, 92, 255, 0.35); }
197
- .btn-primary:hover { filter: brightness(1.1); }
198
- .btn-ghost { background: transparent; border: 1px solid var(--border-strong); color: var(--text-dim); }
199
- .btn-ghost:hover { color: var(--text); border-color: var(--text-dim); }
200
- .btn-secondary { background: var(--panel-strong); border: 1px solid var(--border-strong); color: var(--text-dim); }
201
- .btn-secondary:hover { color: var(--text); }
202
- .btn-danger { background: rgba(248,113,113,0.12); color: var(--red); border: 1px solid rgba(248,113,113,0.25); }
203
- .btn-danger:hover { background: rgba(248,113,113,0.2); }
204
- .btn-success { background: rgba(52,211,153,0.12); color: var(--green); border: 1px solid rgba(52,211,153,0.25); }
205
- .btn-success:hover { background: rgba(52,211,153,0.2); }
206
- .btn-sm { padding: 6px 11px; font-size: 12px; }
207
-
208
- /* ── Agent cards ────────────────────────────────────────────────── */
209
- .agents-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 14px; }
210
-
211
- .agent-card {
212
- background: var(--panel); border: 1px solid var(--border);
213
- border-radius: var(--radius); padding: 18px;
214
- transition: transform 0.15s, border-color 0.15s, box-shadow 0.15s;
215
- display: flex; flex-direction: column; gap: 12px;
216
- }
217
- .agent-card:hover { transform: translateY(-2px); border-color: var(--border-strong); box-shadow: var(--shadow); }
218
-
219
- .agent-card-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }
220
- .agent-name { font-weight: 700; font-size: 15px; }
221
- .agent-model { color: var(--muted); font-size: 12px; margin-top: 2px; font-family: var(--mono); }
222
-
223
- .agent-status {
224
- font-size: 10.5px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase;
225
- padding: 4px 10px; border-radius: 999px; white-space: nowrap;
226
- }
227
- .agent-status.running { color: var(--green); background: rgba(52,211,153,0.1); box-shadow: 0 0 10px rgba(52,211,153,0.25); }
228
- .agent-status.stopped, .agent-status.created { color: var(--muted); background: rgba(255,255,255,0.06); }
229
- .agent-status.error { color: var(--red); background: rgba(248,113,113,0.1); }
230
-
231
- .agent-tools { display: flex; flex-wrap: wrap; gap: 6px; }
232
- .agent-tool-tag {
233
- font-size: 11px; font-weight: 600; padding: 3px 9px; border-radius: 999px;
234
- background: rgba(124,92,255,0.1); color: var(--violet);
235
- border: 1px solid rgba(124,92,255,0.22);
236
- }
237
- .agent-actions { display: flex; gap: 8px; margin-top: auto; }
238
-
239
- /* ── Chat panel ─────────────────────────────────────────────────── */
240
- .chat-panel {
241
- position: fixed; top: 0; right: -420px; width: 400px; max-width: 92vw; height: 100vh;
242
- background: rgba(10, 14, 26, 0.92); backdrop-filter: blur(18px);
243
- border-left: 1px solid var(--border-strong);
244
- display: flex; flex-direction: column;
245
- transition: right 0.28s cubic-bezier(0.22, 1, 0.36, 1);
246
- z-index: 50; box-shadow: -20px 0 60px rgba(0,0,0,0.5);
247
- }
248
- .chat-panel.open { right: 0; }
249
-
250
- .chat-header {
251
- display: flex; align-items: center; justify-content: space-between;
252
- padding: 16px 18px; border-bottom: 1px solid var(--border);
253
- }
254
- .chat-title-wrap { display: flex; align-items: center; gap: 10px; }
255
- .chat-agent-avatar {
256
- width: 30px; height: 30px; border-radius: 9px; background: var(--grad);
257
- display: grid; place-items: center; font-size: 13px; color: white;
258
- }
259
- .chat-header h3 { font-size: 14px; font-weight: 700; }
260
-
261
- .btn-close { background: none; border: none; color: var(--muted); font-size: 14px; cursor: pointer; padding: 6px; border-radius: 8px; }
262
- .btn-close:hover { color: var(--text); background: var(--panel-strong); }
263
-
264
- .chat-messages { flex: 1; overflow-y: auto; padding: 18px; display: flex; flex-direction: column; gap: 10px; scrollbar-width: thin; }
265
- .chat-empty { text-align: center; margin-top: 40px; }
266
-
267
- .chat-msg { max-width: 82%; padding: 10px 14px; border-radius: 14px; font-size: 13.5px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; }
268
- .chat-msg.user { align-self: flex-end; background: var(--grad); color: white; border-bottom-right-radius: 4px; }
269
- .chat-msg.agent { align-self: flex-start; background: var(--panel-strong); border: 1px solid var(--border); border-bottom-left-radius: 4px; }
270
- .chat-msg.error { align-self: flex-start; background: rgba(248,113,113,0.1); border: 1px solid rgba(248,113,113,0.3); color: var(--red); }
271
-
272
- .chat-input { display: flex; gap: 8px; padding: 14px; border-top: 1px solid var(--border); }
273
- .chat-input input {
274
- flex: 1; background: var(--panel-strong); border: 1px solid var(--border);
275
- border-radius: var(--radius-sm); padding: 10px 14px; color: var(--text);
276
- font-family: inherit; font-size: 13.5px; outline: none;
277
- }
278
- .chat-input input:focus { border-color: rgba(124,92,255,0.5); box-shadow: 0 0 0 3px rgba(124,92,255,0.15); }
279
- .send-btn { padding: 10px 16px; }
280
-
281
- /* ── Keys ───────────────────────────────────────────────────────── */
282
- .key-note {
283
- display: flex; gap: 12px; align-items: flex-start;
284
- background: linear-gradient(135deg, rgba(124,92,255,0.08), rgba(34,211,238,0.05));
285
- border: 1px solid rgba(124,92,255,0.25); border-radius: var(--radius);
286
- padding: 14px 16px; margin-bottom: 16px; font-size: 13px; color: var(--text-dim);
287
- }
288
- .key-note-icon { font-size: 16px; }
289
- .key-note strong { color: var(--text); }
290
-
291
- .keys-list { display: flex; flex-direction: column; gap: 10px; }
292
- .key-card {
293
- display: flex; align-items: center; gap: 14px;
294
- background: var(--panel); border: 1px solid var(--border);
295
- border-radius: var(--radius); padding: 14px 16px;
296
- transition: border-color 0.15s;
297
- }
298
- .key-card:hover { border-color: var(--border-strong); }
299
- .key-provider { font-weight: 700; font-size: 14px; text-transform: capitalize; }
300
- .key-label { color: var(--muted); font-size: 12px; }
301
- .key-masked {
302
- margin-left: auto; font-family: var(--mono); font-size: 12px;
303
- color: var(--text-dim); background: rgba(0,0,0,0.25);
304
- padding: 5px 10px; border-radius: 8px; letter-spacing: 0.03em;
305
- }
306
-
307
- /* ── Audit ──────────────────────────────────────────────────────── */
308
- .filter-select {
309
- background: var(--panel-strong); border: 1px solid var(--border-strong);
310
- color: var(--text); border-radius: var(--radius-sm);
311
- padding: 9px 12px; font-family: inherit; font-size: 13px; outline: none; cursor: pointer;
312
- }
313
- .filter-select:focus { border-color: rgba(124,92,255,0.5); }
314
-
315
- .audit-list { display: flex; flex-direction: column; }
316
- .audit-entry {
317
- display: flex; align-items: center; gap: 12px;
318
- padding: 11px 10px; border-bottom: 1px solid var(--border);
319
- font-size: 13px;
320
- }
321
- .audit-entry:last-child { border-bottom: none; }
322
- .audit-entry:hover { background: var(--panel-strong); }
323
- .audit-ts { color: var(--muted); font-size: 11.5px; font-family: var(--mono); white-space: nowrap; }
324
- .audit-type {
325
- font-size: 10px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase;
326
- padding: 3px 8px; border-radius: 6px; white-space: nowrap;
327
- }
328
- .audit-type.llm { background: rgba(34,211,238,0.1); color: var(--cyan); }
329
- .audit-type.agent { background: rgba(167,139,250,0.1); color: var(--violet); }
330
- .audit-type.key { background: rgba(251,191,36,0.1); color: var(--amber); }
331
- .audit-type.tool { background: rgba(52,211,153,0.1); color: var(--green); }
332
- .audit-type.error { background: rgba(248,113,113,0.1); color: var(--red); }
333
-
334
- /* ── Settings ───────────────────────────────────────────────────── */
335
- .setting-row {
336
- display: flex; align-items: center; justify-content: space-between;
337
- padding: 12px 2px; border-bottom: 1px solid var(--border);
338
- }
339
- .setting-row:last-child { border-bottom: none; }
340
- .setting-label { color: var(--text-dim); font-weight: 500; }
341
- .setting-value { color: var(--text); font-family: var(--mono); font-size: 12.5px; }
342
-
343
- /* ── Forms & modal ──────────────────────────────────────────────── */
344
- .modal { position: fixed; inset: 0; z-index: 100; display: none; align-items: center; justify-content: center; }
345
- .modal.open { display: flex; }
346
- .modal-backdrop { position: absolute; inset: 0; background: rgba(4, 6, 12, 0.7); backdrop-filter: blur(6px); }
347
- .modal-content {
348
- position: relative; width: 440px; max-width: 92vw; max-height: 88vh; overflow-y: auto;
349
- background: #0e1322; border: 1px solid var(--border-strong);
350
- border-radius: 18px; padding: 22px; box-shadow: 0 24px 80px rgba(0,0,0,0.6);
351
- animation: popIn 0.18s ease;
352
- }
353
- @keyframes popIn { from { opacity: 0; transform: scale(0.96) translateY(8px); } to { opacity: 1; transform: none; } }
354
- .modal-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
355
- .modal-head h3 { font-size: 16px; font-weight: 700; }
356
-
357
- .modal-content label { display: block; font-size: 12.5px; font-weight: 600; color: var(--text-dim); margin: 14px 0 6px; }
358
- .modal-content .opt { color: var(--muted); font-weight: 400; font-size: 11px; }
359
-
360
- .modal-content input[type="text"],
361
- .modal-content input[type="password"],
362
- .modal-content select,
363
- .modal-content textarea {
364
- width: 100%; background: rgba(0,0,0,0.25);
365
- border: 1px solid var(--border-strong); border-radius: var(--radius-sm);
366
- padding: 10px 12px; color: var(--text); font-family: inherit; font-size: 13.5px;
367
- outline: none; transition: border-color 0.12s, box-shadow 0.12s;
368
- }
369
- .modal-content input:focus, .modal-content select:focus, .modal-content textarea:focus {
370
- border-color: rgba(124,92,255,0.55); box-shadow: 0 0 0 3px rgba(124,92,255,0.14);
371
- }
372
- .modal-content textarea { resize: vertical; }
373
- .modal-content select option { background: #0e1322; color: var(--text); }
374
-
375
- .tools-checkboxes { display: flex; gap: 14px; margin-top: 8px; }
376
- .checkbox-label {
377
- display: flex !important; align-items: center; gap: 7px;
378
- font-size: 13px !important; font-weight: 500 !important; color: var(--text) !important;
379
- margin: 0 !important; cursor: pointer;
380
- }
381
- .checkbox-label input { accent-color: var(--accent-1); width: 15px; height: 15px; }
382
-
383
- .form-hint { color: var(--muted); font-size: 12px; margin-top: 10px; }
384
- .modal-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px; }
385
-
386
- .muted { color: var(--muted); font-size: 13px; padding: 8px 0; }
387
-
388
- .brain-note {
389
- background: rgba(124,92,255,0.08); border: 1px dashed rgba(124,92,255,0.35);
390
- color: var(--violet); border-radius: var(--radius-sm);
391
- padding: 9px 12px; font-size: 12.5px; font-weight: 500;
392
- }
393
- .setting-good { color: var(--green); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/package.json DELETED
@@ -1,26 +0,0 @@
1
- {
2
- "name": "agent.mona.expert-platform",
3
- "version": "1.0.0",
4
- "description": "Agent control plane — container management, LLM proxy, key vault, audit",
5
- "type": "module",
6
- "main": "src/server.js",
7
- "scripts": {
8
- "start": "node src/server.js",
9
- "dev": "node --watch src/server.js",
10
- "test": "node --test"
11
- },
12
- "dependencies": {
13
- "dockerode": "^4.0.2",
14
- "express": "^4.21.0",
15
- "ws": "^8.18.0",
16
- "uuid": "^10.0.0",
17
- "sql.js": "^1.12.0",
18
- "node-fetch": "^3.3.2",
19
- "cors": "^2.8.5",
20
- "multer": "^1.4.5-lts.1"
21
- },
22
- "engines": {
23
- "node": ">=20.0.0"
24
- },
25
- "license": "MIT"
26
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/src/agent-connection.js DELETED
@@ -1,275 +0,0 @@
1
- /**
2
- * Agent Connection Manager — WebSocket comms between platform and agents.
3
- *
4
- * Agents connect via WebSocket. The platform routes messages,
5
- * proxies LLM calls, and streams logs/status back to the dashboard.
6
- */
7
- import { WebSocket } from 'ws';
8
- import { LLMProxy } from './llm-proxy.js';
9
-
10
- export class AgentConnection {
11
- constructor(wss, { vault, containers, audit }) {
12
- this.wss = wss;
13
- this.vault = vault;
14
- this.containers = containers;
15
- this.audit = audit;
16
-
17
- // Connected agents: agentId → { ws, name, model, pendingRequests }
18
- this.agents = new Map();
19
-
20
- // Dashboard clients: ws → Set<agentId>
21
- this.clients = new Map();
22
-
23
- wss.on('connection', (ws, req) => {
24
- const url = new URL(req.url, 'http://localhost');
25
- const clientType = url.searchParams.get('type'); // 'agent' or 'dashboard'
26
- const agentId = url.searchParams.get('agentId');
27
-
28
- if (clientType === 'agent' && agentId) {
29
- this._handleAgentConnection(ws, agentId);
30
- } else if (clientType === 'dashboard') {
31
- this._handleDashboardConnection(ws);
32
- } else {
33
- // Legacy/unknown — treat as agent
34
- this._handleAgentConnection(ws, agentId || 'unknown');
35
- }
36
- });
37
- }
38
-
39
- /**
40
- * Handle an agent connecting to the platform.
41
- */
42
- _handleAgentConnection(ws, agentId) {
43
- console.log(` Agent connected: ${agentId}`);
44
-
45
- const state = {
46
- ws,
47
- name: agentId,
48
- model: 'unknown',
49
- pendingRequests: new Map() // requestId → { resolve, reject }
50
- };
51
-
52
- this.agents.set(agentId, state);
53
-
54
- // Register this agent for all dashboard clients
55
- for (const [_, subscribed] of this.clients) {
56
- subscribed.add(agentId);
57
- }
58
-
59
- ws.on('message', async (data) => {
60
- try {
61
- const msg = JSON.parse(data.toString());
62
- await this._handleAgentMessage(agentId, state, msg);
63
- } catch (err) {
64
- console.error(` Agent ${agentId} message error:`, err.message);
65
- this._send(ws, { type: 'error', error: err.message });
66
- }
67
- });
68
-
69
- ws.on('close', () => {
70
- console.log(` Agent disconnected: ${agentId}`);
71
- this.agents.delete(agentId);
72
- this._broadcast({ type: 'agent:disconnected', agentId });
73
- });
74
-
75
- ws.on('error', (err) => {
76
- console.error(` Agent ${agentId} WS error:`, err.message);
77
- });
78
-
79
- // Send welcome
80
- this._send(ws, { type: 'welcome', agentId, message: 'Connected to agent.mona.expert platform' });
81
- }
82
-
83
- /**
84
- * Handle a dashboard client connecting.
85
- */
86
- _handleDashboardConnection(ws) {
87
- console.log(' Dashboard client connected');
88
- this.clients.set(ws, new Set());
89
-
90
- // Send current agent list
91
- const agentIds = Array.from(this.agents.keys());
92
- this._send(ws, { type: 'agents:list', agents: agentIds });
93
-
94
- ws.on('close', () => {
95
- this.clients.delete(ws);
96
- });
97
- }
98
-
99
- /**
100
- * Handle a message from an agent.
101
- */
102
- async _handleAgentMessage(agentId, state, msg) {
103
- switch (msg.type) {
104
- case 'register': {
105
- state.name = msg.name || agentId;
106
- state.model = msg.model || 'unknown';
107
- console.log(` Agent registered: ${state.name} (${state.model})`);
108
- this._broadcast({ type: 'agent:registered', agentId, name: state.name, model: state.model });
109
- break;
110
- }
111
-
112
- case 'llm:request': {
113
- // Agent wants to make an LLM call — proxy it through the platform
114
- try {
115
- const result = await LLMProxy.call(this.vault, {
116
- provider: msg.provider,
117
- model: msg.model,
118
- messages: msg.messages,
119
- temperature: msg.temperature,
120
- maxTokens: msg.maxTokens,
121
- keyId: msg.keyId
122
- });
123
- this._send(state.ws, {
124
- type: 'llm:response',
125
- requestId: msg.requestId,
126
- content: result.content,
127
- usage: result.usage,
128
- model: result.model,
129
- finishReason: result.finishReason
130
- });
131
- this.audit.record('llm:proxy', {
132
- agentId,
133
- provider: msg.provider || msg.model,
134
- messageCount: msg.messages?.length,
135
- usage: result.usage
136
- }, agentId);
137
- } catch (err) {
138
- this._send(state.ws, {
139
- type: 'llm:error',
140
- requestId: msg.requestId,
141
- error: err.message
142
- });
143
- this.audit.record('llm:proxy:error', {
144
- agentId,
145
- error: err.message
146
- }, agentId);
147
- }
148
- break;
149
- }
150
-
151
- case 'log': {
152
- // Agent is sending a log entry
153
- this._broadcast({
154
- type: 'agent:log',
155
- agentId,
156
- level: msg.level || 'info',
157
- message: msg.message,
158
- timestamp: msg.timestamp || new Date().toISOString()
159
- });
160
- this.audit.record('agent:log', {
161
- level: msg.level,
162
- message: msg.message
163
- }, agentId);
164
- break;
165
- }
166
-
167
- case 'status': {
168
- this._broadcast({
169
- type: 'agent:status',
170
- agentId,
171
- status: msg.status,
172
- details: msg.details || {}
173
- });
174
- break;
175
- }
176
-
177
- case 'tool:executed': {
178
- this.audit.record('tool:executed', {
179
- tool: msg.tool,
180
- args: msg.args,
181
- result: msg.result?.substring(0, 500)
182
- }, agentId);
183
- this._broadcast({
184
- type: 'agent:tool',
185
- agentId,
186
- tool: msg.tool,
187
- status: msg.status
188
- });
189
- break;
190
- }
191
-
192
- case 'chat:response': {
193
- // Agent response to a dashboard chat message
194
- this._broadcast({
195
- type: 'agent:chat',
196
- agentId,
197
- message: msg.message,
198
- requestId: msg.requestId
199
- });
200
- break;
201
- }
202
-
203
- case 'error': {
204
- console.error(` Agent ${agentId} error:`, msg.error);
205
- this._broadcast({ type: 'agent:error', agentId, error: msg.error });
206
- this.audit.record('agent:error', { error: msg.error }, agentId);
207
- break;
208
- }
209
-
210
- default:
211
- console.log(` Agent ${agentId} unknown message type: ${msg.type}`);
212
- }
213
- }
214
-
215
- /**
216
- * Send a chat message to an agent and wait for response.
217
- */
218
- async sendMessage(agentId, message) {
219
- const state = this.agents.get(agentId);
220
- if (!state) throw new Error(`Agent ${agentId} not connected`);
221
-
222
- const requestId = `req_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
223
-
224
- return new Promise((resolve, reject) => {
225
- const timeout = setTimeout(() => {
226
- state.pendingRequests.delete(requestId);
227
- reject(new Error('Agent response timeout'));
228
- }, 120_000);
229
-
230
- state.pendingRequests.set(requestId, { resolve, reject, timeout });
231
-
232
- this._send(state.ws, {
233
- type: 'chat',
234
- requestId,
235
- message
236
- });
237
-
238
- // Listen for response
239
- const handler = (data) => {
240
- try {
241
- const msg = JSON.parse(data.toString());
242
- if (msg.type === 'chat:response' && msg.requestId === requestId) {
243
- clearTimeout(timeout);
244
- state.pendingRequests.delete(requestId);
245
- state.ws.removeListener('message', handler);
246
- resolve(msg.message);
247
- }
248
- } catch { /* ignore parse errors */ }
249
- };
250
-
251
- state.ws.on('message', handler);
252
- });
253
- }
254
-
255
- /**
256
- * Broadcast a message to all dashboard clients.
257
- */
258
- _broadcast(msg) {
259
- const data = JSON.stringify(msg);
260
- for (const [ws] of this.clients) {
261
- if (ws.readyState === WebSocket.OPEN) {
262
- ws.send(data);
263
- }
264
- }
265
- }
266
-
267
- /**
268
- * Send a message to a specific WebSocket.
269
- */
270
- _send(ws, msg) {
271
- if (ws.readyState === WebSocket.OPEN) {
272
- ws.send(JSON.stringify(msg));
273
- }
274
- }
275
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/src/audit.js DELETED
@@ -1,70 +0,0 @@
1
- /**
2
- * Audit Log — tamper-evident record of all platform activity.
3
- *
4
- * Every key action, LLM call, and agent event is logged.
5
- * Entries are append-only with sequential IDs and timestamps.
6
- */
7
- import { getDB } from './db.js';
8
-
9
- export class AuditLog {
10
- constructor(db) {
11
- this.db = db || getDB();
12
- }
13
-
14
- /**
15
- * Record an audit event.
16
- */
17
- record(type, data = {}, agentId = null) {
18
- const stmt = this.db.prepare(
19
- 'INSERT INTO audit_log (type, data, agent_id) VALUES (?, ?, ?)'
20
- );
21
- stmt.run(type, JSON.stringify(data), agentId);
22
- }
23
-
24
- /**
25
- * Query audit entries with optional filters.
26
- */
27
- query({ type, agentId, limit = 100, offset = 0, from, to } = {}) {
28
- let sql = 'SELECT * FROM audit_log WHERE 1=1';
29
- const params = [];
30
-
31
- if (type) {
32
- sql += ' AND type = ?';
33
- params.push(type);
34
- }
35
- if (agentId) {
36
- sql += ' AND agent_id = ?';
37
- params.push(agentId);
38
- }
39
- if (from) {
40
- sql += ' AND timestamp >= ?';
41
- params.push(from);
42
- }
43
- if (to) {
44
- sql += ' AND timestamp <= ?';
45
- params.push(to);
46
- }
47
-
48
- sql += ' ORDER BY id DESC LIMIT ? OFFSET ?';
49
- params.push(limit, offset);
50
-
51
- const rows = this.db.prepare(sql).all(...params);
52
- return rows.map(r => ({
53
- id: r.id,
54
- timestamp: r.timestamp,
55
- type: r.type,
56
- data: JSON.parse(r.data || '{}'),
57
- agentId: r.agent_id
58
- }));
59
- }
60
-
61
- /**
62
- * Count total entries.
63
- */
64
- count(type = null) {
65
- if (type) {
66
- return this.db.prepare('SELECT COUNT(*) as c FROM audit_log WHERE type = ?').get(type).c;
67
- }
68
- return this.db.prepare('SELECT COUNT(*) as c FROM audit_log').get().c;
69
- }
70
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/src/containers.js DELETED
@@ -1,224 +0,0 @@
1
- /**
2
- * Container Manager — Docker-based agent isolation.
3
- *
4
- * Creates, starts, stops, and removes agent containers.
5
- * Each agent runs in its own Docker container with the agent runtime.
6
- */
7
- import crypto from 'node:crypto';
8
- import { getDB } from './db.js';
9
-
10
- // Try to load Dockerode; gracefully degrade if Docker isn't available
11
- let Docker = null;
12
- let dockerAvailable = false;
13
- try {
14
- const dockerModule = await import('dockerode');
15
- Docker = dockerModule.default;
16
- const docker = new Docker();
17
- await docker.ping();
18
- dockerAvailable = true;
19
- console.log(' Docker: connected');
20
- } catch (err) {
21
- console.log(` Docker: unavailable (${err.message?.split('\n')[0] || 'not running'}) — container management disabled`);
22
- console.log(' Starting in dev mode — agents will run as local processes');
23
- }
24
-
25
- const AGENT_IMAGE = process.env.AGENT_IMAGE || 'agent.mona.expert/agent:latest';
26
- const AGENT_PORT_START = parseInt(process.env.AGENT_PORT_START) || 4500;
27
-
28
- export class ContainerManager {
29
- constructor(db) {
30
- this.db = db || getDB();
31
- this.docker = dockerAvailable ? new Docker() : null;
32
- this.nextPort = AGENT_PORT_START;
33
- }
34
-
35
- /**
36
- * List all agents.
37
- */
38
- async list() {
39
- const rows = this.db.prepare('SELECT * FROM agents ORDER BY created DESC').all();
40
-
41
- if (this.docker) {
42
- // Enrich with live Docker status
43
- for (const row of rows) {
44
- if (row.container_id) {
45
- try {
46
- const container = this.docker.getContainer(row.container_id);
47
- const info = await container.inspect();
48
- row.status = info.State?.Running ? 'running' : info.State?.Status || 'unknown';
49
- } catch {
50
- row.status = 'removed';
51
- }
52
- }
53
- }
54
- }
55
-
56
- return rows.map(r => ({
57
- id: r.id,
58
- name: r.name,
59
- model: r.model,
60
- systemPrompt: r.system_prompt,
61
- tools: JSON.parse(r.tools || '[]'),
62
- status: r.status,
63
- created: r.created,
64
- lastActive: r.last_active
65
- }));
66
- }
67
-
68
- /**
69
- * Create a new agent (builds config, creates container).
70
- */
71
- async create({ name, model, systemPrompt, tools }) {
72
- const id = `agent_${crypto.randomUUID().slice(0, 8)}`;
73
- const port = this.nextPort++;
74
-
75
- this.db.prepare(
76
- `INSERT INTO agents (id, name, model, system_prompt, tools, status, port)
77
- VALUES (?, ?, ?, ?, ?, 'creating', ?)`
78
- ).run(id, name, model, systemPrompt || '', JSON.stringify(tools || []), port);
79
-
80
- if (this.docker) {
81
- try {
82
- // Pull image if needed
83
- await this.docker.pull(AGENT_IMAGE).catch(() => {
84
- // Image might not exist yet; try building
85
- console.log(` Image ${AGENT_IMAGE} not found, attempting to use locally...`);
86
- });
87
-
88
- const container = await this.docker.createContainer({
89
- name: `mona-agent-${id}`,
90
- Image: AGENT_IMAGE,
91
- Env: [
92
- `AGENT_ID=${id}`,
93
- `AGENT_NAME=${name}`,
94
- `AGENT_MODEL=${model}`,
95
- `PLATFORM_URL=http://host.docker.internal:${process.env.PORT || 4300}/ws`,
96
- `AGENT_TOOLS=${JSON.stringify(tools)}`,
97
- `AGENT_SYSTEM_PROMPT=${systemPrompt || ''}`
98
- ],
99
- ExposedPorts: { [`${port}/tcp`]: {} },
100
- HostConfig: {
101
- PortBindings: { [`${port}/tcp`]: [{ HostPort: `${port}` }] },
102
- Memory: 512 * 1024 * 1024, // 512MB
103
- NanoCpus: 1_000_000_000, // 1 CPU
104
- ReadonlyRootfs: false,
105
- SecurityOpt: ['no-new-privileges:true'],
106
- CapDrop: ['ALL'],
107
- CapAdd: ['CHOWN', 'DAC_OVERRIDE', 'SETGID', 'SETUID']
108
- }
109
- });
110
-
111
- this.db.prepare('UPDATE agents SET container_id = ?, status = ? WHERE id = ?')
112
- .run(container.id, 'stopped', id);
113
-
114
- console.log(` Agent container created: ${id} (${name})`);
115
- } catch (err) {
116
- this.db.prepare('UPDATE agents SET status = ? WHERE id = ?').run('error', id);
117
- throw new Error(`Docker create failed: ${err.message}`);
118
- }
119
- } else {
120
- // Dev mode: no Docker, just record
121
- this.db.prepare('UPDATE agents SET status = ? WHERE id = ?').run('stopped', id);
122
- console.log(` Agent created (dev mode): ${id} (${name})`);
123
- }
124
-
125
- return { id, name, model, status: 'stopped', tools, port };
126
- }
127
-
128
- /**
129
- * Start an agent container.
130
- */
131
- async start(agentId) {
132
- const agent = this.db.prepare('SELECT * FROM agents WHERE id = ?').get(agentId);
133
- if (!agent) throw new Error(`Agent ${agentId} not found`);
134
-
135
- if (this.docker && agent.container_id) {
136
- const container = this.docker.getContainer(agent.container_id);
137
- await container.start();
138
- }
139
-
140
- this.db.prepare('UPDATE agents SET status = ?, last_active = datetime("now") WHERE id = ?')
141
- .run('running', agentId);
142
- return { ok: true, status: 'running' };
143
- }
144
-
145
- /**
146
- * Stop an agent container.
147
- */
148
- async stop(agentId) {
149
- const agent = this.db.prepare('SELECT * FROM agents WHERE id = ?').get(agentId);
150
- if (!agent) throw new Error(`Agent ${agentId} not found`);
151
-
152
- if (this.docker && agent.container_id) {
153
- try {
154
- const container = this.docker.getContainer(agent.container_id);
155
- await container.stop();
156
- } catch { /* container already stopped */ }
157
- }
158
-
159
- this.db.prepare('UPDATE agents SET status = ? WHERE id = ?').run('stopped', agentId);
160
- return { ok: true, status: 'stopped' };
161
- }
162
-
163
- /**
164
- * Remove an agent and its container.
165
- */
166
- async remove(agentId) {
167
- const agent = this.db.prepare('SELECT * FROM agents WHERE id = ?').get(agentId);
168
- if (!agent) throw new Error(`Agent ${agentId} not found`);
169
-
170
- if (this.docker && agent.container_id) {
171
- try {
172
- const container = this.docker.getContainer(agent.container_id);
173
- await container.stop().catch(() => {});
174
- await container.remove({ force: true });
175
- } catch { /* already removed */ }
176
- }
177
-
178
- this.db.prepare('DELETE FROM agents WHERE id = ?').run(agentId);
179
- return { ok: true };
180
- }
181
-
182
- /**
183
- * Get container logs.
184
- */
185
- async logs(agentId, tail = 200) {
186
- const agent = this.db.prepare('SELECT * FROM agents WHERE id = ?').get(agentId);
187
- if (!agent || !agent.container_id) return '';
188
-
189
- if (this.docker) {
190
- try {
191
- const container = this.docker.getContainer(agent.container_id);
192
- const stream = await container.logs({
193
- stdout: true, stderr: true, tail, timestamps: true
194
- });
195
- return stream.toString('utf8');
196
- } catch {
197
- return '';
198
- }
199
- }
200
-
201
- return '';
202
- }
203
-
204
- /**
205
- * Docker system info.
206
- */
207
- async systemInfo() {
208
- if (!this.docker) return { available: false };
209
-
210
- try {
211
- const info = await this.docker.info();
212
- return {
213
- available: true,
214
- containers: info.Containers,
215
- running: info.ContainersRunning,
216
- memory: info.MemTotal,
217
- cpus: info.NCPU,
218
- os: info.OperatingSystem
219
- };
220
- } catch {
221
- return { available: false };
222
- }
223
- }
224
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/src/db.js DELETED
@@ -1,167 +0,0 @@
1
- /**
2
- * SQLite database layer for agent.mona.expert platform.
3
- * Uses sql.js (WebAssembly) — no native compilation needed.
4
- * Stores API keys, agent configs, and audit logs.
5
- */
6
- import fs from 'node:fs';
7
- import path from 'node:path';
8
- import initSqlJs from 'sql.js';
9
-
10
- let _db = null;
11
- let _dbPath = null;
12
-
13
- /**
14
- * Minimal sync-like wrapper around sql.js async.
15
- * SQL.js runs in WASM so we keep everything in memory and
16
- * periodically flush to disk.
17
- */
18
- class SQLiteDB {
19
- constructor(sqlDb, dbPath) {
20
- this.sqlDb = sqlDb;
21
- this.dbPath = dbPath;
22
- }
23
-
24
- exec(sql) {
25
- this.sqlDb.exec(sql);
26
- }
27
-
28
- prepare(sql) {
29
- return {
30
- run: (...params) => {
31
- this.sqlDb.run(sql, params);
32
- return { changes: this.sqlDb.getRowsModified() };
33
- },
34
- get: (...params) => {
35
- const stmt = this.sqlDb.prepare(sql);
36
- try {
37
- stmt.bind(params);
38
- if (stmt.step()) {
39
- const cols = stmt.getColumnNames();
40
- const vals = stmt.get();
41
- const row = {};
42
- cols.forEach((c, i) => row[c] = vals[i]);
43
- stmt.free();
44
- return row;
45
- }
46
- stmt.free();
47
- return null;
48
- } catch (e) {
49
- stmt.free();
50
- throw e;
51
- }
52
- },
53
- all: (...params) => {
54
- const stmt = this.sqlDb.prepare(sql);
55
- try {
56
- stmt.bind(params);
57
- const rows = [];
58
- const cols = stmt.getColumnNames();
59
- while (stmt.step()) {
60
- const vals = stmt.get();
61
- const row = {};
62
- cols.forEach((c, i) => row[c] = vals[i]);
63
- rows.push(row);
64
- }
65
- stmt.free();
66
- return rows;
67
- } catch (e) {
68
- stmt.free();
69
- throw e;
70
- }
71
- }
72
- };
73
- }
74
-
75
- pragma(pragma) {
76
- // sql.js doesn't support PRAGMA, silently skip
77
- }
78
-
79
- save() {
80
- const data = this.sqlDb.export();
81
- const buffer = Buffer.from(data);
82
- fs.writeFileSync(this.dbPath, buffer);
83
- }
84
- }
85
-
86
- export async function initDB(dataDir) {
87
- fs.mkdirSync(dataDir, { recursive: true });
88
- _dbPath = path.join(dataDir, 'platform.db');
89
-
90
- const SQL = await initSqlJs();
91
-
92
- // Try to load existing database
93
- let sqlDb;
94
- if (fs.existsSync(_dbPath)) {
95
- const buffer = fs.readFileSync(_dbPath);
96
- sqlDb = new SQL.Database(buffer);
97
- } else {
98
- sqlDb = new SQL.Database();
99
- }
100
-
101
- const db = new SQLiteDB(sqlDb, _dbPath);
102
-
103
- // Schema
104
- db.exec(`
105
- CREATE TABLE IF NOT EXISTS api_keys (
106
- id TEXT PRIMARY KEY,
107
- provider TEXT NOT NULL,
108
- label TEXT,
109
- key_encrypted TEXT NOT NULL,
110
- created TEXT DEFAULT (datetime('now')),
111
- last_used TEXT
112
- );
113
-
114
- CREATE TABLE IF NOT EXISTS agents (
115
- id TEXT PRIMARY KEY,
116
- name TEXT NOT NULL,
117
- model TEXT DEFAULT 'openai/gpt-4o',
118
- system_prompt TEXT DEFAULT '',
119
- tools TEXT DEFAULT '["files","web","shell"]',
120
- container_id TEXT,
121
- status TEXT DEFAULT 'stopped',
122
- port INTEGER,
123
- created TEXT DEFAULT (datetime('now')),
124
- last_active TEXT
125
- );
126
-
127
- CREATE TABLE IF NOT EXISTS audit_log (
128
- id INTEGER PRIMARY KEY AUTOINCREMENT,
129
- timestamp TEXT DEFAULT (datetime('now')),
130
- type TEXT NOT NULL,
131
- data TEXT,
132
- agent_id TEXT
133
- );
134
- `);
135
-
136
- // Create indexes (silently fail if they already exist)
137
- try { db.exec('CREATE INDEX IF NOT EXISTS idx_audit_type ON audit_log(type)'); } catch {}
138
- try { db.exec('CREATE INDEX IF NOT EXISTS idx_audit_agent ON audit_log(agent_id)'); } catch {}
139
- try { db.exec('CREATE INDEX IF NOT EXISTS idx_audit_ts ON audit_log(timestamp)'); } catch {}
140
-
141
- db.save();
142
-
143
- console.log(` DB: ${_dbPath}`);
144
- _db = db;
145
- return _db;
146
- }
147
-
148
- export function getDB() {
149
- if (!_db) throw new Error('DB not initialized. Call initDB() first.');
150
- return _db;
151
- }
152
-
153
- // Periodic auto-save
154
- let saveInterval = null;
155
- export function startAutoSave(ms = 30_000) {
156
- if (saveInterval) return;
157
- saveInterval = setInterval(() => {
158
- if (_db) _db.save();
159
- }, ms);
160
- }
161
-
162
- export function stopAutoSave() {
163
- if (saveInterval) {
164
- clearInterval(saveInterval);
165
- saveInterval = null;
166
- }
167
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/src/llm-proxy.js DELETED
@@ -1,203 +0,0 @@
1
- /**
2
- * LLM Proxy — routes LLM calls through the platform.
3
- *
4
- * The platform holds API keys; agents request completions through
5
- * WebSocket and the platform proxies to provider APIs.
6
- *
7
- * Supported providers: OpenAI, Anthropic, Google, DeepSeek, OpenRouter
8
- */
9
- import fetch from 'node-fetch';
10
-
11
- const PROVIDERS = {
12
- openai: {
13
- base: 'https://api.openai.com/v1',
14
- path: '/chat/completions',
15
- authHeader: (key) => `Bearer ${key}`,
16
- bodyFormat: (req) => ({
17
- model: req.model?.replace('openai/', '') || 'gpt-4o',
18
- messages: req.messages,
19
- temperature: req.temperature ?? 0.7,
20
- max_tokens: req.maxTokens ?? 4096
21
- }),
22
- parseResponse: (data) => ({
23
- content: data.choices?.[0]?.message?.content || '',
24
- usage: {
25
- prompt: data.usage?.prompt_tokens || 0,
26
- completion: data.usage?.completion_tokens || 0,
27
- total: data.usage?.total_tokens || 0
28
- },
29
- model: data.model,
30
- finishReason: data.choices?.[0]?.finish_reason
31
- })
32
- },
33
-
34
- anthropic: {
35
- base: 'https://api.anthropic.com/v1',
36
- path: '/messages',
37
- authHeader: (key) => key,
38
- headers: { 'anthropic-version': '2023-06-01', 'x-api-key': null }, // set dynamically
39
- bodyFormat: (req) => {
40
- // Convert OpenAI-style messages to Anthropic format
41
- const systemMsg = req.messages.find(m => m.role === 'system');
42
- const messages = req.messages
43
- .filter(m => m.role !== 'system')
44
- .map(m => ({ role: m.role === 'assistant' ? 'assistant' : 'user', content: m.content }));
45
- return {
46
- model: req.model?.replace('anthropic/', '') || 'claude-sonnet-4-20250514',
47
- max_tokens: req.maxTokens ?? 4096,
48
- system: systemMsg?.content || '',
49
- messages
50
- };
51
- },
52
- authHeaderFn: (key) => ({ 'x-api-key': key, 'anthropic-version': '2023-06-01' }),
53
- parseResponse: (data) => ({
54
- content: data.content?.[0]?.text || '',
55
- usage: {
56
- prompt: data.usage?.input_tokens || 0,
57
- completion: data.usage?.output_tokens || 0,
58
- total: (data.usage?.input_tokens || 0) + (data.usage?.output_tokens || 0)
59
- },
60
- model: data.model,
61
- finishReason: data.stop_reason
62
- })
63
- },
64
-
65
- google: {
66
- base: 'https://generativelanguage.googleapis.com/v1beta',
67
- pathFn: (req) => `/models/${req.model?.replace('google/', '') || 'gemini-2.5-flash'}:generateContent`,
68
- authParam: (key) => `key=${key}`,
69
- bodyFormat: (req) => {
70
- const systemMsg = req.messages.find(m => m.role === 'system');
71
- const contents = req.messages
72
- .filter(m => m.role !== 'system')
73
- .map(m => ({ role: m.role === 'assistant' ? 'model' : 'user', parts: [{ text: m.content }] }));
74
- return {
75
- system_instruction: systemMsg ? { parts: [{ text: systemMsg.content }] } : undefined,
76
- contents,
77
- generationConfig: {
78
- temperature: req.temperature ?? 0.7,
79
- maxOutputTokens: req.maxTokens ?? 4096
80
- }
81
- };
82
- },
83
- parseResponse: (data) => ({
84
- content: data.candidates?.[0]?.content?.parts?.[0]?.text || '',
85
- usage: {
86
- prompt: data.usageMetadata?.promptTokenCount || 0,
87
- completion: data.usageMetadata?.candidatesTokenCount || 0,
88
- total: data.usageMetadata?.totalTokenCount || 0
89
- },
90
- model: data.modelVersion,
91
- finishReason: data.candidates?.[0]?.finishReason
92
- })
93
- },
94
-
95
- deepseek: {
96
- base: 'https://api.deepseek.com/v1',
97
- path: '/chat/completions',
98
- authHeader: (key) => `Bearer ${key}`,
99
- bodyFormat: (req) => ({
100
- model: req.model?.replace('deepseek/', '') || 'deepseek-chat',
101
- messages: req.messages,
102
- temperature: req.temperature ?? 0.7,
103
- max_tokens: req.maxTokens ?? 4096
104
- }),
105
- parseResponse: (data) => ({
106
- content: data.choices?.[0]?.message?.content || '',
107
- usage: {
108
- prompt: data.usage?.prompt_tokens || 0,
109
- completion: data.usage?.completion_tokens || 0,
110
- total: data.usage?.total_tokens || 0
111
- },
112
- model: data.model,
113
- finishReason: data.choices?.[0]?.finish_reason
114
- })
115
- },
116
-
117
- openrouter: {
118
- base: 'https://openrouter.ai/api/v1',
119
- path: '/chat/completions',
120
- authHeader: (key) => `Bearer ${key}`,
121
- bodyFormat: (req) => ({
122
- model: req.model?.replace('openrouter/', '') || 'openai/gpt-4o',
123
- messages: req.messages,
124
- temperature: req.temperature ?? 0.7,
125
- max_tokens: req.maxTokens ?? 4096
126
- }),
127
- parseResponse: (data) => ({
128
- content: data.choices?.[0]?.message?.content || '',
129
- usage: {
130
- prompt: data.usage?.prompt_tokens || 0,
131
- completion: data.usage?.completion_tokens || 0,
132
- total: data.usage?.total_tokens || 0
133
- },
134
- model: data.model,
135
- finishReason: data.choices?.[0]?.finish_reason
136
- })
137
- }
138
- };
139
-
140
- export class LLMProxy {
141
- /**
142
- * Make an LLM API call through the platform.
143
- */
144
- static async call(vault, { provider, model, messages, temperature, maxTokens, keyId }) {
145
- // The platform decides the provider — devices never name one.
146
- if (!provider) {
147
- if (model && model.includes('/')) {
148
- const parts = model.split('/');
149
- provider = parts[0];
150
- model = parts.slice(1).join('/');
151
- } else {
152
- provider = 'openai'; // default
153
- }
154
- }
155
-
156
- const providerConfig = PROVIDERS[provider?.toLowerCase()];
157
- if (!providerConfig) {
158
- throw new Error(`Unsupported provider: ${provider}. Available: ${Object.keys(PROVIDERS).join(', ')}`);
159
- }
160
-
161
- // Get API key from vault
162
- let keyEntry;
163
- if (keyId) {
164
- keyEntry = vault.get(keyId);
165
- } else {
166
- keyEntry = vault.getForProvider(provider);
167
- }
168
-
169
- if (!keyEntry) {
170
- throw new Error(`No API key found for provider "${provider}". Add one in Settings → API Keys.`);
171
- }
172
-
173
- const url = providerConfig.pathFn
174
- ? `${providerConfig.base}${providerConfig.pathFn({ model })}${providerConfig.authParam ? `?${providerConfig.authParam(keyEntry.key)}` : ''}`
175
- : `${providerConfig.base}${providerConfig.path}`;
176
-
177
- const body = providerConfig.bodyFormat({ model, messages, temperature, maxTokens });
178
-
179
- const headers = {
180
- 'Content-Type': 'application/json',
181
- ...(providerConfig.authHeaderFn
182
- ? providerConfig.authHeaderFn(keyEntry.key)
183
- : { 'Authorization': providerConfig.authHeader(keyEntry.key) }),
184
- ...(providerConfig.headers || {})
185
- };
186
-
187
- const response = await fetch(url, {
188
- method: 'POST',
189
- headers,
190
- body: JSON.stringify(body),
191
- signal: AbortSignal.timeout(120_000) // 2 min timeout
192
- });
193
-
194
- const data = await response.json();
195
-
196
- if (!response.ok) {
197
- const errMsg = data.error?.message || data.error?.code || `HTTP ${response.status}`;
198
- throw new Error(`${provider} API error: ${errMsg}`);
199
- }
200
-
201
- return providerConfig.parseResponse(data);
202
- }
203
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/src/server.js DELETED
@@ -1,196 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * agent.mona.expert — Platform Control Plane
4
- *
5
- * Manages Docker containers, API keys, LLM proxying, audit logging,
6
- * and serves the web dashboard. Agents connect via WebSocket.
7
- */
8
-
9
- import http from 'node:http';
10
- import path from 'node:path';
11
- import { fileURLToPath } from 'node:url';
12
- import express from 'express';
13
- import cors from 'cors';
14
- import { WebSocketServer } from 'ws';
15
-
16
- import { initDB, startAutoSave } from './db.js';
17
- import { Vault } from './vault.js';
18
- import { ContainerManager } from './containers.js';
19
- import { LLMProxy } from './llm-proxy.js';
20
- import { AuditLog } from './audit.js';
21
- import { AgentConnection } from './agent-connection.js';
22
-
23
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
24
- const PORT = process.env.PORT || 4300;
25
- const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, '..', 'data');
26
-
27
- // ── Init ──────────────────────────────────────────────────────────
28
- const app = express();
29
- const server = http.createServer(app);
30
- const wss = new WebSocketServer({ server, path: '/ws' });
31
-
32
- app.use(cors());
33
- app.use(express.json({ limit: '10mb' }));
34
-
35
- // Static dashboard
36
- app.use('/dashboard', express.static(path.join(__dirname, '..', 'dashboard')));
37
- app.use(express.static(path.join(__dirname, '..', 'dashboard')));
38
-
39
- // Init subsystems
40
- const db = await initDB(DATA_DIR);
41
- startAutoSave(30_000); // Auto-save every 30s
42
- const vault = new Vault(db);
43
- const containers = new ContainerManager(db);
44
- const audit = new AuditLog(db);
45
- const agentConn = new AgentConnection(wss, { vault, containers, audit });
46
-
47
- // ── REST API ──────────────────────────────────────────────────────
48
-
49
- // Health
50
- app.get('/health', (_req, res) => res.json({ status: 'ok', uptime: process.uptime() }));
51
-
52
- // ── API Keys ──────────────────────────────────────────────────────
53
- app.get('/api/keys', (_req, res) => {
54
- const keys = vault.list().map(k => ({ id: k.id, provider: k.provider, label: k.label, masked: k.masked, created: k.created }));
55
- res.json(keys);
56
- });
57
-
58
- app.post('/api/keys', (req, res) => {
59
- const { provider, label, key } = req.body;
60
- if (!provider || !key) return res.status(400).json({ error: 'provider and key required' });
61
- const id = vault.add(provider, label || `${provider}-key`, key);
62
- audit.record('key:create', { provider, label, id });
63
- res.json({ id });
64
- });
65
-
66
- app.delete('/api/keys/:id', (req, res) => {
67
- const ok = vault.remove(req.params.id);
68
- if (!ok) return res.status(404).json({ error: 'key not found' });
69
- audit.record('key:delete', { id: req.params.id });
70
- res.json({ ok: true });
71
- });
72
-
73
- // ── Agents (Container Management) ─────────────────────────────────
74
- app.get('/api/agents', async (_req, res) => {
75
- const agents = await containers.list();
76
- res.json(agents);
77
- });
78
-
79
- app.post('/api/agents', async (req, res) => {
80
- const { name, model, systemPrompt, tools } = req.body;
81
- if (!name) return res.status(400).json({ error: 'name required' });
82
- try {
83
- const agent = await containers.create({ name, model: model || 'openai/gpt-4o', systemPrompt, tools: tools || ['files', 'web', 'shell'] });
84
- audit.record('agent:create', { name, id: agent.id });
85
- res.json(agent);
86
- } catch (err) {
87
- res.status(500).json({ error: err.message });
88
- }
89
- });
90
-
91
- app.post('/api/agents/:id/start', async (req, res) => {
92
- try {
93
- await containers.start(req.params.id);
94
- audit.record('agent:start', { id: req.params.id });
95
- res.json({ ok: true });
96
- } catch (err) {
97
- res.status(500).json({ error: err.message });
98
- }
99
- });
100
-
101
- app.post('/api/agents/:id/stop', async (req, res) => {
102
- try {
103
- await containers.stop(req.params.id);
104
- audit.record('agent:stop', { id: req.params.id });
105
- res.json({ ok: true });
106
- } catch (err) {
107
- res.status(500).json({ error: err.message });
108
- }
109
- });
110
-
111
- app.delete('/api/agents/:id', async (req, res) => {
112
- try {
113
- await containers.remove(req.params.id);
114
- audit.record('agent:delete', { id: req.params.id });
115
- res.json({ ok: true });
116
- } catch (err) {
117
- res.status(500).json({ error: err.message });
118
- }
119
- });
120
-
121
- app.get('/api/agents/:id/logs', async (req, res) => {
122
- try {
123
- const logs = await containers.logs(req.params.id, parseInt(req.query.tail) || 200);
124
- res.json({ logs });
125
- } catch (err) {
126
- res.status(500).json({ error: err.message });
127
- }
128
- });
129
-
130
- // ── Chat with agent ───────────────────────────────────────────────
131
- app.post('/api/agents/:id/chat', async (req, res) => {
132
- const { message } = req.body;
133
- if (!message) return res.status(400).json({ error: 'message required' });
134
-
135
- try {
136
- // Send message to agent via WebSocket, get response
137
- const reply = await agentConn.sendMessage(req.params.id, message);
138
- res.json({ reply });
139
- } catch (err) {
140
- res.status(500).json({ error: err.message });
141
- }
142
- });
143
-
144
- // ── LLM Proxy (direct, no agent) ──────────────────────────────────
145
- app.post('/api/llm', async (req, res) => {
146
- const { provider, model, messages, temperature, maxTokens, keyId } = req.body;
147
- if (!provider || !messages) return res.status(400).json({ error: 'provider and messages required' });
148
-
149
- try {
150
- const result = await LLMProxy.call(vault, { provider, model, messages, temperature, maxTokens, keyId });
151
- audit.record('llm:call', { provider, model, messageCount: messages.length, tokenUsage: result.usage });
152
- res.json(result);
153
- } catch (err) {
154
- audit.record('llm:error', { provider, model, error: err.message });
155
- res.status(500).json({ error: err.message });
156
- }
157
- });
158
-
159
- // ── Audit ─────────────────────────────────────────────────────────
160
- app.get('/api/audit', (req, res) => {
161
- const { type, limit, offset } = req.query;
162
- const entries = audit.query({ type, limit: parseInt(limit) || 100, offset: parseInt(offset) || 0 });
163
- res.json(entries);
164
- });
165
-
166
- // ── System info ───────────────────────────────────────────────────
167
- app.get('/api/system', async (_req, res) => {
168
- try {
169
- const info = await containers.systemInfo();
170
- const agents = await containers.list();
171
- res.json({
172
- docker: info,
173
- agentsRunning: agents.filter(a => a.status === 'running').length,
174
- agentsTotal: agents.length,
175
- keysStored: vault.list().length,
176
- uptime: process.uptime()
177
- });
178
- } catch (err) {
179
- res.json({ error: err.message, docker: false });
180
- }
181
- });
182
-
183
- // ── Start ─────────────────────────────────────────────────────────
184
- server.listen(PORT, () => {
185
- console.log(`🧠 agent.mona.expert platform → http://localhost:${PORT}`);
186
- console.log(` Dashboard: http://localhost:${PORT}/dashboard`);
187
- console.log(` WebSocket: ws://localhost:${PORT}/ws`);
188
- });
189
-
190
- // Graceful shutdown
191
- process.on('SIGINT', async () => {
192
- console.log('\nShutting down...');
193
- wss.close();
194
- server.close();
195
- process.exit(0);
196
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
platform/src/vault.js DELETED
@@ -1,122 +0,0 @@
1
- /**
2
- * API Key Vault — secure storage for LLM provider keys.
3
- *
4
- * Keys are encrypted at rest (AES-256-GCM) using a platform secret.
5
- * The agent never sees keys; the platform proxies all LLM calls.
6
- */
7
- import crypto from 'node:crypto';
8
- import { getDB } from './db.js';
9
-
10
- const ALGORITHM = 'aes-256-gcm';
11
- const SECRET = process.env.VAULT_SECRET || crypto.randomBytes(32).toString('hex');
12
-
13
- function deriveKey() {
14
- return crypto.scryptSync(SECRET, 'agent.mona.expert', 32);
15
- }
16
-
17
- function encrypt(plaintext) {
18
- const key = deriveKey();
19
- const iv = crypto.randomBytes(16);
20
- const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
21
- const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
22
- const tag = cipher.getAuthTag();
23
- return JSON.stringify({
24
- iv: iv.toString('hex'),
25
- data: encrypted.toString('hex'),
26
- tag: tag.toString('hex')
27
- });
28
- }
29
-
30
- function decrypt(encryptedJSON) {
31
- try {
32
- const { iv, data, tag } = JSON.parse(encryptedJSON);
33
- const key = deriveKey();
34
- const decipher = crypto.createDecipheriv(ALGORITHM, key, Buffer.from(iv, 'hex'));
35
- decipher.setAuthTag(Buffer.from(tag, 'hex'));
36
- return decipher.update(data, 'hex', 'utf8') + decipher.final('utf8');
37
- } catch {
38
- return null;
39
- }
40
- }
41
-
42
- export class Vault {
43
- constructor(db) {
44
- this.db = db || getDB();
45
- }
46
-
47
- /**
48
- * Add an API key to the vault.
49
- */
50
- add(provider, label, key) {
51
- const id = `key_${crypto.randomUUID().slice(0, 12)}`;
52
- const encrypted = encrypt(key);
53
- this.db.prepare(
54
- 'INSERT INTO api_keys (id, provider, label, key_encrypted) VALUES (?, ?, ?, ?)'
55
- ).run(id, provider, label, encrypted);
56
- return id;
57
- }
58
-
59
- /**
60
- * Get the decrypted key for a provider.
61
- * Returns the first matching key if keyId is not specified.
62
- */
63
- get(keyId) {
64
- const row = keyId
65
- ? this.db.prepare('SELECT * FROM api_keys WHERE id = ?').get(keyId)
66
- : this.db.prepare('SELECT * FROM api_keys ORDER BY created DESC LIMIT 1').get();
67
-
68
- if (!row) return null;
69
-
70
- const key = decrypt(row.key_encrypted);
71
- if (!key) return null;
72
-
73
- // Update last_used
74
- this.db.prepare('UPDATE api_keys SET last_used = datetime("now") WHERE id = ?').run(row.id);
75
-
76
- return { id: row.id, provider: row.provider, label: row.label, key };
77
- }
78
-
79
- /**
80
- * Get a key specifically for a provider.
81
- */
82
- getForProvider(provider) {
83
- const row = this.db.prepare(
84
- 'SELECT * FROM api_keys WHERE provider = ? ORDER BY created DESC LIMIT 1'
85
- ).get(provider);
86
- if (!row) return null;
87
- const key = decrypt(row.key_encrypted);
88
- if (!key) return null;
89
- this.db.prepare('UPDATE api_keys SET last_used = datetime("now") WHERE id = ?').run(row.id);
90
- return { id: row.id, provider: row.provider, label: row.label, key };
91
- }
92
-
93
- /**
94
- * List all keys (without the actual key values).
95
- */
96
- list() {
97
- const rows = this.db.prepare('SELECT id, provider, label, key_encrypted, created, last_used FROM api_keys ORDER BY created DESC').all();
98
- return rows.map(r => ({
99
- id: r.id,
100
- provider: r.provider,
101
- label: r.label,
102
- masked: '••••' + (r.label || '').slice(-4),
103
- created: r.created,
104
- lastUsed: r.last_used
105
- }));
106
- }
107
-
108
- /**
109
- * Remove a key from the vault.
110
- */
111
- remove(id) {
112
- const result = this.db.prepare('DELETE FROM api_keys WHERE id = ?').run(id);
113
- return result.changes > 0;
114
- }
115
-
116
- /**
117
- * Count stored keys.
118
- */
119
- count() {
120
- return this.db.prepare('SELECT COUNT(*) as c FROM api_keys').get().c;
121
- }
122
- }