mirror of
https://github.com/R0m1k3/EveFlow.git
synced 2026-10-11 17:29:03 +02:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fc38d335b |
No files matched your search
@@ -1,7 +1,7 @@
|
|||||||
# EveFlow 2 — Interface vocale JARVIS pour Hermes Agent
|
# EveFlow 2 — Interface vocale JARVIS pour Hermes Agent
|
||||||
|
|
||||||
[](https://github.com/R0m1k3/EveFlow/actions)
|
[](https://github.com/R0m1k3/EveFlow/actions)
|
||||||
[](https://github.com/R0m1k3/EveFlow/releases)
|
[](https://github.com/R0m1k3/EveFlow/releases)
|
||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
|
|
||||||
**EveFlow** est un compagnon de bureau Windows qui transforme [Hermes Agent](https://hermes-agent.nousresearch.com/) en assistant vocal à la JARVIS : un noyau holographique réactif au son, une conversation en streaming, les outils, sous-agents, approbations, crons, skills et sessions d'Hermes pilotés depuis un seul HUD.
|
**EveFlow** est un compagnon de bureau Windows qui transforme [Hermes Agent](https://hermes-agent.nousresearch.com/) en assistant vocal à la JARVIS : un noyau holographique réactif au son, une conversation en streaming, les outils, sous-agents, approbations, crons, skills et sessions d'Hermes pilotés depuis un seul HUD.
|
||||||
@@ -26,6 +26,11 @@ La version 2 est une réécriture complète : plus de robot 3D, un pipeline voca
|
|||||||
* **Fin de phrase neuronale** : en écoute permanente, Silero VAD (0,6 Mo, sherpa-onnx) décide du début et de la fin de la commande à la place du seuil d'énergie ; moins de faux départs sur le bruit, coupure plus nette. Repli automatique sur le VAD énergétique si le modèle n'est pas installé.
|
* **Fin de phrase neuronale** : en écoute permanente, Silero VAD (0,6 Mo, sherpa-onnx) décide du début et de la fin de la commande à la place du seuil d'énergie ; moins de faux départs sur le bruit, coupure plus nette. Repli automatique sur le VAD énergétique si le modèle n'est pas installé.
|
||||||
* **Vision d'écran** : « Jarvis, regarde mon écran » (ou le bouton de la barre de commande) joint une capture de l'écran principal à la question envoyée à Hermes.
|
* **Vision d'écran** : « Jarvis, regarde mon écran » (ou le bouton de la barre de commande) joint une capture de l'écran principal à la question envoyée à Hermes.
|
||||||
* **Actions locales instantanées** : « verrouille la session », « monte le son », « coupe le son », « piste suivante », « ouvre Spotify », « ouvre github.com »… exécutées sur le PC sans passer par Hermes, résultat lu à voix haute. Liste blanche d'actions dans le processus principal, désactivable dans les paramètres.
|
* **Actions locales instantanées** : « verrouille la session », « monte le son », « coupe le son », « piste suivante », « ouvre Spotify », « ouvre github.com »… exécutées sur le PC sans passer par Hermes, résultat lu à voix haute. Liste blanche d'actions dans le processus principal, désactivable dans les paramètres.
|
||||||
|
* **Serveur MCP intégré** : Hermes se connecte à `http://<pc>:7842/mcp` et obtient les outils du PC (capture d'écran renvoyée en image, verrouillage, applications, URL, touches média, presse-papiers, recherche de fichiers, voix, notifications, état du HUD, affichage dans le fil). Même port et même secret que le webhook ; en mode chat completions, les mêmes outils sont proposés directement au modèle.
|
||||||
|
* **Heures calmes et priorités** : plage horaire pendant laquelle les messages poussés s'affichent sans être lus ni faire clignoter le noyau (badge « non lus » à la place), thème nuit automatique, mots prioritaires lus quand même, résumé vocal des rapports longs (les premières phrases seulement).
|
||||||
|
* **Mode mission** : un bouton dans la barre de commande bascule sur un second modèle Hermes (plus puissant) pour les tâches longues ; le modèle rapide reste utilisé pour la conversation courante.
|
||||||
|
* **Widget compact « glanceable »** : état (veille, écoute, réflexion, parle), dernière phrase de l'assistant, badge de non-lus, indicateurs heures calmes et mission.
|
||||||
|
* **Barge-in** : en mains libres, parler par-dessus l'assistant coupe sa voix ; le seuil est relevé pendant qu'il parle pour ignorer l'écho du haut-parleur.
|
||||||
* **Écoute permanente** : un détecteur de mot-clé de 3 Mo (sherpa-onnx, keyword spotting) tourne en continu sur le micro, quasi gratuit en CPU. « Jarvis » (ou n'importe quel mot-clé) ouvre l'écoute, « Jarvis, allume… » envoie directement la commande, et le mot coupe la voix en cours. Alternative : filtre du mot après transcription en mains libres.
|
* **Écoute permanente** : un détecteur de mot-clé de 3 Mo (sherpa-onnx, keyword spotting) tourne en continu sur le micro, quasi gratuit en CPU. « Jarvis » (ou n'importe quel mot-clé) ouvre l'écoute, « Jarvis, allume… » envoie directement la commande, et le mot coupe la voix en cours. Alternative : filtre du mot après transcription en mains libres.
|
||||||
* **STT externe** : n'importe quelle API `/v1/audio/transcriptions` compatible OpenAI (Qwen3-ASR, Whisper, Speaches, faster-whisper-server, LocalAI, OpenAI). Repli sur la reconnaissance Chromium.
|
* **STT externe** : n'importe quelle API `/v1/audio/transcriptions` compatible OpenAI (Qwen3-ASR, Whisper, Speaches, faster-whisper-server, LocalAI, OpenAI). Repli sur la reconnaissance Chromium.
|
||||||
* **TTS externe** : API `/v1/audio/speech` compatible OpenAI, voix système Windows ou Google Translate. Lecture phrase par phrase pendant le streaming, préchargement du segment suivant, coupure instantanée.
|
* **TTS externe** : API `/v1/audio/speech` compatible OpenAI, voix système Windows ou Google Translate. Lecture phrase par phrase pendant le streaming, préchargement du segment suivant, coupure instantanée.
|
||||||
@@ -92,6 +97,20 @@ Pour recevoir les résultats de crons ou le miroir d'autres canaux dans EveFlow,
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### Donner à Hermes les outils du PC (MCP)
|
||||||
|
|
||||||
|
Dans `~/.hermes/config.yaml` côté Hermes :
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
mcp_servers:
|
||||||
|
eveflow:
|
||||||
|
url: "http://<ip-du-pc>:7842/mcp"
|
||||||
|
headers:
|
||||||
|
Authorization: "Bearer <secret du webhook EveFlow>"
|
||||||
|
```
|
||||||
|
|
||||||
|
Sans secret, EveFlow n'écoute qu'en local (`127.0.0.1`) ; définissez un secret dans Paramètres → Webhook pour un Hermes distant. Outils exposés : `capture_screen`, `lock_session`, `open_app`, `open_url`, `media_key`, `clipboard_get`, `clipboard_set`, `find_files`, `speak_text`, `notify_user`, `set_hud_state`, `get_app_status`, `get_conversation_history`, `show_message`.
|
||||||
|
|
||||||
## Développement
|
## Développement
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
+19
-9
@@ -13,6 +13,11 @@
|
|||||||
| Mot d'activation après transcription | Fait | Filtre « Jarvis … » en mains libres, tolérant aux erreurs de transcription |
|
| Mot d'activation après transcription | Fait | Filtre « Jarvis … » en mains libres, tolérant aux erreurs de transcription |
|
||||||
| Détection de fin de phrase | Fait (2.3.0) | Silero VAD neuronal dans le worker (segment renvoyé au renderer), repli sur le VAD énergétique si le modèle manque |
|
| Détection de fin de phrase | Fait (2.3.0) | Silero VAD neuronal dans le worker (segment renvoyé au renderer), repli sur le VAD énergétique si le modèle manque |
|
||||||
| Vision d'écran | Fait (2.3.0) | Capture `desktopCapturer` jointe à la requête Hermes (bouton, ou « regarde mon écran ») |
|
| Vision d'écran | Fait (2.3.0) | Capture `desktopCapturer` jointe à la requête Hermes (bouton, ou « regarde mon écran ») |
|
||||||
|
| Serveur MCP local (outils du PC pour Hermes) | Fait (2.4.0) | `/mcp` sur le serveur webhook, JSON-RPC Streamable HTTP, 14 outils dont la capture d'écran renvoyée en image |
|
||||||
|
| Heures calmes, priorités, résumé vocal | Fait (2.4.0) | Paramètres → Notifications ; thème nuit automatique ; badge non-lus |
|
||||||
|
| Mode mission (second modèle) | Fait (2.4.0) | Bouton dans la barre de commande ; modèle dédié aux tâches longues |
|
||||||
|
| Widget compact glanceable | Fait (2.4.0) | État, dernière phrase, non-lus, indicateurs |
|
||||||
|
| Barge-in | Fait (2.4.0) | Coupe la voix dès que l'utilisateur parle ; seuil relevé pendant la synthèse (à valider avec l'annulation d'écho Windows) |
|
||||||
| Actions système locales | Fait (2.3.0) | Verrouillage, volume et touches média, ouvrir une application ou une URL, presse-papiers, recherche de fichiers ; intentions courtes exécutées sans passer par Hermes |
|
| Actions système locales | Fait (2.3.0) | Verrouillage, volume et touches média, ouvrir une application ou une URL, presse-papiers, recherche de fichiers ; intentions courtes exécutées sans passer par Hermes |
|
||||||
| Hermes : runs, sessions, chat completions | Fait | Transport choisi selon `/v1/capabilities` |
|
| Hermes : runs, sessions, chat completions | Fait | Transport choisi selon `/v1/capabilities` |
|
||||||
| Approbations, steer, stop | Fait | Modales, injection de consigne en cours de run |
|
| Approbations, steer, stop | Fait | Modales, injection de consigne en cours de run |
|
||||||
@@ -44,17 +49,21 @@ Sources : [jarvis-desktop-ai](https://github.com/ccarloshenri/jarvis-desktop-ai)
|
|||||||
- Capture d'écran (`desktopCapturer`, JPEG 1600 px) jointe à la requête Hermes : bouton dans la barre de commande, ou phrase « regarde mon écran… » à l'oral comme à l'écrit.
|
- Capture d'écran (`desktopCapturer`, JPEG 1600 px) jointe à la requête Hermes : bouton dans la barre de commande, ou phrase « regarde mon écran… » à l'oral comme à l'écrit.
|
||||||
- Actions locales (processus principal, liste blanche) : verrouiller, volume/mute/lecture/piste, ouvrir une application connue ou une URL http(s), presse-papiers, recherche de fichiers dans Documents/Bureau/Téléchargements/Images.
|
- Actions locales (processus principal, liste blanche) : verrouiller, volume/mute/lecture/piste, ouvrir une application connue ou une URL http(s), presse-papiers, recherche de fichiers dans Documents/Bureau/Téléchargements/Images.
|
||||||
- Routeur d'intentions FR/EN (`src/services/localCommands.ts`) exécuté avant l'envoi à Hermes ; désactivable dans Paramètres → Micro. Les phrases composées (« ouvre X puis… ») partent à Hermes.
|
- Routeur d'intentions FR/EN (`src/services/localCommands.ts`) exécuté avant l'envoi à Hermes ; désactivable dans Paramètres → Micro. Les phrases composées (« ouvre X puis… ») partent à Hermes.
|
||||||
- Reste à faire : exposer ces actions à Hermes lui-même (serveur MCP local) pour qu'un run puisse les enchaîner.
|
- Exposition à Hermes via le serveur MCP local livrée en 2.4.0.
|
||||||
|
|
||||||
### Étape 3 : conversation plus naturelle
|
### Étape 3 : conversation plus naturelle — livrée en 2.4.0
|
||||||
- Barge-in réel : couper la voix dès que l'utilisateur parle (déjà préparé, à valider avec l'annulation d'écho Windows).
|
- Barge-in : l'utilisateur qui parle par-dessus coupe la voix ; seuil d'énergie relevé pendant la synthèse pour ignorer l'écho (à valider sur Windows avec l'annulation d'écho du micro).
|
||||||
- Réponses courtes à l'oral, détails à l'écran : instruction Hermes dédiée déjà en place, à affiner avec des consignes de format (« deux phrases à l'oral, détails en Markdown »).
|
- Mode mission : second modèle Hermes choisi d'un clic pour les tâches longues.
|
||||||
- Modèle rapide pour le bavardage, modèle puissant pour les missions (choix par transport ou par mot-clé).
|
- Serveur MCP local : Hermes enchaîne lui-même les actions du PC dans ses runs.
|
||||||
|
|
||||||
### Étape 4 : présence
|
### Étape 4 : présence — livrée en 2.4.0
|
||||||
- Widget compact « glanceable » : dernière phrase, état, badge d'alertes.
|
- Widget compact glanceable : état, dernière phrase, non-lus, indicateurs heures calmes / mission.
|
||||||
- Heures calmes, priorité des notifications, résumé vocal des crons.
|
- Heures calmes, mots prioritaires, résumé vocal des messages entrants, thème nuit.
|
||||||
- Thèmes et voix par contexte (nuit, travail).
|
|
||||||
|
### Pistes suivantes
|
||||||
|
- Voix différente par contexte (nuit, travail) et profils de réponse.
|
||||||
|
- Mémoire locale des préférences transmise à Hermes (`X-Hermes-Session-Key` déjà en place).
|
||||||
|
- Validation du barge-in et des touches média sur Windows réel (retours utilisateurs).
|
||||||
|
|
||||||
## Résultats du test de bout en bout (Linux, Xvfb, 4 cœurs lents)
|
## Résultats du test de bout en bout (Linux, Xvfb, 4 cœurs lents)
|
||||||
|
|
||||||
@@ -68,5 +77,6 @@ Sources : [jarvis-desktop-ai](https://github.com/ccarloshenri/jarvis-desktop-ai)
|
|||||||
| Silero VAD sur phrase Kokoro de 2,3 s (2.3.0) | un seul segment, début et fin détectés, 6,7 s d'audio traités en 190 ms |
|
| Silero VAD sur phrase Kokoro de 2,3 s (2.3.0) | un seul segment, début et fin détectés, 6,7 s d'audio traités en 190 ms |
|
||||||
| Capture d'écran → Hermes (2.3.0) | JPEG de 107 ko reçu côté Hermes (mock chat completions) |
|
| Capture d'écran → Hermes (2.3.0) | JPEG de 107 ko reçu côté Hermes (mock chat completions) |
|
||||||
| Intention locale « coupe le son » (2.3.0) | traitée sans Hermes, résultat affiché dans le fil |
|
| Intention locale « coupe le son » (2.3.0) | traitée sans Hermes, résultat affiché dans le fil |
|
||||||
|
| Serveur MCP (2.4.0) | initialize, tools/list (14 outils), tools/call côté principal (presse-papiers, capture image) et côté renderer (état, message dans le fil) |
|
||||||
|
|
||||||
Sur un PC à 28 cœurs les temps sont nettement plus courts. Whisper small est maintenant recommandé pour le français.
|
Sur un PC à 28 cœurs les temps sont nettement plus courts. Whisper small est maintenant recommandé pour le français.
|
||||||
+191
@@ -0,0 +1,191 @@
|
|||||||
|
/**
|
||||||
|
* Minimal MCP server (Streamable HTTP, JSON-RPC 2.0) mounted on the webhook HTTP server at /mcp.
|
||||||
|
* Hermes Agent connects to it as a remote MCP server and gains the PC-side tools: screen capture,
|
||||||
|
* system actions, voice, notifications and HUD state. No SDK: initialize / tools/list / tools/call
|
||||||
|
* are the only methods a client needs, and every reply is a plain JSON body.
|
||||||
|
*/
|
||||||
|
import { ipcMain, type BrowserWindow } from 'electron';
|
||||||
|
import type { IncomingMessage, ServerResponse } from 'node:http';
|
||||||
|
import { IPC, type McpToolRequest, type McpToolResponse } from '../shared/ipc';
|
||||||
|
import type { SystemAction } from '../shared/bridge';
|
||||||
|
import { log } from './logger';
|
||||||
|
import { captureScreen, runSystemAction } from './ipc/system';
|
||||||
|
|
||||||
|
export const MCP_PATH = '/mcp';
|
||||||
|
const PROTOCOL = '2025-03-26';
|
||||||
|
const RENDERER_TIMEOUT_MS = 20_000;
|
||||||
|
|
||||||
|
interface ToolSpec {
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
inputSchema: Record<string, unknown>;
|
||||||
|
/** 'main' = executed here; 'renderer' = forwarded to the UI process. */
|
||||||
|
where: 'main' | 'renderer';
|
||||||
|
}
|
||||||
|
|
||||||
|
const obj = (properties: Record<string, unknown>, required: string[] = []) => ({ type: 'object', properties, required, additionalProperties: false });
|
||||||
|
|
||||||
|
export const MCP_TOOLS: ToolSpec[] = [
|
||||||
|
{ name: 'capture_screen', description: "Capture l'écran principal de l'utilisateur et renvoie l'image (JPEG). À utiliser quand l'utilisateur parle de ce qu'il voit ou demande de l'aide sur son écran.", inputSchema: obj({ max_width: { type: 'integer', description: 'Largeur maximale en pixels (défaut 1600)' } }), where: 'main' },
|
||||||
|
{ name: 'lock_session', description: "Verrouille la session Windows/Linux/macOS de l'utilisateur.", inputSchema: obj({}), where: 'main' },
|
||||||
|
{ name: 'open_app', description: "Lance une application sur le PC de l'utilisateur (bloc-notes, calculatrice, chrome, spotify, vscode, terminal, explorateur…).", inputSchema: obj({ name: { type: 'string' } }, ['name']), where: 'main' },
|
||||||
|
{ name: 'open_url', description: "Ouvre une URL http(s) dans le navigateur par défaut de l'utilisateur.", inputSchema: obj({ url: { type: 'string' } }, ['url']), where: 'main' },
|
||||||
|
{ name: 'media_key', description: 'Envoie une touche média : volume-up, volume-down, mute, play-pause, next, previous.', inputSchema: obj({ key: { type: 'string', enum: ['volume-up', 'volume-down', 'mute', 'play-pause', 'next', 'previous'] } }, ['key']), where: 'main' },
|
||||||
|
{ name: 'clipboard_get', description: 'Lit le texte du presse-papiers.', inputSchema: obj({}), where: 'main' },
|
||||||
|
{ name: 'clipboard_set', description: 'Place un texte dans le presse-papiers.', inputSchema: obj({ text: { type: 'string' } }, ['text']), where: 'main' },
|
||||||
|
{ name: 'find_files', description: "Cherche des fichiers par nom dans Documents, Bureau, Téléchargements et Images de l'utilisateur (25 résultats max).", inputSchema: obj({ query: { type: 'string' } }, ['query']), where: 'main' },
|
||||||
|
{ name: 'speak_text', description: "Fait prononcer un texte par la voix d'EveFlow, immédiatement.", inputSchema: obj({ text: { type: 'string' } }, ['text']), where: 'renderer' },
|
||||||
|
{ name: 'notify_user', description: 'Affiche une notification système (titre + corps).', inputSchema: obj({ title: { type: 'string' }, body: { type: 'string' } }, ['body']), where: 'renderer' },
|
||||||
|
{ name: 'set_hud_state', description: 'Change momentanément l’état visuel du HUD : neutral, happy, thinking, alert, error.', inputSchema: obj({ state: { type: 'string', enum: ['neutral', 'happy', 'thinking', 'alert', 'error'] } }, ['state']), where: 'renderer' },
|
||||||
|
{ name: 'get_app_status', description: "État d'EveFlow : transport, liaison, nom de l'assistant, mains libres, voix en cours, heures calmes.", inputSchema: obj({}), where: 'renderer' },
|
||||||
|
{ name: 'get_conversation_history', description: 'Derniers messages de la conversation EveFlow (n ≤ 30).', inputSchema: obj({ n: { type: 'integer' } }), where: 'renderer' },
|
||||||
|
{ name: 'show_message', description: "Affiche un message dans le fil EveFlow (sans le prononcer) — pour les rapports longs ou les résultats de crons.", inputSchema: obj({ text: { type: 'string' }, title: { type: 'string' } }, ['text']), where: 'renderer' }
|
||||||
|
];
|
||||||
|
|
||||||
|
type Rec = Record<string, unknown>;
|
||||||
|
interface RpcRequest {
|
||||||
|
jsonrpc?: string;
|
||||||
|
id?: number | string | null;
|
||||||
|
method?: string;
|
||||||
|
params?: Rec;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pending = new Map<string, { resolve: (r: McpToolResponse) => void; timer: ReturnType<typeof setTimeout> }>();
|
||||||
|
let seq = 0;
|
||||||
|
let ipcRegistered = false;
|
||||||
|
|
||||||
|
function ensureIpc(): void {
|
||||||
|
if (ipcRegistered) return;
|
||||||
|
ipcRegistered = true;
|
||||||
|
ipcMain.on(IPC.mcpResponse, (_e, res: McpToolResponse) => {
|
||||||
|
if (!res || typeof res.id !== 'string') return;
|
||||||
|
const entry = pending.get(res.id);
|
||||||
|
if (!entry) return;
|
||||||
|
clearTimeout(entry.timer);
|
||||||
|
pending.delete(res.id);
|
||||||
|
entry.resolve(res);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function askRenderer(win: BrowserWindow | null, name: string, args: Rec): Promise<McpToolResponse> {
|
||||||
|
ensureIpc();
|
||||||
|
if (!win || win.isDestroyed()) return Promise.resolve({ id: '', ok: false, error: 'EveFlow window unavailable' });
|
||||||
|
const id = `mcp-${++seq}-${Date.now()}`;
|
||||||
|
const req: McpToolRequest = { id, name, args };
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
pending.delete(id);
|
||||||
|
resolve({ id, ok: false, error: 'renderer timeout' });
|
||||||
|
}, RENDERER_TIMEOUT_MS);
|
||||||
|
pending.set(id, { resolve, timer });
|
||||||
|
win.webContents.send(IPC.mcpRequest, req);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function text(value: unknown): { content: Array<Rec>; isError?: boolean } {
|
||||||
|
return { content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value) }] };
|
||||||
|
}
|
||||||
|
|
||||||
|
function failure(message: string): { content: Array<Rec>; isError: boolean } {
|
||||||
|
return { content: [{ type: 'text', text: message }], isError: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function callTool(win: BrowserWindow | null, name: string, args: Rec): Promise<{ content: Array<Rec>; isError?: boolean }> {
|
||||||
|
const spec = MCP_TOOLS.find((t) => t.name === name);
|
||||||
|
if (!spec) return failure(`Outil inconnu : ${name}`);
|
||||||
|
if (spec.where === 'renderer') {
|
||||||
|
const res = await askRenderer(win, name, args);
|
||||||
|
return res.ok ? text(res.result ?? { ok: true }) : failure(res.error ?? 'échec');
|
||||||
|
}
|
||||||
|
const sys = async (action: SystemAction) => {
|
||||||
|
const r = await runSystemAction(action);
|
||||||
|
return r.ok ? text(r.data !== undefined ? { ok: true, message: r.message, data: r.data } : { ok: true, message: r.message }) : failure(r.message ?? 'échec');
|
||||||
|
};
|
||||||
|
switch (name) {
|
||||||
|
case 'capture_screen': {
|
||||||
|
const dataUrl = await captureScreen(Number(args.max_width) || 1600);
|
||||||
|
const base64 = dataUrl.slice(dataUrl.indexOf(',') + 1);
|
||||||
|
return { content: [{ type: 'image', data: base64, mimeType: 'image/jpeg' }, { type: 'text', text: `Capture de l'écran principal (${Math.round(base64.length * 0.75 / 1024)} ko).` }] };
|
||||||
|
}
|
||||||
|
case 'lock_session':
|
||||||
|
return sys({ type: 'lock' });
|
||||||
|
case 'open_app':
|
||||||
|
return sys({ type: 'open-app', name: String(args.name ?? '') });
|
||||||
|
case 'open_url':
|
||||||
|
return sys({ type: 'open-url', url: String(args.url ?? '') });
|
||||||
|
case 'media_key':
|
||||||
|
return sys({ type: 'media', key: String(args.key ?? '') as 'mute' });
|
||||||
|
case 'clipboard_get':
|
||||||
|
return sys({ type: 'clipboard-read' });
|
||||||
|
case 'clipboard_set':
|
||||||
|
return sys({ type: 'clipboard-write', text: String(args.text ?? '') });
|
||||||
|
case 'find_files':
|
||||||
|
return sys({ type: 'find-files', query: String(args.query ?? '') });
|
||||||
|
default:
|
||||||
|
return failure(`Outil non implémenté : ${name}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Handle one JSON-RPC message; returns the response object (or null for notifications). */
|
||||||
|
export async function handleMcpMessage(win: BrowserWindow | null, msg: RpcRequest): Promise<Rec | null> {
|
||||||
|
const id = msg.id ?? null;
|
||||||
|
const reply = (result: unknown) => ({ jsonrpc: '2.0', id, result });
|
||||||
|
const error = (code: number, message: string) => ({ jsonrpc: '2.0', id, error: { code, message } });
|
||||||
|
if (!msg.method) return error(-32600, 'Invalid Request');
|
||||||
|
if (msg.method.startsWith('notifications/')) return null;
|
||||||
|
switch (msg.method) {
|
||||||
|
case 'initialize':
|
||||||
|
return reply({ protocolVersion: PROTOCOL, capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'eveflow', version: process.env.npm_package_version ?? '2.4.0' }, instructions: "Outils du PC de l'utilisateur via EveFlow : écran, applications, volume, presse-papiers, voix et notifications." });
|
||||||
|
case 'ping':
|
||||||
|
return reply({});
|
||||||
|
case 'tools/list':
|
||||||
|
return reply({ tools: MCP_TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) });
|
||||||
|
case 'tools/call': {
|
||||||
|
const params = (msg.params ?? {}) as Rec;
|
||||||
|
const name = String(params.name ?? '');
|
||||||
|
const args = (params.arguments && typeof params.arguments === 'object' ? params.arguments : {}) as Rec;
|
||||||
|
log('INFO', 'mcp', `tools/call ${name}`);
|
||||||
|
try {
|
||||||
|
return reply(await callTool(win, name, args));
|
||||||
|
} catch (err) {
|
||||||
|
return reply(failure((err as Error).message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case 'resources/list':
|
||||||
|
return reply({ resources: [] });
|
||||||
|
case 'prompts/list':
|
||||||
|
return reply({ prompts: [] });
|
||||||
|
default:
|
||||||
|
return error(-32601, `Method not found: ${msg.method}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** HTTP entry point: POST /mcp with one JSON-RPC message or a batch. */
|
||||||
|
export async function handleMcpHttp(win: BrowserWindow | null, req: IncomingMessage, res: ServerResponse, body: string): Promise<void> {
|
||||||
|
const send = (code: number, payload: unknown) => {
|
||||||
|
if (payload === undefined) {
|
||||||
|
res.writeHead(code, { 'Cache-Control': 'no-store' });
|
||||||
|
res.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
||||||
|
res.end(JSON.stringify(payload));
|
||||||
|
};
|
||||||
|
if (req.method === 'GET') return send(405, { error: 'SSE stream not supported; use POST' });
|
||||||
|
if (req.method === 'DELETE') return send(204, undefined);
|
||||||
|
if (req.method !== 'POST') return send(405, { error: 'Method Not Allowed' });
|
||||||
|
let parsed: unknown;
|
||||||
|
try {
|
||||||
|
parsed = body.trim() ? JSON.parse(body) : {};
|
||||||
|
} catch {
|
||||||
|
return send(400, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
|
||||||
|
}
|
||||||
|
const messages = Array.isArray(parsed) ? (parsed as RpcRequest[]) : [parsed as RpcRequest];
|
||||||
|
const replies: Rec[] = [];
|
||||||
|
for (const msg of messages) {
|
||||||
|
const out = await handleMcpMessage(win, msg && typeof msg === 'object' ? msg : {});
|
||||||
|
if (out) replies.push(out);
|
||||||
|
}
|
||||||
|
if (replies.length === 0) return send(202, undefined);
|
||||||
|
return send(200, Array.isArray(parsed) ? replies : replies[0]);
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
type WindowMode
|
type WindowMode
|
||||||
} from '../shared/ipc';
|
} from '../shared/ipc';
|
||||||
import type { EveFlowBridge, SystemAction, SystemActionResult, Unsubscribe } from '../shared/bridge';
|
import type { EveFlowBridge, SystemAction, SystemActionResult, Unsubscribe } from '../shared/bridge';
|
||||||
|
import type { McpToolRequest, McpToolResponse } from '../shared/ipc';
|
||||||
import { VOICE_IPC, type KwsDetection, type KwsStartRequest, type VadEvent, type VadStartRequest, type SynthesizeRequest, type SynthesizeResult, type TranscribeRequest, type TranscribeResult, type VoiceDownloadProgress, type VoiceEngineStatus, type VoiceModelStatus } from '../shared/voice';
|
import { VOICE_IPC, type KwsDetection, type KwsStartRequest, type VadEvent, type VadStartRequest, type SynthesizeRequest, type SynthesizeResult, type TranscribeRequest, type TranscribeResult, type VoiceDownloadProgress, type VoiceEngineStatus, type VoiceModelStatus } from '../shared/voice';
|
||||||
|
|
||||||
function subscribe<T>(channel: string, callback: (payload: T) => void): Unsubscribe {
|
function subscribe<T>(channel: string, callback: (payload: T) => void): Unsubscribe {
|
||||||
@@ -57,6 +58,8 @@ const api: EveFlowBridge = {
|
|||||||
hermes: {
|
hermes: {
|
||||||
onPush: (cb: (event: HermesPushEvent) => void) => subscribe<HermesPushEvent>(IPC.hermesPush, cb),
|
onPush: (cb: (event: HermesPushEvent) => void) => subscribe<HermesPushEvent>(IPC.hermesPush, cb),
|
||||||
webhookStatus: () => ipcRenderer.invoke(IPC.webhookStatus) as Promise<WebhookStatus>,
|
webhookStatus: () => ipcRenderer.invoke(IPC.webhookStatus) as Promise<WebhookStatus>,
|
||||||
|
onToolRequest: (cb: (req: McpToolRequest) => void) => subscribe<McpToolRequest>(IPC.mcpRequest, cb),
|
||||||
|
toolResponse: (res: McpToolResponse) => ipcRenderer.send(IPC.mcpResponse, res),
|
||||||
webhookRestart: () => ipcRenderer.invoke(IPC.webhookRestart) as Promise<WebhookStatus>
|
webhookRestart: () => ipcRenderer.invoke(IPC.webhookRestart) as Promise<WebhookStatus>
|
||||||
},
|
},
|
||||||
hotkeys: {
|
hotkeys: {
|
||||||
|
|||||||
+11
-2
@@ -8,6 +8,7 @@ import type { BrowserWindow } from 'electron';
|
|||||||
import { IPC, type WebhookStatus } from '../shared/ipc';
|
import { IPC, type WebhookStatus } from '../shared/ipc';
|
||||||
import { normalizeHermesPush } from '../shared/hermesPush';
|
import { normalizeHermesPush } from '../shared/hermesPush';
|
||||||
import { log } from './logger';
|
import { log } from './logger';
|
||||||
|
import { handleMcpHttp, MCP_PATH } from './mcp';
|
||||||
|
|
||||||
export const WEBHOOK_PATH = '/eveflow/hook';
|
export const WEBHOOK_PATH = '/eveflow/hook';
|
||||||
const MAX_BODY_BYTES = 2 * 1024 * 1024;
|
const MAX_BODY_BYTES = 2 * 1024 * 1024;
|
||||||
@@ -57,9 +58,10 @@ export async function startWebhookServer(getWindow: () => BrowserWindow | null,
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (req.method === 'GET' && (req.url === '/health' || req.url === '/')) {
|
if (req.method === 'GET' && (req.url === '/health' || req.url === '/')) {
|
||||||
return json(200, { ok: true, app: 'eveflow', path: WEBHOOK_PATH });
|
return json(200, { ok: true, app: 'eveflow', path: WEBHOOK_PATH, mcp: MCP_PATH });
|
||||||
}
|
}
|
||||||
if (req.method !== 'POST' || !req.url?.startsWith(WEBHOOK_PATH)) {
|
const isMcp = !!req.url && (req.url === MCP_PATH || req.url.startsWith(`${MCP_PATH}?`));
|
||||||
|
if (!isMcp && (req.method !== 'POST' || !req.url?.startsWith(WEBHOOK_PATH))) {
|
||||||
return json(404, { error: 'Not Found' });
|
return json(404, { error: 'Not Found' });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,6 +93,13 @@ export async function startWebhookServer(getWindow: () => BrowserWindow | null,
|
|||||||
if (tooLarge) return;
|
if (tooLarge) return;
|
||||||
// Concatenate before decoding so multibyte UTF-8 (accents, emoji) split across chunks stays intact.
|
// Concatenate before decoding so multibyte UTF-8 (accents, emoji) split across chunks stays intact.
|
||||||
const body = Buffer.concat(chunks).toString('utf8');
|
const body = Buffer.concat(chunks).toString('utf8');
|
||||||
|
if (isMcp) {
|
||||||
|
handleMcpHttp(getWindow(), req, res, body).catch((err: Error) => {
|
||||||
|
log('ERROR', 'mcp', err.message);
|
||||||
|
if (!res.headersSent) json(500, { error: err.message });
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const raw: unknown = body.trim() ? JSON.parse(body) : {};
|
const raw: unknown = body.trim() ? JSON.parse(body) : {};
|
||||||
const events = normalizeHermesPush(raw);
|
const events = normalizeHermesPush(raw);
|
||||||
|
|||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "eveflow",
|
"name": "eveflow",
|
||||||
"version": "2.3.0",
|
"version": "2.4.0",
|
||||||
"releaseVersion": "2.3.0",
|
"releaseVersion": "2.4.0",
|
||||||
"description": "JARVIS-style desktop HUD for Hermes Agent: voice, streaming runs, scheduled jobs, skills and telemetry",
|
"description": "JARVIS-style desktop HUD for Hermes Agent: voice, streaming runs, scheduled jobs, skills and telemetry",
|
||||||
"main": "dist-electron/main.js",
|
"main": "dist-electron/main.js",
|
||||||
"private": true,
|
"private": true,
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import type {
|
|||||||
WebhookStatus,
|
WebhookStatus,
|
||||||
WindowMode
|
WindowMode
|
||||||
} from './ipc';
|
} from './ipc';
|
||||||
|
import type { McpToolRequest, McpToolResponse } from './ipc';
|
||||||
import type {
|
import type {
|
||||||
KwsDetection,
|
KwsDetection,
|
||||||
KwsStartRequest,
|
KwsStartRequest,
|
||||||
@@ -57,6 +58,9 @@ export interface EveFlowBridge {
|
|||||||
hermes: {
|
hermes: {
|
||||||
onPush: (cb: (event: HermesPushEvent) => void) => Unsubscribe;
|
onPush: (cb: (event: HermesPushEvent) => void) => Unsubscribe;
|
||||||
webhookStatus: () => Promise<WebhookStatus>;
|
webhookStatus: () => Promise<WebhookStatus>;
|
||||||
|
/** Tool calls from Hermes via the local MCP endpoint that need the renderer. */
|
||||||
|
onToolRequest: (cb: (req: McpToolRequest) => void) => Unsubscribe;
|
||||||
|
toolResponse: (res: McpToolResponse) => void;
|
||||||
webhookRestart: () => Promise<WebhookStatus>;
|
webhookRestart: () => Promise<WebhookStatus>;
|
||||||
};
|
};
|
||||||
hotkeys: {
|
hotkeys: {
|
||||||
|
|||||||
@@ -113,6 +113,8 @@ export const IPC = {
|
|||||||
appInfo: 'app:info',
|
appInfo: 'app:info',
|
||||||
screenCapture: 'system:screen-capture',
|
screenCapture: 'system:screen-capture',
|
||||||
systemAction: 'system:action',
|
systemAction: 'system:action',
|
||||||
|
mcpRequest: 'mcp:request',
|
||||||
|
mcpResponse: 'mcp:response',
|
||||||
readLocalFile: 'files:read-local',
|
readLocalFile: 'files:read-local',
|
||||||
writeSharedFile: 'files:write-shared',
|
writeSharedFile: 'files:write-shared',
|
||||||
openPath: 'files:open-path',
|
openPath: 'files:open-path',
|
||||||
@@ -124,3 +126,17 @@ export const IPC = {
|
|||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type HotkeyEvent = 'ptt-toggle' | 'toggle-window' | 'stop-speaking';
|
export type HotkeyEvent = 'ptt-toggle' | 'toggle-window' | 'stop-speaking';
|
||||||
|
|
||||||
|
/** A tool call arriving from Hermes through the local MCP endpoint that needs the renderer (UI, voice, chat). */
|
||||||
|
export interface McpToolRequest {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
args: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface McpToolResponse {
|
||||||
|
id: string;
|
||||||
|
ok: boolean;
|
||||||
|
result?: unknown;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
+22
-1
@@ -3,7 +3,9 @@ import { AlertTriangle, X } from 'lucide-react';
|
|||||||
import type { WindowMode } from '../shared/ipc';
|
import type { WindowMode } from '../shared/ipc';
|
||||||
import { bridge } from './lib/bridge';
|
import { bridge } from './lib/bridge';
|
||||||
import { Log } from './lib/log';
|
import { Log } from './lib/log';
|
||||||
import { handlePush, stopGeneration } from './services/conversation';
|
import { handlePush, localToolContext, stopGeneration } from './services/conversation';
|
||||||
|
import { initMcpBridge } from './services/mcpBridge';
|
||||||
|
import { isQuietTime } from './lib/quietHours';
|
||||||
import { speech } from './services/voice/speech';
|
import { speech } from './services/voice/speech';
|
||||||
import { voiceController } from './services/voice/voiceController';
|
import { voiceController } from './services/voice/voiceController';
|
||||||
import { useChat } from './state/chat';
|
import { useChat } from './state/chat';
|
||||||
@@ -57,6 +59,7 @@ function useBoot(): boolean {
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
disposers.push(api.hermes.onPush(handlePush));
|
disposers.push(api.hermes.onPush(handlePush));
|
||||||
|
initMcpBridge(localToolContext);
|
||||||
disposers.push(
|
disposers.push(
|
||||||
api.hotkeys.on((event) => {
|
api.hotkeys.on((event) => {
|
||||||
if (event === 'ptt-toggle') voiceController.toggle();
|
if (event === 'ptt-toggle') voiceController.toggle();
|
||||||
@@ -95,6 +98,24 @@ function useBoot(): boolean {
|
|||||||
function useThemeSync(): void {
|
function useThemeSync(): void {
|
||||||
const theme = useSettings((s) => s.settings.theme);
|
const theme = useSettings((s) => s.settings.theme);
|
||||||
const reduce = useSettings((s) => s.settings.ui.reduceMotion);
|
const reduce = useSettings((s) => s.settings.ui.reduceMotion);
|
||||||
|
// Quiet hours: computed every 30 s; dims the HUD (night theme) and silences pushes.
|
||||||
|
const notif = useSettings((s) => s.settings.notifications);
|
||||||
|
useEffect(() => {
|
||||||
|
const tick = () => {
|
||||||
|
const quiet = notif.quietEnabled && isQuietTime(notif.quietStart, notif.quietEnd);
|
||||||
|
useChat.getState().setQuiet(quiet);
|
||||||
|
document.documentElement.toggleAttribute('data-night', quiet && notif.nightTheme);
|
||||||
|
};
|
||||||
|
tick();
|
||||||
|
const timer = setInterval(tick, 30_000);
|
||||||
|
return () => clearInterval(timer);
|
||||||
|
}, [notif]);
|
||||||
|
useEffect(() => {
|
||||||
|
const onVisible = () => { if (!document.hidden) useChat.getState().markRead(); };
|
||||||
|
document.addEventListener('visibilitychange', onVisible);
|
||||||
|
return () => document.removeEventListener('visibilitychange', onVisible);
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
document.documentElement.dataset.theme = theme;
|
document.documentElement.dataset.theme = theme;
|
||||||
document.documentElement.dataset.motion = reduce ? 'reduce' : 'full';
|
document.documentElement.dataset.motion = reduce ? 'reduce' : 'full';
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { Mic, Paperclip, Send, Square, X, Radio, Loader2, Volume2, VolumeX, Navigation, ScanEye } from 'lucide-react';
|
import { Mic, Paperclip, Send, Square, X, Radio, Loader2, Volume2, VolumeX, Navigation, ScanEye, Crosshair } from 'lucide-react';
|
||||||
import { sendMessage, steer, stopGeneration , captureScreen } from '../../services/conversation';
|
import { sendMessage, steer, stopGeneration , captureScreen } from '../../services/conversation';
|
||||||
import { speech } from '../../services/voice/speech';
|
import { speech } from '../../services/voice/speech';
|
||||||
import { voiceController } from '../../services/voice/voiceController';
|
import { voiceController } from '../../services/voice/voiceController';
|
||||||
@@ -50,6 +50,8 @@ export function CommandBar({ compact }: Props) {
|
|||||||
const autoSpeak = useSettings((s) => s.settings.speech.autoSpeak);
|
const autoSpeak = useSettings((s) => s.settings.speech.autoSpeak);
|
||||||
const update = useSettings((s) => s.update);
|
const update = useSettings((s) => s.update);
|
||||||
const [images, setImages] = useState<string[]>([]);
|
const [images, setImages] = useState<string[]>([]);
|
||||||
|
const missionMode = useChat((s) => s.missionMode);
|
||||||
|
const missionModel = useSettings((s) => s.settings.hermes.missionModel);
|
||||||
const [steerMode, setSteerMode] = useState(false);
|
const [steerMode, setSteerMode] = useState(false);
|
||||||
const fileRef = useRef<HTMLInputElement>(null);
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||||
@@ -198,6 +200,9 @@ export function CommandBar({ compact }: Props) {
|
|||||||
<button className={`toggle-btn${handsFree ? ' on' : ''}`} onClick={() => voiceController.setHandsFree(!handsFree)} title="Écoute continue : le micro se réactive après chaque réponse">
|
<button className={`toggle-btn${handsFree ? ' on' : ''}`} onClick={() => voiceController.setHandsFree(!handsFree)} title="Écoute continue : le micro se réactive après chaque réponse">
|
||||||
<Radio size={12} /> mains libres
|
<Radio size={12} /> mains libres
|
||||||
</button>
|
</button>
|
||||||
|
<button className={`toggle-btn${missionMode ? ' on' : ''}`} onClick={() => useChat.getState().setMissionMode(!missionMode)} title={missionModel ? `Mode mission : modèle ${missionModel} pour les tâches longues` : 'Mode mission (définissez un modèle « mission » dans Paramètres → Hermes)'}>
|
||||||
|
<Crosshair size={14} /> Mission
|
||||||
|
</button>
|
||||||
<button className={`toggle-btn${autoSpeak && speechProvider !== 'off' ? ' on' : ''}`} onClick={() => update({ speech: { autoSpeak: !autoSpeak } })} title="Lire les réponses à voix haute">
|
<button className={`toggle-btn${autoSpeak && speechProvider !== 'off' ? ' on' : ''}`} onClick={() => update({ speech: { autoSpeak: !autoSpeak } })} title="Lire les réponses à voix haute">
|
||||||
{autoSpeak && speechProvider !== 'off' ? <Volume2 size={12} /> : <VolumeX size={12} />} voix
|
{autoSpeak && speechProvider !== 'off' ? <Volume2 size={12} /> : <VolumeX size={12} />} voix
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1,13 +1,37 @@
|
|||||||
import { Maximize2, X, Minus } from 'lucide-react';
|
import { Maximize2, X, Minus, Moon, Crosshair } from 'lucide-react';
|
||||||
|
import { useShallow } from 'zustand/react/shallow';
|
||||||
import { bridge } from '../../lib/bridge';
|
import { bridge } from '../../lib/bridge';
|
||||||
import { useSettings } from '../../state/settings';
|
import { useSettings } from '../../state/settings';
|
||||||
|
import { useChat } from '../../state/chat';
|
||||||
|
import { useVoice } from '../../state/voice';
|
||||||
import { CoreStage } from '../hud/CoreStage';
|
import { CoreStage } from '../hud/CoreStage';
|
||||||
import { ChatPanel } from '../chat/ChatPanel';
|
import { ChatPanel } from '../chat/ChatPanel';
|
||||||
|
|
||||||
|
const STATE_LABEL: Record<string, string> = {
|
||||||
|
idle: 'veille',
|
||||||
|
listening: 'écoute',
|
||||||
|
thinking: 'réflexion',
|
||||||
|
speaking: 'parle',
|
||||||
|
alert: 'alerte',
|
||||||
|
error: 'erreur',
|
||||||
|
success: 'terminé'
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Compact mode: a glanceable strip (state, unread, last sentence) above the mini chat. */
|
||||||
export function CompactWidget() {
|
export function CompactWidget() {
|
||||||
const assistantName = useSettings((s) => s.settings.assistantName);
|
const assistantName = useSettings((s) => s.settings.assistantName);
|
||||||
const compactOpacity = useSettings((s) => s.settings.ui.compactOpacity);
|
const compactOpacity = useSettings((s) => s.settings.ui.compactOpacity);
|
||||||
|
const { hud, hudOverride, unread, missionMode, quiet, last } = useChat(
|
||||||
|
useShallow((s) => {
|
||||||
|
const lastAssistant = [...s.messages].reverse().find((m) => m.role === 'assistant' && m.content.trim());
|
||||||
|
return { hud: s.hud, hudOverride: s.hudOverride, unread: s.unread, missionMode: s.missionMode, quiet: s.quiet, last: lastAssistant?.content ?? '' };
|
||||||
|
})
|
||||||
|
);
|
||||||
|
const wake = useVoice((s) => s.wake);
|
||||||
const api = bridge();
|
const api = bridge();
|
||||||
|
const state = hudOverride ?? hud;
|
||||||
|
const label = state === 'idle' && wake === 'spotting' ? 'à l’écoute du mot-clé' : STATE_LABEL[state] ?? state;
|
||||||
|
const sentence = last.replace(/```[\s\S]*?```/g, ' ').replace(/[#*_>`|]/g, '').replace(/\s+/g, ' ').trim().slice(0, 140);
|
||||||
return (
|
return (
|
||||||
<div className="compact-root" style={{ ['--compact-opacity' as string]: compactOpacity }}>
|
<div className="compact-root" style={{ ['--compact-opacity' as string]: compactOpacity }}>
|
||||||
<div className="compact-head">
|
<div className="compact-head">
|
||||||
@@ -21,6 +45,15 @@ export function CompactWidget() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<CoreStage compact />
|
<CoreStage compact />
|
||||||
|
<div className="compact-glance" onClick={() => useChat.getState().markRead()} title={sentence}>
|
||||||
|
<span className={`state${state === 'alert' || state === 'error' ? ' alert' : ''}`}>{label}</span>
|
||||||
|
<span className="last">{sentence || 'Aucun message pour l’instant.'}</span>
|
||||||
|
<span className="badges">
|
||||||
|
{missionMode && <Crosshair size={12} className="mission" aria-label="mode mission" />}
|
||||||
|
{quiet && <Moon size={12} aria-label="heures calmes" />}
|
||||||
|
{unread > 0 && <span className="unread" aria-label={`${unread} non lus`}>{unread}</span>}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
<div className="compact-body">
|
<div className="compact-body">
|
||||||
<ChatPanel compact />
|
<ChatPanel compact />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { useVoice } from '../../state/voice';
|
|||||||
import { installedModels, useVoiceModels } from '../../state/voiceModels';
|
import { installedModels, useVoiceModels } from '../../state/voiceModels';
|
||||||
import { ModelsSection } from './ModelsSection';
|
import { ModelsSection } from './ModelsSection';
|
||||||
|
|
||||||
type Section = 'general' | 'hermes' | 'voice' | 'speech' | 'models' | 'webhook' | 'ui';
|
type Section = 'general' | 'hermes' | 'voice' | 'speech' | 'models' | 'webhook' | 'notifications' | 'ui';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
@@ -151,6 +151,7 @@ export function SettingsDrawer({ onClose }: Props) {
|
|||||||
['speech', 'Voix / TTS'],
|
['speech', 'Voix / TTS'],
|
||||||
['models', 'Modèles locaux'],
|
['models', 'Modèles locaux'],
|
||||||
['webhook', 'Webhook'],
|
['webhook', 'Webhook'],
|
||||||
|
['notifications', 'Notifications'],
|
||||||
['general', 'Général'],
|
['general', 'Général'],
|
||||||
['ui', 'Interface']
|
['ui', 'Interface']
|
||||||
];
|
];
|
||||||
@@ -215,6 +216,11 @@ export function SettingsDrawer({ onClose }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="field">
|
<div className="field">
|
||||||
|
<label>Modèle « mission » (tâches longues)</label>
|
||||||
|
<input className="input" list="hermes-models" value={settings.hermes.missionModel} placeholder="(même modèle)" onChange={(e) => update({ hermes: { missionModel: e.target.value } })} />
|
||||||
|
<span className="hint">Utilisé quand le mode Mission est activé dans la barre de commande. Laissez vide pour garder le modèle principal.</span>
|
||||||
|
</div>
|
||||||
|
<div className="field">
|
||||||
<label>Instructions EveFlow (superposées au prompt Hermes)</label>
|
<label>Instructions EveFlow (superposées au prompt Hermes)</label>
|
||||||
<textarea className="textarea" value={settings.hermes.instructions} onChange={(e) => update({ hermes: { instructions: e.target.value } })} />
|
<textarea className="textarea" value={settings.hermes.instructions} onChange={(e) => update({ hermes: { instructions: e.target.value } })} />
|
||||||
</div>
|
</div>
|
||||||
@@ -471,6 +477,14 @@ export function SettingsDrawer({ onClose }: Props) {
|
|||||||
-d '{"role":"assistant","text":"Rapport terminé","source":"telegram"}'`}</pre>
|
-d '{"role":"assistant","text":"Rapport terminé","source":"telegram"}'`}</pre>
|
||||||
<span className="hint">Formats acceptés : {'{role,text}'}, {'{event:"run.completed",input,output}'}, {'{event:"job.completed",job:{name},output,status}'}, {'{type:"message",payload:{text}}'}.</span>
|
<span className="hint">Formats acceptés : {'{role,text}'}, {'{event:"run.completed",input,output}'}, {'{event:"job.completed",job:{name},output,status}'}, {'{type:"message",payload:{text}}'}.</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="field">
|
||||||
|
<label>Serveur MCP pour Hermes (outils du PC : écran, applications, volume, presse-papiers, voix)</label>
|
||||||
|
<pre className="input" style={{ whiteSpace: 'pre-wrap', fontSize: 11.5, userSelect: 'text' }}>{`# ~/.hermes/config.yaml côté Hermes
|
||||||
|
mcp_servers:
|
||||||
|
eveflow:
|
||||||
|
url: "http://<ip-de-ce-pc>:${settings.webhook.port}/mcp"${settings.webhook.secret ? '\n headers:\n Authorization: "Bearer <secret>"' : ''}`}</pre>
|
||||||
|
<span className="hint">Même port et même secret que le webhook. Sans secret, EveFlow n’écoute qu’en local (127.0.0.1) : définissez un secret pour un Hermes distant.</span>
|
||||||
|
</div>
|
||||||
<div className="row">
|
<div className="row">
|
||||||
<button className="btn primary small" onClick={() => void applyWebhook()} disabled={!bridge()}>Appliquer et redémarrer</button>
|
<button className="btn primary small" onClick={() => void applyWebhook()} disabled={!bridge()}>Appliquer et redémarrer</button>
|
||||||
{hermesWebhook && <span className={`status-pill ${hermesWebhook.listening ? 'online' : 'offline'}`}>{hermesWebhook.listening ? `port ${hermesWebhook.port}` : hermesWebhook.error ?? 'inactif'}</span>}
|
{hermesWebhook && <span className={`status-pill ${hermesWebhook.listening ? 'online' : 'offline'}`}>{hermesWebhook.listening ? `port ${hermesWebhook.port}` : hermesWebhook.error ?? 'inactif'}</span>}
|
||||||
@@ -478,6 +492,35 @@ export function SettingsDrawer({ onClose }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{section === 'notifications' && (
|
||||||
|
<div className="card">
|
||||||
|
<Toggle on={settings.notifications.quietEnabled} onChange={(v) => update({ notifications: { quietEnabled: v } })} label="Heures calmes" hint="Les messages poussés (crons, Telegram) s’affichent sans être lus à voix haute ni faire clignoter le noyau ; le HUD passe en mode nuit." />
|
||||||
|
<div className="grid-2">
|
||||||
|
<div className="field">
|
||||||
|
<label>Début</label>
|
||||||
|
<input className="input" type="time" value={settings.notifications.quietStart} onChange={(e) => update({ notifications: { quietStart: e.target.value } })} />
|
||||||
|
</div>
|
||||||
|
<div className="field">
|
||||||
|
<label>Fin</label>
|
||||||
|
<input className="input" type="time" value={settings.notifications.quietEnd} onChange={(e) => update({ notifications: { quietEnd: e.target.value } })} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Toggle on={settings.notifications.nightTheme} onChange={(v) => update({ notifications: { nightTheme: v } })} label="Thème nuit pendant les heures calmes" />
|
||||||
|
<div className="field" style={{ marginTop: 10 }}>
|
||||||
|
<label>Mots prioritaires (lus même en heures calmes)</label>
|
||||||
|
<input className="input" value={settings.notifications.priorityKeywords} onChange={(e) => update({ notifications: { priorityKeywords: e.target.value } })} placeholder="urgent, alerte, panne" />
|
||||||
|
<span className="hint">Séparés par des virgules ; comparés au texte et au nom du cron. Les échecs de crons sont toujours prioritaires.</span>
|
||||||
|
</div>
|
||||||
|
<Toggle on={settings.notifications.summarizeIncoming} onChange={(v) => update({ notifications: { summarizeIncoming: v } })} label="Résumé vocal des messages entrants" hint="Seules les premières phrases sont lues ; le message complet reste dans le fil." />
|
||||||
|
{settings.notifications.summarizeIncoming && (
|
||||||
|
<div className="field">
|
||||||
|
<label>Phrases lues : {settings.notifications.summarySentences}</label>
|
||||||
|
<input className="range" type="range" min={1} max={5} step={1} value={settings.notifications.summarySentences} onChange={(e) => update({ notifications: { summarySentences: Number(e.target.value) } })} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{section === 'general' && (
|
{section === 'general' && (
|
||||||
<div className="card">
|
<div className="card">
|
||||||
<div className="grid-2">
|
<div className="grid-2">
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
/** Quiet-hours and spoken-summary helpers (pure, unit tested). */
|
||||||
|
|
||||||
|
function minutesOf(hhmm: string): number | null {
|
||||||
|
const m = /^(\d{1,2}):(\d{2})$/.exec(hhmm.trim());
|
||||||
|
if (!m) return null;
|
||||||
|
const h = Number(m[1]);
|
||||||
|
const min = Number(m[2]);
|
||||||
|
if (h > 23 || min > 59) return null;
|
||||||
|
return h * 60 + min;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when `now` falls inside [start, end), with ranges crossing midnight ("22:30" → "07:30"). */
|
||||||
|
export function isQuietTime(start: string, end: string, now: Date = new Date()): boolean {
|
||||||
|
const s = minutesOf(start);
|
||||||
|
const e = minutesOf(end);
|
||||||
|
if (s === null || e === null || s === e) return false;
|
||||||
|
const cur = now.getHours() * 60 + now.getMinutes();
|
||||||
|
return s < e ? cur >= s && cur < e : cur >= s || cur < e;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when the text or job name contains one of the comma-separated priority words. */
|
||||||
|
export function isPriority(text: string, keywords: string, jobName = ''): boolean {
|
||||||
|
const words = keywords
|
||||||
|
.split(/[,;\n]/)
|
||||||
|
.map((w) => w.trim().toLowerCase())
|
||||||
|
.filter(Boolean);
|
||||||
|
if (!words.length) return false;
|
||||||
|
const hay = `${jobName} ${text}`.toLowerCase();
|
||||||
|
return words.some((w) => hay.includes(w));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** First `count` sentences of a text, for a short spoken summary of a long push. */
|
||||||
|
export function summarize(text: string, count: number): string {
|
||||||
|
const clean = text
|
||||||
|
.replace(/```[\s\S]*?```/g, ' ')
|
||||||
|
.replace(/[#*_>`|]/g, '')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim();
|
||||||
|
if (!clean) return '';
|
||||||
|
const sentences = clean.match(/[^.!?…]+[.!?…]+["»)]?\s*|[^.!?…]+$/g) ?? [clean];
|
||||||
|
const picked = sentences.slice(0, Math.max(1, count)).join('').trim();
|
||||||
|
return picked.length < clean.length ? picked : clean;
|
||||||
|
}
|
||||||
@@ -9,7 +9,8 @@ import { previewText } from '../lib/text';
|
|||||||
import { useChat, type PendingRequest } from '../state/chat';
|
import { useChat, type PendingRequest } from '../state/chat';
|
||||||
import { useHermes } from '../state/hermes';
|
import { useHermes } from '../state/hermes';
|
||||||
import { useSettings } from '../state/settings';
|
import { useSettings } from '../state/settings';
|
||||||
import { executeLocalTool, LOCAL_TOOL_DEFINITIONS } from './hermes/localTools';
|
import { executeLocalTool, LOCAL_TOOL_DEFINITIONS, type LocalToolContext } from './hermes/localTools';
|
||||||
|
import { isPriority, summarize } from '../lib/quietHours';
|
||||||
import type { HermesStreamEvent, SendHandle } from './hermes/types';
|
import type { HermesStreamEvent, SendHandle } from './hermes/types';
|
||||||
import { speech } from './voice/speech';
|
import { speech } from './voice/speech';
|
||||||
import { bridge } from '../lib/bridge';
|
import { bridge } from '../lib/bridge';
|
||||||
@@ -48,7 +49,7 @@ export function pingCore(): void {
|
|||||||
useChat.getState().ping();
|
useChat.getState().ping();
|
||||||
}
|
}
|
||||||
|
|
||||||
function localToolContext() {
|
export function localToolContext(): LocalToolContext {
|
||||||
const chat = useChat.getState();
|
const chat = useChat.getState();
|
||||||
const settings = useSettings.getState().settings;
|
const settings = useSettings.getState().settings;
|
||||||
return {
|
return {
|
||||||
@@ -60,13 +61,20 @@ function localToolContext() {
|
|||||||
setTimeout(() => useChat.getState().setHudOverride(null), 6000);
|
setTimeout(() => useChat.getState().setHudOverride(null), 6000);
|
||||||
},
|
},
|
||||||
speak: (text: string) => speech.say(text),
|
speak: (text: string) => speech.say(text),
|
||||||
|
showMessage: (text: string, title?: string) => {
|
||||||
|
if (!text.trim()) return;
|
||||||
|
useChat.getState().addMessage({ role: 'assistant', content: text, source: 'hermes', jobName: title, status: 'done' });
|
||||||
|
},
|
||||||
getStatus: () => ({
|
getStatus: () => ({
|
||||||
transport: useHermes.getState().transport,
|
transport: useHermes.getState().transport,
|
||||||
link: useHermes.getState().link,
|
link: useHermes.getState().link,
|
||||||
assistant: settings.assistantName,
|
assistant: settings.assistantName,
|
||||||
messages: chat.messages.length,
|
messages: chat.messages.length,
|
||||||
speaking: speech.isSpeaking(),
|
speaking: speech.isSpeaking(),
|
||||||
handsFree: settings.voice.handsFree
|
handsFree: settings.voice.handsFree,
|
||||||
|
quietHours: chat.quiet,
|
||||||
|
missionMode: chat.missionMode,
|
||||||
|
wakeMode: settings.voice.wakeMode
|
||||||
}),
|
}),
|
||||||
getHistory: (n: number) => chat.messages.slice(-n).map((m) => ({ role: m.role, content: m.content })),
|
getHistory: (n: number) => chat.messages.slice(-n).map((m) => ({ role: m.role, content: m.content })),
|
||||||
notify: (title: string, body: string) => {
|
notify: (title: string, body: string) => {
|
||||||
@@ -231,7 +239,9 @@ export async function sendMessage(text: string, images: string[] = [], source =
|
|||||||
const timing = { firstToken: null as number | null, startedAt };
|
const timing = { firstToken: null as number | null, startedAt };
|
||||||
const runIdRef = { id: null as string | null };
|
const runIdRef = { id: null as string | null };
|
||||||
|
|
||||||
const client = hermes.client();
|
const mission = chat.missionMode && settings.hermes.missionModel.trim();
|
||||||
|
const client = hermes.client(mission ? settings.hermes.missionModel : undefined);
|
||||||
|
if (mission) Log.info('hermes', `mission mode → model ${settings.hermes.missionModel}`);
|
||||||
const handle = client.send(
|
const handle = client.send(
|
||||||
{
|
{
|
||||||
text: trimmed || 'Analyse cette image.',
|
text: trimmed || 'Analyse cette image.',
|
||||||
@@ -363,11 +373,17 @@ export function handlePush(event: HermesPushEvent): void {
|
|||||||
chat.pushActivity({ kind: 'job', name: event.jobName || 'cron', status: event.status?.includes('fail') ? 'error' : 'done', detail: previewText(event.text, 160) });
|
chat.pushActivity({ kind: 'job', name: event.jobName || 'cron', status: event.status?.includes('fail') ? 'error' : 'done', detail: previewText(event.text, 160) });
|
||||||
void useHermes.getState().refreshJobs();
|
void useHermes.getState().refreshJobs();
|
||||||
}
|
}
|
||||||
if (event.role !== 'user' && settings.speech.speakIncoming) {
|
const n = settings.notifications;
|
||||||
speech.say(event.jobName ? `Résultat de ${event.jobName}. ${event.text}` : event.text);
|
const priority = isPriority(event.text, n.priorityKeywords, event.jobName) || !!event.status?.includes('fail');
|
||||||
|
const silenced = chat.quiet && !priority;
|
||||||
|
if (document.hidden || silenced) chat.incUnread();
|
||||||
|
if (event.role !== 'user' && settings.speech.speakIncoming && !silenced) {
|
||||||
|
const body = n.summarizeIncoming ? summarize(event.text, n.summarySentences) : event.text;
|
||||||
|
speech.say(event.jobName ? `Résultat de ${event.jobName}. ${body}` : body);
|
||||||
}
|
}
|
||||||
|
if (silenced) Log.info('webhook', 'quiet hours: push shown silently');
|
||||||
chat.setHud(event.status?.includes('fail') ? 'alert' : 'success');
|
chat.setHud(event.status?.includes('fail') ? 'alert' : 'success');
|
||||||
pingCore();
|
if (!silenced) pingCore();
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const s = useChat.getState();
|
const s = useChat.getState();
|
||||||
if (s.hud === 'success' || s.hud === 'alert') s.setHud(speech.isSpeaking() ? 'speaking' : 'idle');
|
if (s.hud === 'success' || s.hud === 'alert') s.setHud(speech.isSpeaking() ? 'speaking' : 'idle');
|
||||||
|
|||||||
@@ -3,16 +3,35 @@
|
|||||||
* With the runs/sessions transports Hermes uses its own server-side toolsets instead.
|
* With the runs/sessions transports Hermes uses its own server-side toolsets instead.
|
||||||
*/
|
*/
|
||||||
import { bridge } from '../../lib/bridge';
|
import { bridge } from '../../lib/bridge';
|
||||||
|
import type { SystemAction } from '../../../shared/bridge';
|
||||||
|
|
||||||
export interface LocalToolContext {
|
export interface LocalToolContext {
|
||||||
setEmotion: (emotion: string) => void;
|
setEmotion: (emotion: string) => void;
|
||||||
|
showMessage?: (text: string, title?: string) => void;
|
||||||
speak: (text: string) => void;
|
speak: (text: string) => void;
|
||||||
getStatus: () => Record<string, unknown>;
|
getStatus: () => Record<string, unknown>;
|
||||||
getHistory: (n: number) => Array<{ role: string; content: string }>;
|
getHistory: (n: number) => Array<{ role: string; content: string }>;
|
||||||
notify: (title: string, body: string) => void;
|
notify: (title: string, body: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const fn = (name: string, description: string, properties: Record<string, unknown> = {}, required: string[] = []) => ({
|
||||||
|
type: 'function',
|
||||||
|
function: { name, description, parameters: { type: 'object', properties, required } }
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Tools executed on the user's PC through the Electron main process (allow-listed). */
|
||||||
|
export const SYSTEM_TOOL_DEFINITIONS = [
|
||||||
|
fn('lock_session', "Verrouille la session de l'utilisateur."),
|
||||||
|
fn('open_app', "Lance une application du PC de l'utilisateur (bloc-notes, calculatrice, chrome, spotify, vscode, terminal, explorateur…).", { name: { type: 'string' } }, ['name']),
|
||||||
|
fn('open_url', "Ouvre une URL http(s) dans le navigateur de l'utilisateur.", { url: { type: 'string' } }, ['url']),
|
||||||
|
fn('media_key', 'Touche média : volume-up, volume-down, mute, play-pause, next, previous.', { key: { type: 'string', enum: ['volume-up', 'volume-down', 'mute', 'play-pause', 'next', 'previous'] } }, ['key']),
|
||||||
|
fn('clipboard_get', 'Lit le texte du presse-papiers.'),
|
||||||
|
fn('clipboard_set', 'Place un texte dans le presse-papiers.', { text: { type: 'string' } }, ['text']),
|
||||||
|
fn('find_files', "Cherche des fichiers par nom dans Documents, Bureau, Téléchargements et Images (25 max).", { query: { type: 'string' } }, ['query'])
|
||||||
|
];
|
||||||
|
|
||||||
export const LOCAL_TOOL_DEFINITIONS = [
|
export const LOCAL_TOOL_DEFINITIONS = [
|
||||||
|
...SYSTEM_TOOL_DEFINITIONS,
|
||||||
{
|
{
|
||||||
type: 'function',
|
type: 'function',
|
||||||
function: {
|
function: {
|
||||||
@@ -95,6 +114,29 @@ export async function executeLocalTool(name: string, rawArgs: string, ctx: Local
|
|||||||
case 'notify_user':
|
case 'notify_user':
|
||||||
ctx.notify(String(args.title ?? 'EveFlow'), String(args.body ?? ''));
|
ctx.notify(String(args.title ?? 'EveFlow'), String(args.body ?? ''));
|
||||||
return JSON.stringify({ ok: true });
|
return JSON.stringify({ ok: true });
|
||||||
|
case 'show_message':
|
||||||
|
ctx.showMessage?.(String(args.text ?? ''), typeof args.title === 'string' ? args.title : undefined);
|
||||||
|
return JSON.stringify({ ok: true });
|
||||||
|
case 'lock_session':
|
||||||
|
case 'open_app':
|
||||||
|
case 'open_url':
|
||||||
|
case 'media_key':
|
||||||
|
case 'clipboard_get':
|
||||||
|
case 'clipboard_set':
|
||||||
|
case 'find_files': {
|
||||||
|
const api = bridge();
|
||||||
|
if (!api) return JSON.stringify({ error: 'system actions unavailable outside Electron' });
|
||||||
|
const action: SystemAction =
|
||||||
|
name === 'lock_session' ? { type: 'lock' }
|
||||||
|
: name === 'open_app' ? { type: 'open-app', name: String(args.name ?? '') }
|
||||||
|
: name === 'open_url' ? { type: 'open-url', url: String(args.url ?? '') }
|
||||||
|
: name === 'media_key' ? { type: 'media', key: String(args.key ?? '') as 'mute' }
|
||||||
|
: name === 'clipboard_get' ? { type: 'clipboard-read' }
|
||||||
|
: name === 'clipboard_set' ? { type: 'clipboard-write', text: String(args.text ?? '') }
|
||||||
|
: { type: 'find-files', query: String(args.query ?? '') };
|
||||||
|
const result = await api.system.action(action);
|
||||||
|
return JSON.stringify(result.ok ? { ok: true, message: result.message, data: result.data } : { error: result.message ?? 'failed' });
|
||||||
|
}
|
||||||
case 'write_shared_file': {
|
case 'write_shared_file': {
|
||||||
const api = bridge();
|
const api = bridge();
|
||||||
if (!api) return JSON.stringify({ error: 'file system unavailable outside Electron' });
|
if (!api) return JSON.stringify({ error: 'file system unavailable outside Electron' });
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ export interface HermesConfig {
|
|||||||
reasoningEffort: '' | 'low' | 'medium' | 'high';
|
reasoningEffort: '' | 'low' | 'medium' | 'high';
|
||||||
/** Extra instructions layered on top of the Hermes system prompt. */
|
/** Extra instructions layered on top of the Hermes system prompt. */
|
||||||
instructions: string;
|
instructions: string;
|
||||||
|
/** Model used in "mission" mode (long tasks); empty = same as `model`. */
|
||||||
|
missionModel: string;
|
||||||
/** Expose EveFlow client tools in chat-completions mode. */
|
/** Expose EveFlow client tools in chat-completions mode. */
|
||||||
localTools: boolean;
|
localTools: boolean;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
/**
|
||||||
|
* Answers tool calls that Hermes sends through the local MCP endpoint and that need the renderer
|
||||||
|
* (voice, notifications, HUD, chat). System tools are executed in the main process directly.
|
||||||
|
*/
|
||||||
|
import type { McpToolRequest } from '../../shared/ipc';
|
||||||
|
import { bridge } from '../lib/bridge';
|
||||||
|
import { Log } from '../lib/log';
|
||||||
|
import { useChat } from '../state/chat';
|
||||||
|
import { executeLocalTool, type LocalToolContext } from './hermes/localTools';
|
||||||
|
|
||||||
|
let unsubscribe: (() => void) | null = null;
|
||||||
|
|
||||||
|
export function initMcpBridge(context: () => LocalToolContext): void {
|
||||||
|
const api = bridge();
|
||||||
|
if (!api || unsubscribe) return;
|
||||||
|
unsubscribe = api.hermes.onToolRequest((req: McpToolRequest) => {
|
||||||
|
void handle(req, context)
|
||||||
|
.then((result) => api.hermes.toolResponse({ id: req.id, ok: true, result }))
|
||||||
|
.catch((err: Error) => api.hermes.toolResponse({ id: req.id, ok: false, error: err.message }));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handle(req: McpToolRequest, context: () => LocalToolContext): Promise<unknown> {
|
||||||
|
Log.info('mcp', `tool ${req.name}`);
|
||||||
|
const chat = useChat.getState();
|
||||||
|
if (req.name === 'show_message') {
|
||||||
|
const text = String(req.args.text ?? '');
|
||||||
|
if (!text.trim()) throw new Error('texte vide');
|
||||||
|
chat.addMessage({ role: 'assistant', content: text, source: 'mcp', jobName: typeof req.args.title === 'string' ? req.args.title : undefined, status: 'done' });
|
||||||
|
chat.pushActivity({ kind: 'system', name: 'hermes → eveflow', status: 'done', detail: text.slice(0, 160) });
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
const raw = await executeLocalTool(req.name, JSON.stringify(req.args ?? {}), context());
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw) as { error?: string };
|
||||||
|
if (parsed && typeof parsed === 'object' && parsed.error) throw new Error(parsed.error);
|
||||||
|
return parsed;
|
||||||
|
} catch (err) {
|
||||||
|
if ((err as Error).message && !(err instanceof SyntaxError)) throw err;
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -242,6 +242,8 @@ class VoiceController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const sensitivity = Math.min(5, Math.max(1, Math.round(settings.sensitivity))) as 1 | 2 | 3 | 4 | 5;
|
const sensitivity = Math.min(5, Math.max(1, Math.round(settings.sensitivity))) as 1 | 2 | 3 | 4 | 5;
|
||||||
|
// Barge-in: while the assistant talks, demand a clearly louder signal so the speaker echo cannot trigger.
|
||||||
|
const barging = auto && settings.bargeIn && speech.isSpeaking();
|
||||||
try {
|
try {
|
||||||
await audioBus.resume();
|
await audioBus.resume();
|
||||||
await this.capture.start({
|
await this.capture.start({
|
||||||
@@ -249,8 +251,8 @@ class VoiceController {
|
|||||||
mode: settings.captureMode,
|
mode: settings.captureMode,
|
||||||
vad: {
|
vad: {
|
||||||
silenceMs: settings.silenceMs,
|
silenceMs: settings.silenceMs,
|
||||||
speechRatio: SENSITIVITY_RATIO[sensitivity],
|
speechRatio: barging ? Math.min(0.9, SENSITIVITY_RATIO[sensitivity] + 0.15) : SENSITIVITY_RATIO[sensitivity],
|
||||||
minRms: SENSITIVITY_MIN_RMS[sensitivity],
|
minRms: barging ? SENSITIVITY_MIN_RMS[sensitivity] * 2.5 : SENSITIVITY_MIN_RMS[sensitivity],
|
||||||
noSpeechTimeoutMs: useVoice.getState().handsFree ? Number.POSITIVE_INFINITY : 9_000
|
noSpeechTimeoutMs: useVoice.getState().handsFree ? Number.POSITIVE_INFINITY : 9_000
|
||||||
},
|
},
|
||||||
callbacks: {
|
callbacks: {
|
||||||
@@ -259,6 +261,8 @@ class VoiceController {
|
|||||||
if (q !== useVoice.getState().inputLevel) useVoice.getState().setInputLevel(q);
|
if (q !== useVoice.getState().inputLevel) useVoice.getState().setInputLevel(q);
|
||||||
},
|
},
|
||||||
onSpeechStart: () => {
|
onSpeechStart: () => {
|
||||||
|
// The user started talking over the assistant: cut the voice (barge-in).
|
||||||
|
if (speech.isSpeaking()) speech.stop();
|
||||||
useVoice.getState().setPhase('speech');
|
useVoice.getState().setPhase('speech');
|
||||||
useChat.getState().ping();
|
useChat.getState().ping();
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -57,6 +57,16 @@ interface ChatStore {
|
|||||||
pingCount: number;
|
pingCount: number;
|
||||||
/** Time to first token of the current reply, in ms. */
|
/** Time to first token of the current reply, in ms. */
|
||||||
latencyMs: number | null;
|
latencyMs: number | null;
|
||||||
|
/** Pushes received while the window was hidden / compact, cleared when the user looks. */
|
||||||
|
unread: number;
|
||||||
|
/** Mission mode routes the next messages to the "mission" model (long tasks). */
|
||||||
|
missionMode: boolean;
|
||||||
|
/** True while quiet hours apply (computed by App). */
|
||||||
|
quiet: boolean;
|
||||||
|
incUnread: () => void;
|
||||||
|
markRead: () => void;
|
||||||
|
setMissionMode: (on: boolean) => void;
|
||||||
|
setQuiet: (quiet: boolean) => void;
|
||||||
|
|
||||||
addMessage: (message: Omit<ChatMessage, 'id' | 'timestamp'> & Partial<Pick<ChatMessage, 'id' | 'timestamp'>>) => string;
|
addMessage: (message: Omit<ChatMessage, 'id' | 'timestamp'> & Partial<Pick<ChatMessage, 'id' | 'timestamp'>>) => string;
|
||||||
updateMessage: (id: string, patch: Partial<ChatMessage> | ((m: ChatMessage) => Partial<ChatMessage>)) => void;
|
updateMessage: (id: string, patch: Partial<ChatMessage> | ((m: ChatMessage) => Partial<ChatMessage>)) => void;
|
||||||
@@ -91,6 +101,13 @@ export const useChat = create<ChatStore>((set, get) => ({
|
|||||||
draft: '',
|
draft: '',
|
||||||
pingCount: 0,
|
pingCount: 0,
|
||||||
latencyMs: null,
|
latencyMs: null,
|
||||||
|
unread: 0,
|
||||||
|
missionMode: false,
|
||||||
|
quiet: false,
|
||||||
|
incUnread: () => set((s) => ({ unread: Math.min(99, s.unread + 1) })),
|
||||||
|
markRead: () => set((s) => (s.unread ? { unread: 0 } : {})),
|
||||||
|
setMissionMode: (missionMode) => set({ missionMode }),
|
||||||
|
setQuiet: (quiet) => set((s) => (s.quiet === quiet ? {} : { quiet })),
|
||||||
|
|
||||||
addMessage: (message) => {
|
addMessage: (message) => {
|
||||||
const id = message.id ?? uid('msg');
|
const id = message.id ?? uid('msg');
|
||||||
|
|||||||
+3
-3
@@ -43,7 +43,7 @@ interface HermesStore {
|
|||||||
webhook: WebhookStatus | null;
|
webhook: WebhookStatus | null;
|
||||||
busy: boolean;
|
busy: boolean;
|
||||||
|
|
||||||
client: () => HermesClient;
|
client: (modelOverride?: string) => HermesClient;
|
||||||
connect: () => Promise<void>;
|
connect: () => Promise<void>;
|
||||||
refreshJobs: () => Promise<void>;
|
refreshJobs: () => Promise<void>;
|
||||||
refreshSessions: () => Promise<void>;
|
refreshSessions: () => Promise<void>;
|
||||||
@@ -93,10 +93,10 @@ export const useHermes = create<HermesStore>((set, get) => ({
|
|||||||
webhook: null,
|
webhook: null,
|
||||||
busy: false,
|
busy: false,
|
||||||
|
|
||||||
client: () => {
|
client: (modelOverride) => {
|
||||||
const config = useSettings.getState().settings.hermes;
|
const config = useSettings.getState().settings.hermes;
|
||||||
// Without an explicit model, use the alias advertised by /v1/models (Hermes rejects unknown names).
|
// Without an explicit model, use the alias advertised by /v1/models (Hermes rejects unknown names).
|
||||||
const model = config.model.trim() || get().models[0]?.id || '';
|
const model = (modelOverride ?? '').trim() || config.model.trim() || get().models[0]?.id || '';
|
||||||
return new HermesClient({ ...config, model });
|
return new HermesClient({ ...config, model });
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
+18
-1
@@ -39,6 +39,20 @@ export interface WebhookSettings {
|
|||||||
secret: string;
|
secret: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface NotificationSettings {
|
||||||
|
/** Quiet hours: no spoken pushes, no chime, dimmed HUD (24 h "HH:MM"). */
|
||||||
|
quietEnabled: boolean;
|
||||||
|
quietStart: string;
|
||||||
|
quietEnd: string;
|
||||||
|
/** Pushes whose text or job name contains one of these words are spoken even during quiet hours. */
|
||||||
|
priorityKeywords: string;
|
||||||
|
/** Speak only the first sentences of incoming pushes (cron reports can be long). */
|
||||||
|
summarizeIncoming: boolean;
|
||||||
|
summarySentences: number;
|
||||||
|
/** Dim the HUD (night theme) during quiet hours. */
|
||||||
|
nightTheme: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Settings {
|
export interface Settings {
|
||||||
version: 2;
|
version: 2;
|
||||||
assistantName: string;
|
assistantName: string;
|
||||||
@@ -49,6 +63,7 @@ export interface Settings {
|
|||||||
voice: VoiceSettings;
|
voice: VoiceSettings;
|
||||||
speech: SpeechSettings;
|
speech: SpeechSettings;
|
||||||
webhook: WebhookSettings;
|
webhook: WebhookSettings;
|
||||||
|
notifications: NotificationSettings;
|
||||||
ui: {
|
ui: {
|
||||||
showTelemetry: boolean;
|
showTelemetry: boolean;
|
||||||
showReasoning: boolean;
|
showReasoning: boolean;
|
||||||
@@ -73,7 +88,8 @@ export const DEFAULT_SETTINGS: Settings = {
|
|||||||
reasoningEffort: '',
|
reasoningEffort: '',
|
||||||
instructions:
|
instructions:
|
||||||
"Tu es l'interface vocale EveFlow (style JARVIS). Réponds en français, de façon concise et orale quand la question est simple; utilise le Markdown uniquement pour le contenu structuré (code, listes, tableaux). Les images doivent être des URL http(s) ou des fichiers du dossier partagé.",
|
"Tu es l'interface vocale EveFlow (style JARVIS). Réponds en français, de façon concise et orale quand la question est simple; utilise le Markdown uniquement pour le contenu structuré (code, listes, tableaux). Les images doivent être des URL http(s) ou des fichiers du dossier partagé.",
|
||||||
localTools: true
|
localTools: true,
|
||||||
|
missionModel: ''
|
||||||
},
|
},
|
||||||
voice: {
|
voice: {
|
||||||
provider: 'openai-compatible',
|
provider: 'openai-compatible',
|
||||||
@@ -113,6 +129,7 @@ export const DEFAULT_SETTINGS: Settings = {
|
|||||||
speakIncoming: true
|
speakIncoming: true
|
||||||
},
|
},
|
||||||
webhook: { enabled: true, port: 7842, secret: '' },
|
webhook: { enabled: true, port: 7842, secret: '' },
|
||||||
|
notifications: { quietEnabled: false, quietStart: '22:30', quietEnd: '07:30', priorityKeywords: 'urgent, alerte, alarme, panne', summarizeIncoming: true, summarySentences: 2, nightTheme: true },
|
||||||
ui: { showTelemetry: true, showReasoning: false, reduceMotion: false, compactOpacity: 0.92 },
|
ui: { showTelemetry: true, showReasoning: false, reduceMotion: false, compactOpacity: 0.92 },
|
||||||
hermesSessionId: ''
|
hermesSessionId: ''
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -67,3 +67,54 @@
|
|||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
padding: 8px 11px;
|
padding: 8px 11px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Glanceable strip: state, unread badge, last sentence. */
|
||||||
|
.compact-glance {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: auto 1fr auto;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 4px 12px 8px;
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 10.5px;
|
||||||
|
letter-spacing: 0.12em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--ink-2);
|
||||||
|
}
|
||||||
|
.compact-glance .state {
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
.compact-glance .state.alert {
|
||||||
|
color: var(--danger);
|
||||||
|
}
|
||||||
|
.compact-glance .last {
|
||||||
|
font-family: var(--font-body);
|
||||||
|
font-size: 12.5px;
|
||||||
|
letter-spacing: 0;
|
||||||
|
text-transform: none;
|
||||||
|
color: var(--ink-1);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
.compact-glance .badges {
|
||||||
|
display: flex;
|
||||||
|
gap: 6px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.compact-glance .unread {
|
||||||
|
min-width: 18px;
|
||||||
|
height: 18px;
|
||||||
|
padding: 0 5px;
|
||||||
|
border-radius: 9px;
|
||||||
|
background: var(--accent);
|
||||||
|
color: #03101c;
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 11px;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
.compact-glance .mission {
|
||||||
|
color: var(--warn, #f5c451);
|
||||||
|
}
|
||||||
@@ -159,3 +159,15 @@ textarea {
|
|||||||
.kv dd {
|
.kv dd {
|
||||||
user-select: text;
|
user-select: text;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Quiet hours: dimmer HUD, softer glow. */
|
||||||
|
:root[data-night] {
|
||||||
|
--accent-glow: rgba(var(--accent-rgb), 0.18);
|
||||||
|
}
|
||||||
|
:root[data-night] .hud-root,
|
||||||
|
:root[data-night] .compact-root {
|
||||||
|
filter: brightness(0.72) saturate(0.85);
|
||||||
|
}
|
||||||
|
:root[data-night] .core-stage canvas {
|
||||||
|
opacity: 0.8;
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { isPriority, isQuietTime, summarize } from '../src/lib/quietHours';
|
||||||
|
|
||||||
|
const at = (h: number, m = 0) => new Date(2026, 0, 1, h, m);
|
||||||
|
|
||||||
|
describe('isQuietTime', () => {
|
||||||
|
it('handles ranges crossing midnight', () => {
|
||||||
|
expect(isQuietTime('22:30', '07:30', at(23))).toBe(true);
|
||||||
|
expect(isQuietTime('22:30', '07:30', at(3, 15))).toBe(true);
|
||||||
|
expect(isQuietTime('22:30', '07:30', at(7, 30))).toBe(false);
|
||||||
|
expect(isQuietTime('22:30', '07:30', at(12))).toBe(false);
|
||||||
|
});
|
||||||
|
it('handles same-day ranges and invalid input', () => {
|
||||||
|
expect(isQuietTime('13:00', '14:00', at(13, 30))).toBe(true);
|
||||||
|
expect(isQuietTime('13:00', '14:00', at(14))).toBe(false);
|
||||||
|
expect(isQuietTime('bad', '14:00', at(13))).toBe(false);
|
||||||
|
expect(isQuietTime('10:00', '10:00', at(10))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isPriority', () => {
|
||||||
|
it('matches keywords in text or job name', () => {
|
||||||
|
expect(isPriority('Serveur en panne depuis 5 min', 'urgent, panne')).toBe(true);
|
||||||
|
expect(isPriority('Rapport quotidien', 'urgent', 'Alerte disque')).toBe(false);
|
||||||
|
expect(isPriority('Rapport quotidien', 'alerte', 'Alerte disque')).toBe(true);
|
||||||
|
expect(isPriority('x', '')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('summarize', () => {
|
||||||
|
it('keeps the first sentences and strips markdown', () => {
|
||||||
|
const text = '## Rapport\n\nTrois annonces **majeures** aujourd’hui. Le marché monte de 2 %. Détails ci-dessous :\n\n```\ncode\n```\n- point 1';
|
||||||
|
expect(summarize(text, 2)).toBe('Rapport Trois annonces majeures aujourd’hui. Le marché monte de 2 %.');
|
||||||
|
expect(summarize('Une seule phrase', 2)).toBe('Une seule phrase');
|
||||||
|
expect(summarize('', 2)).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user