henergyqueai 0.1.0 → 0.3.0

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.
package/README.md CHANGED
@@ -10,38 +10,82 @@ npm install -g henergyqueai
10
10
 
11
11
  ## Se connecter
12
12
 
13
- Créez une clé dans **Paramètres → Clés d’API** sur [henergyqueai.fr](https://henergyqueai.fr/parametres), puis :
13
+ Rien à faire. Lancez-le :
14
14
 
15
15
  ```bash
16
- henergyqueai connexion
16
+ henergyqueai
17
17
  ```
18
18
 
19
- La clé est enregistrée dans `~/.henergyqueai/config.json`, lisible par vous seul.
19
+ Votre navigateur s’ouvre, vous cliquez sur **Autoriser**, c’est fini. Aucune clé à copier.
20
+
21
+ Au premier lancement dans un dossier, il demande si vous lui faites confiance. Répondez, et l’écran se nettoie pour lui laisser la place.
20
22
 
21
23
  ## Utiliser
22
24
 
23
25
  ```bash
24
- henergyqueai "explique-moi ce que fait src/panier.js"
26
+ henergyqueai ouvre une session
25
27
  henergyqueai "corrige le bug de date dans facture.js"
26
28
  cat erreur.log | henergyqueai "d'où vient cette erreur ?"
27
- henergyqueai # session interactive
29
+ henergyqueai -c reprend la conversation de ce dossier
28
30
  ```
29
31
 
30
- L’assistant n’a accès qu’au dossier depuis lequel vous l’avez lancé.
32
+ Il n’a accès qu’au dossier depuis lequel vous l’avez lancé.
31
33
 
32
34
  ## Options
33
35
 
34
- | Option | Effet |
35
- | -------------------------------- | ----------------------------------------- |
36
- | `--modele <aelyr\|oryne\|velys>` | Choisit l’assistant |
37
- | `--lecture-seule` | Interdit toute écriture et toute commande |
38
- | `--oui` | Accepte les modifications sans demander |
39
-
40
- ## Ce qu’il fait sans demander, et ce qu’il vous soumet
36
+ | Option | Effet |
37
+ | -------------------------------- | ------------------------------------- |
38
+ | `--modele <aelyr\|oryne\|velys>` | Choisit l’assistant |
39
+ | `--mode <mode>` | Voir les modes ci-dessous |
40
+ | `--continuer`, `-c` | Reprend la conversation du dossier |
41
+ | `--direct`, `-p` | Répond sans rien enregistrer |
42
+ | `--lecture-seule` | Raccourci pour `--mode lecture-seule` |
43
+ | `--oui` | Raccourci pour `--mode sans-demander` |
44
+
45
+ ## Modes
46
+
47
+ | Mode | Ce qu’il peut faire |
48
+ | ------------------------ | ------------------------------------------------- |
49
+ | `demander` | Demande avant d’écrire ou d’exécuter. Par défaut. |
50
+ | `accepter-modifications` | Écrit sans demander, demande pour les commandes |
51
+ | `lecture-seule` | Ne peut ni écrire ni exécuter |
52
+ | `sans-demander` | Ne demande jamais rien |
53
+
54
+ ## En session
55
+
56
+ | Commande | Effet |
57
+ | ------------------------------- | ---------------------------------------------- |
58
+ | `/aide` | Liste les commandes |
59
+ | `/modele <aelyr\|oryne\|velys>` | Change d’assistant |
60
+ | `/mode <mode>` | Change ce qu’il peut faire |
61
+ | `/statut` | Ce qui est chargé : réglages, règles, échanges |
62
+ | `/effacer` | Oublie la conversation |
63
+ | `/connexion` | Change de compte |
64
+ | `/quitter` | Sort |
65
+
66
+ ## Réglages
67
+
68
+ Deux fichiers, le plus proche l’emporte :
69
+
70
+ | Fichier | Portée |
71
+ | -------------------------------------- | ------------- |
72
+ | `~/.henergyqueai/settings.json` | Vous, partout |
73
+ | `<projet>/.henergyqueai/settings.json` | Ce projet |
74
+
75
+ ```json
76
+ {
77
+ "modele": "oryne",
78
+ "mode": "demander",
79
+ "permissions": {
80
+ "autoriser": ["Executer(npm run test *)", "Lire"],
81
+ "refuser": ["Executer(rm *)", "Ecrire(.env*)"]
82
+ }
83
+ }
84
+ ```
41
85
 
42
- Lire un fichier, explorer le projet et chercher un texte se font librement.
86
+ Une règle nomme un outil — `Lire`, `Ecrire`, `Executer`, `Lister`, `Chercher` — avec un motif facultatif où `*` remplace n’importe quoi. **Un refus l’emporte toujours sur une autorisation.**
43
87
 
44
- Écrire dans un fichier ou exécuter une commande vous est **toujours** soumis. Pour une modification, les lignes retirées et ajoutées s’affichent avant que vous répondiez.
88
+ Une règle autorisée dispense de la question. Une règle refusée arrête l’action avant qu’elle ne parte.
45
89
 
46
90
  ## Variables d’environnement
47
91
 
@@ -51,9 +95,9 @@ Lire un fichier, explorer le projet et chercher un texte se font librement.
51
95
  | `HENERGYQUEAI_URL` | Adresse du service, pour un déploiement privé |
52
96
  | `NO_COLOR` | Désactive les couleurs |
53
97
 
54
- ## Votre clé
98
+ ## Votre accès
55
99
 
56
- Elle donne accès à votre compte et consomme votre quota quotidien. Ne la placez jamais dans un dépôt de code. En cas de doute, révoquez-la depuis vos paramètres : l’accès est coupé immédiatement.
100
+ Chaque terminal autorisé crée une clé au nom de votre machine, visible dans **Paramètres → Clés d’API** avec sa date de dernière utilisation. Révocable à tout moment, sans toucher à vos autres machines.
57
101
 
58
102
  ## Licence
59
103
 
@@ -3,6 +3,7 @@ import { readFile, writeFile, mkdir, chmod } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import path from "node:path";
5
5
  import { ask } from "../src/client.js";
6
+ import { awaitAuthorization } from "../src/connexion.js";
6
7
  import { definitions, execute, needsApproval } from "../src/tools.js";
7
8
  import {
8
9
  activity,
@@ -13,10 +14,20 @@ import {
13
14
  style,
14
15
  write,
15
16
  } from "../src/ui.js";
16
- import { brand, butterfly } from "../src/butterfly.js";
17
+ import { brand, flutter, still } from "../src/butterfly.js";
18
+ import { choose, clearScreen } from "../src/confiance.js";
19
+ import {
20
+ MODES,
21
+ loadSettings,
22
+ ruling,
23
+ saveUserSetting,
24
+ } from "../src/reglages.js";
25
+ import { lastSession, saveSession } from "../src/sessions.js";
17
26
 
27
+ const VERSION = "0.3.0";
18
28
  const CONFIG = path.join(homedir(), ".henergyqueai", "config.json");
19
29
  const DEFAULT_BASE = process.env.HENERGYQUEAI_URL || "https://henergyqueai.fr";
30
+ const MODELS = { aelyr: "Aelyr", oryne: "Oryne", velys: "Velys" };
20
31
 
21
32
  async function loadConfig() {
22
33
  const raw = await readFile(CONFIG, "utf8").catch(() => null);
@@ -31,49 +42,57 @@ async function loadConfig() {
31
42
  async function saveConfig(config) {
32
43
  await mkdir(path.dirname(CONFIG), { recursive: true });
33
44
  await writeFile(CONFIG, JSON.stringify(config, null, 2), "utf8");
34
- // The key is a credential: keep it readable by its owner only.
45
+ // The key is a credential: readable by its owner only.
35
46
  await chmod(CONFIG, 0o600).catch(() => {});
36
47
  }
37
48
 
38
49
  function usage() {
39
50
  say(`
40
- ${butterfly()}
41
-
42
- ${brand("henergyqueai")} — votre assistant dans le terminal
51
+ ${brand("henergyqueai")} ${style.dim(`v${VERSION}`)}
43
52
 
44
- henergyqueai "corrige le bug de date dans src/facture.js"
45
- henergyqueai démarre une session interactive
46
- henergyqueai connexion enregistre votre clé d’API
47
- henergyqueai deconnexion efface la clé enregistrée
53
+ ${style.bold("henergyqueai")} ouvre une session
54
+ ${style.bold('henergyqueai "votre demande"')} répond puis rend la main
55
+ ${style.dim('cat fichier | henergyqueai "…"')} lit l’entrée standard
48
56
 
49
- Options
50
- --modele <aelyr|oryne|velys> choisit l’assistant
51
- --lecture-seule interdit toute écriture et commande
52
- --oui accepte les modifications sans demander
57
+ ${style.dim("--modele aelyr|oryne|velys")} choisit l’assistant
58
+ ${style.dim("--mode <mode>")} demander · accepter-modifications
59
+ ${style.dim("")} lecture-seule · sans-demander
60
+ ${style.dim("--continuer, -c")} reprend la conversation du dossier
61
+ ${style.dim("--direct, -p")} répond sans rien enregistrer
53
62
 
54
- Créez une clé depuis ${DEFAULT_BASE}/parametres`);
63
+ ${style.dim("En session : /aide /modele /mode /statut /effacer /quitter")}
64
+ ${style.dim("Réglages : ~/.henergyqueai/settings.json ou .henergyqueai/settings.json")}
65
+ `);
55
66
  }
56
67
 
57
- async function login() {
58
- say(`\n${butterfly()}\n`);
59
- say(
60
- ` Créez une clé sur ${brand(`${DEFAULT_BASE}/parametres`)}, puis collez-la ici.`,
61
- );
62
- const key = await prompt("Clé : ");
63
- if (!/^hak_[A-Za-z0-9_-]{20,90}$/.test(key)) {
64
- say(style.red("Cette clé n’a pas le format attendu."));
65
- process.exit(1);
68
+ // First run opens the browser, the way a sign-in should. Nothing to copy.
69
+ async function connect() {
70
+ say("");
71
+ still().forEach((line) => say(` ${line}`));
72
+ say("");
73
+ say(style.dim(" Ouverture de votre navigateur pour autoriser ce terminal…"));
74
+ try {
75
+ const key = await awaitAuthorization({
76
+ base: DEFAULT_BASE,
77
+ onUrl: (url, opened) => {
78
+ if (!opened) say(style.dim(" Ouvrez cette adresse :"));
79
+ say(style.dim(` ${url}\n`));
80
+ say(style.dim(" En attente de votre accord…"));
81
+ },
82
+ });
83
+ await saveConfig({ ...(await loadConfig()), key });
84
+ say(style.green("\n Connecté.\n"));
85
+ return key;
86
+ } catch (error) {
87
+ say(style.red(`\n ${error.message}\n`));
88
+ return null;
66
89
  }
67
- const config = await loadConfig();
68
- await saveConfig({ ...config, key });
69
- say(style.green(`Clé enregistrée dans ${CONFIG}.`));
70
90
  }
71
91
 
72
- // One exchange: the model answers, may ask for tools, and we loop until it
73
- // stops asking. Every write or command passes through the user first.
74
92
  async function turn(session, messages) {
75
93
  for (let round = 0; round < 24; round += 1) {
76
94
  let printed = false;
95
+ let settle = flutter(round === 0 ? "" : "");
77
96
  const answer = await ask({
78
97
  base: session.base,
79
98
  key: session.key,
@@ -81,11 +100,17 @@ async function turn(session, messages) {
81
100
  tools: session.tools,
82
101
  modelId: session.modelId,
83
102
  onDelta: (text) => {
103
+ if (settle) {
104
+ settle();
105
+ settle = null;
106
+ }
84
107
  printed = true;
85
108
  write(text);
86
109
  },
87
- });
88
- if (printed) say();
110
+ }).finally(() => settle?.());
111
+ // A short answer can arrive whole, without a single streamed fragment.
112
+ if (!printed && answer.content) write(answer.content);
113
+ if (printed || answer.content) say();
89
114
 
90
115
  if (!answer.toolCalls?.length) {
91
116
  messages.push({ role: "assistant", content: answer.content });
@@ -112,8 +137,18 @@ async function turn(session, messages) {
112
137
  activity(call.name, args);
113
138
 
114
139
  let approved = true;
115
- if (needsApproval(call.name)) {
116
- if (session.readOnly) {
140
+ const verdict = ruling(session.permissions, call.name, args);
141
+ if (verdict === "refuse") {
142
+ messages.push({
143
+ role: "tool",
144
+ tool_call_id: call.id,
145
+ content: "Interdit par les règles du projet.",
146
+ });
147
+ say(style.dim(" refusé par une règle"));
148
+ continue;
149
+ }
150
+ if (needsApproval(call.name) && verdict !== "autorise") {
151
+ if (session.mode === "lecture-seule") {
117
152
  messages.push({
118
153
  role: "tool",
119
154
  tool_call_id: call.id,
@@ -127,8 +162,12 @@ async function turn(session, messages) {
127
162
  await preview(session.root, args.chemin, String(args.contenu ?? ""));
128
163
  if (call.name === "executer" && args.raison)
129
164
  say(style.dim(` ${args.raison}`));
165
+ const silent =
166
+ session.mode === "sans-demander" ||
167
+ (session.mode === "accepter-modifications" &&
168
+ call.name === "ecrire_fichier");
130
169
  approved =
131
- session.yes ||
170
+ silent ||
132
171
  (await confirm(
133
172
  call.name === "ecrire_fichier"
134
173
  ? ` Écrire ${args.chemin} ?`
@@ -151,11 +190,138 @@ async function turn(session, messages) {
151
190
  say(style.dim(" (trop d’étapes, arrêt)"));
152
191
  }
153
192
 
193
+ async function trusted(root) {
194
+ const config = await loadConfig();
195
+ const known = Array.isArray(config.dossiers) ? config.dossiers : [];
196
+ if (known.includes(root)) return true;
197
+ if (!process.stdin.isTTY) return true;
198
+
199
+ say("");
200
+ say(` ${style.bold("Dossier de travail")}`);
201
+ say(` ${brand(root)}`);
202
+ say("");
203
+ say(
204
+ style.dim(
205
+ " Est-ce un projet que vous avez créé, ou en qui vous avez confiance ?",
206
+ ),
207
+ );
208
+ say(
209
+ style.dim(
210
+ " L’assistant pourra y lire, y écrire et y exécuter des commandes.",
211
+ ),
212
+ );
213
+ say("");
214
+ const answer = await choose(
215
+ ["Non, quitter", "Oui, je fais confiance à ce dossier"],
216
+ {
217
+ paint: (option, active) =>
218
+ active
219
+ ? ` ${brand("›")} ${style.bold(option)}`
220
+ : ` ${style.dim(option)}`,
221
+ },
222
+ );
223
+ say("");
224
+ say(style.dim(" Entrée pour confirmer · Échap pour annuler"));
225
+ if (!answer || answer.startsWith("Non")) return false;
226
+ await saveConfig({ ...config, dossiers: [...known, root].slice(-50) });
227
+ return true;
228
+ }
229
+
230
+ function header(session) {
231
+ const place = session.root.replace(homedir(), "~");
232
+ const facts = [
233
+ "",
234
+ `${brand("HenergyqueAI")} ${style.dim(`v${VERSION}`)}`,
235
+ style.dim(
236
+ `${MODELS[session.modelId] || "Velys"}${session.mode === "demander" ? "" : ` · ${session.mode}`}`,
237
+ ),
238
+ style.dim(place),
239
+ style.dim("/aide pour les commandes"),
240
+ ];
241
+ say("");
242
+ still().forEach((line, index) => say(` ${line} ${facts[index] ?? ""}`));
243
+ say("");
244
+ }
245
+
246
+ // Slash commands, handled here so a session never needs to be restarted.
247
+ async function slash(line, session, messages) {
248
+ const [name, value] = line.slice(1).trim().split(/\s+/);
249
+ if (["quitter", "exit", "q"].includes(name)) return "fin";
250
+ if (name === "aide") {
251
+ say(style.dim(" /modele <aelyr|oryne|velys> change d’assistant"));
252
+ say(style.dim(" /mode <…> change ce qu’il peut faire"));
253
+ say(style.dim(" /statut ce qui est chargé"));
254
+ say(style.dim(" /effacer oublie la conversation"));
255
+ say(style.dim(" /connexion change de compte"));
256
+ say(style.dim(" /quitter sort"));
257
+ return "fait";
258
+ }
259
+ if (name === "effacer") {
260
+ messages.length = 0;
261
+ say(style.dim(" Conversation oubliée."));
262
+ return "fait";
263
+ }
264
+ if (name === "modele") {
265
+ if (!MODELS[value]) {
266
+ say(style.dim(` Assistants : ${Object.keys(MODELS).join(", ")}`));
267
+ return "fait";
268
+ }
269
+ session.modelId = value;
270
+ await saveConfig({ ...(await loadConfig()), modelId: value });
271
+ say(style.dim(` Assistant : ${MODELS[value]}`));
272
+ return "fait";
273
+ }
274
+ if (name === "connexion") {
275
+ const key = await connect();
276
+ if (key) session.key = key;
277
+ return "fait";
278
+ }
279
+ if (name === "mode") {
280
+ if (!MODES[value]) {
281
+ for (const [nom, quoi] of Object.entries(MODES))
282
+ say(style.dim(` ${nom.padEnd(24)} ${quoi}`));
283
+ say(style.dim(` actuel : ${session.mode}`));
284
+ return "fait";
285
+ }
286
+ session.mode = value;
287
+ say(style.dim(` Mode : ${value} — ${MODES[value]}`));
288
+ return "fait";
289
+ }
290
+ if (name === "statut") {
291
+ say(
292
+ style.dim(` assistant ${MODELS[session.modelId] || session.modelId}`),
293
+ );
294
+ say(style.dim(` mode ${session.mode} — ${MODES[session.mode]}`));
295
+ say(style.dim(` dossier ${session.root}`));
296
+ say(
297
+ style.dim(
298
+ ` réglages ${session.reglages.sources.length ? session.reglages.sources.join(", ") : "aucun fichier"}`,
299
+ ),
300
+ );
301
+ const { autoriser, refuser } = session.permissions || {};
302
+ if (autoriser?.length)
303
+ say(style.dim(` autorisé ${autoriser.join(", ")}`));
304
+ if (refuser?.length) say(style.dim(` refusé ${refuser.join(", ")}`));
305
+ say(
306
+ style.dim(
307
+ ` échanges ${messages.filter((m) => m.role === "user").length}`,
308
+ ),
309
+ );
310
+ return "fait";
311
+ }
312
+ say(style.dim(` Commande inconnue. /aide pour la liste.`));
313
+ return "fait";
314
+ }
315
+
154
316
  async function main() {
155
317
  const argv = process.argv.slice(2);
156
318
  if (argv.includes("--aide") || argv.includes("-h") || argv.includes("--help"))
157
319
  return usage();
158
- if (argv[0] === "connexion" || argv[0] === "login") return login();
320
+ if (argv.includes("--version") || argv.includes("-v")) return say(VERSION);
321
+ if (argv[0] === "connexion" || argv[0] === "login") {
322
+ await connect();
323
+ return;
324
+ }
159
325
  if (argv[0] === "deconnexion" || argv[0] === "logout") {
160
326
  await saveConfig({ ...(await loadConfig()), key: undefined });
161
327
  return say("Clé effacée.");
@@ -168,30 +334,35 @@ async function main() {
168
334
  argv.splice(at, value ? 2 : 1);
169
335
  return value ?? null;
170
336
  };
171
- const modelId = take("--modele") || take("--model");
172
- const readOnly = argv.includes("--lecture-seule");
173
- const yes = argv.includes("--oui");
174
- const words = argv.filter((item) => !item.startsWith("--"));
337
+ const chosen = take("--modele") || take("--model");
338
+ const askedMode = take("--mode");
339
+ const resume = argv.includes("--continuer") || argv.includes("-c");
340
+ const once = argv.includes("--direct") || argv.includes("-p");
341
+ const words = argv.filter(
342
+ (item) => !item.startsWith("--") && item !== "-c" && item !== "-p",
343
+ );
175
344
 
176
345
  const config = await loadConfig();
177
- const key = process.env.HENERGYQUEAI_KEY || config.key;
178
- if (!key) {
179
- say(style.red("Aucune clé enregistrée."));
180
- say(`Lancez ${style.bold("henergyqueai connexion")} pour en ajouter une.`);
181
- process.exit(1);
182
- }
183
-
346
+ const root = process.cwd();
347
+ const reglages = await loadSettings(root);
184
348
  const session = {
185
349
  base: config.base || DEFAULT_BASE,
186
- key,
187
- modelId: modelId || config.modelId,
188
- root: process.cwd(),
350
+ key: process.env.HENERGYQUEAI_KEY || config.key,
351
+ modelId: chosen || config.modelId || reglages.modele || "velys",
352
+ root,
189
353
  tools: definitions,
190
- readOnly,
191
- yes,
354
+ mode:
355
+ (argv.includes("--lecture-seule") && "lecture-seule") ||
356
+ (argv.includes("--oui") && "sans-demander") ||
357
+ (MODES[askedMode] ? askedMode : null) ||
358
+ reglages.mode ||
359
+ "demander",
360
+ permissions: reglages.permissions,
361
+ reglages,
192
362
  };
363
+ for (const file of reglages.casses)
364
+ say(style.red(`Réglages illisibles, ignorés : ${file}`));
193
365
 
194
- const messages = [];
195
366
  const piped = !process.stdin.isTTY
196
367
  ? await new Promise((resolve) => {
197
368
  let raw = "";
@@ -200,26 +371,53 @@ async function main() {
200
371
  process.stdin.on("end", () => resolve(raw));
201
372
  })
202
373
  : "";
203
-
204
374
  const first = [words.join(" "), piped && `\n\n${piped.slice(0, 100000)}`]
205
375
  .filter(Boolean)
206
376
  .join("");
207
377
 
378
+ // No key yet: connect instead of telling the user what to go and do.
379
+ if (!session.key) {
380
+ if (!process.stdin.isTTY) {
381
+ say(style.red("Aucune clé. Lancez henergyqueai connexion."));
382
+ process.exit(1);
383
+ }
384
+ session.key = await connect();
385
+ if (!session.key) process.exit(1);
386
+ }
387
+
388
+ const messages = [];
389
+ if (resume) {
390
+ const saved = await lastSession(session.root);
391
+ if (saved) {
392
+ messages.push(...saved.messages);
393
+ say(
394
+ style.dim(
395
+ ` ${saved.messages.filter((m) => m.role === "user").length} échange(s) repris.`,
396
+ ),
397
+ );
398
+ } else say(style.dim(" Aucune conversation à reprendre ici."));
399
+ }
208
400
  try {
209
401
  if (first) {
210
402
  messages.push({ role: "user", content: first });
211
403
  await turn(session, messages);
404
+ if (!once) await saveSession(session.root, messages);
212
405
  return;
213
406
  }
214
- say(`\n${butterfly()}\n`);
215
- say(` ${brand("HenergyqueAI")}${style.dim(` — ${session.root}`)}`);
216
- say(style.dim(" Écrivez votre demande. « quitter » pour sortir.\n"));
407
+ if (!(await trusted(session.root))) return;
408
+ clearScreen();
409
+ header(session);
217
410
  for (;;) {
218
- const line = await prompt("› ");
411
+ const line = await prompt(`${brand("›")} `);
219
412
  if (!line) continue;
220
- if (["quitter", "exit", "quit"].includes(line.toLowerCase())) return;
413
+ if (line.startsWith("/")) {
414
+ if ((await slash(line, session, messages)) === "fin") return;
415
+ say();
416
+ continue;
417
+ }
221
418
  messages.push({ role: "user", content: line });
222
419
  await turn(session, messages);
420
+ await saveSession(session.root, messages);
223
421
  say();
224
422
  }
225
423
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "henergyqueai",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "L’assistant HenergyqueAI dans votre terminal : il lit votre projet, propose des modifications et lance des commandes, avec votre accord.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/butterfly.js CHANGED
@@ -1,30 +1,145 @@
1
- // The HenergyqueAI butterfly, in the brand's own colours. Terminals without
2
- // colour still get the shape.
1
+ // The butterfly is pixel art: each character cell carries two pixels, the upper
2
+ // one as the foreground of "▀" and the lower one as its background. Only the
3
+ // left half of the wings is written down and then mirrored, so the drawing can
4
+ // never drift out of symmetry.
3
5
  const plain = !process.stdout.isTTY || process.env.NO_COLOR;
4
6
 
5
- const rgb = (hex, text) => {
6
- if (plain) return text;
7
- const value = parseInt(hex.slice(1), 16);
8
- return `\u001b[38;2;${(value >> 16) & 255};${(value >> 8) & 255};${value & 255}m${text}\u001b[0m`;
7
+ const INK = {
8
+ a: "#f6c9a8",
9
+ b: "#edac88",
10
+ c: "#c46c4f",
11
+ d: "#95503f",
12
+ e: "#784e3e",
13
+ f: "#5d3b2f",
9
14
  };
10
15
 
11
- // Light at the wingtips, deep near the body, like the logo.
12
- const WINGS = ["#edac88", "#c46c4f", "#95503f", "#95503f", "#784e3e"];
13
- const BODY = "#5d3b2f";
16
+ const fg = (hex) => {
17
+ const v = parseInt(hex.slice(1), 16);
18
+ return `38;2;${(v >> 16) & 255};${(v >> 8) & 255};${v & 255}`;
19
+ };
20
+ const bg = (hex) => {
21
+ const v = parseInt(hex.slice(1), 16);
22
+ return `48;2;${(v >> 16) & 255};${(v >> 8) & 255};${v & 255}`;
23
+ };
24
+
25
+ // Antennae are written whole: mirroring them would undo the head turning.
26
+ const HEADS = {
27
+ gauche: ["·b..........b..", "..b........b..."],
28
+ face: ["..b.........b..", "...b.......b..."],
29
+ droite: ["..b..........b·", "...b........b.."],
30
+ };
31
+
32
+ const mirror = (rows) =>
33
+ rows.map(([half, body]) => half + body + [...half].reverse().join(""));
14
34
 
15
- const shape = [
16
- " ▗▄▄▖ ▗▄▄▖ ",
17
- " ▟███▙▓▟███▙ ",
18
- "▐█████▓█████▌",
19
- " ▜███▛▓▜███▛ ",
20
- " ▝▀▘ ▀ ▝▀▘",
35
+ const OUVERT = mirror([
36
+ [".bbbb..", "e"],
37
+ ["bbaabb.", "e"],
38
+ ["bbaabbe", "f"],
39
+ [".bbbcce", "f"],
40
+ ["..cccc.", "f"],
41
+ ["..cddc.", "f"],
42
+ ["...dd..", "e"],
43
+ [".......", "e"],
44
+ ]);
45
+
46
+ const MI = mirror([
47
+ ["...bbb.", "e"],
48
+ ["..bbaab", "e"],
49
+ ["..bbaab", "f"],
50
+ ["...bbcc", "f"],
51
+ ["...cccc", "f"],
52
+ ["...cddc", "f"],
53
+ ["....dd.", "e"],
54
+ [".......", "e"],
55
+ ]);
56
+
57
+ const FERME = mirror([
58
+ ["....bb.", "e"],
59
+ ["....baa", "e"],
60
+ ["....bba", "f"],
61
+ ["....bbc", "f"],
62
+ [".....cc", "f"],
63
+ [".....cd", "f"],
64
+ ["......d", "e"],
65
+ [".......", "e"],
66
+ ]);
67
+
68
+ // One full wingbeat, with the head glancing left then right between beats.
69
+ export const FRAMES = [
70
+ [...HEADS.face, ...OUVERT],
71
+ [...HEADS.gauche, ...MI],
72
+ [...HEADS.gauche, ...FERME],
73
+ [...HEADS.gauche, ...MI],
74
+ [...HEADS.face, ...OUVERT],
75
+ [...HEADS.droite, ...MI],
76
+ [...HEADS.droite, ...FERME],
77
+ [...HEADS.droite, ...MI],
21
78
  ];
22
79
 
23
- // The body runs down the middle, so column 6 is tinted apart from the wings.
24
- const tinted = (line, wing) =>
25
- rgb(wing, line.slice(0, 6)) + rgb(BODY, line[6]) + rgb(wing, line.slice(7));
80
+ export const WIDTH = 15;
81
+ export const HEIGHT = 5;
82
+
83
+ // Turns a pixel grid into five printable lines.
84
+ export function paint(grid) {
85
+ const lines = [];
86
+ for (let y = 0; y < grid.length; y += 2) {
87
+ let line = "";
88
+ for (let x = 0; x < WIDTH; x += 1) {
89
+ const top = INK[grid[y]?.[x]];
90
+ const bottom = INK[grid[y + 1]?.[x]];
91
+ if (plain) {
92
+ line += top || bottom ? "#" : " ";
93
+ continue;
94
+ }
95
+ if (!top && !bottom) line += " ";
96
+ else if (top && !bottom) line += `\u001b[${fg(top)}m▀\u001b[0m`;
97
+ else if (!top && bottom) line += `\u001b[${fg(bottom)}m▄\u001b[0m`;
98
+ else line += `\u001b[${fg(top)};${bg(bottom)}m▀\u001b[0m`;
99
+ }
100
+ lines.push(line);
101
+ }
102
+ return lines;
103
+ }
104
+
105
+ export const still = () => paint(FRAMES[0]);
26
106
 
27
- export const butterfly = () =>
28
- shape.map((line, index) => tinted(line, WINGS[index])).join("\n");
107
+ export const brand = (text) =>
108
+ plain ? text : `\u001b[${fg("#c46c4f")}m${text}\u001b[0m`;
29
109
 
30
- export const brand = (text) => rgb("#c46c4f", text);
110
+ // Flaps in place while something is being waited for. Returns the function
111
+ // that stops it and wipes the drawing away.
112
+ export function flutter(label = "") {
113
+ if (plain || !process.stdout.isTTY) {
114
+ if (label) process.stdout.write(`${label}\n`);
115
+ return () => {};
116
+ }
117
+ let at = 0;
118
+ let drawn = false;
119
+ const show = () => {
120
+ if (drawn) process.stdout.write(`\u001b[${HEIGHT}A`);
121
+ const lines = paint(FRAMES[at % FRAMES.length]);
122
+ process.stdout.write(
123
+ lines
124
+ .map(
125
+ (line, index) =>
126
+ `\u001b[2K${line}${index === 2 && label ? ` \u001b[2m${label}\u001b[0m` : ""}\n`,
127
+ )
128
+ .join(""),
129
+ );
130
+ drawn = true;
131
+ at += 1;
132
+ };
133
+ process.stdout.write("\u001b[?25l");
134
+ show();
135
+ const timer = setInterval(show, 140);
136
+ return () => {
137
+ clearInterval(timer);
138
+ if (drawn) {
139
+ process.stdout.write(`\u001b[${HEIGHT}A`);
140
+ process.stdout.write(`\u001b[2K\n`.repeat(HEIGHT));
141
+ process.stdout.write(`\u001b[${HEIGHT}A`);
142
+ }
143
+ process.stdout.write("\u001b[?25h");
144
+ };
145
+ }
@@ -0,0 +1,50 @@
1
+ import { emitKeypressEvents } from "node:readline";
2
+
3
+ // An arrow-key choice, the way a terminal asks a real question: one line per
4
+ // option, Entrée to confirm, Échap to back out.
5
+ export function choose(options, { selected = 0, paint } = {}) {
6
+ if (!process.stdin.isTTY) return Promise.resolve(null);
7
+ return new Promise((resolve) => {
8
+ let at = selected;
9
+ let drawn = false;
10
+ const show = () => {
11
+ if (drawn) process.stdout.write(`\u001b[${options.length}A`);
12
+ process.stdout.write(
13
+ options
14
+ .map((option, index) => `\u001b[2K${paint(option, index === at)}\n`)
15
+ .join(""),
16
+ );
17
+ drawn = true;
18
+ };
19
+ emitKeypressEvents(process.stdin);
20
+ process.stdin.setRawMode(true);
21
+ process.stdin.resume();
22
+ process.stdout.write("\u001b[?25l");
23
+ show();
24
+ const onKey = (_, key) => {
25
+ if (!key) return;
26
+ if (key.name === "up" || key.name === "k")
27
+ at = (at - 1 + options.length) % options.length;
28
+ else if (key.name === "down" || key.name === "j")
29
+ at = (at + 1) % options.length;
30
+ else if (key.name === "return" || key.name === "enter") return done(at);
31
+ else if (key.name === "escape" || (key.ctrl && key.name === "c"))
32
+ return done(null);
33
+ else return;
34
+ show();
35
+ };
36
+ const done = (value) => {
37
+ process.stdin.off("keypress", onKey);
38
+ process.stdin.setRawMode(false);
39
+ process.stdin.pause();
40
+ process.stdout.write("\u001b[?25h");
41
+ resolve(value === null ? null : options[value]);
42
+ };
43
+ process.stdin.on("keypress", onKey);
44
+ });
45
+ }
46
+
47
+ // Wipes the screen and its scrollback, so the session starts on a clean page.
48
+ export const clearScreen = () => {
49
+ if (process.stdout.isTTY) process.stdout.write("\u001b[2J\u001b[3J\u001b[H");
50
+ };
@@ -0,0 +1,78 @@
1
+ import { createServer } from "node:http";
2
+ import { randomBytes } from "node:crypto";
3
+ import { hostname } from "node:os";
4
+ import { spawn } from "node:child_process";
5
+
6
+ const openBrowser = (url) => {
7
+ const [command, args] =
8
+ process.platform === "win32"
9
+ ? ["cmd", ["/c", "start", "", url]]
10
+ : process.platform === "darwin"
11
+ ? ["open", [url]]
12
+ : ["xdg-open", [url]];
13
+ try {
14
+ spawn(command, args, { detached: true, stdio: "ignore" }).unref();
15
+ return true;
16
+ } catch {
17
+ return false;
18
+ }
19
+ };
20
+
21
+ const page = (title, body) => `<!doctype html><html lang="fr"><head>
22
+ <meta charset="utf-8"><title>${title}</title><style>
23
+ body{font-family:system-ui,sans-serif;background:#faf9f6;color:#3a4132;
24
+ display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
25
+ div{text-align:center;max-width:420px;padding:0 24px}
26
+ h1{font-size:22px;margin:0 0 10px}p{color:#626c56;line-height:1.7;font-size:14px}
27
+ </style></head><body><div><h1>${title}</h1><p>${body}</p></div></body></html>`;
28
+
29
+ // Waits for the browser to hand the key back, the way a loopback sign-in does.
30
+ // Nothing is typed, nothing is pasted.
31
+ export function awaitAuthorization({ base, onUrl, timeout = 180000 }) {
32
+ const code = randomBytes(24).toString("base64url");
33
+ return new Promise((resolve, reject) => {
34
+ const server = createServer((req, res) => {
35
+ const url = new URL(req.url, "http://127.0.0.1");
36
+ // The browser also asks for a favicon; only the landing path matters.
37
+ if (url.pathname !== "/") {
38
+ res.writeHead(204).end();
39
+ return;
40
+ }
41
+ const key = url.searchParams.get("cle");
42
+ const given = url.searchParams.get("code");
43
+ const good = key && given === code;
44
+ res.writeHead(good ? 200 : 400, {
45
+ "Content-Type": "text/html; charset=utf-8",
46
+ });
47
+ res.end(
48
+ good
49
+ ? page(
50
+ "C’est bon.",
51
+ "Vous pouvez fermer cet onglet et retourner à votre terminal.",
52
+ )
53
+ : page(
54
+ "Demande invalide.",
55
+ "Relancez henergyqueai depuis votre terminal.",
56
+ ),
57
+ );
58
+ if (!good) return;
59
+ clearTimeout(limit);
60
+ server.close();
61
+ resolve(key);
62
+ });
63
+ const limit = setTimeout(() => {
64
+ server.close();
65
+ reject(new Error("Délai dépassé : personne n’a autorisé la connexion."));
66
+ }, timeout);
67
+ server.on("error", (error) => {
68
+ clearTimeout(limit);
69
+ reject(error);
70
+ });
71
+ // Port 0 lets the system choose a free one, bound to this machine only.
72
+ server.listen(0, "127.0.0.1", () => {
73
+ const { port } = server.address();
74
+ const target = `${base}/terminal?port=${port}&code=${encodeURIComponent(code)}&machine=${encodeURIComponent(hostname().slice(0, 40))}`;
75
+ onUrl(target, openBrowser(target));
76
+ });
77
+ });
78
+ }
@@ -0,0 +1,122 @@
1
+ import { readFile, writeFile, mkdir } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+
5
+ // Settings come from two files, the nearer one winning, so a project can set
6
+ // its own rules without touching anyone's personal preferences.
7
+ // ~/.henergyqueai/settings.json you, everywhere
8
+ // <projet>/.henergyqueai/settings.json this project
9
+ export const USER_FILE = path.join(homedir(), ".henergyqueai", "settings.json");
10
+ export const projectFile = (root) =>
11
+ path.join(root, ".henergyqueai", "settings.json");
12
+
13
+ const readJson = async (file) => {
14
+ const raw = await readFile(file, "utf8").catch(() => null);
15
+ if (!raw) return null;
16
+ try {
17
+ return JSON.parse(raw);
18
+ } catch {
19
+ return { __casse: file };
20
+ }
21
+ };
22
+
23
+ const DEFAULTS = {
24
+ modele: "velys",
25
+ mode: "demander",
26
+ permissions: { autoriser: [], refuser: [] },
27
+ };
28
+
29
+ export async function loadSettings(root) {
30
+ const user = await readJson(USER_FILE);
31
+ const project = await readJson(projectFile(root));
32
+ const broken = [user, project]
33
+ .filter((item) => item?.__casse)
34
+ .map((i) => i.__casse);
35
+ const merge = (a = {}, b = {}) => ({
36
+ ...DEFAULTS,
37
+ ...a,
38
+ ...b,
39
+ permissions: {
40
+ autoriser: [
41
+ ...(a.permissions?.autoriser || []),
42
+ ...(b.permissions?.autoriser || []),
43
+ ],
44
+ refuser: [
45
+ ...(a.permissions?.refuser || []),
46
+ ...(b.permissions?.refuser || []),
47
+ ],
48
+ },
49
+ });
50
+ return {
51
+ // A missing file reads as null, which would slip past a default
52
+ // parameter: it has to become an object here.
53
+ ...merge(
54
+ user && !user.__casse ? user : {},
55
+ project && !project.__casse ? project : {},
56
+ ),
57
+ sources: [
58
+ user && !user.__casse && USER_FILE,
59
+ project && !project.__casse && projectFile(root),
60
+ ].filter(Boolean),
61
+ casses: broken,
62
+ };
63
+ }
64
+
65
+ export async function saveUserSetting(key, value) {
66
+ const current = (await readJson(USER_FILE)) || {};
67
+ const next = { ...(current.__casse ? {} : current), [key]: value };
68
+ await mkdir(path.dirname(USER_FILE), { recursive: true });
69
+ await writeFile(USER_FILE, JSON.stringify(next, null, 2), "utf8");
70
+ }
71
+
72
+ // A rule is a tool name with an optional argument pattern, where * stands for
73
+ // any run of characters: Executer(npm run test *) Ecrire(src/**)
74
+ const compile = (rule) => {
75
+ const match = /^([A-Za-z]+)(?:\((.*)\))?$/.exec(String(rule).trim());
76
+ if (!match) return null;
77
+ const [, tool, pattern] = match;
78
+ return {
79
+ tool: tool.toLowerCase(),
80
+ test:
81
+ pattern === undefined
82
+ ? () => true
83
+ : (value) =>
84
+ new RegExp(
85
+ `^${pattern
86
+ .replace(/[.+?^${}()|[\]\\]/g, "\\$&")
87
+ .replace(/\*/g, ".*")}$`,
88
+ ).test(value ?? ""),
89
+ };
90
+ };
91
+
92
+ const SUBJECT = {
93
+ ecrire_fichier: ["ecrire", (args) => args.chemin],
94
+ executer: ["executer", (args) => args.commande],
95
+ lire_fichier: ["lire", (args) => args.chemin],
96
+ lister_fichiers: ["lister", (args) => args.dossier || "."],
97
+ chercher: ["chercher", (args) => args.motif],
98
+ };
99
+
100
+ // Returns "autorise", "refuse" or null when no rule has an opinion.
101
+ export function ruling(permissions, name, args) {
102
+ const known = SUBJECT[name];
103
+ if (!known) return null;
104
+ const [tool, pick] = known;
105
+ const value = String(pick(args) ?? "");
106
+ const matches = (list) =>
107
+ (list || [])
108
+ .map(compile)
109
+ .filter(Boolean)
110
+ .some((rule) => rule.tool === tool && rule.test(value));
111
+ if (matches(permissions?.refuser)) return "refuse";
112
+ if (matches(permissions?.autoriser)) return "autorise";
113
+ return null;
114
+ }
115
+
116
+ export const MODES = {
117
+ demander: "demande avant d’écrire ou d’exécuter",
118
+ "accepter-modifications":
119
+ "écrit sans demander, mais demande pour les commandes",
120
+ "lecture-seule": "ne peut ni écrire ni exécuter",
121
+ "sans-demander": "ne demande jamais rien",
122
+ };
@@ -0,0 +1,39 @@
1
+ import { readFile, writeFile, mkdir } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { createHash } from "node:crypto";
4
+ import path from "node:path";
5
+
6
+ // One saved conversation per project folder, so a session can be picked up
7
+ // where it stopped. Kept beside the settings, never inside the project.
8
+ const store = (root) =>
9
+ path.join(
10
+ homedir(),
11
+ ".henergyqueai",
12
+ "sessions",
13
+ `${createHash("sha256").update(root).digest("hex").slice(0, 16)}.json`,
14
+ );
15
+
16
+ export async function saveSession(root, messages) {
17
+ const file = store(root);
18
+ await mkdir(path.dirname(file), { recursive: true });
19
+ await writeFile(
20
+ file,
21
+ JSON.stringify(
22
+ { root, date: Date.now(), messages: messages.slice(-60) },
23
+ null,
24
+ 2,
25
+ ),
26
+ "utf8",
27
+ );
28
+ }
29
+
30
+ export async function lastSession(root) {
31
+ const raw = await readFile(store(root), "utf8").catch(() => null);
32
+ if (!raw) return null;
33
+ try {
34
+ const saved = JSON.parse(raw);
35
+ return Array.isArray(saved.messages) ? saved : null;
36
+ } catch {
37
+ return null;
38
+ }
39
+ }