henergyqueai 0.9.5 → 0.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2336 +1,2360 @@
1
- import React, { useEffect, useMemo, useRef, useState } from "react";
2
- import { Box, Text, render, useApp, useInput, useStdout } from "ink";
3
- import { randomUUID } from "node:crypto";
4
- import { EventEmitter } from "node:events";
5
- import { Readable } from "node:stream";
6
- import { readFileSync } from "node:fs";
7
- import { appendFile, readFile, writeFile } from "node:fs/promises";
8
- import { homedir } from "node:os";
9
- import path from "node:path";
10
- import { execute } from "./tools.js";
11
- import { MODES, saveUserSetting } from "./reglages.js";
12
- import { listSessions, saveSession } from "./sessions.js";
13
- import { HEIGHT as LOGO_HEIGHT, WIDTH as LOGO_WIDTH, creature } from "./butterfly.js";
14
- import { interactiveDefinitions, runAgentTurn } from "./agent-loop.js";
15
- import { compactHistory, historySize } from "./compact.js";
16
- import { listTasks, manageTasks } from "./tasks.js";
17
- import { contextReport, diagnose } from "./diagnostic.js";
18
- import { listSkills, readSkill } from "./skills.js";
19
- import { getUsage } from "./client.js";
20
- import { MCP_CONFIG } from "./mcp.js";
21
- import { expandReferences, referencedImages, visibleQuestion } from "./references.js";
22
- import { projectContext } from "./contexte.js";
23
- import { createCheckpoints } from "./checkpoints.js";
24
- import { listJobs, stopAll, stopJob } from "./background.js";
25
- import { clipboardImage, copyText } from "./clipboard.js";
26
- import { loadHistory, remember } from "./history.js";
27
- import { conversationMarkdown } from "./export.js";
28
- import { HOOK_EVENTS, countHooks } from "./hooks.js";
29
-
30
- const h = React.createElement;
31
- const VERSION = (() => {
32
- try {
33
- return JSON.parse(
34
- readFileSync(new URL("../package.json", import.meta.url), "utf8"),
35
- ).version;
36
- } catch {
37
- return "";
38
- }
39
- })();
40
-
41
- const MODELS = { velys: "Velys", oryne: "Oryne", aelyr: "Aelyr" };
42
- const MODEL_NOTES = {
43
- velys: "Pour vos idées du quotidien",
44
- oryne: "Pour écrire et améliorer votre code",
45
- aelyr: "Pour les projets exigeants",
46
- };
47
- const THEMES = {
48
- papillon: { accent: "#c46c4f", muted: "#8b8d83", code: "#e3a07c" },
49
- aube: { accent: "#d69150", muted: "#9b9185", code: "#e8b782" },
50
- nuit: { accent: "#b49ad5", muted: "#9699a6", code: "#c7b5ea" },
51
- };
52
- const COLORS = {
53
- success: "#5fb86b",
54
- error: "#e0605e",
55
- warning: "#d9a441",
56
- added: "#1f4d2c",
57
- removed: "#5c2230",
58
- shell: "#d7609b",
59
- edits: "#a987e6",
60
- plan: "#4fa39a",
61
- border: "#6b6d66",
62
- };
63
- const MODE_HINTS = {
64
- "accepter-modifications": ["⏵⏵ modifications acceptées", COLORS.edits],
65
- plan: ["⏸ mode plan", COLORS.plan],
66
- "lecture-seule": ["◼ lecture seule", COLORS.plan],
67
- "sans-demander": ["⏵⏵ aucune autorisation demandée", COLORS.error],
68
- };
69
- // Maj+Tab fait tourner ces trois modes, les deux autres restent dans /mode.
70
- const MODE_CYCLE = ["demander", "accepter-modifications", "plan"];
71
- const GLYPHS = ["·", "∗", "✧", "✦", "✶", "✦", "✧", "∗"];
72
- // Ce qui s'affiche pendant l'attente, puis une fois la réponse terminée.
73
- const VERBS = [
74
- ["Réflexion", "Réfléchi"],
75
- ["Butinage", "Butiné"],
76
- ["Cogitation", "Cogité"],
77
- ["Envol", "Envolé"],
78
- ["Méditation", "Médité"],
79
- ["Élaboration", "Élaboré"],
80
- ["Maturation", "Mûri"],
81
- ["Pollinisation", "Pollinisé"],
82
- ["Métamorphose", "Métamorphosé"],
83
- ["Déploiement des ailes", "Déployé"],
84
- ["Vol plané", "Plané"],
85
- ["Distillation", "Distillé"],
86
- ["Exploration", "Exploré"],
87
- ["Papillonnage", "Papillonné"],
88
- ];
89
- const TIPS = [
90
- "/mode pour autoriser ou bloquer les modifications et les commandes",
91
- "@ suivi d’un nom de fichier le joint à votre demande",
92
- "! devant une commande l’exécute directement dans le terminal",
93
- "Maj+Tab passe en mode plan pour préparer sans rien modifier",
94
- "/compact résume la conversation quand elle devient longue",
95
- "Échap interrompt la réponse en cours",
96
- "/reprendre rouvre une conversation précédente",
97
- "PgUp et PgDn font défiler la conversation",
98
- "Un fichier HENERGYQUEAI.md donne vos consignes à chaque demande",
99
- "Échap deux fois pour revenir à une demande précédente et annuler ses modifications",
100
- "# au début d’un message ajoute une consigne au projet",
101
- "Ctrl+O affiche le détail des outils, Ctrl+R cherche dans l’historique",
102
- "Alt+V colle une capture d’écran",
103
- "/init prépare le fichier HENERGYQUEAI.md du projet",
104
- ];
105
- const EXAMPLES = [
106
- "explique l’architecture de ce projet",
107
- "corrige le test qui échoue",
108
- "ajoute des tests pour ce module",
109
- "trouve pourquoi la page se charge lentement",
110
- ];
111
- const pick = (list) => list[Math.floor(Math.random() * list.length)];
112
- const SHELL_MARKER = "\n\n--- Commandes lancées par l’utilisateur ---\n";
113
- const NOTE_MARKER = "\n\n--- Consignes ajoutées au projet ---\n";
114
- const HEADER_HEIGHT = LOGO_HEIGHT + 2;
115
- const LONG_TURN = 30000;
116
- const INIT_PROMPT =
117
- "Analyse ce projet : structure, commandes d’installation, de build, de test et de lancement, architecture d’ensemble et conventions qui ne se devinent pas en lisant un seul fichier. Crée ensuite à la racine un fichier HENERGYQUEAI.md concis, destiné à un assistant de code qui découvre le projet. S’il existe déjà, améliore-le sans perdre ce qu’il contient. N’invente rien, ne liste pas chaque fichier et reste court.";
118
- const IMAGE_TAG = /\[Image n°(\d+)\]/g;
119
-
120
- export const COMMANDS = [
121
- { name: "aide", aliases: ["help"], description: "Afficher l’aide et les raccourcis" },
122
- { name: "compact", description: "Résumer la conversation pour libérer du contexte" },
123
- { name: "competences", aliases: ["skills"], description: "Parcourir les compétences du projet" },
124
- { name: "contexte", aliases: ["context"], description: "Voir le contexte utilisé" },
125
- { name: "couleurs", aliases: ["theme"], description: "Changer les couleurs de l’interface" },
126
- { name: "diagnostic", aliases: ["doctor"], description: "Vérifier l’installation et le service" },
127
- { name: "diff", description: "Afficher les modifications Git non indexées" },
128
- { name: "effacer", aliases: ["clear"], description: "Commencer une nouvelle conversation" },
129
- { name: "exporter", aliases: ["export"], description: "Copier ou enregistrer la conversation en Markdown" },
130
- { name: "fichiers", description: "Parcourir les fichiers du projet" },
131
- { name: "git", description: "Afficher l’état Git du projet" },
132
- { name: "hooks", description: "Voir les commandes lancées autour des outils" },
133
- { name: "init", description: "Créer ou améliorer le fichier HENERGYQUEAI.md du projet" },
134
- { name: "mcp", description: "Voir les serveurs MCP connectés" },
135
- { name: "menu", description: "Ouvrir toutes les actions" },
136
- { name: "mode", description: "Choisir le mode d’autorisation" },
137
- { name: "modele", aliases: ["model"], description: "Choisir l’assistant : Velys, Oryne ou Aelyr" },
138
- { name: "plan", description: "Activer ou couper le mode plan" },
139
- { name: "processus", aliases: ["bashes", "jobs"], description: "Voir et arrêter les commandes en arrière-plan" },
140
- { name: "quitter", aliases: ["exit", "q"], description: "Quitter HenergyqueAI" },
141
- { name: "rembobiner", aliases: ["rewind"], description: "Revenir à une demande précédente (échap échap)" },
142
- { name: "reprendre", aliases: ["resume", "sessions"], description: "Reprendre une conversation précédente" },
143
- { name: "revue", aliases: ["review"], description: "Relire les modifications Git du projet" },
144
- { name: "statut", aliases: ["status"], description: "Voir l’assistant, le mode et le projet" },
145
- { name: "taches", aliases: ["tasks"], description: "Voir et cocher les tâches du projet" },
146
- { name: "utilisation", aliases: ["usage", "cout"], description: "Voir le quota du jour" },
147
- ];
148
- const findCommand = (name) =>
149
- COMMANDS.find(
150
- (command) => command.name === name || command.aliases?.includes(name),
151
- );
152
-
153
- let sequence = 0;
154
- const entry = (fields) => ({ id: ++sequence, ...fields });
155
-
156
- const textContent = (content) =>
157
- Array.isArray(content)
158
- ? content.filter((part) => part.type === "text").map((part) => part.text).join("\n")
159
- : String(content || "");
160
- const cleanQuestion = (content) =>
161
- visibleQuestion(textContent(content).split(SHELL_MARKER)[0].split(NOTE_MARKER)[0]);
162
-
163
- const plural = (count, one, many) =>
164
- `${count.toLocaleString("fr-FR")} ${count > 1 ? many : one}`;
165
- const formatTokens = (count) =>
166
- count < 1000
167
- ? String(count)
168
- : `${(count / 1000).toFixed(1).replace(".", ",")} k`;
169
- const since = (date) => {
170
- const minutes = Math.round((Date.now() - date) / 60000);
171
- if (minutes < 1) return "à l’instant";
172
- if (minutes < 60) return `il y a ${minutes} min`;
173
- if (minutes < 1440) return `il y a ${Math.round(minutes / 60)} h`;
174
- return `il y a ${Math.round(minutes / 1440)} j`;
175
- };
176
- const firstLine = (value, limit = 100) => {
177
- const [line = "", ...rest] = String(value ?? "").split("\n");
178
- return line.length > limit || rest.length
179
- ? `${line.slice(0, limit)}…`
180
- : line;
181
- };
182
-
183
- function initialLog(messages, model) {
184
- return messages
185
- .filter(
186
- (message) =>
187
- (message.role === "user" && typeof message.content === "string") ||
188
- (message.role === "assistant" && String(message.content || "").trim()),
189
- )
190
- .map((message, index, all) =>
191
- message.role === "user"
192
- ? entry({ kind: "user", text: cleanQuestion(message.content) })
193
- : entry({
194
- kind: "assistant",
195
- text: String(message.content),
196
- model: MODELS[model],
197
- header: all[index - 1]?.role !== "assistant",
198
- }),
199
- );
200
- }
201
-
202
- // Ce que chaque outil affiche : un nom lisible et son argument principal.
203
- export function toolLabel(name, args = {}) {
204
- if (name.startsWith("mcp_")) return ["MCP", name.slice(4)];
205
- const labels = {
206
- lire_fichier: ["Lire", args.chemin],
207
- lister_fichiers: ["Lister", args.dossier || "."],
208
- chercher: [
209
- "Chercher",
210
- `« ${args.motif ?? ""} »${args.dossier ? ` dans ${args.dossier}` : ""}`,
211
- ],
212
- trouver_fichiers: ["Trouver", args.motif],
213
- editer_fichier: ["Modifier", args.chemin],
214
- ecrire_fichier: ["Écrire", args.chemin],
215
- executer: [
216
- args.arriere_plan ? "Arrière-plan" : "Terminal",
217
- args.commande,
218
- ],
219
- etat_git: ["Git", "status"],
220
- diff_git: ["Git", `diff${args.chemin ? ` ${args.chemin}` : ""}`],
221
- gerer_taches: ["Tâches", args.action],
222
- competence: ["Compétence", args.nom || args.action],
223
- recherche_web: ["Web", `« ${args.requete ?? ""} »`],
224
- lire_une_page: ["Page", args.url],
225
- sortie_commande: ["Sortie", args.id],
226
- arreter_commande: ["Arrêt", args.id],
227
- poser_question: ["Question", args.question],
228
- proposer_plan: ["Plan", ""],
229
- deleguer: ["Agent", args.description],
230
- };
231
- const [label, detail] = labels[name] || [name, ""];
232
- return [label, detail ? firstLine(detail) : ""];
233
- }
234
-
235
- // La ligne « ⎿ » sous un outil terminé.
236
- export function toolSummary(name, result, diff) {
237
- const text = String(result ?? "");
238
- const lines = text.split("\n");
239
- const head = (count) =>
240
- lines.length > count
241
- ? [...lines.slice(0, count), `… +${plural(lines.length - count, "ligne", "lignes")}`]
242
- : lines;
243
- if (/^(L’utilisateur a refusé|Action refusée|Action annulée|Bloqué par un hook|Échec de l’outil)/.test(text))
244
- return { tone: "error", lines: [lines[0]] };
245
- if (name === "recherche_web" || name === "lire_une_page") {
246
- if (/^(Web indisponible|Adresse invalide|La recherche web)/.test(text))
247
- return { tone: "error", lines: [lines[0]] };
248
- if (name === "lire_une_page") return { lines: [`Page lue : ${firstLine(lines[0], 70)}`] };
249
- const found = lines.filter((line) => /^\d+\. /.test(line)).length;
250
- return { lines: [found ? plural(found, "résultat", "résultats") : lines[0]] };
251
- }
252
- if (name === "deleguer")
253
- return /^Le sous-agent/.test(text)
254
- ? { tone: "error", lines: [lines[0]] }
255
- : { lines: [`Compte rendu reçu (${plural(lines.length, "ligne", "lignes")})`] };
256
- if (name === "proposer_plan" || name === "poser_question")
257
- return { lines: [firstLine(text, 90)] };
258
- if (name === "lire_fichier")
259
- return /^1\t/.test(text)
260
- ? { lines: [plural(lines.length, "ligne lue", "lignes lues")] }
261
- : { tone: "error", lines: [lines[0]] };
262
- if (name === "lister_fichiers" || name === "trouver_fichiers")
263
- return /^Aucun/.test(text)
264
- ? { lines: [lines[0]] }
265
- : { lines: [plural(lines.filter(Boolean).length, "fichier trouvé", "fichiers trouvés")] };
266
- if (name === "chercher")
267
- return /^Aucune/.test(text)
268
- ? { lines: [lines[0]] }
269
- : { lines: [plural(lines.filter(Boolean).length, "résultat", "résultats")] };
270
- if (name === "editer_fichier" || name === "ecrire_fichier") {
271
- if (!diff || !/(modifié|enregistré)\.$/.test(text))
272
- return { tone: "error", lines: [lines[0]] };
273
- if (diff.created)
274
- return { lines: [`${plural(diff.added, "ligne écrite", "lignes écrites")} dans ${diff.path}`] };
275
- return {
276
- lines: [
277
- `Mis à jour : ${plural(diff.added, "ajout", "ajouts")} et ${plural(diff.removed, "suppression", "suppressions")}`,
278
- ],
279
- };
280
- }
281
- if (name === "executer")
282
- return { tone: /^Échec/.test(text) ? "error" : undefined, lines: head(4) };
283
- return { lines: head(3) };
284
- }
285
-
286
- // Les trois réponses possibles à une demande d'autorisation.
287
- export function approvalOptions({ name, args = {} }) {
288
- const second =
289
- name === "executer"
290
- ? `Oui, et ne plus demander pour « ${firstLine(args.commande, 40)} » pendant cette session`
291
- : name.startsWith("mcp_")
292
- ? "Oui, et ne plus demander pour cet outil pendant cette session"
293
- : "Oui, et accepter toutes les modifications de cette session (maj+tab)";
294
- return [
295
- "Oui",
296
- second,
297
- "Non, et dire à HenergyqueAI quoi faire autrement (échap)",
298
- ];
299
- }
300
-
301
- // --- Mise en lignes -------------------------------------------------------
302
- // La conversation est découpée en lignes de terminal déjà coupées à la bonne
303
- // largeur : la zone du milieu peut alors défiler ligne par ligne, entre le
304
- // papillon toujours visible en haut et la saisie fixée en bas.
305
-
306
- const seg = (text, style = {}) => ({ text: String(text), ...style });
307
- const blank = () => [seg("")];
308
-
309
- function wrapSegments(prefix, body, width, next) {
310
- const following = next || [seg(" ".repeat(prefix.reduce((n, p) => n + p.text.length, 0)))];
311
- const room = (pre) =>
312
- Math.max(8, width - pre.reduce((n, p) => n + p.text.length, 0));
313
- const rows = [];
314
- let current = [...prefix];
315
- let used = 0;
316
- let limit = room(prefix);
317
- const newline = () => {
318
- rows.push(current);
319
- current = [...following];
320
- used = 0;
321
- limit = room(following);
322
- };
323
- for (const part of body) {
324
- for (const token of part.text.split(/(\s+)/)) {
325
- if (!token) continue;
326
- let text = token;
327
- const space = /^\s+$/.test(text);
328
- if (space && used === 0 && rows.length) continue;
329
- while (text) {
330
- if (used + text.length <= limit) {
331
- current.push({ ...part, text });
332
- used += text.length;
333
- text = "";
334
- } else if (space) {
335
- newline();
336
- text = "";
337
- } else if (used === 0) {
338
- current.push({ ...part, text: text.slice(0, limit) });
339
- text = text.slice(limit);
340
- newline();
341
- } else newline();
342
- }
343
- }
344
- }
345
- rows.push(current);
346
- return rows;
347
- }
348
-
349
- const INLINE =
350
- /(\*\*[^*\n]+\*\*|`[^`\n]+`|(?<![\w*])\*[^*\s][^*\n]*\*(?![\w*])|(?<![\w_])_[^_\s][^_\n]*_(?![\w_]))/;
351
- function inlineSegments(text, palette, base = {}) {
352
- return text
353
- .split(INLINE)
354
- .filter(Boolean)
355
- .map((part) => {
356
- if (/^\*\*.+\*\*$/.test(part)) return seg(part.slice(2, -2), { ...base, bold: true });
357
- if (/^`.+`$/.test(part)) return seg(part.slice(1, -1), { ...base, color: palette.code });
358
- if (/^\*.+\*$|^_.+_$/.test(part)) return seg(part.slice(1, -1), { ...base, italic: true });
359
- return seg(part, base);
360
- });
361
- }
362
-
363
- function markdownRows(text, palette, width, indent = " ") {
364
- const rows = [];
365
- let fence = false;
366
- const lines = String(text || "").replace(/^\s*\n/, "").trimEnd().split("\n");
367
- for (const line of lines) {
368
- if (/^\s*```/.test(line)) {
369
- fence = !fence;
370
- continue;
371
- }
372
- if (fence) {
373
- rows.push(...wrapSegments([seg(`${indent} `)], [seg(line || " ", { color: palette.code })], width));
374
- continue;
375
- }
376
- const heading = /^#{1,6}\s+(.*)$/.exec(line);
377
- if (heading) {
378
- rows.push(...wrapSegments([seg(indent)], inlineSegments(heading[1], palette, { bold: true }), width));
379
- continue;
380
- }
381
- const quote = /^>\s?(.*)$/.exec(line);
382
- if (quote) {
383
- rows.push(
384
- ...wrapSegments(
385
- [seg(indent), seg("▎ ", { color: palette.muted })],
386
- inlineSegments(quote[1], palette, { italic: true, color: palette.muted }),
387
- width,
388
- ),
389
- );
390
- continue;
391
- }
392
- if (/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/.test(line)) {
393
- rows.push([seg(indent), seg("─".repeat(24), { color: palette.muted })]);
394
- continue;
395
- }
396
- const item = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(line);
397
- if (item) {
398
- const bullet = /\d/.test(item[2]) ? `${item[2]} ` : "• ";
399
- rows.push(
400
- ...wrapSegments(
401
- [seg(indent + item[1]), seg(bullet, { color: palette.accent })],
402
- inlineSegments(item[3], palette),
403
- width,
404
- ),
405
- );
406
- continue;
407
- }
408
- rows.push(...(line.trim() ? wrapSegments([seg(indent)], inlineSegments(line, palette), width) : [blank()]));
409
- }
410
- return rows;
411
- }
412
-
413
- function diffRows(diff, palette, width, indent = "", limit = 40) {
414
- const numbers = diff.lines.map((line) => line.b || line.a || 0);
415
- const pad = String(Math.max(1, ...numbers)).length;
416
- const room = Math.max(10, width - indent.length - pad - 3);
417
- const rows = diff.lines.slice(0, limit).map((line) => {
418
- if (line.type === "…")
419
- return [seg(indent), seg(`${" ".repeat(pad)} …`, { color: palette.muted })];
420
- const number = String(line.type === "-" ? line.a : line.b).padStart(pad);
421
- const body = line.text.replace(/\t/g, " ").slice(0, room).padEnd(room);
422
- return [
423
- seg(indent),
424
- seg(`${number} ${line.type} ${body}`, {
425
- bg: line.type === "+" ? COLORS.added : line.type === "-" ? COLORS.removed : undefined,
426
- color: line.type === " " ? palette.muted : "white",
427
- }),
428
- ];
429
- });
430
- if (diff.lines.length > limit)
431
- rows.push([
432
- seg(indent),
433
- seg(`… +${plural(diff.lines.length - limit, "ligne", "lignes")}`, { color: palette.muted }),
434
- ]);
435
- return rows;
436
- }
437
-
438
- function resultRows(lines, color, palette, width) {
439
- return lines.map((line, index) => [
440
- seg(index ? " " : " ⎿ ", { color: palette.muted }),
441
- seg(String(line).slice(0, Math.max(8, width - 5)) || " ", { color }),
442
- ]);
443
- }
444
-
445
- function toolRows(item, palette, width, frame, verbose = false) {
446
- const [label, detail] = toolLabel(item.name, item.args);
447
- const running = item.status === "running";
448
- const progress = item.progress?.length
449
- ? [
450
- ...item.progress.slice(-3).map((step) => `↳ ${step}`),
451
- `${plural(item.steps || item.progress.length, "étape", "étapes")}`,
452
- ]
453
- : null;
454
- let summary = running
455
- ? { lines: progress || [item.waiting ? "En attente de votre accord…" : "En cours…"] }
456
- : toolSummary(item.name, item.result, item.diff);
457
- // Ctrl+O : le résultat complet plutôt que son résumé.
458
- if (verbose && !running && item.result && !item.diff?.lines.length && summary.tone !== "error") {
459
- const lines = String(item.result).split("\n");
460
- summary = {
461
- lines: lines.length > 40 ? [...lines.slice(0, 40), `… +${plural(lines.length - 40, "ligne", "lignes")}`] : lines,
462
- };
463
- }
464
- const failed = summary.tone === "error";
465
- const dot = running
466
- ? Math.floor(frame / 4) % 2
467
- ? palette.muted
468
- : "white"
469
- : failed
470
- ? COLORS.error
471
- : COLORS.success;
472
- const rows = wrapSegments(
473
- [seg("● ", { color: dot })],
474
- [seg(label, { bold: true }), seg(detail ? `(${detail})` : "")],
475
- width,
476
- );
477
- if (item.name === "proposer_plan" && item.args?.plan)
478
- rows.push(...markdownRows(item.args.plan, palette, width, " "));
479
- if (item.tasks)
480
- rows.push(
481
- ...(item.tasks.length
482
- ? item.tasks.map((task, index) => [
483
- seg(index ? " " : " ⎿ ", { color: palette.muted }),
484
- seg(`${task.status === "terminée" ? "☒" : "☐"} ${task.title}`, {
485
- color: task.status === "terminée" ? palette.muted : undefined,
486
- strike: task.status === "terminée",
487
- bold: task.status === "en cours",
488
- }),
489
- ])
490
- : resultRows(["Aucune tâche"], palette.muted, palette, width)),
491
- );
492
- else rows.push(...resultRows(summary.lines, failed ? COLORS.error : palette.muted, palette, width));
493
- if (!running && !failed && item.diff?.lines.length)
494
- rows.push(...diffRows(item.diff, palette, width, " "));
495
- return rows;
496
- }
497
-
498
- function helpRows(palette, width) {
499
- const rows = [
500
- [seg(`HenergyqueAI${VERSION ? ` · ${VERSION}` : ""}`, { color: palette.accent, bold: true })],
501
- blank(),
502
- [seg("Raccourcis", { bold: true })],
503
- ];
504
- for (const line of [
505
- "! pour lancer une commande dans le terminal",
506
- "@ pour joindre un fichier du projet (texte ou image)",
507
- "# pour ajouter une consigne au fichier HENERGYQUEAI.md",
508
- "/ pour les commandes",
509
- "Maj+Tab pour changer de mode",
510
- "Maj+Entrée pour aller à la ligne",
511
- "PgUp / PgDn ou la molette pour faire défiler la conversation",
512
- "Alt+V (ou Ctrl+V) pour coller une capture d’écran",
513
- "Ctrl+O pour le détail des outils, Ctrl+R pour l’historique",
514
- "Échap pour interrompre, Échap deux fois pour revenir en arrière",
515
- "Ctrl+C deux fois pour quitter",
516
- ])
517
- rows.push([seg(` ${line}`, { color: palette.muted })]);
518
- rows.push(blank(), [seg("Commandes", { bold: true })]);
519
- for (const command of COMMANDS)
520
- rows.push([
521
- seg(` /${command.name.padEnd(14)}`),
522
- seg(command.description.slice(0, Math.max(8, width - 17)), { color: palette.muted }),
523
- ]);
524
- return rows;
525
- }
526
-
527
- function entryRows(item, palette, width, frame, verbose = false) {
528
- switch (item.kind) {
529
- case "user":
530
- return String(item.text)
531
- .split("\n")
532
- .flatMap((line, index) =>
533
- wrapSegments(
534
- [seg(index ? " " : "❯ ", { color: palette.accent, bold: true })],
535
- [seg(line || " ", { bold: true, color: "white" })],
536
- width,
537
- ),
538
- );
539
- case "assistant":
540
- return [
541
- ...(item.header
542
- ? [[seg("✦ ", { color: palette.accent }), seg(item.model || "Assistant", { color: palette.accent, bold: true })]]
543
- : []),
544
- ...markdownRows(item.text, palette, width),
545
- ];
546
- case "turn":
547
- return [
548
- [
549
- seg(
550
- `✻ ${item.verb} pendant ${item.seconds} s${item.tokens ? ` · ↓ ${formatTokens(item.tokens)} tokens` : ""} · terminé ${item.time}`,
551
- { color: palette.muted },
552
- ),
553
- ],
554
- ];
555
- case "tool":
556
- return toolRows(item, palette, width, frame, verbose);
557
- case "shell":
558
- return [
559
- [seg("! ", { color: COLORS.shell, bold: true }), seg(item.command.slice(0, width - 2))],
560
- ...resultRows(
561
- item.output === undefined ? ["En cours…"] : toolSummary("executer", item.output).lines,
562
- palette.muted,
563
- palette,
564
- width,
565
- ),
566
- ];
567
- case "help":
568
- return helpRows(palette, width);
569
- default: {
570
- const color =
571
- item.kind === "error" || item.kind === "interrupted" ? COLORS.error : palette.muted;
572
- return String(item.text)
573
- .split("\n")
574
- .flatMap((line, index) =>
575
- wrapSegments(
576
- [seg(index ? " " : " ⎿ ", { color: palette.muted })],
577
- [seg(line || " ", { color })],
578
- width,
579
- ),
580
- );
581
- }
582
- }
583
- }
584
-
585
- // Les lignes d'une entrée terminée ne changent plus : elles sont gardées en
586
- // mémoire pour ne pas tout recalculer à chaque image de l'animation.
587
- const rowCache = new WeakMap();
588
- function cachedRows(item, palette, width, frame, verbose) {
589
- const live = item.kind === "tool" && item.status === "running";
590
- const cached = rowCache.get(item);
591
- if (!live && cached?.width === width && cached.palette === palette && cached.verbose === verbose)
592
- return cached.rows;
593
- const rows = [...entryRows(item, palette, width, frame, verbose), blank()];
594
- if (!live) rowCache.set(item, { width, palette, verbose, rows });
595
- return rows;
596
- }
597
-
598
- function Rows({ rows }) {
599
- return h(
600
- Box,
601
- { flexDirection: "column", flexShrink: 0 },
602
- rows.map((row, index) =>
603
- h(
604
- Text,
605
- { key: index, wrap: "truncate" },
606
- row.some((part) => part.text)
607
- ? row.map((part, at) =>
608
- h(
609
- Text,
610
- {
611
- key: at,
612
- color: part.color,
613
- backgroundColor: part.bg,
614
- bold: part.bold,
615
- italic: part.italic,
616
- strikethrough: part.strike,
617
- },
618
- part.text,
619
- ),
620
- )
621
- : " ",
622
- ),
623
- ),
624
- );
625
- }
626
-
627
- // --- Composants -----------------------------------------------------------
628
-
629
- function Header({ palette, model, mode, root, frame, busy, status }) {
630
- const logo = creature(model, busy ? frame : model === "velys" ? 1 : 0);
631
- return h(
632
- Box,
633
- {
634
- borderStyle: "round",
635
- borderColor: palette.accent,
636
- paddingX: 1,
637
- flexShrink: 0,
638
- height: HEADER_HEIGHT,
639
- },
640
- h(
641
- Box,
642
- { flexDirection: "column", width: LOGO_WIDTH, marginRight: 3, flexShrink: 0 },
643
- ...logo.map((line, index) => h(Text, { key: index }, line)),
644
- ),
645
- h(
646
- Box,
647
- { flexDirection: "column", flexGrow: 1 },
648
- h(
649
- Text,
650
- { color: palette.accent, bold: true },
651
- `HenergyqueAI${VERSION ? ` · ${VERSION}` : ""}`,
652
- ),
653
- h(Text, null, `${MODELS[model]} · ${mode}`),
654
- h(Text, { color: palette.muted, wrap: "truncate-middle" }, root.replace(homedir(), "~")),
655
- h(Text, { color: palette.muted, wrap: "truncate-end" }, status),
656
- ),
657
- );
658
- }
659
-
660
- function Picker({ menu, options, active, filter, palette }) {
661
- const rows = Math.min(options.length, 8);
662
- const start = Math.max(
663
- 0,
664
- Math.min(active - Math.floor(rows / 2), options.length - rows),
665
- );
666
- return h(
667
- Box,
668
- {
669
- flexDirection: "column",
670
- borderStyle: "round",
671
- borderColor: palette.accent,
672
- paddingX: 1,
673
- flexShrink: 0,
674
- },
675
- h(Text, { bold: true, color: palette.accent }, menu.title),
676
- menu.subtitle ? h(Text, { color: palette.muted }, menu.subtitle) : null,
677
- filter ? h(Text, { color: palette.muted }, `Recherche : ${filter}`) : null,
678
- ...options.slice(start, start + rows).map((option, index) => {
679
- const at = start + index;
680
- const selected = at === active;
681
- return h(
682
- Text,
683
- {
684
- key: at,
685
- color: selected ? palette.accent : undefined,
686
- wrap: "truncate-end",
687
- },
688
- `${selected ? "❯" : " "} ${at + 1}. ${option.label}`,
689
- option.current ? h(Text, { color: COLORS.success }, " ✔") : "",
690
- option.detail
691
- ? h(Text, { color: palette.muted }, ` ${option.detail}`)
692
- : "",
693
- );
694
- }),
695
- options.length
696
- ? null
697
- : h(Text, { color: palette.muted }, "Aucun résultat"),
698
- options.length > rows
699
- ? h(Text, { color: palette.muted }, `${active + 1} sur ${options.length}`)
700
- : null,
701
- );
702
- }
703
-
704
- function ApprovalDialog({ approval, choice, palette, columns, rows }) {
705
- const { name, args = {}, diff, preview } = approval;
706
- const file = args.chemin ? path.basename(String(args.chemin)) : "";
707
- const kind =
708
- name === "executer" ? "command" : name.startsWith("mcp_") ? "mcp" : "edit";
709
- const title =
710
- kind === "command"
711
- ? "Commande terminal"
712
- : kind === "mcp"
713
- ? "Outil MCP"
714
- : diff?.created
715
- ? "Créer un fichier"
716
- : "Modifier un fichier";
717
- const question =
718
- kind === "command"
719
- ? "Voulez-vous exécuter cette commande ?"
720
- : kind === "mcp"
721
- ? "Voulez-vous utiliser cet outil ?"
722
- : diff?.created
723
- ? `Voulez-vous créer ${file} ?`
724
- : `Voulez-vous modifier ${file} ?`;
725
- const body =
726
- kind === "command"
727
- ? h(
728
- Box,
729
- { flexDirection: "column", paddingLeft: 2, marginY: 1 },
730
- h(Text, null, String(args.commande || "")),
731
- args.raison ? h(Text, { color: palette.muted }, args.raison) : null,
732
- )
733
- : kind === "edit" && diff
734
- ? h(
735
- Box,
736
- {
737
- flexDirection: "column",
738
- borderStyle: "round",
739
- borderColor: COLORS.border,
740
- paddingX: 1,
741
- },
742
- h(Text, { bold: true }, diff.path),
743
- h(Rows, {
744
- rows: diffRows(diff, palette, columns - 10, "", Math.max(4, rows - HEADER_HEIGHT - 14)),
745
- }),
746
- )
747
- : h(
748
- Box,
749
- { flexDirection: "column", paddingLeft: 2, marginY: 1 },
750
- ...String(preview || "")
751
- .split("\n")
752
- .slice(0, 8)
753
- .map((line, index) =>
754
- h(Text, { key: index, color: palette.muted, wrap: "truncate-end" }, line || " "),
755
- ),
756
- );
757
- return h(
758
- Box,
759
- {
760
- flexDirection: "column",
761
- borderStyle: "round",
762
- borderColor: palette.accent,
763
- paddingX: 1,
764
- flexShrink: 0,
765
- },
766
- h(Text, { bold: true, color: palette.accent }, title),
767
- body,
768
- h(Text, null, question),
769
- ...approvalOptions(approval).map((label, index) =>
770
- h(
771
- Text,
772
- {
773
- key: index,
774
- color: index === choice ? palette.accent : undefined,
775
- wrap: "truncate-end",
776
- },
777
- `${index === choice ? "❯" : " "} ${index + 1}. ${label}`,
778
- ),
779
- ),
780
- );
781
- }
782
-
783
- // Une question à choix de l'assistant, ou son plan à valider.
784
- function ChoiceDialog({ dialog, choice, palette, columns, rows }) {
785
- const plan = dialog.type === "plan";
786
- const planRows = plan ? markdownRows(dialog.plan, palette, columns - 6, "") : [];
787
- const room = Math.max(4, rows - HEADER_HEIGHT - dialog.options.length - 10);
788
- return h(
789
- Box,
790
- {
791
- flexDirection: "column",
792
- borderStyle: "round",
793
- borderColor: plan ? COLORS.plan : palette.accent,
794
- paddingX: 1,
795
- flexShrink: 0,
796
- },
797
- h(Text, { bold: true, color: plan ? COLORS.plan : palette.accent }, plan ? "Plan prêt" : "Question"),
798
- plan
799
- ? h(
800
- Box,
801
- { flexDirection: "column", marginY: 1 },
802
- h(Rows, { rows: planRows.slice(0, room) }),
803
- planRows.length > room
804
- ? h(Text, { color: palette.muted }, `… +${plural(planRows.length - room, "ligne", "lignes")} (visibles dans la conversation)`)
805
- : null,
806
- )
807
- : h(Box, { marginY: 1 }, h(Text, null, dialog.question)),
808
- plan ? h(Text, null, "Voulez-vous lancer ce plan ?") : null,
809
- ...dialog.options.map((option, index) =>
810
- h(
811
- Text,
812
- { key: index, color: index === choice ? palette.accent : undefined, wrap: "truncate-end" },
813
- `${index === choice ? "❯" : " "} ${index + 1}. ${option.label}`,
814
- option.detail ? h(Text, { color: palette.muted }, ` ${option.detail}`) : "",
815
- ),
816
- ),
817
- );
818
- }
819
-
820
- function Shimmer({ text, frame, palette }) {
821
- const at = frame % (text.length + 8);
822
- return h(
823
- Text,
824
- null,
825
- [...text].map((character, index) =>
826
- h(
827
- Text,
828
- {
829
- key: index,
830
- color: Math.abs(index - at) <= 1 ? "#f6c9a8" : palette.accent,
831
- },
832
- character,
833
- ),
834
- ),
835
- );
836
- }
837
-
838
- function InputBox({ input, cursor, busy, palette, placeholder }) {
839
- const shell = input.startsWith("!");
840
- const lines = input.split("\n");
841
- const cursorLine = input.slice(0, cursor).split("\n").length - 1;
842
- const cursorColumn = cursor - input.slice(0, cursor).lastIndexOf("\n") - 1;
843
- const first = Math.max(0, Math.min(cursorLine - 3, lines.length - 6));
844
- return h(
845
- Box,
846
- {
847
- borderStyle: "round",
848
- borderColor: shell ? COLORS.shell : palette.accent,
849
- paddingX: 1,
850
- flexShrink: 0,
851
- },
852
- h(
853
- Box,
854
- { width: 2, flexShrink: 0 },
855
- h(Text, { color: shell ? COLORS.shell : palette.accent, bold: true }, shell ? "!" : "❯"),
856
- ),
857
- h(
858
- Box,
859
- { flexDirection: "column", flexGrow: 1 },
860
- input
861
- ? lines.slice(first, first + 6).map((line, offset) => {
862
- const index = first + offset;
863
- const shown = index === 0 && shell ? line.slice(1) : line;
864
- const column = index === 0 && shell ? cursorColumn - 1 : cursorColumn;
865
- if (index !== cursorLine)
866
- return h(Text, { key: index }, shown || " ");
867
- return h(
868
- Text,
869
- { key: index },
870
- shown.slice(0, column),
871
- h(Text, { inverse: true }, shown[column] || " "),
872
- shown.slice(column + 1),
873
- );
874
- })
875
- : [
876
- h(
877
- Text,
878
- { key: "vide", wrap: "truncate-end" },
879
- h(Text, { inverse: true }, " "),
880
- busy ? "" : h(Text, { color: palette.muted }, placeholder),
881
- ),
882
- ],
883
- ),
884
- );
885
- }
886
-
887
- function Suggestions({ suggestions, active, palette }) {
888
- const rows = Math.min(suggestions.items.length, 6);
889
- const start = Math.max(
890
- 0,
891
- Math.min(active - Math.floor(rows / 2), suggestions.items.length - rows),
892
- );
893
- return h(
894
- Box,
895
- { flexDirection: "column", paddingX: 2, flexShrink: 0 },
896
- suggestions.items.slice(start, start + rows).map((item, index) => {
897
- const selected = start + index === active;
898
- return suggestions.type === "command"
899
- ? h(
900
- Text,
901
- { key: item.name, wrap: "truncate-end", color: selected ? palette.accent : undefined },
902
- `/${item.name}`.padEnd(16),
903
- h(Text, { color: selected ? palette.accent : palette.muted }, item.description),
904
- )
905
- : h(
906
- Text,
907
- { key: item, wrap: "truncate-end", color: selected ? palette.accent : palette.muted },
908
- `+ ${item}`,
909
- );
910
- }),
911
- );
912
- }
913
-
914
- function ShortcutHelp({ palette }) {
915
- const columns = [
916
- ["! pour le mode terminal", "/ pour les commandes", "@ pour joindre un fichier", "# pour une consigne du projet"],
917
- ["maj+tab pour changer de mode", "maj+entrée pour aller à la ligne", "pgup/pgdn pour défiler", "alt+v pour coller une image"],
918
- ["échap pour effacer ou interrompre", "échap échap pour revenir en arrière", "ctrl+o détail · ctrl+r historique", "ctrl+k actions · ctrl+c ×2 quitter"],
919
- ];
920
- return h(
921
- Box,
922
- { paddingX: 2, flexShrink: 0 },
923
- columns.map((column, index) =>
924
- h(
925
- Box,
926
- { key: index, flexDirection: "column", marginRight: 4 },
927
- column.map((line) => h(Text, { key: line, color: palette.muted }, line)),
928
- ),
929
- ),
930
- );
931
- }
932
-
933
- function App({ session, messages, saveConfig, recent = [], wheel, notify }) {
934
- const { exit } = useApp();
935
- const { stdout } = useStdout();
936
- const history = useRef([]);
937
- const toolIds = useRef(new Map());
938
- const checkpointsRef = useRef(null);
939
- if (!checkpointsRef.current) checkpointsRef.current = createCheckpoints(session.root);
940
- const imagesRef = useRef(new Map());
941
- const imageCounter = useRef(0);
942
- const notesRef = useRef([]);
943
- const answerRef = useRef(null);
944
- const dialogResolve = useRef(null);
945
- const lastEscape = useRef(0);
946
- const [dialog, setDialog] = useState(null);
947
- const [dialogChoice, setDialogChoice] = useState(0);
948
- const dialogChoiceRef = useRef(0);
949
- const [awaitingAnswer, setAwaitingAnswer] = useState(null);
950
- const [verbose, setVerbose] = useState(false);
951
- const historyAt = useRef(-1);
952
- const messagesRef = useRef(messages);
953
- const busyRef = useRef(false);
954
- const approvalResolve = useRef(null);
955
- const abortRef = useRef(null);
956
- const turnId = useRef(0);
957
- const turnHeader = useRef(false);
958
- const queuedDelta = useRef("");
959
- const queuedRound = useRef(0);
960
- const flushTimer = useRef(null);
961
- const toolIdRef = useRef(null);
962
- const queueRef = useRef([]);
963
- const shellContext = useRef([]);
964
- const filesRef = useRef([]);
965
- const submitRef = useRef(null);
966
- const exitArmed = useRef(null);
967
- const startedAt = useRef(Date.now());
968
- const outputChars = useRef(0);
969
- const tokensRef = useRef(0);
970
- const tokenParts = useRef({});
971
- const [entries, setEntries] = useState(() => initialLog(messages, session.modelId));
972
- const [scroll, setScroll] = useState(0);
973
- const [input, setInput] = useState("");
974
- const [cursor, setCursor] = useState(0);
975
- const inputRef = useRef("");
976
- const cursorRef = useRef(0);
977
- const [busy, setBusy] = useState(false);
978
- const [phase, setPhase] = useState("");
979
- const [verb, setVerb] = useState(VERBS[0]);
980
- const [tip, setTip] = useState(TIPS[0]);
981
- const [tokens, setTokens] = useState(0);
982
- const [frame, setFrame] = useState(0);
983
- const [menu, setMenu] = useState(null);
984
- const [menuFilter, setMenuFilter] = useState("");
985
- const [selected, setSelected] = useState(0);
986
- const selectedRef = useRef(0);
987
- const [approval, setApproval] = useState(null);
988
- const [approvalChoice, setApprovalChoice] = useState(0);
989
- const approvalChoiceRef = useRef(0);
990
- const [suggestionAt, setSuggestionAt] = useState(0);
991
- const suggestionRef = useRef(null);
992
- const [showHelp, setShowHelp] = useState(false);
993
- const [queued, setQueued] = useState([]);
994
- const [exitHint, setExitHint] = useState(false);
995
- const [model, setModel] = useState(session.modelId);
996
- const [mode, setMode] = useState(session.mode);
997
- const [theme, setTheme] = useState(session.theme || "papillon");
998
- const [placeholder] = useState(() => `Essayez « ${pick(EXAMPLES)} »`);
999
- const palette = THEMES[theme] || THEMES.papillon;
1000
- const [size, setSize] = useState({
1001
- columns: stdout?.columns || 80,
1002
- rows: stdout?.rows || 24,
1003
- });
1004
-
1005
- useEffect(() => {
1006
- if (!stdout?.on) return;
1007
- const resize = () =>
1008
- setSize({ columns: stdout.columns || 80, rows: stdout.rows || 24 });
1009
- stdout.on("resize", resize);
1010
- return () => stdout.off("resize", resize);
1011
- }, [stdout]);
1012
- useEffect(() => {
1013
- if (!busy) return;
1014
- const timer = setInterval(() => setFrame((value) => value + 1), 120);
1015
- return () => clearInterval(timer);
1016
- }, [busy]);
1017
- const refreshFiles = () =>
1018
- execute("lister_fichiers", {}, { root: session.root, approved: true })
1019
- .then((found) => {
1020
- filesRef.current = found === "Aucun fichier." ? [] : found.split("\n");
1021
- })
1022
- .catch(() => {});
1023
- useEffect(() => {
1024
- void refreshFiles();
1025
- void loadHistory().then((saved) => {
1026
- const known = new Set(history.current);
1027
- history.current = [...history.current, ...saved.reverse().filter((line) => !known.has(line))].slice(0, 200);
1028
- });
1029
- return () => {
1030
- if (flushTimer.current) clearTimeout(flushTimer.current);
1031
- approvalResolve.current?.(false);
1032
- answerRef.current?.(null);
1033
- dialogResolve.current?.(null);
1034
- abortRef.current?.abort();
1035
- };
1036
- }, []);
1037
- // Barre de progression de Windows Terminal et titre de l'onglet.
1038
- useEffect(() => {
1039
- notify?.(busy ? "busy" : "idle");
1040
- }, [busy]);
1041
-
1042
- const push = (...items) => setEntries((previous) => [...previous, ...items]);
1043
- const add = (text, kind = "system") => push(entry({ kind, text: String(text) }));
1044
- const updateTool = (id, change) =>
1045
- setEntries((previous) =>
1046
- previous.map((item) =>
1047
- item.id === id
1048
- ? { ...item, ...(typeof change === "function" ? change(item) : change) }
1049
- : item,
1050
- ),
1051
- );
1052
- // Plusieurs outils peuvent tourner ensemble : chaque appel retrouve sa ligne.
1053
- const toolFor = (callId) => toolIds.current.get(callId) ?? toolIdRef.current;
1054
- const finishStreaming = () =>
1055
- setEntries((previous) =>
1056
- previous.some((item) => item.streaming)
1057
- ? previous.map((item) =>
1058
- item.streaming ? { ...item, streaming: false } : item,
1059
- )
1060
- : previous,
1061
- );
1062
- const flushDelta = () => {
1063
- if (flushTimer.current) clearTimeout(flushTimer.current);
1064
- flushTimer.current = null;
1065
- const delta = queuedDelta.current;
1066
- if (!delta) return;
1067
- queuedDelta.current = "";
1068
- const round = queuedRound.current;
1069
- const id = turnId.current;
1070
- setEntries((previous) => {
1071
- const last = previous.at(-1);
1072
- if (last?.kind === "assistant" && last.streaming && last.turn === id && last.round === round)
1073
- return [...previous.slice(0, -1), { ...last, text: last.text + delta }];
1074
- // Le nom de l'assistant n'apparaît qu'une fois par réponse, même quand
1075
- // il reprend la parole entre deux actions.
1076
- const header = !turnHeader.current;
1077
- turnHeader.current = true;
1078
- return [
1079
- ...previous,
1080
- entry({
1081
- kind: "assistant",
1082
- turn: id,
1083
- round,
1084
- streaming: true,
1085
- header,
1086
- model: MODELS[session.modelId],
1087
- text: delta,
1088
- }),
1089
- ];
1090
- });
1091
- };
1092
-
1093
- const onEvent = (event) => {
1094
- if (event.type === "delta") {
1095
- if (queuedDelta.current && queuedRound.current !== event.round)
1096
- flushDelta();
1097
- queuedRound.current = event.round;
1098
- queuedDelta.current += event.text;
1099
- outputChars.current += event.text.length;
1100
- if (!flushTimer.current) flushTimer.current = setTimeout(flushDelta, 45);
1101
- return;
1102
- }
1103
- flushDelta();
1104
- // Chaque étape et chaque sous-agent comptent séparément ; le total est
1105
- // leur somme, pour que le compteur avance d'une étape à l'autre.
1106
- if (event.type === "thinking" || event.type === "agent-tokens") {
1107
- const part = event.type === "thinking" ? `étape ${event.round ?? 0}` : `agent ${event.id}`;
1108
- const value = Number(event.tokens) || 0;
1109
- tokenParts.current[part] =
1110
- event.type === "thinking" ? Math.max(tokenParts.current[part] || 0, value) : value;
1111
- tokensRef.current = Object.values(tokenParts.current).reduce((sum, count) => sum + count, 0);
1112
- setTokens(tokensRef.current);
1113
- } else if (event.type === "tool-start") {
1114
- finishStreaming();
1115
- const item = entry({
1116
- kind: "tool",
1117
- name: event.name,
1118
- args: event.args,
1119
- status: "running",
1120
- });
1121
- if (event.id) toolIds.current.set(event.id, item.id);
1122
- toolIdRef.current = item.id;
1123
- push(item);
1124
- } else if (event.type === "tool-preview") {
1125
- updateTool(toolFor(event.id), { preview: event.preview, diff: event.diff });
1126
- } else if (event.type === "tool-progress") {
1127
- const [label, detail] = toolLabel(event.name, event.args);
1128
- updateTool(toolFor(event.id), (item) => ({
1129
- progress: [...(item.progress || []), detail ? `${label}(${detail})` : label].slice(-6),
1130
- steps: event.steps,
1131
- }));
1132
- } else if (event.type === "hook") {
1133
- finishStreaming();
1134
- add(`Hook de fin : ${firstLine(event.text, 200)}`);
1135
- } else if (event.type === "tool-end") {
1136
- const id = toolFor(event.id);
1137
- if (event.name === "gerer_taches")
1138
- void listTasks(session.root)
1139
- .catch(() => null)
1140
- .then((tasks) =>
1141
- updateTool(id, { status: "done", result: event.result, tasks: tasks || undefined }),
1142
- );
1143
- else updateTool(id, { status: "done", waiting: false, result: event.result });
1144
- } else if (event.type === "done") finishStreaming();
1145
- };
1146
-
1147
- const bellIfLong = () => {
1148
- if (Date.now() - startedAt.current >= LONG_TURN) notify?.("bell");
1149
- };
1150
- const requestApproval = (request) =>
1151
- new Promise((resolve) => {
1152
- approvalResolve.current = (answer) => resolve(answer);
1153
- updateTool(toolFor(request.id), { waiting: true });
1154
- setApproval(request);
1155
- setApprovalChoice(0);
1156
- approvalChoiceRef.current = 0;
1157
- setScroll(0);
1158
- bellIfLong();
1159
- });
1160
- const openDialog = (next, resolve) => {
1161
- dialogResolve.current = resolve;
1162
- updateTool(toolFor(next.id), { waiting: true });
1163
- setDialog(next);
1164
- setDialogChoice(0);
1165
- dialogChoiceRef.current = 0;
1166
- setScroll(0);
1167
- bellIfLong();
1168
- };
1169
- const requestChoice = ({ id, question, options }) =>
1170
- new Promise((resolve) =>
1171
- openDialog(
1172
- {
1173
- type: "question",
1174
- id,
1175
- question,
1176
- options: [
1177
- ...options.map((option) => ({ label: option.intitule, detail: option.detail, value: option.intitule })),
1178
- { label: "Autre", detail: "écrire votre propre réponse", other: true },
1179
- ],
1180
- },
1181
- resolve,
1182
- ),
1183
- );
1184
- const requestPlan = ({ id, plan }) =>
1185
- new Promise((resolve) =>
1186
- openDialog(
1187
- {
1188
- type: "plan",
1189
- id,
1190
- plan,
1191
- options: [
1192
- { label: "Oui, et accepter les modifications automatiquement", value: "auto" },
1193
- { label: "Oui, en validant chaque modification", value: "manuel" },
1194
- { label: "Non, continuer à préparer le plan", detail: "échap", value: "refus" },
1195
- ],
1196
- },
1197
- resolve,
1198
- ),
1199
- );
1200
- const answerDialog = (index) => {
1201
- const current = dialog;
1202
- const resolve = dialogResolve.current;
1203
- const option = current?.options[index];
1204
- if (!option || !resolve) return;
1205
- setDialog(null);
1206
- const settle = (value) => {
1207
- dialogResolve.current = null;
1208
- answerRef.current = null;
1209
- setAwaitingAnswer(null);
1210
- updateTool(toolFor(current.id), { waiting: false });
1211
- resolve(value);
1212
- };
1213
- // « Autre » : la prochaine saisie devient la réponse.
1214
- if (option.other) {
1215
- answerRef.current = settle;
1216
- setAwaitingAnswer(current.question);
1217
- return;
1218
- }
1219
- if (current.type === "plan" && option.value !== "refus")
1220
- chooseMode(option.value === "auto" ? "accepter-modifications" : "demander", true);
1221
- settle(option.value);
1222
- };
1223
- const interrupt = () => {
1224
- answerRef.current?.(null);
1225
- if (dialogResolve.current) {
1226
- const resolve = dialogResolve.current;
1227
- dialogResolve.current = null;
1228
- setDialog(null);
1229
- resolve(null);
1230
- }
1231
- abortRef.current?.abort();
1232
- };
1233
- const cancelDialog = () =>
1234
- dialog?.type === "plan" ? answerDialog(dialog.options.length - 1) : interrupt();
1235
- const answerApproval = (choice) => {
1236
- const resolve = approvalResolve.current;
1237
- const current = approval;
1238
- approvalResolve.current = null;
1239
- setApproval(null);
1240
- updateTool(toolFor(current?.id), { waiting: false });
1241
- if (choice === 1 && current) {
1242
- if (current.name === "executer" || current.name.startsWith("mcp_")) {
1243
- const rule =
1244
- current.name === "executer"
1245
- ? `Executer(${String(current.args?.commande || "").replace(/[()]/g, "")})`
1246
- : `Mcp(${current.name.slice(4)})`;
1247
- session.permissions = {
1248
- ...session.permissions,
1249
- autoriser: [...(session.permissions?.autoriser || []), rule],
1250
- };
1251
- } else {
1252
- session.mode = "accepter-modifications";
1253
- setMode(session.mode);
1254
- }
1255
- }
1256
- if (choice === 2) abortRef.current?.abort();
1257
- resolve?.(choice !== 2);
1258
- };
1259
-
1260
- const runRequest = async (value, { display } = {}) => {
1261
- if (busyRef.current) return;
1262
- busyRef.current = true;
1263
- turnId.current += 1;
1264
- turnHeader.current = false;
1265
- startedAt.current = Date.now();
1266
- outputChars.current = 0;
1267
- tokensRef.current = 0;
1268
- tokenParts.current = {};
1269
- const verbPair = pick(VERBS);
1270
- setVerb(verbPair);
1271
- setTip(pick(TIPS));
1272
- setBusy(true);
1273
- setTokens(0);
1274
- setPhase("");
1275
- setScroll(0);
1276
- const controller = new AbortController();
1277
- abortRef.current = controller;
1278
- try {
1279
- const question = entry({ kind: "user", text: display || value });
1280
- push(question);
1281
- const compacted = await compactHistory(session, messagesRef.current, {
1282
- onStatus: setPhase,
1283
- });
1284
- setPhase("");
1285
- if (compacted) {
1286
- add("Contexte précédent résumé pour poursuivre la conversation.");
1287
- checkpointsRef.current.forgetConversation();
1288
- }
1289
- checkpointsRef.current.begin({
1290
- text: display || value,
1291
- messageCount: messagesRef.current.length,
1292
- entryId: question.id,
1293
- });
1294
- const shell = shellContext.current.splice(0);
1295
- const notes = notesRef.current.splice(0);
1296
- const expanded = await expandReferences(session.root, value);
1297
- const text = taskContent(
1298
- `${expanded}${shell.length ? `${SHELL_MARKER}${shell.join("\n\n")}` : ""}${notes.length ? `${NOTE_MARKER}${notes.join("\n")}` : ""}`,
1299
- session,
1300
- );
1301
- // Captures collées ([Image n°1]) et images citées avec @.
1302
- const tags = [...value.matchAll(IMAGE_TAG)].map((match) => Number(match[1]));
1303
- const pasted = tags.map((number) => imagesRef.current.get(number)).filter(Boolean);
1304
- for (const number of tags) imagesRef.current.delete(number);
1305
- const referenced = await referencedImages(session.root, value);
1306
- const images = [...pasted, ...referenced.map((image) => image.url)].slice(0, 4);
1307
- messagesRef.current.push({
1308
- role: "user",
1309
- content: images.length
1310
- ? [{ type: "text", text }, ...images.map((url) => ({ type: "image_url", image_url: { url } }))]
1311
- : text,
1312
- });
1313
- session.projectContextSent = true;
1314
- await runAgentTurn(session, messagesRef.current, {
1315
- emit: onEvent,
1316
- requestApproval,
1317
- requestChoice,
1318
- requestPlan,
1319
- checkpoints: checkpointsRef.current,
1320
- signal: controller.signal,
1321
- });
1322
- flushDelta();
1323
- } catch (error) {
1324
- flushDelta();
1325
- if (controller.signal.aborted)
1326
- add("Interrompu · Que doit faire HenergyqueAI à la place ?", "interrupted");
1327
- else add(error.message, "error");
1328
- } finally {
1329
- finishStreaming();
1330
- setEntries((previous) =>
1331
- previous.map((item) =>
1332
- item.kind === "tool" && item.status === "running"
1333
- ? { ...item, status: "done", result: item.result || "Action annulée : interrompu." }
1334
- : item,
1335
- ),
1336
- );
1337
- if (!controller.signal.aborted)
1338
- push(
1339
- entry({
1340
- kind: "turn",
1341
- verb: verbPair[1],
1342
- seconds: Math.max(1, Math.round((Date.now() - startedAt.current) / 1000)),
1343
- tokens: tokensRef.current + Math.round(outputChars.current / 4),
1344
- time: new Date().toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" }),
1345
- }),
1346
- );
1347
- if (!controller.signal.aborted && Date.now() - startedAt.current >= LONG_TURN)
1348
- notify?.("bell");
1349
- // Les images ne repartent pas à chaque demande : une fois la réponse
1350
- // donnée, elles laissent place à une simple mention.
1351
- for (const message of messagesRef.current)
1352
- if (Array.isArray(message.content)) {
1353
- const count = message.content.filter((part) => part.type === "image_url").length;
1354
- message.content = `${textContent(message.content)}\n[${plural(count, "image jointe", "images jointes")}]`;
1355
- }
1356
- session.projectContext = await projectContext(session.root).catch(() => session.projectContext);
1357
- toolIds.current.clear();
1358
- try {
1359
- await saveSession(session.root, messagesRef.current, session.conversationId);
1360
- } catch (error) {
1361
- add(`Enregistrement impossible : ${error.message}`, "error");
1362
- }
1363
- abortRef.current = null;
1364
- busyRef.current = false;
1365
- setBusy(false);
1366
- setPhase("");
1367
- void refreshFiles();
1368
- const next = queueRef.current.shift();
1369
- setQueued([...queueRef.current]);
1370
- if (next) setTimeout(() => submitRef.current?.(next), 0);
1371
- }
1372
- };
1373
-
1374
- const runShell = async (command) => {
1375
- if (!command) return;
1376
- const item = entry({ kind: "shell", command });
1377
- push(item);
1378
- busyRef.current = true;
1379
- startedAt.current = Date.now();
1380
- setBusy(true);
1381
- setPhase("Commande");
1382
- setScroll(0);
1383
- try {
1384
- const output = await execute(
1385
- "executer",
1386
- { commande: command },
1387
- { root: session.root, approved: true },
1388
- );
1389
- updateTool(item.id, { output });
1390
- shellContext.current.push(`$ ${command}\n${String(output).slice(0, 4000)}`);
1391
- } finally {
1392
- busyRef.current = false;
1393
- setBusy(false);
1394
- setPhase("");
1395
- }
1396
- };
1397
-
1398
- const setMenuOptions = (title, options, subtitle) => {
1399
- setMenu({ title, options, subtitle });
1400
- setMenuFilter("");
1401
- const current = Math.max(0, options.findIndex((option) => option.current));
1402
- setSelected(current);
1403
- selectedRef.current = current;
1404
- };
1405
- const closeMenu = () => {
1406
- setMenu(null);
1407
- setMenuFilter("");
1408
- setSelected(0);
1409
- selectedRef.current = 0;
1410
- };
1411
- const editInput = (next, position) => {
1412
- inputRef.current = next;
1413
- cursorRef.current = position;
1414
- setInput(next);
1415
- setCursor(position);
1416
- setSuggestionAt(0);
1417
- };
1418
- const setAssistant = async (id) => {
1419
- session.modelId = id;
1420
- setModel(id);
1421
- await saveConfig({ modelId: id });
1422
- add(`Assistant sélectionné : ${MODELS[id]}.`);
1423
- };
1424
- const chooseMode = (value, quiet = false) => {
1425
- session.mode = value;
1426
- setMode(value);
1427
- if (!quiet) add(`Mode : ${value} — ${MODES[value]}`);
1428
- };
1429
- const chooseTheme = async (value) => {
1430
- session.theme = value;
1431
- setTheme(value);
1432
- await saveUserSetting("theme", value);
1433
- add(`Couleurs : ${value}`);
1434
- };
1435
- const showTool = async (name, args = {}) =>
1436
- add(await execute(name, args, { root: session.root, approved: true }));
1437
- const pickModel = () =>
1438
- setMenuOptions(
1439
- "Choisir l’assistant",
1440
- Object.entries(MODELS).map(([id, label]) => ({
1441
- label,
1442
- detail: MODEL_NOTES[id],
1443
- current: id === session.modelId,
1444
- action: () => setAssistant(id),
1445
- })),
1446
- "L’assistant répond à toutes vos prochaines demandes.",
1447
- );
1448
- const pickMode = () =>
1449
- setMenuOptions(
1450
- "Mode d’autorisation",
1451
- Object.entries(MODES).map(([id, detail]) => ({
1452
- label: id,
1453
- detail,
1454
- current: id === session.mode,
1455
- action: () => chooseMode(id),
1456
- })),
1457
- );
1458
- const pickTheme = () =>
1459
- setMenuOptions(
1460
- "Couleurs",
1461
- Object.keys(THEMES).map((name) => ({
1462
- label: name,
1463
- current: name === theme,
1464
- action: () => chooseTheme(name),
1465
- })),
1466
- );
1467
- const replaceLog = (items) => {
1468
- setEntries(items);
1469
- setScroll(0);
1470
- };
1471
- const openSessions = async () => {
1472
- const sessions = await listSessions(session.root);
1473
- if (!sessions.length) return add("Aucune conversation enregistrée ici.");
1474
- setMenuOptions(
1475
- "Reprendre une conversation",
1476
- sessions.map((saved) => ({
1477
- label:
1478
- cleanQuestion(
1479
- saved.messages.find((message) => message.role === "user")?.content,
1480
- ).slice(0, 55) || "Conversation",
1481
- detail: since(saved.date),
1482
- action: () => {
1483
- messagesRef.current = [...saved.messages];
1484
- session.conversationId = saved.id || randomUUID();
1485
- session.projectContextSent = true;
1486
- checkpointsRef.current.clear();
1487
- replaceLog(initialLog(saved.messages, session.modelId));
1488
- },
1489
- })),
1490
- );
1491
- };
1492
- const openFiles = () => {
1493
- if (!filesRef.current.length) return add("Aucun fichier trouvé.");
1494
- setMenuOptions(
1495
- "Fichiers du projet",
1496
- filesRef.current.map((file) => ({
1497
- label: file,
1498
- action: () => showTool("lire_fichier", { chemin: file }),
1499
- })),
1500
- );
1501
- };
1502
- const insertReference = (file, tokenStart = cursorRef.current) => {
1503
- const reference = /\s/.test(file) ? `@{${file}}` : `@${file}`;
1504
- const prefix = inputRef.current.slice(0, tokenStart);
1505
- const suffix = inputRef.current.slice(cursorRef.current);
1506
- const inserted = `${prefix}${prefix && !/\s$/.test(prefix) ? " " : ""}${reference} `;
1507
- editInput(inserted + suffix, inserted.length);
1508
- };
1509
- const openReferencePicker = () => {
1510
- if (!filesRef.current.length) return add("Aucun fichier trouvé.");
1511
- setMenuOptions(
1512
- "Joindre un fichier",
1513
- filesRef.current.map((file) => ({
1514
- label: file,
1515
- action: () => insertReference(file),
1516
- })),
1517
- );
1518
- };
1519
- const openTasks = async () => {
1520
- const tasks = await listTasks(session.root);
1521
- setMenuOptions("Tâches du projet", [
1522
- {
1523
- label: "Nouvelle tâche",
1524
- detail: "saisir un titre",
1525
- action: () => editInput("/tache ajouter ", 15),
1526
- },
1527
- ...tasks.map((task) => ({
1528
- label: `${task.status === "terminée" ? "☒" : "☐"} ${task.title}`,
1529
- detail: task.status,
1530
- action: async () =>
1531
- add(
1532
- await manageTasks(session.root, {
1533
- action: "modifier",
1534
- id: task.id,
1535
- status: task.status === "terminée" ? "à faire" : "terminée",
1536
- }),
1537
- ),
1538
- })),
1539
- ]);
1540
- };
1541
- const openSkills = async () => {
1542
- const skills = await listSkills(session.root);
1543
- if (!skills.length)
1544
- return add("Aucune compétence. Ajoutez un fichier .henergyqueai/skills/<nom>/SKILL.md.");
1545
- setMenuOptions(
1546
- "Compétences",
1547
- skills.map((skill) => ({
1548
- label: skill.name,
1549
- detail: skill.scope,
1550
- action: async () => add(await readSkill(session.root, skill.name)),
1551
- })),
1552
- );
1553
- };
1554
- const showStatus = () =>
1555
- add(
1556
- [
1557
- `Assistant : ${MODELS[session.modelId]}`,
1558
- `Mode : ${session.mode}`,
1559
- `Projet : ${session.root}`,
1560
- `Messages : ${messagesRef.current.length}`,
1561
- `Consignes : ${session.projectContext ? "chargées" : "aucune"}`,
1562
- ].join("\n"),
1563
- );
1564
- const showUsage = async () => {
1565
- const { plan, usage } = await getUsage(session);
1566
- add(`Abonnement : ${plan}\nUtilisation aujourd’hui : ${usage.used} / ${usage.limit} demandes`);
1567
- };
1568
- const showMcp = () =>
1569
- add(
1570
- [
1571
- session.mcp?.servers.length
1572
- ? session.mcp.servers.map((server) => `${server.name} · ${server.tools} outil(s)`).join("\n")
1573
- : `Aucun serveur MCP connecté. Configuration : ${MCP_CONFIG}`,
1574
- ...(session.mcp?.errors || []),
1575
- ].join("\n"),
1576
- );
1577
- const reviewChanges = async () => {
1578
- const previous = session.mode;
1579
- session.mode = "lecture-seule";
1580
- setMode("lecture-seule");
1581
- try {
1582
- await runRequest(
1583
- "Fais une revue des modifications Git de ce projet. Commence par l’état et le diff, inspecte les fichiers utiles, puis signale les problèmes concrets avec leur chemin et leur ligne. Ne modifie rien.",
1584
- );
1585
- } finally {
1586
- session.mode = previous;
1587
- setMode(previous);
1588
- }
1589
- };
1590
- const compactConversation = async () => {
1591
- if (busyRef.current) return;
1592
- busyRef.current = true;
1593
- startedAt.current = Date.now();
1594
- setBusy(true);
1595
- setPhase("Compression du contexte");
1596
- try {
1597
- const changed = await compactHistory(session, messagesRef.current, {
1598
- force: true,
1599
- onStatus: setPhase,
1600
- });
1601
- add(changed ? "Conversation résumée. Vous pouvez continuer." : "Pas assez de contexte à résumer.");
1602
- if (changed)
1603
- await saveSession(session.root, messagesRef.current, session.conversationId);
1604
- } catch (error) {
1605
- add(error.message, "error");
1606
- } finally {
1607
- busyRef.current = false;
1608
- setBusy(false);
1609
- setPhase("");
1610
- }
1611
- };
1612
- const clearConversation = () => {
1613
- messagesRef.current = [];
1614
- session.conversationId = randomUUID();
1615
- session.projectContextSent = false;
1616
- checkpointsRef.current.clear();
1617
- replaceLog([]);
1618
- };
1619
-
1620
- // Échap Échap : revenir à l'état d'avant une demande.
1621
- const rewind = async (index, conversation, code) => {
1622
- const checkpoints = checkpointsRef.current;
1623
- const point = checkpoints.point(index);
1624
- if (!point) return;
1625
- const restored = code ? await checkpoints.restoreCode(index) : 0;
1626
- if (conversation && point.messageCount !== null) {
1627
- messagesRef.current.splice(point.messageCount);
1628
- if (point.messageCount === 0) session.projectContextSent = false;
1629
- setEntries((previous) => {
1630
- const at = previous.findIndex((item) => item.id === point.entryId);
1631
- return at < 0 ? previous : previous.slice(0, at);
1632
- });
1633
- checkpoints.truncate(index);
1634
- const again = point.text.startsWith("/") ? "" : point.text;
1635
- editInput(again, again.length);
1636
- setScroll(0);
1637
- await saveSession(session.root, messagesRef.current, session.conversationId);
1638
- }
1639
- add(
1640
- [
1641
- conversation ? "Conversation ramenée avant cette demande." : null,
1642
- code ? `${plural(restored, "fichier rétabli", "fichiers rétablis")}.` : null,
1643
- ]
1644
- .filter(Boolean)
1645
- .join(" "),
1646
- );
1647
- };
1648
- const chooseRewind = (point) => {
1649
- const files = point.files.length
1650
- ? `${point.files.slice(0, 3).join(", ")}${point.files.length > 3 ? "…" : ""}`
1651
- : "";
1652
- const options = [];
1653
- if (point.conversation && point.files.length)
1654
- options.push({ label: "Conversation et code", detail: files, action: () => rewind(point.index, true, true) });
1655
- if (point.conversation)
1656
- options.push({ label: "Conversation seulement", detail: "les fichiers restent tels quels", action: () => rewind(point.index, true, false) });
1657
- if (point.files.length)
1658
- options.push({ label: "Code seulement", detail: files, action: () => rewind(point.index, false, true) });
1659
- options.push({ label: "Annuler", action: () => {} });
1660
- setMenuOptions(
1661
- `Revenir avant « ${firstLine(point.text, 40)} »`,
1662
- options,
1663
- "Les commandes lancées dans le terminal ne sont pas annulées.",
1664
- );
1665
- };
1666
- const openRewind = () => {
1667
- const points = checkpointsRef.current.list();
1668
- if (!points.length) return add("Aucune demande de cette session à laquelle revenir.");
1669
- setMenuOptions(
1670
- "Revenir à une demande",
1671
- points.reverse().map((point) => ({
1672
- label: firstLine(point.text, 60) || "Demande",
1673
- detail: `${since(point.date)}${point.files.length ? ` · ${plural(point.files.length, "fichier", "fichiers")} à rétablir` : ""}`,
1674
- action: () => chooseRewind(point),
1675
- })),
1676
- "La conversation et/ou le code reviennent à l’état d’avant cette demande.",
1677
- );
1678
- };
1679
-
1680
- // # au début d'une ligne : une consigne de plus dans HENERGYQUEAI.md.
1681
- const addNote = async (text) => {
1682
- const file = path.join(session.root, "HENERGYQUEAI.md");
1683
- const existing = await readFile(file, "utf8").catch(() => null);
1684
- const lead = existing === null ? "# Consignes du projet\n\n" : existing.endsWith("\n") ? "" : "\n";
1685
- await appendFile(file, `${lead}- ${text}\n`, "utf8");
1686
- session.projectContext = await projectContext(session.root);
1687
- if (session.projectContextSent) notesRef.current.push(`- ${text}`);
1688
- add(`Consigne ajoutée à HENERGYQUEAI.md : ${text}`);
1689
- };
1690
-
1691
- const exportConversation = async (target) => {
1692
- if (!messagesRef.current.length) return add("Rien à exporter pour l’instant.");
1693
- const markdown = conversationMarkdown(messagesRef.current, { model: MODELS[session.modelId] });
1694
- if (target) {
1695
- const file = path.resolve(session.root, target);
1696
- await writeFile(file, markdown, "utf8");
1697
- return add(`Conversation enregistrée dans ${path.relative(session.root, file) || file}.`);
1698
- }
1699
- const name = `conversation-${new Date().toISOString().slice(0, 16).replace(/[:T]/g, "-")}.md`;
1700
- setMenuOptions("Exporter la conversation", [
1701
- {
1702
- label: "Copier dans le presse-papiers",
1703
- action: async () =>
1704
- (await copyText(markdown))
1705
- ? add("Conversation copiée dans le presse-papiers.")
1706
- : add("Presse-papiers indisponible. Essayez /exporter fichier.md", "error"),
1707
- },
1708
- { label: "Enregistrer dans un fichier", detail: name, action: () => exportConversation(name) },
1709
- ]);
1710
- };
1711
-
1712
- const openJobs = () => {
1713
- const jobs = listJobs();
1714
- if (!jobs.length) return add("Aucune commande en arrière-plan.");
1715
- setMenuOptions(
1716
- "Commandes en arrière-plan",
1717
- jobs.map((job) => ({
1718
- label: `${job.id} · ${firstLine(job.command, 50)}`,
1719
- detail: job.status,
1720
- action: () => add(job.running ? stopJob(job.id) : `${job.id} est ${job.status}.`),
1721
- })),
1722
- "Entrée arrête la commande choisie.",
1723
- );
1724
- };
1725
-
1726
- const showHooks = () => {
1727
- const hooks = session.hooks;
1728
- if (!countHooks(hooks))
1729
- return add(
1730
- "Aucun hook. Ajoutez une clé « hooks » (avant_outil, apres_outil, fin) dans .henergyqueai/settings.json ou ~/.henergyqueai/settings.json.",
1731
- );
1732
- add(
1733
- HOOK_EVENTS.flatMap((event) =>
1734
- (hooks[event] || []).map(
1735
- (hook) => `${event}${hook.outils ? ` (${hook.outils})` : ""} · ${hook.scope} · ${hook.commande}`,
1736
- ),
1737
- ).join("\n"),
1738
- );
1739
- };
1740
-
1741
- const openHistorySearch = () => {
1742
- if (!history.current.length) return add("Historique vide.");
1743
- setMenuOptions(
1744
- "Historique des demandes",
1745
- history.current.map((line) => ({
1746
- label: firstLine(line, 90),
1747
- action: () => editInput(line, line.length),
1748
- })),
1749
- "Tapez pour filtrer, Entrée pour reprendre la demande.",
1750
- );
1751
- };
1752
-
1753
- const pasteImage = async () => {
1754
- const url = await clipboardImage();
1755
- if (!url) return add("Aucune image dans le presse-papiers.");
1756
- imageCounter.current += 1;
1757
- imagesRef.current.set(imageCounter.current, url);
1758
- const tag = `[Image n°${imageCounter.current}] `;
1759
- editInput(
1760
- inputRef.current.slice(0, cursorRef.current) + tag + inputRef.current.slice(cursorRef.current),
1761
- cursorRef.current + tag.length,
1762
- );
1763
- };
1764
- const openMainMenu = () =>
1765
- setMenuOptions("Actions", [
1766
- { label: "Choisir l’assistant", detail: MODELS[session.modelId], action: pickModel },
1767
- { label: "Changer le mode", detail: session.mode, action: pickMode },
1768
- { label: "Couleurs", detail: theme, action: pickTheme },
1769
- { label: "État Git", action: () => showTool("etat_git") },
1770
- { label: "Diff Git", action: () => showTool("diff_git") },
1771
- { label: "Revue du code", detail: "analyse sans modification", action: reviewChanges },
1772
- { label: "Compacter le contexte", detail: "résumer l’historique", action: compactConversation },
1773
- { label: "Fichiers", detail: "parcourir le projet", action: openFiles },
1774
- { label: "Joindre un fichier", detail: "insérer une référence", action: openReferencePicker },
1775
- { label: "Conversations", detail: "reprendre une session", action: openSessions },
1776
- { label: "Revenir en arrière", detail: "échap échap", action: openRewind },
1777
- { label: "Historique", detail: "ctrl+r", action: openHistorySearch },
1778
- { label: "Exporter", detail: "Markdown", action: () => exportConversation() },
1779
- { label: "Commandes en arrière-plan", detail: `${listJobs().filter((job) => job.running).length} en cours`, action: openJobs },
1780
- { label: "Hooks", detail: `${countHooks(session.hooks)} configuré(s)`, action: showHooks },
1781
- { label: "Préparer HENERGYQUEAI.md", detail: "/init", action: () => runRequest(INIT_PROMPT, { display: "/init" }) },
1782
- { label: "État de la session", action: showStatus },
1783
- { label: "Utilisation", detail: "quota du jour", action: showUsage },
1784
- { label: "Contexte", detail: "volume et consignes", action: () => add(contextReport(session, messagesRef.current)) },
1785
- { label: "Tâches", detail: "suivi du projet", action: openTasks },
1786
- { label: "Compétences", detail: "méthodes du projet", action: openSkills },
1787
- { label: "Outils MCP", detail: `${session.mcp?.definitions.length || 0} disponibles`, action: showMcp },
1788
- { label: "Diagnostic", detail: "environnement et service", action: async () => add(await diagnose(session)) },
1789
- { label: "Nouvelle conversation", action: clearConversation },
1790
- { label: "Quitter", action: exit },
1791
- ]);
1792
-
1793
- const safely = (promise) =>
1794
- void Promise.resolve(promise).catch((error) => add(error.message, "error"));
1795
-
1796
- const submit = (value) => {
1797
- const line = value.trim();
1798
- editInput("", 0);
1799
- historyAt.current = -1;
1800
- setShowHelp(false);
1801
- setScroll(0);
1802
- if (!line) return;
1803
- if (history.current[0] !== line) history.current.unshift(line);
1804
- history.current = history.current.slice(0, 200);
1805
- void remember(line).catch(() => {});
1806
- // Réponse libre à une question de l'assistant.
1807
- if (answerRef.current) {
1808
- push(entry({ kind: "user", text: line }));
1809
- return answerRef.current(line);
1810
- }
1811
- if (line.startsWith("#")) {
1812
- const note = line.replace(/^#+\s*/, "").trim();
1813
- return note ? safely(addNote(note)) : undefined;
1814
- }
1815
- if (busyRef.current) {
1816
- queueRef.current.push(line);
1817
- setQueued([...queueRef.current]);
1818
- return;
1819
- }
1820
- if (line.startsWith("!")) return safely(runShell(line.slice(1).trim()));
1821
- if (!line.startsWith("/")) return void runRequest(line);
1822
- const [raw, ...argumentsList] = line.slice(1).split(/\s+/);
1823
- const name = raw.toLowerCase();
1824
- const argument = argumentsList[0];
1825
- if (name === "tache" || name === "task") {
1826
- push(entry({ kind: "user", text: line }));
1827
- const action = { finir: "modifier", terminer: "modifier", supprimer: "supprimer" }[argument] || argument;
1828
- const args =
1829
- action === "ajouter"
1830
- ? { action, title: argumentsList.slice(1).join(" ") }
1831
- : { action, id: argumentsList[1], status: "terminée" };
1832
- return safely(manageTasks(session.root, args).then(add));
1833
- }
1834
- if (name === "competence" || name === "skill") {
1835
- push(entry({ kind: "user", text: line }));
1836
- return safely(readSkill(session.root, argument).then(add));
1837
- }
1838
- const command = findCommand(name);
1839
- if (!command) return add(`Commande inconnue : /${raw}. Tapez / pour voir la liste.`, "error");
1840
- if (command.name === "quitter") return exit();
1841
- if (command.name === "effacer") return clearConversation();
1842
- if (command.name === "revue") return void reviewChanges();
1843
- if (command.name === "init") return void runRequest(INIT_PROMPT, { display: line });
1844
- if (command.name === "rembobiner") return openRewind();
1845
- push(entry({ kind: "user", text: line }));
1846
- switch (command.name) {
1847
- case "aide":
1848
- return push(entry({ kind: "help" }));
1849
- case "menu":
1850
- return openMainMenu();
1851
- case "modele":
1852
- return MODELS[argument] ? safely(setAssistant(argument)) : pickModel();
1853
- case "mode":
1854
- return MODES[argument] ? chooseMode(argument) : pickMode();
1855
- case "couleurs":
1856
- return THEMES[argument] ? safely(chooseTheme(argument)) : pickTheme();
1857
- case "plan":
1858
- return chooseMode(session.mode === "plan" ? "demander" : "plan");
1859
- case "git":
1860
- return safely(showTool("etat_git"));
1861
- case "diff":
1862
- return safely(showTool("diff_git"));
1863
- case "compact":
1864
- return void compactConversation();
1865
- case "fichiers":
1866
- return openFiles();
1867
- case "reprendre":
1868
- return safely(openSessions());
1869
- case "statut":
1870
- return showStatus();
1871
- case "utilisation":
1872
- return safely(showUsage());
1873
- case "mcp":
1874
- return showMcp();
1875
- case "contexte":
1876
- return add(contextReport(session, messagesRef.current));
1877
- case "diagnostic":
1878
- return safely(diagnose(session).then(add));
1879
- case "taches":
1880
- return safely(openTasks());
1881
- case "competences":
1882
- return safely(openSkills());
1883
- case "exporter":
1884
- return safely(exportConversation(argumentsList.join(" ").trim() || undefined));
1885
- case "processus":
1886
- return openJobs();
1887
- case "hooks":
1888
- return showHooks();
1889
- }
1890
- };
1891
- submitRef.current = submit;
1892
-
1893
- const suggestions = useMemo(() => {
1894
- if (menu || approval || dialog) return null;
1895
- if (/^\/\S*$/.test(input) && cursor === input.length) {
1896
- const typed = input.slice(1).toLowerCase();
1897
- const items = COMMANDS.filter(
1898
- (command) =>
1899
- command.name.startsWith(typed) ||
1900
- command.aliases?.some((alias) => alias.startsWith(typed)),
1901
- );
1902
- return items.length ? { type: "command", items } : null;
1903
- }
1904
- const at = /(?:^|\s)@([^\s@]*)$/.exec(input.slice(0, cursor));
1905
- if (!at) return null;
1906
- const query = at[1].toLowerCase();
1907
- const items = filesRef.current
1908
- .filter((file) => file.toLowerCase().includes(query))
1909
- .sort(
1910
- (a, b) =>
1911
- Number(!path.basename(a).toLowerCase().startsWith(query)) -
1912
- Number(!path.basename(b).toLowerCase().startsWith(query)) ||
1913
- a.length - b.length,
1914
- )
1915
- .slice(0, 30);
1916
- return items.length
1917
- ? { type: "file", items, start: cursor - at[1].length - 1 }
1918
- : null;
1919
- }, [input, cursor, menu, approval, dialog]);
1920
- suggestionRef.current = suggestions;
1921
-
1922
- const filteredOptions = menuFilter
1923
- ? (menu?.options || []).filter((option) =>
1924
- `${option.label} ${option.detail || ""}`
1925
- .toLocaleLowerCase("fr-FR")
1926
- .includes(menuFilter.toLocaleLowerCase("fr-FR")),
1927
- )
1928
- : menu?.options || [];
1929
-
1930
- const acceptSuggestion = (submitCommand) => {
1931
- const list = suggestionRef.current;
1932
- const item = list?.items[Math.min(suggestionAt, list.items.length - 1)];
1933
- if (!item) return false;
1934
- if (list.type === "command") {
1935
- if (submitCommand) submit(`/${item.name}`);
1936
- else editInput(`/${item.name} `, item.name.length + 2);
1937
- } else insertReference(item, list.start);
1938
- return true;
1939
- };
1940
-
1941
- const columns = Math.max(40, size.columns);
1942
- const width = columns - 2;
1943
- const rows = useMemo(() => {
1944
- const all = entries.flatMap((item) => cachedRows(item, palette, width, frame, verbose));
1945
- if (all.length) return all;
1946
- const note = recent[0]
1947
- ? `Dernière conversation ${since(recent[0].date)} · /reprendre pour la rouvrir`
1948
- : session.projectContext
1949
- ? "Consignes du projet chargées · /aide pour voir les commandes"
1950
- : "Donnez vos consignes au projet dans un fichier HENERGYQUEAI.md";
1951
- return [[seg(note, { color: palette.muted })]];
1952
- }, [entries, palette, width, frame, recent, verbose]);
1953
- const page = Math.max(3, size.rows - HEADER_HEIGHT - 8);
1954
- const maxScroll = Math.max(0, rows.length - page);
1955
- const offset = Math.min(scroll, maxScroll);
1956
- const end = rows.length - offset;
1957
- const visible = rows.slice(Math.max(0, end - size.rows), end);
1958
- const maxScrollRef = useRef(0);
1959
- maxScrollRef.current = maxScroll;
1960
- useEffect(() => {
1961
- if (!wheel) return;
1962
- const onWheel = (direction) =>
1963
- setScroll((current) =>
1964
- Math.max(0, Math.min(maxScrollRef.current, Math.min(current, maxScrollRef.current) + direction * 3)),
1965
- );
1966
- wheel.on("wheel", onWheel);
1967
- return () => wheel.off("wheel", onWheel);
1968
- }, [wheel]);
1969
-
1970
- useInput((value, key) => {
1971
- if (key.ctrl && value === "c") {
1972
- if (approval) return answerApproval(2);
1973
- if (busyRef.current) return interrupt();
1974
- if (inputRef.current) return editInput("", 0);
1975
- if (exitArmed.current) return exit();
1976
- setExitHint(true);
1977
- exitArmed.current = setTimeout(() => {
1978
- exitArmed.current = null;
1979
- setExitHint(false);
1980
- }, 1500);
1981
- return;
1982
- }
1983
- if (key.pageUp || (key.ctrl && value === "b"))
1984
- return setScroll(Math.min(maxScroll, offset + page - 2));
1985
- if (key.pageDown || (key.ctrl && value === "f"))
1986
- return setScroll(Math.max(0, offset - (page - 2)));
1987
- if (approval) {
1988
- const count = approvalOptions(approval).length;
1989
- if (key.upArrow || key.downArrow)
1990
- setApprovalChoice(
1991
- (approvalChoiceRef.current =
1992
- (approvalChoiceRef.current + (key.upArrow ? count - 1 : 1)) % count),
1993
- );
1994
- else if (key.return) answerApproval(approvalChoiceRef.current);
1995
- else if (key.escape) answerApproval(2);
1996
- else if (/^[1-3]$/.test(value)) answerApproval(Number(value) - 1);
1997
- return;
1998
- }
1999
- if (dialog) {
2000
- const count = dialog.options.length;
2001
- if (key.upArrow || key.downArrow)
2002
- setDialogChoice(
2003
- (dialogChoiceRef.current =
2004
- (dialogChoiceRef.current + (key.upArrow ? count - 1 : 1)) % count),
2005
- );
2006
- else if (key.return) answerDialog(dialogChoiceRef.current);
2007
- else if (key.escape) cancelDialog();
2008
- else if (/^[1-9]$/.test(value) && Number(value) <= count) answerDialog(Number(value) - 1);
2009
- return;
2010
- }
2011
- if (key.ctrl && value === "o") return setVerbose((shown) => !shown);
2012
- if (menu) {
2013
- const count = filteredOptions.length;
2014
- if (key.backspace || key.delete) {
2015
- setMenuFilter((current) => current.slice(0, -1));
2016
- setSelected((selectedRef.current = 0));
2017
- } else if (key.upArrow && count)
2018
- setSelected((selectedRef.current = (selectedRef.current - 1 + count) % count));
2019
- else if (key.downArrow && count)
2020
- setSelected((selectedRef.current = (selectedRef.current + 1) % count));
2021
- else if (key.return || (/^[1-9]$/.test(value) && !menuFilter && Number(value) <= count)) {
2022
- const option = filteredOptions[key.return ? selectedRef.current : Number(value) - 1];
2023
- closeMenu();
2024
- safely(option?.action?.());
2025
- } else if (key.escape) closeMenu();
2026
- else if (value && !key.ctrl && !key.meta) {
2027
- setMenuFilter((current) => current + value);
2028
- setSelected((selectedRef.current = 0));
2029
- }
2030
- return;
2031
- }
2032
- if (key.ctrl && value === "k" && !busyRef.current) return openMainMenu();
2033
- if (key.ctrl && value === "r") return openHistorySearch();
2034
- if ((key.meta || key.ctrl) && value === "v") return safely(pasteImage());
2035
- if (key.tab && key.shift) {
2036
- const at = MODE_CYCLE.indexOf(session.mode);
2037
- return chooseMode(MODE_CYCLE[(at + 1) % MODE_CYCLE.length], true);
2038
- }
2039
- if (key.escape) {
2040
- if (busyRef.current && !answerRef.current) return interrupt();
2041
- if (answerRef.current && !inputRef.current) return interrupt();
2042
- const now = Date.now();
2043
- if (!busyRef.current && !inputRef.current && now - lastEscape.current < 700) {
2044
- lastEscape.current = 0;
2045
- return openRewind();
2046
- }
2047
- lastEscape.current = now;
2048
- setShowHelp(false);
2049
- setScroll(0);
2050
- return editInput("", 0);
2051
- }
2052
- const list = suggestionRef.current;
2053
- if (list && (key.upArrow || key.downArrow)) {
2054
- const count = list.items.length;
2055
- return setSuggestionAt((current) => (current + (key.upArrow ? count - 1 : 1)) % count);
2056
- }
2057
- if (list && key.tab) return void acceptSuggestion(false);
2058
- if (key.return) {
2059
- if (key.shift || key.meta) {
2060
- const next = `${inputRef.current.slice(0, cursorRef.current)}\n${inputRef.current.slice(cursorRef.current)}`;
2061
- return editInput(next, cursorRef.current + 1);
2062
- }
2063
- if (list && acceptSuggestion(list.type === "command")) return;
2064
- return submit(inputRef.current);
2065
- }
2066
- if (key.upArrow || key.downArrow) {
2067
- const next = Math.max(
2068
- -1,
2069
- Math.min(history.current.length - 1, historyAt.current + (key.upArrow ? 1 : -1)),
2070
- );
2071
- historyAt.current = next;
2072
- const picked = next < 0 ? "" : history.current[next];
2073
- return editInput(picked, picked.length);
2074
- }
2075
- if (key.leftArrow)
2076
- return editInput(inputRef.current, Math.max(0, cursorRef.current - 1));
2077
- if (key.rightArrow)
2078
- return editInput(inputRef.current, Math.min(inputRef.current.length, cursorRef.current + 1));
2079
- if (key.ctrl && value === "a") return editInput(inputRef.current, 0);
2080
- if (key.ctrl && value === "e")
2081
- return editInput(inputRef.current, inputRef.current.length);
2082
- if (key.ctrl && value === "u")
2083
- return editInput(inputRef.current.slice(cursorRef.current), 0);
2084
- if (key.ctrl && value === "w") {
2085
- const before = inputRef.current.slice(0, cursorRef.current).replace(/\S+\s*$/, "");
2086
- return editInput(before + inputRef.current.slice(cursorRef.current), before.length);
2087
- }
2088
- if (key.backspace || key.delete) {
2089
- if (cursorRef.current > 0)
2090
- editInput(
2091
- inputRef.current.slice(0, cursorRef.current - 1) + inputRef.current.slice(cursorRef.current),
2092
- cursorRef.current - 1,
2093
- );
2094
- return;
2095
- }
2096
- if (value === "?" && !inputRef.current) return setShowHelp((shown) => !shown);
2097
- if (value && !key.ctrl && !key.meta && !key.tab) {
2098
- setShowHelp(false);
2099
- const pasted = value.replace(/\r\n?/g, "\n");
2100
- editInput(
2101
- (inputRef.current.slice(0, cursorRef.current) + pasted + inputRef.current.slice(cursorRef.current)).slice(0, 20000),
2102
- Math.min(20000, cursorRef.current + pasted.length),
2103
- );
2104
- }
2105
- });
2106
-
2107
- const seconds = Math.max(0, Math.round((Date.now() - startedAt.current) / 1000));
2108
- const shownTokens = tokens + Math.round(outputChars.current / 4);
2109
- const label = phase && phase !== "Réflexion" ? phase : verb[0];
2110
- const [modeHint, modeColor] = MODE_HINTS[mode] || [];
2111
- const footerLeft = exitHint
2112
- ? h(Text, { color: palette.muted }, "Appuyez de nouveau sur Ctrl+C pour quitter")
2113
- : input.startsWith("!")
2114
- ? h(Text, { color: COLORS.shell }, "! mode terminal : la commande s’exécute dans le projet")
2115
- : modeHint
2116
- ? h(Text, { color: modeColor, wrap: "truncate-end" }, `${modeHint} `, h(Text, { color: palette.muted }, "(maj+tab pour changer)"))
2117
- : h(
2118
- Text,
2119
- { color: palette.muted, wrap: "truncate-end" },
2120
- "Entrée envoyer · Maj+Entrée ligne · PgUp/PgDn défiler · ? raccourcis",
2121
- );
2122
- const sent = messagesRef.current;
2123
- const contextLeft = Math.max(0, 1 - Math.max(sent.length / 55, historySize(sent) / 240000));
2124
- const waiting = approval || dialog;
2125
- const footerRight = offset
2126
- ? h(Text, { color: palette.accent }, `↓ ${plural(offset, "ligne", "lignes")} plus bas`)
2127
- : awaitingAnswer
2128
- ? h(Text, { color: palette.muted }, "échap pour annuler")
2129
- : busy
2130
- ? h(Text, { color: palette.muted }, "échap pour interrompre")
2131
- : contextLeft <= 0.3
2132
- ? h(Text, { color: COLORS.warning }, `Contexte restant : ${Math.round(contextLeft * 100)} % · /compact`)
2133
- : verbose
2134
- ? h(Text, { color: palette.muted }, "vue détaillée · ctrl+o")
2135
- : null;
2136
-
2137
- return h(
2138
- Box,
2139
- { flexDirection: "column", height: size.rows, width: columns },
2140
- h(Header, {
2141
- palette,
2142
- model,
2143
- mode,
2144
- root: session.root,
2145
- frame,
2146
- busy: busy && !waiting && !awaitingAnswer,
2147
- status: approval
2148
- ? "En attente de votre accord"
2149
- : dialog
2150
- ? dialog.type === "plan"
2151
- ? "Plan à valider"
2152
- : "Question en attente"
2153
- : awaitingAnswer
2154
- ? "En attente de votre réponse"
2155
- : busy
2156
- ? `${label}…`
2157
- : "Prêt à travailler",
2158
- }),
2159
- h(
2160
- Box,
2161
- {
2162
- flexDirection: "column",
2163
- flexGrow: 1,
2164
- flexShrink: 1,
2165
- overflow: "hidden",
2166
- justifyContent: "flex-end",
2167
- paddingX: 1,
2168
- marginTop: 1,
2169
- },
2170
- h(Rows, { rows: visible }),
2171
- ),
2172
- busy && !waiting && !awaitingAnswer
2173
- ? h(
2174
- Box,
2175
- { flexDirection: "column", flexShrink: 0, paddingX: 1 },
2176
- h(
2177
- Text,
2178
- { wrap: "truncate-end" },
2179
- h(Text, { color: palette.accent }, `${GLYPHS[frame % GLYPHS.length]} `),
2180
- h(Shimmer, { text: `${label}…`, frame, palette }),
2181
- h(
2182
- Text,
2183
- { color: palette.muted },
2184
- ` (${seconds} s${shownTokens ? ` · ↓ ${formatTokens(shownTokens)} tokens` : ""} · ${MODELS[model]})`,
2185
- ),
2186
- ),
2187
- phase
2188
- ? null
2189
- : h(Text, { color: palette.muted, wrap: "truncate-end" }, ` ⎿ Astuce : ${tip}`),
2190
- )
2191
- : null,
2192
- ...queued.map((line, index) =>
2193
- h(Text, { key: `q${index}`, color: palette.muted, wrap: "truncate-end" }, ` ⎿ En attente : ${line}`),
2194
- ),
2195
- approval
2196
- ? h(ApprovalDialog, {
2197
- approval,
2198
- choice: approvalChoice,
2199
- palette,
2200
- columns,
2201
- rows: size.rows,
2202
- })
2203
- : dialog
2204
- ? h(ChoiceDialog, { dialog, choice: dialogChoice, palette, columns, rows: size.rows })
2205
- : menu
2206
- ? h(Picker, {
2207
- menu,
2208
- options: filteredOptions,
2209
- active: selected,
2210
- filter: menuFilter,
2211
- palette,
2212
- })
2213
- : h(InputBox, {
2214
- input,
2215
- cursor,
2216
- busy: busy && !awaitingAnswer,
2217
- palette,
2218
- placeholder: awaitingAnswer ? `Votre réponse : ${awaitingAnswer}` : placeholder,
2219
- }),
2220
- approval
2221
- ? h(Text, { color: palette.muted }, " ↑↓ choisir · Entrée confirmer · Échap refuser")
2222
- : dialog
2223
- ? h(Text, { color: palette.muted }, " ↑↓ choisir · Entrée confirmer · Échap annuler")
2224
- : menu
2225
- ? h(Text, { color: palette.muted }, " ↑↓ choisir · Entrée confirmer · tapez pour filtrer · Échap fermer")
2226
- : suggestions
2227
- ? h(Suggestions, { suggestions, active: Math.min(suggestionAt, suggestions.items.length - 1), palette })
2228
- : showHelp
2229
- ? h(ShortcutHelp, { palette })
2230
- : h(
2231
- Box,
2232
- { paddingX: 1, justifyContent: "space-between", flexShrink: 0 },
2233
- footerLeft,
2234
- footerRight,
2235
- ),
2236
- );
2237
- }
2238
-
2239
- const taskContent = (content, session) => {
2240
- const task =
2241
- session.mode === "plan"
2242
- ? `Pour cette demande, explore le projet et propose un plan concret. Ne modifie aucun fichier et n’exécute aucune commande. Quand le plan est prêt, présente-le avec l’outil proposer_plan pour que l’utilisateur l’approuve.\n\n${content}`
2243
- : content;
2244
- return session.projectContextSent || !session.projectContext
2245
- ? task
2246
- : `Consignes locales du projet :\n\n${session.projectContext}\n\n---\nDemande actuelle :\n${task}`;
2247
- };
2248
-
2249
- // Le terminal signale la molette par des séquences « ESC [ < bouton ; x ; y M ».
2250
- // Elles sont retirées du flux avant Ink pour ne jamais finir dans la saisie :
2251
- // 64 et 65 font défiler la conversation, les clics sont ignorés.
2252
- const MOUSE = /\u001b\[<(\d+);\d+;\d+[Mm]/g;
2253
- export function mouseInput(source, onWheel) {
2254
- const stream = new Readable({ read() {} });
2255
- stream.isTTY = true;
2256
- stream.setRawMode = (enabled) => {
2257
- source.setRawMode?.(enabled);
2258
- return stream;
2259
- };
2260
- stream.ref = () => {
2261
- source.ref?.();
2262
- return stream;
2263
- };
2264
- stream.unref = () => {
2265
- source.unref?.();
2266
- return stream;
2267
- };
2268
- let pending = "";
2269
- const onData = (chunk) => {
2270
- let text = pending + chunk.toString("utf8");
2271
- pending = "";
2272
- text = text.replace(MOUSE, (_, button) => {
2273
- const code = Number(button);
2274
- if (code & 64) onWheel(code & 1 ? -1 : 1);
2275
- return "";
2276
- });
2277
- // Une séquence coupée entre deux lectures est gardée pour la suivante.
2278
- const partial = /\u001b\[<[\d;]*$/.exec(text);
2279
- if (partial) {
2280
- pending = partial[0];
2281
- text = text.slice(0, partial.index);
2282
- }
2283
- if (text) stream.push(text);
2284
- };
2285
- source.on("data", onData);
2286
- stream.stop = () => {
2287
- source.off("data", onData);
2288
- source.pause?.();
2289
- };
2290
- return stream;
2291
- }
2292
-
2293
- export async function runTerminalApp(session, messages, { saveConfig }) {
2294
- const recent = await listSessions(session.root).catch(() => []);
2295
- const mouse = process.env.HENERGYQUEAI_SOURIS !== "0";
2296
- const wheel = new EventEmitter();
2297
- const stdin = mouse
2298
- ? mouseInput(process.stdin, (direction) => wheel.emit("wheel", direction))
2299
- : process.stdin;
2300
- // Plein écran : le terminal d'origine est masqué pendant la session puis
2301
- // retrouvé intact en quittant. La souris sert à faire défiler la conversation.
2302
- process.stdout.write(
2303
- `\u001b]0;HenergyqueAI\u0007\u001b[?1049h\u001b[2J\u001b[H${mouse ? "\u001b[?1000h\u001b[?1006h" : ""}`,
2304
- );
2305
- // Outils propres au mode interactif : questions, plan à valider, agents.
2306
- const known = new Set((session.tools || []).map((tool) => tool.function?.name));
2307
- session.tools = [
2308
- ...(session.tools || []),
2309
- ...interactiveDefinitions.filter((tool) => !known.has(tool.function.name)),
2310
- ];
2311
- // Barre de progression de Windows Terminal, titre de l'onglet et cloche
2312
- // quand une longue tâche attend l'utilisateur.
2313
- const notify = (kind) =>
2314
- process.stdout.write(
2315
- kind === "bell"
2316
- ? "\u0007"
2317
- : kind === "busy"
2318
- ? "\u001b]9;4;3;0\u0007\u001b]0;✦ HenergyqueAI\u0007"
2319
- : "\u001b]9;4;0;0\u0007\u001b]0;HenergyqueAI\u0007",
2320
- );
2321
- const instance = render(
2322
- h(App, { session, messages, saveConfig, recent, wheel, notify }),
2323
- { stdin, exitOnCtrlC: false, patchConsole: false },
2324
- );
2325
- try {
2326
- await instance.waitUntilExit();
2327
- } finally {
2328
- stopAll();
2329
- process.stdout.write(
2330
- `${mouse ? "\u001b[?1000l\u001b[?1006l" : ""}\u001b]9;4;0;0\u0007\u001b[?1049l\u001b]0;\u0007`,
2331
- );
2332
- stdin.stop?.();
2333
- }
2334
- }
2335
-
2336
- export { App, entryRows };
1
+ import React, { useEffect, useMemo, useRef, useState } from "react";
2
+ import { Box, Text, render, useApp, useInput, useStdout } from "ink";
3
+ import { randomUUID } from "node:crypto";
4
+ import { EventEmitter } from "node:events";
5
+ import { Readable } from "node:stream";
6
+ import { readFileSync } from "node:fs";
7
+ import { appendFile, readFile, writeFile } from "node:fs/promises";
8
+ import { homedir } from "node:os";
9
+ import path from "node:path";
10
+ import { execute } from "./tools.js";
11
+ import { MODES, saveUserSetting } from "./reglages.js";
12
+ import { listSessions, saveSession } from "./sessions.js";
13
+ import { HEIGHT as LOGO_HEIGHT, WIDTH as LOGO_WIDTH, creature } from "./butterfly.js";
14
+ import { interactiveDefinitions, runAgentTurn } from "./agent-loop.js";
15
+ import { compactHistory, historySize } from "./compact.js";
16
+ import { listTasks, manageTasks } from "./tasks.js";
17
+ import { contextReport, diagnose } from "./diagnostic.js";
18
+ import { listSkills, readSkill } from "./skills.js";
19
+ import { getUsage } from "./client.js";
20
+ import { createWarmer } from "./warm.js";
21
+ import { MCP_CONFIG } from "./mcp.js";
22
+ import { expandReferences, referencedImages, visibleQuestion } from "./references.js";
23
+ import { projectContext } from "./contexte.js";
24
+ import { createCheckpoints } from "./checkpoints.js";
25
+ import { listJobs, stopAll, stopJob } from "./background.js";
26
+ import { clipboardImage, copyText } from "./clipboard.js";
27
+ import { loadHistory, remember } from "./history.js";
28
+ import { conversationMarkdown } from "./export.js";
29
+ import { HOOK_EVENTS, countHooks } from "./hooks.js";
30
+
31
+ const h = React.createElement;
32
+ const VERSION = (() => {
33
+ try {
34
+ return JSON.parse(
35
+ readFileSync(new URL("../package.json", import.meta.url), "utf8"),
36
+ ).version;
37
+ } catch {
38
+ return "";
39
+ }
40
+ })();
41
+
42
+ const MODELS = {
43
+ velys: "Velys 3.0",
44
+ oryne: "Oryne 2.6",
45
+ aelyr: "Aelyr 4.2 Pro",
46
+ "aelyr-4": "Aelyr 4.0",
47
+ };
48
+ const MODEL_NOTES = {
49
+ velys: "Pour vos idées du quotidien",
50
+ oryne: "Pour écrire et améliorer votre code",
51
+ aelyr: "Pour les projets exigeants",
52
+ "aelyr-4": "La génération précédente d’Aelyr",
53
+ };
54
+ const THEMES = {
55
+ papillon: { accent: "#c46c4f", muted: "#8b8d83", code: "#e3a07c" },
56
+ aube: { accent: "#d69150", muted: "#9b9185", code: "#e8b782" },
57
+ nuit: { accent: "#b49ad5", muted: "#9699a6", code: "#c7b5ea" },
58
+ };
59
+ const COLORS = {
60
+ success: "#5fb86b",
61
+ error: "#e0605e",
62
+ warning: "#d9a441",
63
+ added: "#1f4d2c",
64
+ removed: "#5c2230",
65
+ shell: "#d7609b",
66
+ edits: "#a987e6",
67
+ plan: "#4fa39a",
68
+ border: "#6b6d66",
69
+ };
70
+ const MODE_HINTS = {
71
+ "accepter-modifications": ["⏵⏵ modifications acceptées", COLORS.edits],
72
+ plan: ["⏸ mode plan", COLORS.plan],
73
+ "lecture-seule": ["◼ lecture seule", COLORS.plan],
74
+ "sans-demander": ["⏵⏵ aucune autorisation demandée", COLORS.error],
75
+ };
76
+ // Maj+Tab fait tourner ces trois modes, les deux autres restent dans /mode.
77
+ const MODE_CYCLE = ["demander", "accepter-modifications", "plan"];
78
+ const GLYPHS = ["·", "∗", "✧", "✦", "✶", "✦", "✧", "∗"];
79
+ // Ce qui s'affiche pendant l'attente, puis une fois la réponse terminée.
80
+ const VERBS = [
81
+ ["Réflexion", "Réfléchi"],
82
+ ["Butinage", "Butiné"],
83
+ ["Cogitation", "Cogité"],
84
+ ["Envol", "Envolé"],
85
+ ["Méditation", "Médité"],
86
+ ["Élaboration", "Élaboré"],
87
+ ["Maturation", "Mûri"],
88
+ ["Pollinisation", "Pollinisé"],
89
+ ["Métamorphose", "Métamorphosé"],
90
+ ["Déploiement des ailes", "Déployé"],
91
+ ["Vol plané", "Plané"],
92
+ ["Distillation", "Distillé"],
93
+ ["Exploration", "Exploré"],
94
+ ["Papillonnage", "Papillonné"],
95
+ ];
96
+ const TIPS = [
97
+ "/mode pour autoriser ou bloquer les modifications et les commandes",
98
+ "@ suivi d’un nom de fichier le joint à votre demande",
99
+ "! devant une commande l’exécute directement dans le terminal",
100
+ "Maj+Tab passe en mode plan pour préparer sans rien modifier",
101
+ "/compact résume la conversation quand elle devient longue",
102
+ "Échap interrompt la réponse en cours",
103
+ "/reprendre rouvre une conversation précédente",
104
+ "PgUp et PgDn font défiler la conversation",
105
+ "Un fichier HENERGYQUEAI.md donne vos consignes à chaque demande",
106
+ "Échap deux fois pour revenir à une demande précédente et annuler ses modifications",
107
+ "# au début d’un message ajoute une consigne au projet",
108
+ "Ctrl+O affiche le détail des outils, Ctrl+R cherche dans l’historique",
109
+ "Alt+V colle une capture d’écran",
110
+ "/init prépare le fichier HENERGYQUEAI.md du projet",
111
+ ];
112
+ const EXAMPLES = [
113
+ "explique l’architecture de ce projet",
114
+ "corrige le test qui échoue",
115
+ "ajoute des tests pour ce module",
116
+ "trouve pourquoi la page se charge lentement",
117
+ ];
118
+ const pick = (list) => list[Math.floor(Math.random() * list.length)];
119
+ const SHELL_MARKER = "\n\n--- Commandes lancées par l’utilisateur ---\n";
120
+ const NOTE_MARKER = "\n\n--- Consignes ajoutées au projet ---\n";
121
+ const HEADER_HEIGHT = LOGO_HEIGHT + 2;
122
+ const LONG_TURN = 30000;
123
+ const INIT_PROMPT =
124
+ "Analyse ce projet : structure, commandes d’installation, de build, de test et de lancement, architecture d’ensemble et conventions qui ne se devinent pas en lisant un seul fichier. Crée ensuite à la racine un fichier HENERGYQUEAI.md concis, destiné à un assistant de code qui découvre le projet. S’il existe déjà, améliore-le sans perdre ce qu’il contient. N’invente rien, ne liste pas chaque fichier et reste court.";
125
+ const IMAGE_TAG = /\[Image n°(\d+)\]/g;
126
+
127
+ export const COMMANDS = [
128
+ { name: "aide", aliases: ["help"], description: "Afficher l’aide et les raccourcis" },
129
+ { name: "compact", description: "Résumer la conversation pour libérer du contexte" },
130
+ { name: "competences", aliases: ["skills"], description: "Parcourir les compétences du projet" },
131
+ { name: "contexte", aliases: ["context"], description: "Voir le contexte utilisé" },
132
+ { name: "couleurs", aliases: ["theme"], description: "Changer les couleurs de l’interface" },
133
+ { name: "diagnostic", aliases: ["doctor"], description: "Vérifier l’installation et le service" },
134
+ { name: "diff", description: "Afficher les modifications Git non indexées" },
135
+ { name: "effacer", aliases: ["clear"], description: "Commencer une nouvelle conversation" },
136
+ { name: "exporter", aliases: ["export"], description: "Copier ou enregistrer la conversation en Markdown" },
137
+ { name: "fichiers", description: "Parcourir les fichiers du projet" },
138
+ { name: "git", description: "Afficher l’état Git du projet" },
139
+ { name: "hooks", description: "Voir les commandes lancées autour des outils" },
140
+ { name: "init", description: "Créer ou améliorer le fichier HENERGYQUEAI.md du projet" },
141
+ { name: "mcp", description: "Voir les serveurs MCP connectés" },
142
+ { name: "menu", description: "Ouvrir toutes les actions" },
143
+ { name: "mode", description: "Choisir le mode d’autorisation" },
144
+ { name: "modele", aliases: ["model"], description: "Choisir l’assistant : Velys, Oryne ou Aelyr" },
145
+ { name: "plan", description: "Activer ou couper le mode plan" },
146
+ { name: "processus", aliases: ["bashes", "jobs"], description: "Voir et arrêter les commandes en arrière-plan" },
147
+ { name: "quitter", aliases: ["exit", "q"], description: "Quitter HenergyqueAI" },
148
+ { name: "rembobiner", aliases: ["rewind"], description: "Revenir à une demande précédente (échap échap)" },
149
+ { name: "reprendre", aliases: ["resume", "sessions"], description: "Reprendre une conversation précédente" },
150
+ { name: "revue", aliases: ["review"], description: "Relire les modifications Git du projet" },
151
+ { name: "statut", aliases: ["status"], description: "Voir l’assistant, le mode et le projet" },
152
+ { name: "taches", aliases: ["tasks"], description: "Voir et cocher les tâches du projet" },
153
+ { name: "utilisation", aliases: ["usage", "cout"], description: "Voir le quota du jour" },
154
+ ];
155
+ const findCommand = (name) =>
156
+ COMMANDS.find(
157
+ (command) => command.name === name || command.aliases?.includes(name),
158
+ );
159
+
160
+ let sequence = 0;
161
+ const entry = (fields) => ({ id: ++sequence, ...fields });
162
+
163
+ const textContent = (content) =>
164
+ Array.isArray(content)
165
+ ? content.filter((part) => part.type === "text").map((part) => part.text).join("\n")
166
+ : String(content || "");
167
+ const cleanQuestion = (content) =>
168
+ visibleQuestion(textContent(content).split(SHELL_MARKER)[0].split(NOTE_MARKER)[0]);
169
+
170
+ const plural = (count, one, many) =>
171
+ `${count.toLocaleString("fr-FR")} ${count > 1 ? many : one}`;
172
+ const formatTokens = (count) =>
173
+ count < 1000
174
+ ? String(count)
175
+ : `${(count / 1000).toFixed(1).replace(".", ",")} k`;
176
+ const since = (date) => {
177
+ const minutes = Math.round((Date.now() - date) / 60000);
178
+ if (minutes < 1) return "à l’instant";
179
+ if (minutes < 60) return `il y a ${minutes} min`;
180
+ if (minutes < 1440) return `il y a ${Math.round(minutes / 60)} h`;
181
+ return `il y a ${Math.round(minutes / 1440)} j`;
182
+ };
183
+ const firstLine = (value, limit = 100) => {
184
+ const [line = "", ...rest] = String(value ?? "").split("\n");
185
+ return line.length > limit || rest.length
186
+ ? `${line.slice(0, limit)}…`
187
+ : line;
188
+ };
189
+
190
+ function initialLog(messages, model) {
191
+ return messages
192
+ .filter(
193
+ (message) =>
194
+ (message.role === "user" && typeof message.content === "string") ||
195
+ (message.role === "assistant" && String(message.content || "").trim()),
196
+ )
197
+ .map((message, index, all) =>
198
+ message.role === "user"
199
+ ? entry({ kind: "user", text: cleanQuestion(message.content) })
200
+ : entry({
201
+ kind: "assistant",
202
+ text: String(message.content),
203
+ model: MODELS[model],
204
+ header: all[index - 1]?.role !== "assistant",
205
+ }),
206
+ );
207
+ }
208
+
209
+ // Ce que chaque outil affiche : un nom lisible et son argument principal.
210
+ export function toolLabel(name, args = {}) {
211
+ if (name.startsWith("mcp_")) return ["MCP", name.slice(4)];
212
+ const labels = {
213
+ lire_fichier: ["Lire", args.chemin],
214
+ lister_fichiers: ["Lister", args.dossier || "."],
215
+ chercher: [
216
+ "Chercher",
217
+ `« ${args.motif ?? ""} »${args.dossier ? ` dans ${args.dossier}` : ""}`,
218
+ ],
219
+ trouver_fichiers: ["Trouver", args.motif],
220
+ editer_fichier: ["Modifier", args.chemin],
221
+ ecrire_fichier: ["Écrire", args.chemin],
222
+ executer: [
223
+ args.arriere_plan ? "Arrière-plan" : "Terminal",
224
+ args.commande,
225
+ ],
226
+ etat_git: ["Git", "status"],
227
+ diff_git: ["Git", `diff${args.chemin ? ` ${args.chemin}` : ""}`],
228
+ gerer_taches: ["Tâches", args.action],
229
+ competence: ["Compétence", args.nom || args.action],
230
+ recherche_web: ["Web", `« ${args.requete ?? ""} »`],
231
+ lire_une_page: ["Page", args.url],
232
+ sortie_commande: ["Sortie", args.id],
233
+ arreter_commande: ["Arrêt", args.id],
234
+ poser_question: ["Question", args.question],
235
+ proposer_plan: ["Plan", ""],
236
+ deleguer: ["Agent", args.description],
237
+ };
238
+ const [label, detail] = labels[name] || [name, ""];
239
+ return [label, detail ? firstLine(detail) : ""];
240
+ }
241
+
242
+ // La ligne « ⎿ » sous un outil terminé.
243
+ export function toolSummary(name, result, diff) {
244
+ const text = String(result ?? "");
245
+ const lines = text.split("\n");
246
+ const head = (count) =>
247
+ lines.length > count
248
+ ? [...lines.slice(0, count), `… +${plural(lines.length - count, "ligne", "lignes")}`]
249
+ : lines;
250
+ if (/^(L’utilisateur a refusé|Action refusée|Action annulée|Bloqué par un hook|Échec de l’outil)/.test(text))
251
+ return { tone: "error", lines: [lines[0]] };
252
+ if (name === "recherche_web" || name === "lire_une_page") {
253
+ if (/^(Web indisponible|Adresse invalide|La recherche web)/.test(text))
254
+ return { tone: "error", lines: [lines[0]] };
255
+ if (name === "lire_une_page") return { lines: [`Page lue : ${firstLine(lines[0], 70)}`] };
256
+ const found = lines.filter((line) => /^\d+\. /.test(line)).length;
257
+ return { lines: [found ? plural(found, "résultat", "résultats") : lines[0]] };
258
+ }
259
+ if (name === "deleguer")
260
+ return /^Le sous-agent/.test(text)
261
+ ? { tone: "error", lines: [lines[0]] }
262
+ : { lines: [`Compte rendu reçu (${plural(lines.length, "ligne", "lignes")})`] };
263
+ if (name === "proposer_plan" || name === "poser_question")
264
+ return { lines: [firstLine(text, 90)] };
265
+ if (name === "lire_fichier")
266
+ return /^1\t/.test(text)
267
+ ? { lines: [plural(lines.length, "ligne lue", "lignes lues")] }
268
+ : { tone: "error", lines: [lines[0]] };
269
+ if (name === "lister_fichiers" || name === "trouver_fichiers")
270
+ return /^Aucun/.test(text)
271
+ ? { lines: [lines[0]] }
272
+ : { lines: [plural(lines.filter(Boolean).length, "fichier trouvé", "fichiers trouvés")] };
273
+ if (name === "chercher")
274
+ return /^Aucune/.test(text)
275
+ ? { lines: [lines[0]] }
276
+ : { lines: [plural(lines.filter(Boolean).length, "résultat", "résultats")] };
277
+ if (name === "editer_fichier" || name === "ecrire_fichier") {
278
+ if (!diff || !/(modifié|enregistré)\.$/.test(text))
279
+ return { tone: "error", lines: [lines[0]] };
280
+ if (diff.created)
281
+ return { lines: [`${plural(diff.added, "ligne écrite", "lignes écrites")} dans ${diff.path}`] };
282
+ return {
283
+ lines: [
284
+ `Mis à jour : ${plural(diff.added, "ajout", "ajouts")} et ${plural(diff.removed, "suppression", "suppressions")}`,
285
+ ],
286
+ };
287
+ }
288
+ if (name === "executer")
289
+ return { tone: /^Échec/.test(text) ? "error" : undefined, lines: head(4) };
290
+ return { lines: head(3) };
291
+ }
292
+
293
+ // Les trois réponses possibles à une demande d'autorisation.
294
+ export function approvalOptions({ name, args = {} }) {
295
+ const second =
296
+ name === "executer"
297
+ ? `Oui, et ne plus demander pour « ${firstLine(args.commande, 40)} » pendant cette session`
298
+ : name.startsWith("mcp_")
299
+ ? "Oui, et ne plus demander pour cet outil pendant cette session"
300
+ : "Oui, et accepter toutes les modifications de cette session (maj+tab)";
301
+ return [
302
+ "Oui",
303
+ second,
304
+ "Non, et dire à HenergyqueAI quoi faire autrement (échap)",
305
+ ];
306
+ }
307
+
308
+ // --- Mise en lignes -------------------------------------------------------
309
+ // La conversation est découpée en lignes de terminal déjà coupées à la bonne
310
+ // largeur : la zone du milieu peut alors défiler ligne par ligne, entre le
311
+ // papillon toujours visible en haut et la saisie fixée en bas.
312
+
313
+ const seg = (text, style = {}) => ({ text: String(text), ...style });
314
+ const blank = () => [seg("")];
315
+
316
+ function wrapSegments(prefix, body, width, next) {
317
+ const following = next || [seg(" ".repeat(prefix.reduce((n, p) => n + p.text.length, 0)))];
318
+ const room = (pre) =>
319
+ Math.max(8, width - pre.reduce((n, p) => n + p.text.length, 0));
320
+ const rows = [];
321
+ let current = [...prefix];
322
+ let used = 0;
323
+ let limit = room(prefix);
324
+ const newline = () => {
325
+ rows.push(current);
326
+ current = [...following];
327
+ used = 0;
328
+ limit = room(following);
329
+ };
330
+ for (const part of body) {
331
+ for (const token of part.text.split(/(\s+)/)) {
332
+ if (!token) continue;
333
+ let text = token;
334
+ const space = /^\s+$/.test(text);
335
+ if (space && used === 0 && rows.length) continue;
336
+ while (text) {
337
+ if (used + text.length <= limit) {
338
+ current.push({ ...part, text });
339
+ used += text.length;
340
+ text = "";
341
+ } else if (space) {
342
+ newline();
343
+ text = "";
344
+ } else if (used === 0) {
345
+ current.push({ ...part, text: text.slice(0, limit) });
346
+ text = text.slice(limit);
347
+ newline();
348
+ } else newline();
349
+ }
350
+ }
351
+ }
352
+ rows.push(current);
353
+ return rows;
354
+ }
355
+
356
+ const INLINE =
357
+ /(\*\*[^*\n]+\*\*|`[^`\n]+`|(?<![\w*])\*[^*\s][^*\n]*\*(?![\w*])|(?<![\w_])_[^_\s][^_\n]*_(?![\w_]))/;
358
+ function inlineSegments(text, palette, base = {}) {
359
+ return text
360
+ .split(INLINE)
361
+ .filter(Boolean)
362
+ .map((part) => {
363
+ if (/^\*\*.+\*\*$/.test(part)) return seg(part.slice(2, -2), { ...base, bold: true });
364
+ if (/^`.+`$/.test(part)) return seg(part.slice(1, -1), { ...base, color: palette.code });
365
+ if (/^\*.+\*$|^_.+_$/.test(part)) return seg(part.slice(1, -1), { ...base, italic: true });
366
+ return seg(part, base);
367
+ });
368
+ }
369
+
370
+ function markdownRows(text, palette, width, indent = " ") {
371
+ const rows = [];
372
+ let fence = false;
373
+ const lines = String(text || "").replace(/^\s*\n/, "").trimEnd().split("\n");
374
+ for (const line of lines) {
375
+ if (/^\s*```/.test(line)) {
376
+ fence = !fence;
377
+ continue;
378
+ }
379
+ if (fence) {
380
+ rows.push(...wrapSegments([seg(`${indent} `)], [seg(line || " ", { color: palette.code })], width));
381
+ continue;
382
+ }
383
+ const heading = /^#{1,6}\s+(.*)$/.exec(line);
384
+ if (heading) {
385
+ rows.push(...wrapSegments([seg(indent)], inlineSegments(heading[1], palette, { bold: true }), width));
386
+ continue;
387
+ }
388
+ const quote = /^>\s?(.*)$/.exec(line);
389
+ if (quote) {
390
+ rows.push(
391
+ ...wrapSegments(
392
+ [seg(indent), seg("▎ ", { color: palette.muted })],
393
+ inlineSegments(quote[1], palette, { italic: true, color: palette.muted }),
394
+ width,
395
+ ),
396
+ );
397
+ continue;
398
+ }
399
+ if (/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/.test(line)) {
400
+ rows.push([seg(indent), seg("─".repeat(24), { color: palette.muted })]);
401
+ continue;
402
+ }
403
+ const item = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(line);
404
+ if (item) {
405
+ const bullet = /\d/.test(item[2]) ? `${item[2]} ` : "• ";
406
+ rows.push(
407
+ ...wrapSegments(
408
+ [seg(indent + item[1]), seg(bullet, { color: palette.accent })],
409
+ inlineSegments(item[3], palette),
410
+ width,
411
+ ),
412
+ );
413
+ continue;
414
+ }
415
+ rows.push(...(line.trim() ? wrapSegments([seg(indent)], inlineSegments(line, palette), width) : [blank()]));
416
+ }
417
+ return rows;
418
+ }
419
+
420
+ function diffRows(diff, palette, width, indent = "", limit = 40) {
421
+ const numbers = diff.lines.map((line) => line.b || line.a || 0);
422
+ const pad = String(Math.max(1, ...numbers)).length;
423
+ const room = Math.max(10, width - indent.length - pad - 3);
424
+ const rows = diff.lines.slice(0, limit).map((line) => {
425
+ if (line.type === "…")
426
+ return [seg(indent), seg(`${" ".repeat(pad)} …`, { color: palette.muted })];
427
+ const number = String(line.type === "-" ? line.a : line.b).padStart(pad);
428
+ const body = line.text.replace(/\t/g, " ").slice(0, room).padEnd(room);
429
+ return [
430
+ seg(indent),
431
+ seg(`${number} ${line.type} ${body}`, {
432
+ bg: line.type === "+" ? COLORS.added : line.type === "-" ? COLORS.removed : undefined,
433
+ color: line.type === " " ? palette.muted : "white",
434
+ }),
435
+ ];
436
+ });
437
+ if (diff.lines.length > limit)
438
+ rows.push([
439
+ seg(indent),
440
+ seg(`… +${plural(diff.lines.length - limit, "ligne", "lignes")}`, { color: palette.muted }),
441
+ ]);
442
+ return rows;
443
+ }
444
+
445
+ function resultRows(lines, color, palette, width) {
446
+ return lines.map((line, index) => [
447
+ seg(index ? " " : " ⎿ ", { color: palette.muted }),
448
+ seg(String(line).slice(0, Math.max(8, width - 5)) || " ", { color }),
449
+ ]);
450
+ }
451
+
452
+ function toolRows(item, palette, width, frame, verbose = false) {
453
+ const [label, detail] = toolLabel(item.name, item.args);
454
+ const running = item.status === "running";
455
+ const progress = item.progress?.length
456
+ ? [
457
+ ...item.progress.slice(-3).map((step) => `↳ ${step}`),
458
+ `${plural(item.steps || item.progress.length, "étape", "étapes")}`,
459
+ ]
460
+ : null;
461
+ let summary = running
462
+ ? { lines: progress || [item.waiting ? "En attente de votre accord…" : "En cours…"] }
463
+ : toolSummary(item.name, item.result, item.diff);
464
+ // Ctrl+O : le résultat complet plutôt que son résumé.
465
+ if (verbose && !running && item.result && !item.diff?.lines.length && summary.tone !== "error") {
466
+ const lines = String(item.result).split("\n");
467
+ summary = {
468
+ lines: lines.length > 40 ? [...lines.slice(0, 40), `… +${plural(lines.length - 40, "ligne", "lignes")}`] : lines,
469
+ };
470
+ }
471
+ const failed = summary.tone === "error";
472
+ const dot = running
473
+ ? Math.floor(frame / 4) % 2
474
+ ? palette.muted
475
+ : "white"
476
+ : failed
477
+ ? COLORS.error
478
+ : COLORS.success;
479
+ const rows = wrapSegments(
480
+ [seg("● ", { color: dot })],
481
+ [seg(label, { bold: true }), seg(detail ? `(${detail})` : "")],
482
+ width,
483
+ );
484
+ if (item.name === "proposer_plan" && item.args?.plan)
485
+ rows.push(...markdownRows(item.args.plan, palette, width, " "));
486
+ if (item.tasks)
487
+ rows.push(
488
+ ...(item.tasks.length
489
+ ? item.tasks.map((task, index) => [
490
+ seg(index ? " " : " ⎿ ", { color: palette.muted }),
491
+ seg(`${task.status === "terminée" ? "☒" : "☐"} ${task.title}`, {
492
+ color: task.status === "terminée" ? palette.muted : undefined,
493
+ strike: task.status === "terminée",
494
+ bold: task.status === "en cours",
495
+ }),
496
+ ])
497
+ : resultRows(["Aucune tâche"], palette.muted, palette, width)),
498
+ );
499
+ else rows.push(...resultRows(summary.lines, failed ? COLORS.error : palette.muted, palette, width));
500
+ if (!running && !failed && item.diff?.lines.length)
501
+ rows.push(...diffRows(item.diff, palette, width, " "));
502
+ return rows;
503
+ }
504
+
505
+ function helpRows(palette, width) {
506
+ const rows = [
507
+ [seg(`HenergyqueAI${VERSION ? ` · ${VERSION}` : ""}`, { color: palette.accent, bold: true })],
508
+ blank(),
509
+ [seg("Raccourcis", { bold: true })],
510
+ ];
511
+ for (const line of [
512
+ "! pour lancer une commande dans le terminal",
513
+ "@ pour joindre un fichier du projet (texte ou image)",
514
+ "# pour ajouter une consigne au fichier HENERGYQUEAI.md",
515
+ "/ pour les commandes",
516
+ "Maj+Tab pour changer de mode",
517
+ "Maj+Entrée pour aller à la ligne",
518
+ "PgUp / PgDn ou la molette pour faire défiler la conversation",
519
+ "Alt+V (ou Ctrl+V) pour coller une capture d’écran",
520
+ "Ctrl+O pour le détail des outils, Ctrl+R pour l’historique",
521
+ "Échap pour interrompre, Échap deux fois pour revenir en arrière",
522
+ "Ctrl+C deux fois pour quitter",
523
+ ])
524
+ rows.push([seg(` ${line}`, { color: palette.muted })]);
525
+ rows.push(blank(), [seg("Commandes", { bold: true })]);
526
+ for (const command of COMMANDS)
527
+ rows.push([
528
+ seg(` /${command.name.padEnd(14)}`),
529
+ seg(command.description.slice(0, Math.max(8, width - 17)), { color: palette.muted }),
530
+ ]);
531
+ return rows;
532
+ }
533
+
534
+ function entryRows(item, palette, width, frame, verbose = false) {
535
+ switch (item.kind) {
536
+ case "user":
537
+ return String(item.text)
538
+ .split("\n")
539
+ .flatMap((line, index) =>
540
+ wrapSegments(
541
+ [seg(index ? " " : "❯ ", { color: palette.accent, bold: true })],
542
+ [seg(line || " ", { bold: true, color: "white" })],
543
+ width,
544
+ ),
545
+ );
546
+ case "assistant":
547
+ return [
548
+ ...(item.header
549
+ ? [[seg("✦ ", { color: palette.accent }), seg(item.model || "Assistant", { color: palette.accent, bold: true })]]
550
+ : []),
551
+ ...markdownRows(item.text, palette, width),
552
+ ];
553
+ case "turn":
554
+ return [
555
+ [
556
+ seg(
557
+ `✻ ${item.verb} pendant ${item.seconds} s${item.tokens ? ` · ↓ ${formatTokens(item.tokens)} tokens` : ""} · terminé ${item.time}`,
558
+ { color: palette.muted },
559
+ ),
560
+ ],
561
+ ];
562
+ case "tool":
563
+ return toolRows(item, palette, width, frame, verbose);
564
+ case "shell":
565
+ return [
566
+ [seg("! ", { color: COLORS.shell, bold: true }), seg(item.command.slice(0, width - 2))],
567
+ ...resultRows(
568
+ item.output === undefined ? ["En cours…"] : toolSummary("executer", item.output).lines,
569
+ palette.muted,
570
+ palette,
571
+ width,
572
+ ),
573
+ ];
574
+ case "help":
575
+ return helpRows(palette, width);
576
+ default: {
577
+ const color =
578
+ item.kind === "error" || item.kind === "interrupted" ? COLORS.error : palette.muted;
579
+ return String(item.text)
580
+ .split("\n")
581
+ .flatMap((line, index) =>
582
+ wrapSegments(
583
+ [seg(index ? " " : " ⎿ ", { color: palette.muted })],
584
+ [seg(line || " ", { color })],
585
+ width,
586
+ ),
587
+ );
588
+ }
589
+ }
590
+ }
591
+
592
+ // Les lignes d'une entrée terminée ne changent plus : elles sont gardées en
593
+ // mémoire pour ne pas tout recalculer à chaque image de l'animation.
594
+ const rowCache = new WeakMap();
595
+ function cachedRows(item, palette, width, frame, verbose) {
596
+ const live = item.kind === "tool" && item.status === "running";
597
+ const cached = rowCache.get(item);
598
+ if (!live && cached?.width === width && cached.palette === palette && cached.verbose === verbose)
599
+ return cached.rows;
600
+ const rows = [...entryRows(item, palette, width, frame, verbose), blank()];
601
+ if (!live) rowCache.set(item, { width, palette, verbose, rows });
602
+ return rows;
603
+ }
604
+
605
+ function Rows({ rows }) {
606
+ return h(
607
+ Box,
608
+ { flexDirection: "column", flexShrink: 0 },
609
+ rows.map((row, index) =>
610
+ h(
611
+ Text,
612
+ { key: index, wrap: "truncate" },
613
+ row.some((part) => part.text)
614
+ ? row.map((part, at) =>
615
+ h(
616
+ Text,
617
+ {
618
+ key: at,
619
+ color: part.color,
620
+ backgroundColor: part.bg,
621
+ bold: part.bold,
622
+ italic: part.italic,
623
+ strikethrough: part.strike,
624
+ },
625
+ part.text,
626
+ ),
627
+ )
628
+ : " ",
629
+ ),
630
+ ),
631
+ );
632
+ }
633
+
634
+ // --- Composants -----------------------------------------------------------
635
+
636
+ function Header({ palette, model, mode, root, frame, busy, status }) {
637
+ const logo = creature(model, busy ? frame : model === "velys" ? 1 : 0);
638
+ return h(
639
+ Box,
640
+ {
641
+ borderStyle: "round",
642
+ borderColor: palette.accent,
643
+ paddingX: 1,
644
+ flexShrink: 0,
645
+ height: HEADER_HEIGHT,
646
+ },
647
+ h(
648
+ Box,
649
+ { flexDirection: "column", width: LOGO_WIDTH, marginRight: 3, flexShrink: 0 },
650
+ ...logo.map((line, index) => h(Text, { key: index }, line)),
651
+ ),
652
+ h(
653
+ Box,
654
+ { flexDirection: "column", flexGrow: 1 },
655
+ h(
656
+ Text,
657
+ { color: palette.accent, bold: true },
658
+ `HenergyqueAI${VERSION ? ` · ${VERSION}` : ""}`,
659
+ ),
660
+ h(Text, null, `${MODELS[model]} · ${mode}`),
661
+ h(Text, { color: palette.muted, wrap: "truncate-middle" }, root.replace(homedir(), "~")),
662
+ h(Text, { color: palette.muted, wrap: "truncate-end" }, status),
663
+ ),
664
+ );
665
+ }
666
+
667
+ function Picker({ menu, options, active, filter, palette }) {
668
+ const rows = Math.min(options.length, 8);
669
+ const start = Math.max(
670
+ 0,
671
+ Math.min(active - Math.floor(rows / 2), options.length - rows),
672
+ );
673
+ return h(
674
+ Box,
675
+ {
676
+ flexDirection: "column",
677
+ borderStyle: "round",
678
+ borderColor: palette.accent,
679
+ paddingX: 1,
680
+ flexShrink: 0,
681
+ },
682
+ h(Text, { bold: true, color: palette.accent }, menu.title),
683
+ menu.subtitle ? h(Text, { color: palette.muted }, menu.subtitle) : null,
684
+ filter ? h(Text, { color: palette.muted }, `Recherche : ${filter}`) : null,
685
+ ...options.slice(start, start + rows).map((option, index) => {
686
+ const at = start + index;
687
+ const selected = at === active;
688
+ return h(
689
+ Text,
690
+ {
691
+ key: at,
692
+ color: selected ? palette.accent : undefined,
693
+ wrap: "truncate-end",
694
+ },
695
+ `${selected ? "❯" : " "} ${at + 1}. ${option.label}`,
696
+ option.current ? h(Text, { color: COLORS.success }, " ✔") : "",
697
+ option.detail
698
+ ? h(Text, { color: palette.muted }, ` ${option.detail}`)
699
+ : "",
700
+ );
701
+ }),
702
+ options.length
703
+ ? null
704
+ : h(Text, { color: palette.muted }, "Aucun résultat"),
705
+ options.length > rows
706
+ ? h(Text, { color: palette.muted }, `${active + 1} sur ${options.length}`)
707
+ : null,
708
+ );
709
+ }
710
+
711
+ function ApprovalDialog({ approval, choice, palette, columns, rows }) {
712
+ const { name, args = {}, diff, preview } = approval;
713
+ const file = args.chemin ? path.basename(String(args.chemin)) : "";
714
+ const kind =
715
+ name === "executer" ? "command" : name.startsWith("mcp_") ? "mcp" : "edit";
716
+ const title =
717
+ kind === "command"
718
+ ? "Commande terminal"
719
+ : kind === "mcp"
720
+ ? "Outil MCP"
721
+ : diff?.created
722
+ ? "Créer un fichier"
723
+ : "Modifier un fichier";
724
+ const question =
725
+ kind === "command"
726
+ ? "Voulez-vous exécuter cette commande ?"
727
+ : kind === "mcp"
728
+ ? "Voulez-vous utiliser cet outil ?"
729
+ : diff?.created
730
+ ? `Voulez-vous créer ${file} ?`
731
+ : `Voulez-vous modifier ${file} ?`;
732
+ const body =
733
+ kind === "command"
734
+ ? h(
735
+ Box,
736
+ { flexDirection: "column", paddingLeft: 2, marginY: 1 },
737
+ h(Text, null, String(args.commande || "")),
738
+ args.raison ? h(Text, { color: palette.muted }, args.raison) : null,
739
+ )
740
+ : kind === "edit" && diff
741
+ ? h(
742
+ Box,
743
+ {
744
+ flexDirection: "column",
745
+ borderStyle: "round",
746
+ borderColor: COLORS.border,
747
+ paddingX: 1,
748
+ },
749
+ h(Text, { bold: true }, diff.path),
750
+ h(Rows, {
751
+ rows: diffRows(diff, palette, columns - 10, "", Math.max(4, rows - HEADER_HEIGHT - 14)),
752
+ }),
753
+ )
754
+ : h(
755
+ Box,
756
+ { flexDirection: "column", paddingLeft: 2, marginY: 1 },
757
+ ...String(preview || "")
758
+ .split("\n")
759
+ .slice(0, 8)
760
+ .map((line, index) =>
761
+ h(Text, { key: index, color: palette.muted, wrap: "truncate-end" }, line || " "),
762
+ ),
763
+ );
764
+ return h(
765
+ Box,
766
+ {
767
+ flexDirection: "column",
768
+ borderStyle: "round",
769
+ borderColor: palette.accent,
770
+ paddingX: 1,
771
+ flexShrink: 0,
772
+ },
773
+ h(Text, { bold: true, color: palette.accent }, title),
774
+ body,
775
+ h(Text, null, question),
776
+ ...approvalOptions(approval).map((label, index) =>
777
+ h(
778
+ Text,
779
+ {
780
+ key: index,
781
+ color: index === choice ? palette.accent : undefined,
782
+ wrap: "truncate-end",
783
+ },
784
+ `${index === choice ? "❯" : " "} ${index + 1}. ${label}`,
785
+ ),
786
+ ),
787
+ );
788
+ }
789
+
790
+ // Une question à choix de l'assistant, ou son plan à valider.
791
+ function ChoiceDialog({ dialog, choice, palette, columns, rows }) {
792
+ const plan = dialog.type === "plan";
793
+ const planRows = plan ? markdownRows(dialog.plan, palette, columns - 6, "") : [];
794
+ const room = Math.max(4, rows - HEADER_HEIGHT - dialog.options.length - 10);
795
+ return h(
796
+ Box,
797
+ {
798
+ flexDirection: "column",
799
+ borderStyle: "round",
800
+ borderColor: plan ? COLORS.plan : palette.accent,
801
+ paddingX: 1,
802
+ flexShrink: 0,
803
+ },
804
+ h(Text, { bold: true, color: plan ? COLORS.plan : palette.accent }, plan ? "Plan prêt" : "Question"),
805
+ plan
806
+ ? h(
807
+ Box,
808
+ { flexDirection: "column", marginY: 1 },
809
+ h(Rows, { rows: planRows.slice(0, room) }),
810
+ planRows.length > room
811
+ ? h(Text, { color: palette.muted }, `… +${plural(planRows.length - room, "ligne", "lignes")} (visibles dans la conversation)`)
812
+ : null,
813
+ )
814
+ : h(Box, { marginY: 1 }, h(Text, null, dialog.question)),
815
+ plan ? h(Text, null, "Voulez-vous lancer ce plan ?") : null,
816
+ ...dialog.options.map((option, index) =>
817
+ h(
818
+ Text,
819
+ { key: index, color: index === choice ? palette.accent : undefined, wrap: "truncate-end" },
820
+ `${index === choice ? "❯" : " "} ${index + 1}. ${option.label}`,
821
+ option.detail ? h(Text, { color: palette.muted }, ` ${option.detail}`) : "",
822
+ ),
823
+ ),
824
+ );
825
+ }
826
+
827
+ function Shimmer({ text, frame, palette }) {
828
+ const at = frame % (text.length + 8);
829
+ return h(
830
+ Text,
831
+ null,
832
+ [...text].map((character, index) =>
833
+ h(
834
+ Text,
835
+ {
836
+ key: index,
837
+ color: Math.abs(index - at) <= 1 ? "#f6c9a8" : palette.accent,
838
+ },
839
+ character,
840
+ ),
841
+ ),
842
+ );
843
+ }
844
+
845
+ function InputBox({ input, cursor, busy, palette, placeholder }) {
846
+ const shell = input.startsWith("!");
847
+ const lines = input.split("\n");
848
+ const cursorLine = input.slice(0, cursor).split("\n").length - 1;
849
+ const cursorColumn = cursor - input.slice(0, cursor).lastIndexOf("\n") - 1;
850
+ const first = Math.max(0, Math.min(cursorLine - 3, lines.length - 6));
851
+ return h(
852
+ Box,
853
+ {
854
+ borderStyle: "round",
855
+ borderColor: shell ? COLORS.shell : palette.accent,
856
+ paddingX: 1,
857
+ flexShrink: 0,
858
+ },
859
+ h(
860
+ Box,
861
+ { width: 2, flexShrink: 0 },
862
+ h(Text, { color: shell ? COLORS.shell : palette.accent, bold: true }, shell ? "!" : "❯"),
863
+ ),
864
+ h(
865
+ Box,
866
+ { flexDirection: "column", flexGrow: 1 },
867
+ input
868
+ ? lines.slice(first, first + 6).map((line, offset) => {
869
+ const index = first + offset;
870
+ const shown = index === 0 && shell ? line.slice(1) : line;
871
+ const column = index === 0 && shell ? cursorColumn - 1 : cursorColumn;
872
+ if (index !== cursorLine)
873
+ return h(Text, { key: index }, shown || " ");
874
+ return h(
875
+ Text,
876
+ { key: index },
877
+ shown.slice(0, column),
878
+ h(Text, { inverse: true }, shown[column] || " "),
879
+ shown.slice(column + 1),
880
+ );
881
+ })
882
+ : [
883
+ h(
884
+ Text,
885
+ { key: "vide", wrap: "truncate-end" },
886
+ h(Text, { inverse: true }, " "),
887
+ busy ? "" : h(Text, { color: palette.muted }, placeholder),
888
+ ),
889
+ ],
890
+ ),
891
+ );
892
+ }
893
+
894
+ function Suggestions({ suggestions, active, palette }) {
895
+ const rows = Math.min(suggestions.items.length, 6);
896
+ const start = Math.max(
897
+ 0,
898
+ Math.min(active - Math.floor(rows / 2), suggestions.items.length - rows),
899
+ );
900
+ return h(
901
+ Box,
902
+ { flexDirection: "column", paddingX: 2, flexShrink: 0 },
903
+ suggestions.items.slice(start, start + rows).map((item, index) => {
904
+ const selected = start + index === active;
905
+ return suggestions.type === "command"
906
+ ? h(
907
+ Text,
908
+ { key: item.name, wrap: "truncate-end", color: selected ? palette.accent : undefined },
909
+ `/${item.name}`.padEnd(16),
910
+ h(Text, { color: selected ? palette.accent : palette.muted }, item.description),
911
+ )
912
+ : h(
913
+ Text,
914
+ { key: item, wrap: "truncate-end", color: selected ? palette.accent : palette.muted },
915
+ `+ ${item}`,
916
+ );
917
+ }),
918
+ );
919
+ }
920
+
921
+ function ShortcutHelp({ palette }) {
922
+ const columns = [
923
+ ["! pour le mode terminal", "/ pour les commandes", "@ pour joindre un fichier", "# pour une consigne du projet"],
924
+ ["maj+tab pour changer de mode", "maj+entrée pour aller à la ligne", "pgup/pgdn pour défiler", "alt+v pour coller une image"],
925
+ ["échap pour effacer ou interrompre", "échap échap pour revenir en arrière", "ctrl+o détail · ctrl+r historique", "ctrl+k actions · ctrl+c ×2 quitter"],
926
+ ];
927
+ return h(
928
+ Box,
929
+ { paddingX: 2, flexShrink: 0 },
930
+ columns.map((column, index) =>
931
+ h(
932
+ Box,
933
+ { key: index, flexDirection: "column", marginRight: 4 },
934
+ column.map((line) => h(Text, { key: line, color: palette.muted }, line)),
935
+ ),
936
+ ),
937
+ );
938
+ }
939
+
940
+ function App({ session, messages, saveConfig, recent = [], wheel, notify }) {
941
+ const { exit } = useApp();
942
+ const { stdout } = useStdout();
943
+ const history = useRef([]);
944
+ const toolIds = useRef(new Map());
945
+ const checkpointsRef = useRef(null);
946
+ if (!checkpointsRef.current) checkpointsRef.current = createCheckpoints(session.root);
947
+ const imagesRef = useRef(new Map());
948
+ const imageCounter = useRef(0);
949
+ const notesRef = useRef([]);
950
+ const answerRef = useRef(null);
951
+ const dialogResolve = useRef(null);
952
+ const lastEscape = useRef(0);
953
+ const [dialog, setDialog] = useState(null);
954
+ const [dialogChoice, setDialogChoice] = useState(0);
955
+ const dialogChoiceRef = useRef(0);
956
+ const [awaitingAnswer, setAwaitingAnswer] = useState(null);
957
+ const [verbose, setVerbose] = useState(false);
958
+ const historyAt = useRef(-1);
959
+ const messagesRef = useRef(messages);
960
+ // Le cache reste au chaud pendant les pauses, sans rien afficher.
961
+ const warmerRef = useRef(null);
962
+ warmerRef.current ??= createWarmer(session, () => messagesRef.current);
963
+ const busyRef = useRef(false);
964
+ const approvalResolve = useRef(null);
965
+ const abortRef = useRef(null);
966
+ const turnId = useRef(0);
967
+ const turnHeader = useRef(false);
968
+ const queuedDelta = useRef("");
969
+ const queuedRound = useRef(0);
970
+ const flushTimer = useRef(null);
971
+ const toolIdRef = useRef(null);
972
+ const queueRef = useRef([]);
973
+ const shellContext = useRef([]);
974
+ const filesRef = useRef([]);
975
+ const submitRef = useRef(null);
976
+ const exitArmed = useRef(null);
977
+ const startedAt = useRef(Date.now());
978
+ const outputChars = useRef(0);
979
+ const tokensRef = useRef(0);
980
+ const tokenParts = useRef({});
981
+ const [entries, setEntries] = useState(() => initialLog(messages, session.modelId));
982
+ const [scroll, setScroll] = useState(0);
983
+ const [input, setInput] = useState("");
984
+ const [cursor, setCursor] = useState(0);
985
+ const inputRef = useRef("");
986
+ const cursorRef = useRef(0);
987
+ const [busy, setBusy] = useState(false);
988
+ const [phase, setPhase] = useState("");
989
+ const [verb, setVerb] = useState(VERBS[0]);
990
+ const [tip, setTip] = useState(TIPS[0]);
991
+ const [tokens, setTokens] = useState(0);
992
+ const [frame, setFrame] = useState(0);
993
+ const [menu, setMenu] = useState(null);
994
+ const [menuFilter, setMenuFilter] = useState("");
995
+ const [selected, setSelected] = useState(0);
996
+ const selectedRef = useRef(0);
997
+ const [approval, setApproval] = useState(null);
998
+ const [approvalChoice, setApprovalChoice] = useState(0);
999
+ const approvalChoiceRef = useRef(0);
1000
+ const [suggestionAt, setSuggestionAt] = useState(0);
1001
+ const suggestionRef = useRef(null);
1002
+ const [showHelp, setShowHelp] = useState(false);
1003
+ const [queued, setQueued] = useState([]);
1004
+ const [exitHint, setExitHint] = useState(false);
1005
+ const [model, setModel] = useState(session.modelId);
1006
+ const [mode, setMode] = useState(session.mode);
1007
+ const [theme, setTheme] = useState(session.theme || "papillon");
1008
+ const [placeholder] = useState(() => `Essayez « ${pick(EXAMPLES)} »`);
1009
+ const palette = THEMES[theme] || THEMES.papillon;
1010
+ const [size, setSize] = useState({
1011
+ columns: stdout?.columns || 80,
1012
+ rows: stdout?.rows || 24,
1013
+ });
1014
+
1015
+ useEffect(() => {
1016
+ if (!stdout?.on) return;
1017
+ const resize = () =>
1018
+ setSize({ columns: stdout.columns || 80, rows: stdout.rows || 24 });
1019
+ stdout.on("resize", resize);
1020
+ return () => stdout.off("resize", resize);
1021
+ }, [stdout]);
1022
+ useEffect(() => {
1023
+ if (!busy) return;
1024
+ const timer = setInterval(() => setFrame((value) => value + 1), 120);
1025
+ return () => clearInterval(timer);
1026
+ }, [busy]);
1027
+ const refreshFiles = () =>
1028
+ execute("lister_fichiers", {}, { root: session.root, approved: true })
1029
+ .then((found) => {
1030
+ filesRef.current = found === "Aucun fichier." ? [] : found.split("\n");
1031
+ })
1032
+ .catch(() => {});
1033
+ useEffect(() => {
1034
+ void refreshFiles();
1035
+ void loadHistory().then((saved) => {
1036
+ const known = new Set(history.current);
1037
+ history.current = [...history.current, ...saved.reverse().filter((line) => !known.has(line))].slice(0, 200);
1038
+ });
1039
+ return () => {
1040
+ if (flushTimer.current) clearTimeout(flushTimer.current);
1041
+ approvalResolve.current?.(false);
1042
+ answerRef.current?.(null);
1043
+ dialogResolve.current?.(null);
1044
+ abortRef.current?.abort();
1045
+ };
1046
+ }, []);
1047
+ // Barre de progression de Windows Terminal et titre de l'onglet.
1048
+ useEffect(() => {
1049
+ notify?.(busy ? "busy" : "idle");
1050
+ }, [busy]);
1051
+
1052
+ const push = (...items) => setEntries((previous) => [...previous, ...items]);
1053
+ const add = (text, kind = "system") => push(entry({ kind, text: String(text) }));
1054
+ const updateTool = (id, change) =>
1055
+ setEntries((previous) =>
1056
+ previous.map((item) =>
1057
+ item.id === id
1058
+ ? { ...item, ...(typeof change === "function" ? change(item) : change) }
1059
+ : item,
1060
+ ),
1061
+ );
1062
+ // Plusieurs outils peuvent tourner ensemble : chaque appel retrouve sa ligne.
1063
+ const toolFor = (callId) => toolIds.current.get(callId) ?? toolIdRef.current;
1064
+ const finishStreaming = () =>
1065
+ setEntries((previous) =>
1066
+ previous.some((item) => item.streaming)
1067
+ ? previous.map((item) =>
1068
+ item.streaming ? { ...item, streaming: false } : item,
1069
+ )
1070
+ : previous,
1071
+ );
1072
+ const flushDelta = () => {
1073
+ if (flushTimer.current) clearTimeout(flushTimer.current);
1074
+ flushTimer.current = null;
1075
+ const delta = queuedDelta.current;
1076
+ if (!delta) return;
1077
+ queuedDelta.current = "";
1078
+ const round = queuedRound.current;
1079
+ const id = turnId.current;
1080
+ setEntries((previous) => {
1081
+ const last = previous.at(-1);
1082
+ if (last?.kind === "assistant" && last.streaming && last.turn === id && last.round === round)
1083
+ return [...previous.slice(0, -1), { ...last, text: last.text + delta }];
1084
+ // Le nom de l'assistant n'apparaît qu'une fois par réponse, même quand
1085
+ // il reprend la parole entre deux actions.
1086
+ const header = !turnHeader.current;
1087
+ turnHeader.current = true;
1088
+ return [
1089
+ ...previous,
1090
+ entry({
1091
+ kind: "assistant",
1092
+ turn: id,
1093
+ round,
1094
+ streaming: true,
1095
+ header,
1096
+ model: MODELS[session.modelId],
1097
+ text: delta,
1098
+ }),
1099
+ ];
1100
+ });
1101
+ };
1102
+
1103
+ const onEvent = (event) => {
1104
+ if (event.type === "delta") {
1105
+ if (queuedDelta.current && queuedRound.current !== event.round)
1106
+ flushDelta();
1107
+ queuedRound.current = event.round;
1108
+ queuedDelta.current += event.text;
1109
+ outputChars.current += event.text.length;
1110
+ if (!flushTimer.current) flushTimer.current = setTimeout(flushDelta, 45);
1111
+ return;
1112
+ }
1113
+ flushDelta();
1114
+ // Chaque étape et chaque sous-agent comptent séparément ; le total est
1115
+ // leur somme, pour que le compteur avance d'une étape à l'autre.
1116
+ if (event.type === "thinking" || event.type === "agent-tokens") {
1117
+ const part = event.type === "thinking" ? `étape ${event.round ?? 0}` : `agent ${event.id}`;
1118
+ const value = Number(event.tokens) || 0;
1119
+ tokenParts.current[part] =
1120
+ event.type === "thinking" ? Math.max(tokenParts.current[part] || 0, value) : value;
1121
+ tokensRef.current = Object.values(tokenParts.current).reduce((sum, count) => sum + count, 0);
1122
+ setTokens(tokensRef.current);
1123
+ } else if (event.type === "tool-start") {
1124
+ finishStreaming();
1125
+ const item = entry({
1126
+ kind: "tool",
1127
+ name: event.name,
1128
+ args: event.args,
1129
+ status: "running",
1130
+ });
1131
+ if (event.id) toolIds.current.set(event.id, item.id);
1132
+ toolIdRef.current = item.id;
1133
+ push(item);
1134
+ } else if (event.type === "tool-preview") {
1135
+ updateTool(toolFor(event.id), { preview: event.preview, diff: event.diff });
1136
+ } else if (event.type === "tool-progress") {
1137
+ const [label, detail] = toolLabel(event.name, event.args);
1138
+ updateTool(toolFor(event.id), (item) => ({
1139
+ progress: [...(item.progress || []), detail ? `${label}(${detail})` : label].slice(-6),
1140
+ steps: event.steps,
1141
+ }));
1142
+ } else if (event.type === "hook") {
1143
+ finishStreaming();
1144
+ add(`Hook de fin : ${firstLine(event.text, 200)}`);
1145
+ } else if (event.type === "tool-end") {
1146
+ const id = toolFor(event.id);
1147
+ if (event.name === "gerer_taches")
1148
+ void listTasks(session.root)
1149
+ .catch(() => null)
1150
+ .then((tasks) =>
1151
+ updateTool(id, { status: "done", result: event.result, tasks: tasks || undefined }),
1152
+ );
1153
+ else updateTool(id, { status: "done", waiting: false, result: event.result });
1154
+ } else if (event.type === "done") finishStreaming();
1155
+ };
1156
+
1157
+ const bellIfLong = () => {
1158
+ if (Date.now() - startedAt.current >= LONG_TURN) notify?.("bell");
1159
+ };
1160
+ const requestApproval = (request) =>
1161
+ new Promise((resolve) => {
1162
+ approvalResolve.current = (answer) => resolve(answer);
1163
+ updateTool(toolFor(request.id), { waiting: true });
1164
+ setApproval(request);
1165
+ setApprovalChoice(0);
1166
+ approvalChoiceRef.current = 0;
1167
+ setScroll(0);
1168
+ bellIfLong();
1169
+ });
1170
+ const openDialog = (next, resolve) => {
1171
+ dialogResolve.current = resolve;
1172
+ updateTool(toolFor(next.id), { waiting: true });
1173
+ setDialog(next);
1174
+ setDialogChoice(0);
1175
+ dialogChoiceRef.current = 0;
1176
+ setScroll(0);
1177
+ bellIfLong();
1178
+ };
1179
+ const requestChoice = ({ id, question, options }) =>
1180
+ new Promise((resolve) =>
1181
+ openDialog(
1182
+ {
1183
+ type: "question",
1184
+ id,
1185
+ question,
1186
+ options: [
1187
+ ...options.map((option) => ({ label: option.intitule, detail: option.detail, value: option.intitule })),
1188
+ { label: "Autre", detail: "écrire votre propre réponse", other: true },
1189
+ ],
1190
+ },
1191
+ resolve,
1192
+ ),
1193
+ );
1194
+ const requestPlan = ({ id, plan }) =>
1195
+ new Promise((resolve) =>
1196
+ openDialog(
1197
+ {
1198
+ type: "plan",
1199
+ id,
1200
+ plan,
1201
+ options: [
1202
+ { label: "Oui, et accepter les modifications automatiquement", value: "auto" },
1203
+ { label: "Oui, en validant chaque modification", value: "manuel" },
1204
+ { label: "Non, continuer à préparer le plan", detail: "échap", value: "refus" },
1205
+ ],
1206
+ },
1207
+ resolve,
1208
+ ),
1209
+ );
1210
+ const answerDialog = (index) => {
1211
+ const current = dialog;
1212
+ const resolve = dialogResolve.current;
1213
+ const option = current?.options[index];
1214
+ if (!option || !resolve) return;
1215
+ setDialog(null);
1216
+ const settle = (value) => {
1217
+ dialogResolve.current = null;
1218
+ answerRef.current = null;
1219
+ setAwaitingAnswer(null);
1220
+ updateTool(toolFor(current.id), { waiting: false });
1221
+ resolve(value);
1222
+ };
1223
+ // « Autre » : la prochaine saisie devient la réponse.
1224
+ if (option.other) {
1225
+ answerRef.current = settle;
1226
+ setAwaitingAnswer(current.question);
1227
+ return;
1228
+ }
1229
+ if (current.type === "plan" && option.value !== "refus")
1230
+ chooseMode(option.value === "auto" ? "accepter-modifications" : "demander", true);
1231
+ settle(option.value);
1232
+ };
1233
+ const interrupt = () => {
1234
+ answerRef.current?.(null);
1235
+ if (dialogResolve.current) {
1236
+ const resolve = dialogResolve.current;
1237
+ dialogResolve.current = null;
1238
+ setDialog(null);
1239
+ resolve(null);
1240
+ }
1241
+ abortRef.current?.abort();
1242
+ };
1243
+ const cancelDialog = () =>
1244
+ dialog?.type === "plan" ? answerDialog(dialog.options.length - 1) : interrupt();
1245
+ const answerApproval = (choice) => {
1246
+ const resolve = approvalResolve.current;
1247
+ const current = approval;
1248
+ approvalResolve.current = null;
1249
+ setApproval(null);
1250
+ updateTool(toolFor(current?.id), { waiting: false });
1251
+ if (choice === 1 && current) {
1252
+ if (current.name === "executer" || current.name.startsWith("mcp_")) {
1253
+ const rule =
1254
+ current.name === "executer"
1255
+ ? `Executer(${String(current.args?.commande || "").replace(/[()]/g, "")})`
1256
+ : `Mcp(${current.name.slice(4)})`;
1257
+ session.permissions = {
1258
+ ...session.permissions,
1259
+ autoriser: [...(session.permissions?.autoriser || []), rule],
1260
+ };
1261
+ } else {
1262
+ session.mode = "accepter-modifications";
1263
+ setMode(session.mode);
1264
+ }
1265
+ }
1266
+ if (choice === 2) abortRef.current?.abort();
1267
+ resolve?.(choice !== 2);
1268
+ };
1269
+
1270
+ const runRequest = async (value, { display } = {}) => {
1271
+ if (busyRef.current) return;
1272
+ busyRef.current = true;
1273
+ turnId.current += 1;
1274
+ turnHeader.current = false;
1275
+ startedAt.current = Date.now();
1276
+ outputChars.current = 0;
1277
+ tokensRef.current = 0;
1278
+ tokenParts.current = {};
1279
+ const verbPair = pick(VERBS);
1280
+ setVerb(verbPair);
1281
+ setTip(pick(TIPS));
1282
+ setBusy(true);
1283
+ setTokens(0);
1284
+ setPhase("");
1285
+ setScroll(0);
1286
+ warmerRef.current.stop();
1287
+ const controller = new AbortController();
1288
+ abortRef.current = controller;
1289
+ try {
1290
+ const question = entry({ kind: "user", text: display || value });
1291
+ push(question);
1292
+ const compacted = await compactHistory(session, messagesRef.current, {
1293
+ onStatus: setPhase,
1294
+ });
1295
+ setPhase("");
1296
+ if (compacted) {
1297
+ add("Contexte précédent résumé pour poursuivre la conversation.");
1298
+ checkpointsRef.current.forgetConversation();
1299
+ }
1300
+ checkpointsRef.current.begin({
1301
+ text: display || value,
1302
+ messageCount: messagesRef.current.length,
1303
+ entryId: question.id,
1304
+ });
1305
+ const shell = shellContext.current.splice(0);
1306
+ const notes = notesRef.current.splice(0);
1307
+ const expanded = await expandReferences(session.root, value);
1308
+ const text = taskContent(
1309
+ `${expanded}${shell.length ? `${SHELL_MARKER}${shell.join("\n\n")}` : ""}${notes.length ? `${NOTE_MARKER}${notes.join("\n")}` : ""}`,
1310
+ session,
1311
+ );
1312
+ // Captures collées ([Image n°1]) et images citées avec @.
1313
+ const tags = [...value.matchAll(IMAGE_TAG)].map((match) => Number(match[1]));
1314
+ const pasted = tags.map((number) => imagesRef.current.get(number)).filter(Boolean);
1315
+ for (const number of tags) imagesRef.current.delete(number);
1316
+ const referenced = await referencedImages(session.root, value);
1317
+ const images = [...pasted, ...referenced.map((image) => image.url)].slice(0, 4);
1318
+ messagesRef.current.push({
1319
+ role: "user",
1320
+ content: images.length
1321
+ ? [{ type: "text", text }, ...images.map((url) => ({ type: "image_url", image_url: { url } }))]
1322
+ : text,
1323
+ });
1324
+ session.projectContextSent = true;
1325
+ await runAgentTurn(session, messagesRef.current, {
1326
+ emit: onEvent,
1327
+ requestApproval,
1328
+ requestChoice,
1329
+ requestPlan,
1330
+ checkpoints: checkpointsRef.current,
1331
+ signal: controller.signal,
1332
+ });
1333
+ flushDelta();
1334
+ } catch (error) {
1335
+ flushDelta();
1336
+ if (controller.signal.aborted)
1337
+ add("Interrompu · Que doit faire HenergyqueAI à la place ?", "interrupted");
1338
+ else add(error.message, "error");
1339
+ } finally {
1340
+ finishStreaming();
1341
+ setEntries((previous) =>
1342
+ previous.map((item) =>
1343
+ item.kind === "tool" && item.status === "running"
1344
+ ? { ...item, status: "done", result: item.result || "Action annulée : interrompu." }
1345
+ : item,
1346
+ ),
1347
+ );
1348
+ if (!controller.signal.aborted)
1349
+ push(
1350
+ entry({
1351
+ kind: "turn",
1352
+ verb: verbPair[1],
1353
+ seconds: Math.max(1, Math.round((Date.now() - startedAt.current) / 1000)),
1354
+ tokens: tokensRef.current + Math.round(outputChars.current / 4),
1355
+ time: new Date().toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" }),
1356
+ }),
1357
+ );
1358
+ if (!controller.signal.aborted && Date.now() - startedAt.current >= LONG_TURN)
1359
+ notify?.("bell");
1360
+ // Les images ne repartent pas à chaque demande : une fois la réponse
1361
+ // donnée, elles laissent place à une simple mention.
1362
+ for (const message of messagesRef.current)
1363
+ if (Array.isArray(message.content)) {
1364
+ const count = message.content.filter((part) => part.type === "image_url").length;
1365
+ message.content = `${textContent(message.content)}\n[${plural(count, "image jointe", "images jointes")}]`;
1366
+ }
1367
+ session.projectContext = await projectContext(session.root).catch(() => session.projectContext);
1368
+ toolIds.current.clear();
1369
+ try {
1370
+ await saveSession(session.root, messagesRef.current, session.conversationId);
1371
+ } catch (error) {
1372
+ add(`Enregistrement impossible : ${error.message}`, "error");
1373
+ }
1374
+ abortRef.current = null;
1375
+ if (!controller.signal.aborted) warmerRef.current.arm();
1376
+ busyRef.current = false;
1377
+ setBusy(false);
1378
+ setPhase("");
1379
+ void refreshFiles();
1380
+ const next = queueRef.current.shift();
1381
+ setQueued([...queueRef.current]);
1382
+ if (next) setTimeout(() => submitRef.current?.(next), 0);
1383
+ }
1384
+ };
1385
+
1386
+ const runShell = async (command) => {
1387
+ if (!command) return;
1388
+ const item = entry({ kind: "shell", command });
1389
+ push(item);
1390
+ busyRef.current = true;
1391
+ startedAt.current = Date.now();
1392
+ setBusy(true);
1393
+ setPhase("Commande");
1394
+ setScroll(0);
1395
+ try {
1396
+ const output = await execute(
1397
+ "executer",
1398
+ { commande: command },
1399
+ { root: session.root, approved: true },
1400
+ );
1401
+ updateTool(item.id, { output });
1402
+ shellContext.current.push(`$ ${command}\n${String(output).slice(0, 4000)}`);
1403
+ } finally {
1404
+ busyRef.current = false;
1405
+ setBusy(false);
1406
+ setPhase("");
1407
+ }
1408
+ };
1409
+
1410
+ const setMenuOptions = (title, options, subtitle) => {
1411
+ setMenu({ title, options, subtitle });
1412
+ setMenuFilter("");
1413
+ const current = Math.max(0, options.findIndex((option) => option.current));
1414
+ setSelected(current);
1415
+ selectedRef.current = current;
1416
+ };
1417
+ const closeMenu = () => {
1418
+ setMenu(null);
1419
+ setMenuFilter("");
1420
+ setSelected(0);
1421
+ selectedRef.current = 0;
1422
+ };
1423
+ const editInput = (next, position) => {
1424
+ inputRef.current = next;
1425
+ cursorRef.current = position;
1426
+ setInput(next);
1427
+ setCursor(position);
1428
+ setSuggestionAt(0);
1429
+ };
1430
+ const setAssistant = async (id) => {
1431
+ session.modelId = id;
1432
+ setModel(id);
1433
+ await saveConfig({ modelId: id });
1434
+ add(`Assistant sélectionné : ${MODELS[id]}.`);
1435
+ };
1436
+ const chooseMode = (value, quiet = false) => {
1437
+ session.mode = value;
1438
+ setMode(value);
1439
+ if (!quiet) add(`Mode : ${value} — ${MODES[value]}`);
1440
+ };
1441
+ const chooseTheme = async (value) => {
1442
+ session.theme = value;
1443
+ setTheme(value);
1444
+ await saveUserSetting("theme", value);
1445
+ add(`Couleurs : ${value}`);
1446
+ };
1447
+ const showTool = async (name, args = {}) =>
1448
+ add(await execute(name, args, { root: session.root, approved: true }));
1449
+ const pickModel = () =>
1450
+ setMenuOptions(
1451
+ "Choisir l’assistant",
1452
+ Object.entries(MODELS).map(([id, label]) => ({
1453
+ label,
1454
+ detail: MODEL_NOTES[id],
1455
+ current: id === session.modelId,
1456
+ action: () => setAssistant(id),
1457
+ })),
1458
+ "L’assistant répond à toutes vos prochaines demandes.",
1459
+ );
1460
+ const pickMode = () =>
1461
+ setMenuOptions(
1462
+ "Mode d’autorisation",
1463
+ Object.entries(MODES).map(([id, detail]) => ({
1464
+ label: id,
1465
+ detail,
1466
+ current: id === session.mode,
1467
+ action: () => chooseMode(id),
1468
+ })),
1469
+ );
1470
+ const pickTheme = () =>
1471
+ setMenuOptions(
1472
+ "Couleurs",
1473
+ Object.keys(THEMES).map((name) => ({
1474
+ label: name,
1475
+ current: name === theme,
1476
+ action: () => chooseTheme(name),
1477
+ })),
1478
+ );
1479
+ const replaceLog = (items) => {
1480
+ setEntries(items);
1481
+ setScroll(0);
1482
+ };
1483
+ const openSessions = async () => {
1484
+ const sessions = await listSessions(session.root);
1485
+ if (!sessions.length) return add("Aucune conversation enregistrée ici.");
1486
+ setMenuOptions(
1487
+ "Reprendre une conversation",
1488
+ sessions.map((saved) => ({
1489
+ label:
1490
+ cleanQuestion(
1491
+ saved.messages.find((message) => message.role === "user")?.content,
1492
+ ).slice(0, 55) || "Conversation",
1493
+ detail: since(saved.date),
1494
+ action: () => {
1495
+ warmerRef.current.stop();
1496
+ messagesRef.current = [...saved.messages];
1497
+ session.conversationId = saved.id || randomUUID();
1498
+ session.projectContextSent = true;
1499
+ checkpointsRef.current.clear();
1500
+ replaceLog(initialLog(saved.messages, session.modelId));
1501
+ },
1502
+ })),
1503
+ );
1504
+ };
1505
+ const openFiles = () => {
1506
+ if (!filesRef.current.length) return add("Aucun fichier trouvé.");
1507
+ setMenuOptions(
1508
+ "Fichiers du projet",
1509
+ filesRef.current.map((file) => ({
1510
+ label: file,
1511
+ action: () => showTool("lire_fichier", { chemin: file }),
1512
+ })),
1513
+ );
1514
+ };
1515
+ const insertReference = (file, tokenStart = cursorRef.current) => {
1516
+ const reference = /\s/.test(file) ? `@{${file}}` : `@${file}`;
1517
+ const prefix = inputRef.current.slice(0, tokenStart);
1518
+ const suffix = inputRef.current.slice(cursorRef.current);
1519
+ const inserted = `${prefix}${prefix && !/\s$/.test(prefix) ? " " : ""}${reference} `;
1520
+ editInput(inserted + suffix, inserted.length);
1521
+ };
1522
+ const openReferencePicker = () => {
1523
+ if (!filesRef.current.length) return add("Aucun fichier trouvé.");
1524
+ setMenuOptions(
1525
+ "Joindre un fichier",
1526
+ filesRef.current.map((file) => ({
1527
+ label: file,
1528
+ action: () => insertReference(file),
1529
+ })),
1530
+ );
1531
+ };
1532
+ const openTasks = async () => {
1533
+ const tasks = await listTasks(session.root);
1534
+ setMenuOptions("Tâches du projet", [
1535
+ {
1536
+ label: "Nouvelle tâche",
1537
+ detail: "saisir un titre",
1538
+ action: () => editInput("/tache ajouter ", 15),
1539
+ },
1540
+ ...tasks.map((task) => ({
1541
+ label: `${task.status === "terminée" ? "☒" : "☐"} ${task.title}`,
1542
+ detail: task.status,
1543
+ action: async () =>
1544
+ add(
1545
+ await manageTasks(session.root, {
1546
+ action: "modifier",
1547
+ id: task.id,
1548
+ status: task.status === "terminée" ? "à faire" : "terminée",
1549
+ }),
1550
+ ),
1551
+ })),
1552
+ ]);
1553
+ };
1554
+ const openSkills = async () => {
1555
+ const skills = await listSkills(session.root);
1556
+ if (!skills.length)
1557
+ return add("Aucune compétence. Ajoutez un fichier .henergyqueai/skills/<nom>/SKILL.md.");
1558
+ setMenuOptions(
1559
+ "Compétences",
1560
+ skills.map((skill) => ({
1561
+ label: skill.name,
1562
+ detail: skill.scope,
1563
+ action: async () => add(await readSkill(session.root, skill.name)),
1564
+ })),
1565
+ );
1566
+ };
1567
+ const showStatus = () =>
1568
+ add(
1569
+ [
1570
+ `Assistant : ${MODELS[session.modelId]}`,
1571
+ `Mode : ${session.mode}`,
1572
+ `Projet : ${session.root}`,
1573
+ `Messages : ${messagesRef.current.length}`,
1574
+ `Consignes : ${session.projectContext ? "chargées" : "aucune"}`,
1575
+ ].join("\n"),
1576
+ );
1577
+ const showUsage = async () => {
1578
+ const { plan, usage } = await getUsage(session);
1579
+ // Un serveur plus ancien répond encore en nombre de demandes.
1580
+ add(
1581
+ usage.day
1582
+ ? [
1583
+ `Abonnement : ${plan}`,
1584
+ `Aujourd’hui : ${usage.day.percent} % utilisés`,
1585
+ `Cette semaine : ${usage.week.percent} % utilisés`,
1586
+ ...(usage.relay ? ["Velys prend le relais jusqu’au renouvellement."] : []),
1587
+ ].join("\n")
1588
+ : `Abonnement : ${plan}\nUtilisation aujourd’hui : ${usage.used} / ${usage.limit} demandes`,
1589
+ );
1590
+ };
1591
+ const showMcp = () =>
1592
+ add(
1593
+ [
1594
+ session.mcp?.servers.length
1595
+ ? session.mcp.servers.map((server) => `${server.name} · ${server.tools} outil(s)`).join("\n")
1596
+ : `Aucun serveur MCP connecté. Configuration : ${MCP_CONFIG}`,
1597
+ ...(session.mcp?.errors || []),
1598
+ ].join("\n"),
1599
+ );
1600
+ const reviewChanges = async () => {
1601
+ const previous = session.mode;
1602
+ session.mode = "lecture-seule";
1603
+ setMode("lecture-seule");
1604
+ try {
1605
+ await runRequest(
1606
+ "Fais une revue des modifications Git de ce projet. Commence par l’état et le diff, inspecte les fichiers utiles, puis signale les problèmes concrets avec leur chemin et leur ligne. Ne modifie rien.",
1607
+ );
1608
+ } finally {
1609
+ session.mode = previous;
1610
+ setMode(previous);
1611
+ }
1612
+ };
1613
+ const compactConversation = async () => {
1614
+ if (busyRef.current) return;
1615
+ busyRef.current = true;
1616
+ startedAt.current = Date.now();
1617
+ setBusy(true);
1618
+ setPhase("Compression du contexte");
1619
+ try {
1620
+ const changed = await compactHistory(session, messagesRef.current, {
1621
+ force: true,
1622
+ onStatus: setPhase,
1623
+ });
1624
+ add(changed ? "Conversation résumée. Vous pouvez continuer." : "Pas assez de contexte à résumer.");
1625
+ if (changed)
1626
+ await saveSession(session.root, messagesRef.current, session.conversationId);
1627
+ } catch (error) {
1628
+ add(error.message, "error");
1629
+ } finally {
1630
+ busyRef.current = false;
1631
+ setBusy(false);
1632
+ setPhase("");
1633
+ }
1634
+ };
1635
+ const clearConversation = () => {
1636
+ warmerRef.current.stop();
1637
+ messagesRef.current = [];
1638
+ session.conversationId = randomUUID();
1639
+ session.projectContextSent = false;
1640
+ checkpointsRef.current.clear();
1641
+ replaceLog([]);
1642
+ };
1643
+
1644
+ // Échap Échap : revenir à l'état d'avant une demande.
1645
+ const rewind = async (index, conversation, code) => {
1646
+ const checkpoints = checkpointsRef.current;
1647
+ const point = checkpoints.point(index);
1648
+ if (!point) return;
1649
+ const restored = code ? await checkpoints.restoreCode(index) : 0;
1650
+ if (conversation && point.messageCount !== null) {
1651
+ messagesRef.current.splice(point.messageCount);
1652
+ if (point.messageCount === 0) session.projectContextSent = false;
1653
+ setEntries((previous) => {
1654
+ const at = previous.findIndex((item) => item.id === point.entryId);
1655
+ return at < 0 ? previous : previous.slice(0, at);
1656
+ });
1657
+ checkpoints.truncate(index);
1658
+ const again = point.text.startsWith("/") ? "" : point.text;
1659
+ editInput(again, again.length);
1660
+ setScroll(0);
1661
+ await saveSession(session.root, messagesRef.current, session.conversationId);
1662
+ }
1663
+ add(
1664
+ [
1665
+ conversation ? "Conversation ramenée avant cette demande." : null,
1666
+ code ? `${plural(restored, "fichier rétabli", "fichiers rétablis")}.` : null,
1667
+ ]
1668
+ .filter(Boolean)
1669
+ .join(" "),
1670
+ );
1671
+ };
1672
+ const chooseRewind = (point) => {
1673
+ const files = point.files.length
1674
+ ? `${point.files.slice(0, 3).join(", ")}${point.files.length > 3 ? "…" : ""}`
1675
+ : "";
1676
+ const options = [];
1677
+ if (point.conversation && point.files.length)
1678
+ options.push({ label: "Conversation et code", detail: files, action: () => rewind(point.index, true, true) });
1679
+ if (point.conversation)
1680
+ options.push({ label: "Conversation seulement", detail: "les fichiers restent tels quels", action: () => rewind(point.index, true, false) });
1681
+ if (point.files.length)
1682
+ options.push({ label: "Code seulement", detail: files, action: () => rewind(point.index, false, true) });
1683
+ options.push({ label: "Annuler", action: () => {} });
1684
+ setMenuOptions(
1685
+ `Revenir avant « ${firstLine(point.text, 40)} »`,
1686
+ options,
1687
+ "Les commandes lancées dans le terminal ne sont pas annulées.",
1688
+ );
1689
+ };
1690
+ const openRewind = () => {
1691
+ const points = checkpointsRef.current.list();
1692
+ if (!points.length) return add("Aucune demande de cette session à laquelle revenir.");
1693
+ setMenuOptions(
1694
+ "Revenir à une demande",
1695
+ points.reverse().map((point) => ({
1696
+ label: firstLine(point.text, 60) || "Demande",
1697
+ detail: `${since(point.date)}${point.files.length ? ` · ${plural(point.files.length, "fichier", "fichiers")} à rétablir` : ""}`,
1698
+ action: () => chooseRewind(point),
1699
+ })),
1700
+ "La conversation et/ou le code reviennent à l’état d’avant cette demande.",
1701
+ );
1702
+ };
1703
+
1704
+ // # au début d'une ligne : une consigne de plus dans HENERGYQUEAI.md.
1705
+ const addNote = async (text) => {
1706
+ const file = path.join(session.root, "HENERGYQUEAI.md");
1707
+ const existing = await readFile(file, "utf8").catch(() => null);
1708
+ const lead = existing === null ? "# Consignes du projet\n\n" : existing.endsWith("\n") ? "" : "\n";
1709
+ await appendFile(file, `${lead}- ${text}\n`, "utf8");
1710
+ session.projectContext = await projectContext(session.root);
1711
+ if (session.projectContextSent) notesRef.current.push(`- ${text}`);
1712
+ add(`Consigne ajoutée à HENERGYQUEAI.md : ${text}`);
1713
+ };
1714
+
1715
+ const exportConversation = async (target) => {
1716
+ if (!messagesRef.current.length) return add("Rien à exporter pour l’instant.");
1717
+ const markdown = conversationMarkdown(messagesRef.current, { model: MODELS[session.modelId] });
1718
+ if (target) {
1719
+ const file = path.resolve(session.root, target);
1720
+ await writeFile(file, markdown, "utf8");
1721
+ return add(`Conversation enregistrée dans ${path.relative(session.root, file) || file}.`);
1722
+ }
1723
+ const name = `conversation-${new Date().toISOString().slice(0, 16).replace(/[:T]/g, "-")}.md`;
1724
+ setMenuOptions("Exporter la conversation", [
1725
+ {
1726
+ label: "Copier dans le presse-papiers",
1727
+ action: async () =>
1728
+ (await copyText(markdown))
1729
+ ? add("Conversation copiée dans le presse-papiers.")
1730
+ : add("Presse-papiers indisponible. Essayez /exporter fichier.md", "error"),
1731
+ },
1732
+ { label: "Enregistrer dans un fichier", detail: name, action: () => exportConversation(name) },
1733
+ ]);
1734
+ };
1735
+
1736
+ const openJobs = () => {
1737
+ const jobs = listJobs();
1738
+ if (!jobs.length) return add("Aucune commande en arrière-plan.");
1739
+ setMenuOptions(
1740
+ "Commandes en arrière-plan",
1741
+ jobs.map((job) => ({
1742
+ label: `${job.id} · ${firstLine(job.command, 50)}`,
1743
+ detail: job.status,
1744
+ action: () => add(job.running ? stopJob(job.id) : `${job.id} est ${job.status}.`),
1745
+ })),
1746
+ "Entrée arrête la commande choisie.",
1747
+ );
1748
+ };
1749
+
1750
+ const showHooks = () => {
1751
+ const hooks = session.hooks;
1752
+ if (!countHooks(hooks))
1753
+ return add(
1754
+ "Aucun hook. Ajoutez une clé « hooks » (avant_outil, apres_outil, fin) dans .henergyqueai/settings.json ou ~/.henergyqueai/settings.json.",
1755
+ );
1756
+ add(
1757
+ HOOK_EVENTS.flatMap((event) =>
1758
+ (hooks[event] || []).map(
1759
+ (hook) => `${event}${hook.outils ? ` (${hook.outils})` : ""} · ${hook.scope} · ${hook.commande}`,
1760
+ ),
1761
+ ).join("\n"),
1762
+ );
1763
+ };
1764
+
1765
+ const openHistorySearch = () => {
1766
+ if (!history.current.length) return add("Historique vide.");
1767
+ setMenuOptions(
1768
+ "Historique des demandes",
1769
+ history.current.map((line) => ({
1770
+ label: firstLine(line, 90),
1771
+ action: () => editInput(line, line.length),
1772
+ })),
1773
+ "Tapez pour filtrer, Entrée pour reprendre la demande.",
1774
+ );
1775
+ };
1776
+
1777
+ const pasteImage = async () => {
1778
+ const url = await clipboardImage();
1779
+ if (!url) return add("Aucune image dans le presse-papiers.");
1780
+ imageCounter.current += 1;
1781
+ imagesRef.current.set(imageCounter.current, url);
1782
+ const tag = `[Image n°${imageCounter.current}] `;
1783
+ editInput(
1784
+ inputRef.current.slice(0, cursorRef.current) + tag + inputRef.current.slice(cursorRef.current),
1785
+ cursorRef.current + tag.length,
1786
+ );
1787
+ };
1788
+ const openMainMenu = () =>
1789
+ setMenuOptions("Actions", [
1790
+ { label: "Choisir l’assistant", detail: MODELS[session.modelId], action: pickModel },
1791
+ { label: "Changer le mode", detail: session.mode, action: pickMode },
1792
+ { label: "Couleurs", detail: theme, action: pickTheme },
1793
+ { label: "État Git", action: () => showTool("etat_git") },
1794
+ { label: "Diff Git", action: () => showTool("diff_git") },
1795
+ { label: "Revue du code", detail: "analyse sans modification", action: reviewChanges },
1796
+ { label: "Compacter le contexte", detail: "résumer l’historique", action: compactConversation },
1797
+ { label: "Fichiers", detail: "parcourir le projet", action: openFiles },
1798
+ { label: "Joindre un fichier", detail: "insérer une référence", action: openReferencePicker },
1799
+ { label: "Conversations", detail: "reprendre une session", action: openSessions },
1800
+ { label: "Revenir en arrière", detail: "échap échap", action: openRewind },
1801
+ { label: "Historique", detail: "ctrl+r", action: openHistorySearch },
1802
+ { label: "Exporter", detail: "Markdown", action: () => exportConversation() },
1803
+ { label: "Commandes en arrière-plan", detail: `${listJobs().filter((job) => job.running).length} en cours`, action: openJobs },
1804
+ { label: "Hooks", detail: `${countHooks(session.hooks)} configuré(s)`, action: showHooks },
1805
+ { label: "Préparer HENERGYQUEAI.md", detail: "/init", action: () => runRequest(INIT_PROMPT, { display: "/init" }) },
1806
+ { label: "État de la session", action: showStatus },
1807
+ { label: "Utilisation", detail: "quota du jour", action: showUsage },
1808
+ { label: "Contexte", detail: "volume et consignes", action: () => add(contextReport(session, messagesRef.current)) },
1809
+ { label: "Tâches", detail: "suivi du projet", action: openTasks },
1810
+ { label: "Compétences", detail: "méthodes du projet", action: openSkills },
1811
+ { label: "Outils MCP", detail: `${session.mcp?.definitions.length || 0} disponibles`, action: showMcp },
1812
+ { label: "Diagnostic", detail: "environnement et service", action: async () => add(await diagnose(session)) },
1813
+ { label: "Nouvelle conversation", action: clearConversation },
1814
+ { label: "Quitter", action: exit },
1815
+ ]);
1816
+
1817
+ const safely = (promise) =>
1818
+ void Promise.resolve(promise).catch((error) => add(error.message, "error"));
1819
+
1820
+ const submit = (value) => {
1821
+ const line = value.trim();
1822
+ editInput("", 0);
1823
+ historyAt.current = -1;
1824
+ setShowHelp(false);
1825
+ setScroll(0);
1826
+ if (!line) return;
1827
+ if (history.current[0] !== line) history.current.unshift(line);
1828
+ history.current = history.current.slice(0, 200);
1829
+ void remember(line).catch(() => {});
1830
+ // Réponse libre à une question de l'assistant.
1831
+ if (answerRef.current) {
1832
+ push(entry({ kind: "user", text: line }));
1833
+ return answerRef.current(line);
1834
+ }
1835
+ if (line.startsWith("#")) {
1836
+ const note = line.replace(/^#+\s*/, "").trim();
1837
+ return note ? safely(addNote(note)) : undefined;
1838
+ }
1839
+ if (busyRef.current) {
1840
+ queueRef.current.push(line);
1841
+ setQueued([...queueRef.current]);
1842
+ return;
1843
+ }
1844
+ if (line.startsWith("!")) return safely(runShell(line.slice(1).trim()));
1845
+ if (!line.startsWith("/")) return void runRequest(line);
1846
+ const [raw, ...argumentsList] = line.slice(1).split(/\s+/);
1847
+ const name = raw.toLowerCase();
1848
+ const argument = argumentsList[0];
1849
+ if (name === "tache" || name === "task") {
1850
+ push(entry({ kind: "user", text: line }));
1851
+ const action = { finir: "modifier", terminer: "modifier", supprimer: "supprimer" }[argument] || argument;
1852
+ const args =
1853
+ action === "ajouter"
1854
+ ? { action, title: argumentsList.slice(1).join(" ") }
1855
+ : { action, id: argumentsList[1], status: "terminée" };
1856
+ return safely(manageTasks(session.root, args).then(add));
1857
+ }
1858
+ if (name === "competence" || name === "skill") {
1859
+ push(entry({ kind: "user", text: line }));
1860
+ return safely(readSkill(session.root, argument).then(add));
1861
+ }
1862
+ const command = findCommand(name);
1863
+ if (!command) return add(`Commande inconnue : /${raw}. Tapez / pour voir la liste.`, "error");
1864
+ if (command.name === "quitter") return exit();
1865
+ if (command.name === "effacer") return clearConversation();
1866
+ if (command.name === "revue") return void reviewChanges();
1867
+ if (command.name === "init") return void runRequest(INIT_PROMPT, { display: line });
1868
+ if (command.name === "rembobiner") return openRewind();
1869
+ push(entry({ kind: "user", text: line }));
1870
+ switch (command.name) {
1871
+ case "aide":
1872
+ return push(entry({ kind: "help" }));
1873
+ case "menu":
1874
+ return openMainMenu();
1875
+ case "modele":
1876
+ return MODELS[argument] ? safely(setAssistant(argument)) : pickModel();
1877
+ case "mode":
1878
+ return MODES[argument] ? chooseMode(argument) : pickMode();
1879
+ case "couleurs":
1880
+ return THEMES[argument] ? safely(chooseTheme(argument)) : pickTheme();
1881
+ case "plan":
1882
+ return chooseMode(session.mode === "plan" ? "demander" : "plan");
1883
+ case "git":
1884
+ return safely(showTool("etat_git"));
1885
+ case "diff":
1886
+ return safely(showTool("diff_git"));
1887
+ case "compact":
1888
+ return void compactConversation();
1889
+ case "fichiers":
1890
+ return openFiles();
1891
+ case "reprendre":
1892
+ return safely(openSessions());
1893
+ case "statut":
1894
+ return showStatus();
1895
+ case "utilisation":
1896
+ return safely(showUsage());
1897
+ case "mcp":
1898
+ return showMcp();
1899
+ case "contexte":
1900
+ return add(contextReport(session, messagesRef.current));
1901
+ case "diagnostic":
1902
+ return safely(diagnose(session).then(add));
1903
+ case "taches":
1904
+ return safely(openTasks());
1905
+ case "competences":
1906
+ return safely(openSkills());
1907
+ case "exporter":
1908
+ return safely(exportConversation(argumentsList.join(" ").trim() || undefined));
1909
+ case "processus":
1910
+ return openJobs();
1911
+ case "hooks":
1912
+ return showHooks();
1913
+ }
1914
+ };
1915
+ submitRef.current = submit;
1916
+
1917
+ const suggestions = useMemo(() => {
1918
+ if (menu || approval || dialog) return null;
1919
+ if (/^\/\S*$/.test(input) && cursor === input.length) {
1920
+ const typed = input.slice(1).toLowerCase();
1921
+ const items = COMMANDS.filter(
1922
+ (command) =>
1923
+ command.name.startsWith(typed) ||
1924
+ command.aliases?.some((alias) => alias.startsWith(typed)),
1925
+ );
1926
+ return items.length ? { type: "command", items } : null;
1927
+ }
1928
+ const at = /(?:^|\s)@([^\s@]*)$/.exec(input.slice(0, cursor));
1929
+ if (!at) return null;
1930
+ const query = at[1].toLowerCase();
1931
+ const items = filesRef.current
1932
+ .filter((file) => file.toLowerCase().includes(query))
1933
+ .sort(
1934
+ (a, b) =>
1935
+ Number(!path.basename(a).toLowerCase().startsWith(query)) -
1936
+ Number(!path.basename(b).toLowerCase().startsWith(query)) ||
1937
+ a.length - b.length,
1938
+ )
1939
+ .slice(0, 30);
1940
+ return items.length
1941
+ ? { type: "file", items, start: cursor - at[1].length - 1 }
1942
+ : null;
1943
+ }, [input, cursor, menu, approval, dialog]);
1944
+ suggestionRef.current = suggestions;
1945
+
1946
+ const filteredOptions = menuFilter
1947
+ ? (menu?.options || []).filter((option) =>
1948
+ `${option.label} ${option.detail || ""}`
1949
+ .toLocaleLowerCase("fr-FR")
1950
+ .includes(menuFilter.toLocaleLowerCase("fr-FR")),
1951
+ )
1952
+ : menu?.options || [];
1953
+
1954
+ const acceptSuggestion = (submitCommand) => {
1955
+ const list = suggestionRef.current;
1956
+ const item = list?.items[Math.min(suggestionAt, list.items.length - 1)];
1957
+ if (!item) return false;
1958
+ if (list.type === "command") {
1959
+ if (submitCommand) submit(`/${item.name}`);
1960
+ else editInput(`/${item.name} `, item.name.length + 2);
1961
+ } else insertReference(item, list.start);
1962
+ return true;
1963
+ };
1964
+
1965
+ const columns = Math.max(40, size.columns);
1966
+ const width = columns - 2;
1967
+ const rows = useMemo(() => {
1968
+ const all = entries.flatMap((item) => cachedRows(item, palette, width, frame, verbose));
1969
+ if (all.length) return all;
1970
+ const note = recent[0]
1971
+ ? `Dernière conversation ${since(recent[0].date)} · /reprendre pour la rouvrir`
1972
+ : session.projectContext
1973
+ ? "Consignes du projet chargées · /aide pour voir les commandes"
1974
+ : "Donnez vos consignes au projet dans un fichier HENERGYQUEAI.md";
1975
+ return [[seg(note, { color: palette.muted })]];
1976
+ }, [entries, palette, width, frame, recent, verbose]);
1977
+ const page = Math.max(3, size.rows - HEADER_HEIGHT - 8);
1978
+ const maxScroll = Math.max(0, rows.length - page);
1979
+ const offset = Math.min(scroll, maxScroll);
1980
+ const end = rows.length - offset;
1981
+ const visible = rows.slice(Math.max(0, end - size.rows), end);
1982
+ const maxScrollRef = useRef(0);
1983
+ maxScrollRef.current = maxScroll;
1984
+ useEffect(() => {
1985
+ if (!wheel) return;
1986
+ const onWheel = (direction) =>
1987
+ setScroll((current) =>
1988
+ Math.max(0, Math.min(maxScrollRef.current, Math.min(current, maxScrollRef.current) + direction * 3)),
1989
+ );
1990
+ wheel.on("wheel", onWheel);
1991
+ return () => wheel.off("wheel", onWheel);
1992
+ }, [wheel]);
1993
+
1994
+ useInput((value, key) => {
1995
+ if (key.ctrl && value === "c") {
1996
+ if (approval) return answerApproval(2);
1997
+ if (busyRef.current) return interrupt();
1998
+ if (inputRef.current) return editInput("", 0);
1999
+ if (exitArmed.current) return exit();
2000
+ setExitHint(true);
2001
+ exitArmed.current = setTimeout(() => {
2002
+ exitArmed.current = null;
2003
+ setExitHint(false);
2004
+ }, 1500);
2005
+ return;
2006
+ }
2007
+ if (key.pageUp || (key.ctrl && value === "b"))
2008
+ return setScroll(Math.min(maxScroll, offset + page - 2));
2009
+ if (key.pageDown || (key.ctrl && value === "f"))
2010
+ return setScroll(Math.max(0, offset - (page - 2)));
2011
+ if (approval) {
2012
+ const count = approvalOptions(approval).length;
2013
+ if (key.upArrow || key.downArrow)
2014
+ setApprovalChoice(
2015
+ (approvalChoiceRef.current =
2016
+ (approvalChoiceRef.current + (key.upArrow ? count - 1 : 1)) % count),
2017
+ );
2018
+ else if (key.return) answerApproval(approvalChoiceRef.current);
2019
+ else if (key.escape) answerApproval(2);
2020
+ else if (/^[1-3]$/.test(value)) answerApproval(Number(value) - 1);
2021
+ return;
2022
+ }
2023
+ if (dialog) {
2024
+ const count = dialog.options.length;
2025
+ if (key.upArrow || key.downArrow)
2026
+ setDialogChoice(
2027
+ (dialogChoiceRef.current =
2028
+ (dialogChoiceRef.current + (key.upArrow ? count - 1 : 1)) % count),
2029
+ );
2030
+ else if (key.return) answerDialog(dialogChoiceRef.current);
2031
+ else if (key.escape) cancelDialog();
2032
+ else if (/^[1-9]$/.test(value) && Number(value) <= count) answerDialog(Number(value) - 1);
2033
+ return;
2034
+ }
2035
+ if (key.ctrl && value === "o") return setVerbose((shown) => !shown);
2036
+ if (menu) {
2037
+ const count = filteredOptions.length;
2038
+ if (key.backspace || key.delete) {
2039
+ setMenuFilter((current) => current.slice(0, -1));
2040
+ setSelected((selectedRef.current = 0));
2041
+ } else if (key.upArrow && count)
2042
+ setSelected((selectedRef.current = (selectedRef.current - 1 + count) % count));
2043
+ else if (key.downArrow && count)
2044
+ setSelected((selectedRef.current = (selectedRef.current + 1) % count));
2045
+ else if (key.return || (/^[1-9]$/.test(value) && !menuFilter && Number(value) <= count)) {
2046
+ const option = filteredOptions[key.return ? selectedRef.current : Number(value) - 1];
2047
+ closeMenu();
2048
+ safely(option?.action?.());
2049
+ } else if (key.escape) closeMenu();
2050
+ else if (value && !key.ctrl && !key.meta) {
2051
+ setMenuFilter((current) => current + value);
2052
+ setSelected((selectedRef.current = 0));
2053
+ }
2054
+ return;
2055
+ }
2056
+ if (key.ctrl && value === "k" && !busyRef.current) return openMainMenu();
2057
+ if (key.ctrl && value === "r") return openHistorySearch();
2058
+ if ((key.meta || key.ctrl) && value === "v") return safely(pasteImage());
2059
+ if (key.tab && key.shift) {
2060
+ const at = MODE_CYCLE.indexOf(session.mode);
2061
+ return chooseMode(MODE_CYCLE[(at + 1) % MODE_CYCLE.length], true);
2062
+ }
2063
+ if (key.escape) {
2064
+ if (busyRef.current && !answerRef.current) return interrupt();
2065
+ if (answerRef.current && !inputRef.current) return interrupt();
2066
+ const now = Date.now();
2067
+ if (!busyRef.current && !inputRef.current && now - lastEscape.current < 700) {
2068
+ lastEscape.current = 0;
2069
+ return openRewind();
2070
+ }
2071
+ lastEscape.current = now;
2072
+ setShowHelp(false);
2073
+ setScroll(0);
2074
+ return editInput("", 0);
2075
+ }
2076
+ const list = suggestionRef.current;
2077
+ if (list && (key.upArrow || key.downArrow)) {
2078
+ const count = list.items.length;
2079
+ return setSuggestionAt((current) => (current + (key.upArrow ? count - 1 : 1)) % count);
2080
+ }
2081
+ if (list && key.tab) return void acceptSuggestion(false);
2082
+ if (key.return) {
2083
+ if (key.shift || key.meta) {
2084
+ const next = `${inputRef.current.slice(0, cursorRef.current)}\n${inputRef.current.slice(cursorRef.current)}`;
2085
+ return editInput(next, cursorRef.current + 1);
2086
+ }
2087
+ if (list && acceptSuggestion(list.type === "command")) return;
2088
+ return submit(inputRef.current);
2089
+ }
2090
+ if (key.upArrow || key.downArrow) {
2091
+ const next = Math.max(
2092
+ -1,
2093
+ Math.min(history.current.length - 1, historyAt.current + (key.upArrow ? 1 : -1)),
2094
+ );
2095
+ historyAt.current = next;
2096
+ const picked = next < 0 ? "" : history.current[next];
2097
+ return editInput(picked, picked.length);
2098
+ }
2099
+ if (key.leftArrow)
2100
+ return editInput(inputRef.current, Math.max(0, cursorRef.current - 1));
2101
+ if (key.rightArrow)
2102
+ return editInput(inputRef.current, Math.min(inputRef.current.length, cursorRef.current + 1));
2103
+ if (key.ctrl && value === "a") return editInput(inputRef.current, 0);
2104
+ if (key.ctrl && value === "e")
2105
+ return editInput(inputRef.current, inputRef.current.length);
2106
+ if (key.ctrl && value === "u")
2107
+ return editInput(inputRef.current.slice(cursorRef.current), 0);
2108
+ if (key.ctrl && value === "w") {
2109
+ const before = inputRef.current.slice(0, cursorRef.current).replace(/\S+\s*$/, "");
2110
+ return editInput(before + inputRef.current.slice(cursorRef.current), before.length);
2111
+ }
2112
+ if (key.backspace || key.delete) {
2113
+ if (cursorRef.current > 0)
2114
+ editInput(
2115
+ inputRef.current.slice(0, cursorRef.current - 1) + inputRef.current.slice(cursorRef.current),
2116
+ cursorRef.current - 1,
2117
+ );
2118
+ return;
2119
+ }
2120
+ if (value === "?" && !inputRef.current) return setShowHelp((shown) => !shown);
2121
+ if (value && !key.ctrl && !key.meta && !key.tab) {
2122
+ setShowHelp(false);
2123
+ const pasted = value.replace(/\r\n?/g, "\n");
2124
+ editInput(
2125
+ (inputRef.current.slice(0, cursorRef.current) + pasted + inputRef.current.slice(cursorRef.current)).slice(0, 20000),
2126
+ Math.min(20000, cursorRef.current + pasted.length),
2127
+ );
2128
+ }
2129
+ });
2130
+
2131
+ const seconds = Math.max(0, Math.round((Date.now() - startedAt.current) / 1000));
2132
+ const shownTokens = tokens + Math.round(outputChars.current / 4);
2133
+ const label = phase && phase !== "Réflexion" ? phase : verb[0];
2134
+ const [modeHint, modeColor] = MODE_HINTS[mode] || [];
2135
+ const footerLeft = exitHint
2136
+ ? h(Text, { color: palette.muted }, "Appuyez de nouveau sur Ctrl+C pour quitter")
2137
+ : input.startsWith("!")
2138
+ ? h(Text, { color: COLORS.shell }, "! mode terminal : la commande s’exécute dans le projet")
2139
+ : modeHint
2140
+ ? h(Text, { color: modeColor, wrap: "truncate-end" }, `${modeHint} `, h(Text, { color: palette.muted }, "(maj+tab pour changer)"))
2141
+ : h(
2142
+ Text,
2143
+ { color: palette.muted, wrap: "truncate-end" },
2144
+ "Entrée envoyer · Maj+Entrée ligne · PgUp/PgDn défiler · ? raccourcis",
2145
+ );
2146
+ const sent = messagesRef.current;
2147
+ const contextLeft = Math.max(0, 1 - Math.max(sent.length / 55, historySize(sent) / 240000));
2148
+ const waiting = approval || dialog;
2149
+ const footerRight = offset
2150
+ ? h(Text, { color: palette.accent }, `↓ ${plural(offset, "ligne", "lignes")} plus bas`)
2151
+ : awaitingAnswer
2152
+ ? h(Text, { color: palette.muted }, "échap pour annuler")
2153
+ : busy
2154
+ ? h(Text, { color: palette.muted }, "échap pour interrompre")
2155
+ : contextLeft <= 0.3
2156
+ ? h(Text, { color: COLORS.warning }, `Contexte restant : ${Math.round(contextLeft * 100)} % · /compact`)
2157
+ : verbose
2158
+ ? h(Text, { color: palette.muted }, "vue détaillée · ctrl+o")
2159
+ : null;
2160
+
2161
+ return h(
2162
+ Box,
2163
+ { flexDirection: "column", height: size.rows, width: columns },
2164
+ h(Header, {
2165
+ palette,
2166
+ model,
2167
+ mode,
2168
+ root: session.root,
2169
+ frame,
2170
+ busy: busy && !waiting && !awaitingAnswer,
2171
+ status: approval
2172
+ ? "En attente de votre accord"
2173
+ : dialog
2174
+ ? dialog.type === "plan"
2175
+ ? "Plan à valider"
2176
+ : "Question en attente"
2177
+ : awaitingAnswer
2178
+ ? "En attente de votre réponse"
2179
+ : busy
2180
+ ? `${label}…`
2181
+ : "Prêt à travailler",
2182
+ }),
2183
+ h(
2184
+ Box,
2185
+ {
2186
+ flexDirection: "column",
2187
+ flexGrow: 1,
2188
+ flexShrink: 1,
2189
+ overflow: "hidden",
2190
+ justifyContent: "flex-end",
2191
+ paddingX: 1,
2192
+ marginTop: 1,
2193
+ },
2194
+ h(Rows, { rows: visible }),
2195
+ ),
2196
+ busy && !waiting && !awaitingAnswer
2197
+ ? h(
2198
+ Box,
2199
+ { flexDirection: "column", flexShrink: 0, paddingX: 1 },
2200
+ h(
2201
+ Text,
2202
+ { wrap: "truncate-end" },
2203
+ h(Text, { color: palette.accent }, `${GLYPHS[frame % GLYPHS.length]} `),
2204
+ h(Shimmer, { text: `${label}…`, frame, palette }),
2205
+ h(
2206
+ Text,
2207
+ { color: palette.muted },
2208
+ ` (${seconds} s${shownTokens ? ` · ↓ ${formatTokens(shownTokens)} tokens` : ""} · ${MODELS[model]})`,
2209
+ ),
2210
+ ),
2211
+ phase
2212
+ ? null
2213
+ : h(Text, { color: palette.muted, wrap: "truncate-end" }, ` ⎿ Astuce : ${tip}`),
2214
+ )
2215
+ : null,
2216
+ ...queued.map((line, index) =>
2217
+ h(Text, { key: `q${index}`, color: palette.muted, wrap: "truncate-end" }, ` ⎿ En attente : ${line}`),
2218
+ ),
2219
+ approval
2220
+ ? h(ApprovalDialog, {
2221
+ approval,
2222
+ choice: approvalChoice,
2223
+ palette,
2224
+ columns,
2225
+ rows: size.rows,
2226
+ })
2227
+ : dialog
2228
+ ? h(ChoiceDialog, { dialog, choice: dialogChoice, palette, columns, rows: size.rows })
2229
+ : menu
2230
+ ? h(Picker, {
2231
+ menu,
2232
+ options: filteredOptions,
2233
+ active: selected,
2234
+ filter: menuFilter,
2235
+ palette,
2236
+ })
2237
+ : h(InputBox, {
2238
+ input,
2239
+ cursor,
2240
+ busy: busy && !awaitingAnswer,
2241
+ palette,
2242
+ placeholder: awaitingAnswer ? `Votre réponse : ${awaitingAnswer}` : placeholder,
2243
+ }),
2244
+ approval
2245
+ ? h(Text, { color: palette.muted }, " ↑↓ choisir · Entrée confirmer · Échap refuser")
2246
+ : dialog
2247
+ ? h(Text, { color: palette.muted }, " ↑↓ choisir · Entrée confirmer · Échap annuler")
2248
+ : menu
2249
+ ? h(Text, { color: palette.muted }, " ↑↓ choisir · Entrée confirmer · tapez pour filtrer · Échap fermer")
2250
+ : suggestions
2251
+ ? h(Suggestions, { suggestions, active: Math.min(suggestionAt, suggestions.items.length - 1), palette })
2252
+ : showHelp
2253
+ ? h(ShortcutHelp, { palette })
2254
+ : h(
2255
+ Box,
2256
+ { paddingX: 1, justifyContent: "space-between", flexShrink: 0 },
2257
+ footerLeft,
2258
+ footerRight,
2259
+ ),
2260
+ );
2261
+ }
2262
+
2263
+ const taskContent = (content, session) => {
2264
+ const task =
2265
+ session.mode === "plan"
2266
+ ? `Pour cette demande, explore le projet et propose un plan concret. Ne modifie aucun fichier et n’exécute aucune commande. Quand le plan est prêt, présente-le avec l’outil proposer_plan pour que l’utilisateur l’approuve.\n\n${content}`
2267
+ : content;
2268
+ return session.projectContextSent || !session.projectContext
2269
+ ? task
2270
+ : `Consignes locales du projet :\n\n${session.projectContext}\n\n---\nDemande actuelle :\n${task}`;
2271
+ };
2272
+
2273
+ // Le terminal signale la molette par des séquences « ESC [ < bouton ; x ; y M ».
2274
+ // Elles sont retirées du flux avant Ink pour ne jamais finir dans la saisie :
2275
+ // 64 et 65 font défiler la conversation, les clics sont ignorés.
2276
+ const MOUSE = /\u001b\[<(\d+);\d+;\d+[Mm]/g;
2277
+ export function mouseInput(source, onWheel) {
2278
+ const stream = new Readable({ read() {} });
2279
+ stream.isTTY = true;
2280
+ stream.setRawMode = (enabled) => {
2281
+ source.setRawMode?.(enabled);
2282
+ return stream;
2283
+ };
2284
+ stream.ref = () => {
2285
+ source.ref?.();
2286
+ return stream;
2287
+ };
2288
+ stream.unref = () => {
2289
+ source.unref?.();
2290
+ return stream;
2291
+ };
2292
+ let pending = "";
2293
+ const onData = (chunk) => {
2294
+ let text = pending + chunk.toString("utf8");
2295
+ pending = "";
2296
+ text = text.replace(MOUSE, (_, button) => {
2297
+ const code = Number(button);
2298
+ if (code & 64) onWheel(code & 1 ? -1 : 1);
2299
+ return "";
2300
+ });
2301
+ // Une séquence coupée entre deux lectures est gardée pour la suivante.
2302
+ const partial = /\u001b\[<[\d;]*$/.exec(text);
2303
+ if (partial) {
2304
+ pending = partial[0];
2305
+ text = text.slice(0, partial.index);
2306
+ }
2307
+ if (text) stream.push(text);
2308
+ };
2309
+ source.on("data", onData);
2310
+ stream.stop = () => {
2311
+ source.off("data", onData);
2312
+ source.pause?.();
2313
+ };
2314
+ return stream;
2315
+ }
2316
+
2317
+ export async function runTerminalApp(session, messages, { saveConfig }) {
2318
+ const recent = await listSessions(session.root).catch(() => []);
2319
+ const mouse = process.env.HENERGYQUEAI_SOURIS !== "0";
2320
+ const wheel = new EventEmitter();
2321
+ const stdin = mouse
2322
+ ? mouseInput(process.stdin, (direction) => wheel.emit("wheel", direction))
2323
+ : process.stdin;
2324
+ // Plein écran : le terminal d'origine est masqué pendant la session puis
2325
+ // retrouvé intact en quittant. La souris sert à faire défiler la conversation.
2326
+ process.stdout.write(
2327
+ `\u001b]0;HenergyqueAI\u0007\u001b[?1049h\u001b[2J\u001b[H${mouse ? "\u001b[?1000h\u001b[?1006h" : ""}`,
2328
+ );
2329
+ // Outils propres au mode interactif : questions, plan à valider, agents.
2330
+ const known = new Set((session.tools || []).map((tool) => tool.function?.name));
2331
+ session.tools = [
2332
+ ...(session.tools || []),
2333
+ ...interactiveDefinitions.filter((tool) => !known.has(tool.function.name)),
2334
+ ];
2335
+ // Barre de progression de Windows Terminal, titre de l'onglet et cloche
2336
+ // quand une longue tâche attend l'utilisateur.
2337
+ const notify = (kind) =>
2338
+ process.stdout.write(
2339
+ kind === "bell"
2340
+ ? "\u0007"
2341
+ : kind === "busy"
2342
+ ? "\u001b]9;4;3;0\u0007\u001b]0;✦ HenergyqueAI\u0007"
2343
+ : "\u001b]9;4;0;0\u0007\u001b]0;HenergyqueAI\u0007",
2344
+ );
2345
+ const instance = render(
2346
+ h(App, { session, messages, saveConfig, recent, wheel, notify }),
2347
+ { stdin, exitOnCtrlC: false, patchConsole: false },
2348
+ );
2349
+ try {
2350
+ await instance.waitUntilExit();
2351
+ } finally {
2352
+ stopAll();
2353
+ process.stdout.write(
2354
+ `${mouse ? "\u001b[?1000l\u001b[?1006l" : ""}\u001b]9;4;0;0\u0007\u001b[?1049l\u001b]0;\u0007`,
2355
+ );
2356
+ stdin.stop?.();
2357
+ }
2358
+ }
2359
+
2360
+ export { App, entryRows };