henergyqueai 0.4.2 → 0.8.1

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/src/tools.js CHANGED
@@ -1,10 +1,22 @@
1
- import { readFile, writeFile, readdir, stat } from "node:fs/promises";
1
+ import {
2
+ readFile,
3
+ writeFile,
4
+ readdir,
5
+ stat,
6
+ realpath,
7
+ mkdir,
8
+ } from "node:fs/promises";
2
9
  import { existsSync } from "node:fs";
3
- import { exec } from "node:child_process";
10
+ import { exec, execFile } from "node:child_process";
4
11
  import path from "node:path";
5
12
  import { promisify } from "node:util";
13
+ import { manageTasks } from "./tasks.js";
14
+ import { listSkills, readSkill } from "./skills.js";
15
+ import { readJob, startJob, stopJob } from "./background.js";
16
+ import { webRequest } from "./client.js";
6
17
 
7
18
  const run = promisify(exec);
19
+ const runFile = promisify(execFile);
8
20
  const SKIP = new Set([
9
21
  "node_modules",
10
22
  ".git",
@@ -25,6 +37,44 @@ export function inside(root, candidate) {
25
37
  return target;
26
38
  }
27
39
 
40
+ export async function safePath(root, candidate) {
41
+ const target = inside(root, candidate);
42
+ if (!target) return null;
43
+ const base = await realpath(root);
44
+ let ancestor = target;
45
+ while (!existsSync(ancestor)) {
46
+ const parent = path.dirname(ancestor);
47
+ if (parent === ancestor) return null;
48
+ ancestor = parent;
49
+ }
50
+ const actual = await realpath(ancestor).catch(() => null);
51
+ if (!actual || (actual !== base && !actual.startsWith(base + path.sep)))
52
+ return null;
53
+ return target;
54
+ }
55
+
56
+ const relativeName = (root, file) =>
57
+ path.relative(root, file).replaceAll(path.sep, "/");
58
+
59
+ const globRegex = (pattern) => {
60
+ const normalized = String(pattern || "*").replaceAll("\\", "/");
61
+ if (normalized.length > 200 || normalized.includes("..")) return null;
62
+ let expression = "";
63
+ for (let index = 0; index < normalized.length; index += 1) {
64
+ const character = normalized[index];
65
+ if (character === "*" && normalized[index + 1] === "*") {
66
+ index += 1;
67
+ if (normalized[index + 1] === "/") {
68
+ expression += "(?:.*/)?";
69
+ index += 1;
70
+ } else expression += ".*";
71
+ } else if (character === "*") expression += "[^/]*";
72
+ else if (character === "?") expression += "[^/]";
73
+ else expression += character.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
74
+ }
75
+ return new RegExp(`^${expression}$`, "i");
76
+ };
77
+
28
78
  async function walk(root, current, found, limit) {
29
79
  if (found.length >= limit) return;
30
80
  const entries = await readdir(current, { withFileTypes: true }).catch(
@@ -92,6 +142,60 @@ export const definitions = [
92
142
  },
93
143
  },
94
144
  },
145
+ {
146
+ type: "function",
147
+ function: {
148
+ name: "trouver_fichiers",
149
+ description:
150
+ "Trouve des fichiers du projet par motif, par exemple src/**/*.js ou *test*.",
151
+ parameters: {
152
+ type: "object",
153
+ properties: { motif: { type: "string" } },
154
+ required: ["motif"],
155
+ },
156
+ },
157
+ },
158
+ {
159
+ type: "function",
160
+ function: {
161
+ name: "editer_fichier",
162
+ description:
163
+ "Remplace un extrait exact et unique d'un fichier déjà lu. Préférer cet outil à la réécriture complète.",
164
+ parameters: {
165
+ type: "object",
166
+ properties: {
167
+ chemin: { type: "string" },
168
+ ancien: {
169
+ type: "string",
170
+ description: "Extrait exact à remplacer, présent une seule fois.",
171
+ },
172
+ nouveau: { type: "string", description: "Texte de remplacement." },
173
+ },
174
+ required: ["chemin", "ancien", "nouveau"],
175
+ },
176
+ },
177
+ },
178
+ {
179
+ type: "function",
180
+ function: {
181
+ name: "etat_git",
182
+ description:
183
+ "Affiche la branche, les fichiers modifiés et un résumé des changements Git du projet.",
184
+ parameters: { type: "object", properties: {} },
185
+ },
186
+ },
187
+ {
188
+ type: "function",
189
+ function: {
190
+ name: "diff_git",
191
+ description:
192
+ "Affiche le diff Git des modifications non indexées, éventuellement pour un fichier précis.",
193
+ parameters: {
194
+ type: "object",
195
+ properties: { chemin: { type: "string" } },
196
+ },
197
+ },
198
+ },
95
199
  {
96
200
  type: "function",
97
201
  function: {
@@ -125,20 +229,177 @@ export const definitions = [
125
229
  type: "string",
126
230
  description: "Pourquoi cette commande est nécessaire.",
127
231
  },
232
+ arriere_plan: {
233
+ type: "boolean",
234
+ description:
235
+ "Lance la commande sans l’attendre (serveur de développement, surveillance). Relis sa sortie avec sortie_commande.",
236
+ },
128
237
  },
129
238
  required: ["commande"],
130
239
  },
131
240
  },
132
241
  },
242
+ {
243
+ type: "function",
244
+ function: {
245
+ name: "sortie_commande",
246
+ description:
247
+ "Lit la sortie produite par une commande lancée en arrière-plan depuis la dernière lecture.",
248
+ parameters: {
249
+ type: "object",
250
+ properties: { id: { type: "string", description: "Identifiant, par exemple fond-1." } },
251
+ required: ["id"],
252
+ },
253
+ },
254
+ },
255
+ {
256
+ type: "function",
257
+ function: {
258
+ name: "arreter_commande",
259
+ description: "Arrête une commande lancée en arrière-plan.",
260
+ parameters: {
261
+ type: "object",
262
+ properties: { id: { type: "string" } },
263
+ required: ["id"],
264
+ },
265
+ },
266
+ },
267
+ {
268
+ type: "function",
269
+ function: {
270
+ name: "recherche_web",
271
+ description:
272
+ "Cherche sur le web. À utiliser pour une documentation, une version récente ou un message d’erreur que tu ne connais pas avec certitude.",
273
+ parameters: {
274
+ type: "object",
275
+ properties: { requete: { type: "string", description: "Mots-clés de la recherche." } },
276
+ required: ["requete"],
277
+ },
278
+ },
279
+ },
280
+ {
281
+ type: "function",
282
+ function: {
283
+ name: "lire_une_page",
284
+ description:
285
+ "Lit le texte d’une page web publique, par exemple une documentation trouvée avec recherche_web.",
286
+ parameters: {
287
+ type: "object",
288
+ properties: { url: { type: "string", description: "Adresse https de la page." } },
289
+ required: ["url"],
290
+ },
291
+ },
292
+ },
293
+ {
294
+ type: "function",
295
+ function: {
296
+ name: "gerer_taches",
297
+ description:
298
+ "Suit les étapes d’un travail long dans une liste persistante propre au projet. Lister, ajouter, modifier le statut ou supprimer une tâche.",
299
+ parameters: {
300
+ type: "object",
301
+ properties: {
302
+ action: { type: "string", enum: ["lister", "ajouter", "modifier", "supprimer"] },
303
+ id: { type: "string", description: "Identifiant d’une tâche existante." },
304
+ title: { type: "string", description: "Titre court pour une nouvelle tâche." },
305
+ status: { type: "string", enum: ["à faire", "en cours", "terminée"] },
306
+ },
307
+ required: ["action"],
308
+ },
309
+ },
310
+ },
311
+ {
312
+ type: "function",
313
+ function: {
314
+ name: "competence",
315
+ description:
316
+ "Liste ou lit une compétence HenergyqueAI locale (SKILL.md). Lis-la quand l’utilisateur demande une méthode propre au projet.",
317
+ parameters: {
318
+ type: "object",
319
+ properties: {
320
+ action: { type: "string", enum: ["lister", "lire"] },
321
+ nom: { type: "string", description: "Nom de la compétence à lire." },
322
+ },
323
+ required: ["action"],
324
+ },
325
+ },
326
+ },
133
327
  ];
134
328
 
135
329
  // Whether a tool needs the user's explicit blessing before it runs.
136
330
  export const needsApproval = (name) =>
137
- ["ecrire_fichier", "executer"].includes(name);
331
+ ["ecrire_fichier", "editer_fichier", "executer"].includes(name) ||
332
+ name.startsWith("mcp_");
333
+
334
+ // Outils qui ne font que lire : ils peuvent tourner ensemble, en mode plan ou
335
+ // lecture seule, et dans un sous-agent.
336
+ export const READ_ONLY = new Set([
337
+ "lire_fichier",
338
+ "lister_fichiers",
339
+ "chercher",
340
+ "trouver_fichiers",
341
+ "etat_git",
342
+ "diff_git",
343
+ "competence",
344
+ "sortie_commande",
345
+ "recherche_web",
346
+ "lire_une_page",
347
+ ]);
348
+
349
+ export function formatSearch(results) {
350
+ if (!results?.length) return "Aucun résultat.";
351
+ return results
352
+ .slice(0, 8)
353
+ .map(
354
+ (item, index) =>
355
+ `${index + 1}. ${item.titre}\n ${item.url}${item.date ? ` · ${item.date}` : ""}\n ${item.extrait || ""}`,
356
+ )
357
+ .join("\n");
358
+ }
138
359
 
139
- export async function execute(name, args, { root, approved }) {
360
+ export async function execute(name, args, { root, approved, mcp, session, signal, checkpoints }) {
361
+ if (name === "recherche_web" || name === "lire_une_page") {
362
+ if (!session?.key) return "La recherche web n’est pas disponible ici.";
363
+ try {
364
+ if (name === "recherche_web") {
365
+ const query = String(args.requete || "").trim().slice(0, 300);
366
+ if (!query) return "Requête vide.";
367
+ const data = await webRequest(session, { action: "recherche", requete: query }, signal);
368
+ return formatSearch(data.resultats);
369
+ }
370
+ const url = String(args.url || "").trim();
371
+ if (!/^https?:\/\//i.test(url)) return "Adresse invalide : elle doit commencer par https://.";
372
+ const data = await webRequest(session, { action: "page", url }, signal);
373
+ const page = data.page || {};
374
+ const text = String(page.texte ?? page.text ?? page.contenu ?? (typeof page === "string" ? page : ""));
375
+ return `${page.titre || page.title || url}\n${url}\n\n${text.slice(0, 20000) || "(page vide)"}`;
376
+ } catch (error) {
377
+ return `Web indisponible : ${error.message}`;
378
+ }
379
+ }
380
+ if (name === "sortie_commande") return readJob(String(args.id || ""));
381
+ if (name === "arreter_commande") return stopJob(String(args.id || ""));
382
+ if (
383
+ approved &&
384
+ (name === "ecrire_fichier" || name === "editer_fichier") &&
385
+ checkpoints
386
+ )
387
+ await checkpoints.remember(args.chemin);
388
+ if (name.startsWith("mcp_"))
389
+ return approved ? (await mcp?.call(name, args)) || "Outil MCP indisponible." : "L’utilisateur a refusé cet outil MCP.";
390
+ if (name === "gerer_taches") return manageTasks(root, args);
391
+ if (name === "competence") {
392
+ if (args.action === "lire") return readSkill(root, args.nom);
393
+ if (args.action === "lister") {
394
+ const skills = await listSkills(root);
395
+ return skills.length
396
+ ? skills.map((skill) => `${skill.name} · ${skill.scope}`).join("\n")
397
+ : "Aucune compétence installée.";
398
+ }
399
+ return "Action de compétence inconnue.";
400
+ }
140
401
  if (name === "lire_fichier") {
141
- const target = inside(root, args.chemin);
402
+ const target = await safePath(root, args.chemin);
142
403
  if (!target) return "Chemin hors du projet : refusé.";
143
404
  if (!existsSync(target)) return `Le fichier ${args.chemin} n’existe pas.`;
144
405
  const size = (await stat(target)).size;
@@ -153,7 +414,7 @@ export async function execute(name, args, { root, approved }) {
153
414
  }
154
415
 
155
416
  if (name === "lister_fichiers") {
156
- const target = inside(root, args.dossier || ".");
417
+ const target = await safePath(root, args.dossier || ".");
157
418
  if (!target) return "Chemin hors du projet : refusé.";
158
419
  const found = [];
159
420
  await walk(root, target, found, 400);
@@ -161,7 +422,7 @@ export async function execute(name, args, { root, approved }) {
161
422
  }
162
423
 
163
424
  if (name === "chercher") {
164
- const target = inside(root, args.dossier || ".");
425
+ const target = await safePath(root, args.dossier || ".");
165
426
  if (!target) return "Chemin hors du projet : refusé.";
166
427
  const files = [];
167
428
  await walk(root, target, files, 400);
@@ -170,9 +431,11 @@ export async function execute(name, args, { root, approved }) {
170
431
  const hits = [];
171
432
  for (const relative of files) {
172
433
  if (hits.length >= 80) break;
173
- const body = await readFile(path.join(root, relative), "utf8").catch(
174
- () => null,
175
- );
434
+ const targetFile = await safePath(root, relative);
435
+ if (!targetFile) continue;
436
+ const details = await stat(targetFile).catch(() => null);
437
+ if (!details?.isFile() || details.size > 400_000) continue;
438
+ const body = await readFile(targetFile, "utf8").catch(() => null);
176
439
  if (body === null) continue;
177
440
  body.split("\n").forEach((line, index) => {
178
441
  if (hits.length < 80 && line.includes(needle))
@@ -184,16 +447,75 @@ export async function execute(name, args, { root, approved }) {
184
447
  : `Aucune occurrence de « ${needle} ».`;
185
448
  }
186
449
 
450
+ if (name === "trouver_fichiers") {
451
+ const matcher = globRegex(args.motif);
452
+ if (!matcher) return "Motif de fichiers invalide.";
453
+ const files = [];
454
+ await walk(root, root, files, 2000);
455
+ const found = files.filter((file) => matcher.test(file)).slice(0, 200);
456
+ return found.length ? found.join("\n") : "Aucun fichier correspondant.";
457
+ }
458
+
459
+ if (name === "etat_git" || name === "diff_git") {
460
+ const argsGit =
461
+ name === "etat_git"
462
+ ? ["status", "--short", "--branch"]
463
+ : [
464
+ "diff",
465
+ "--no-ext-diff",
466
+ "--",
467
+ ...(args.chemin ? [args.chemin] : []),
468
+ ];
469
+ if (args.chemin && !(await safePath(root, args.chemin)))
470
+ return "Chemin hors du projet : refusé.";
471
+ try {
472
+ const { stdout } = await runFile("git", argsGit, {
473
+ cwd: root,
474
+ timeout: 15000,
475
+ maxBuffer: 500000,
476
+ });
477
+ return stdout.slice(0, 30000) || "(aucun changement)";
478
+ } catch (error) {
479
+ return `Git indisponible : ${String(error.stderr || error.message).slice(0, 1000)}`;
480
+ }
481
+ }
482
+
483
+ if (name === "editer_fichier") {
484
+ if (!approved) return "L’utilisateur a refusé cette modification.";
485
+ const target = await safePath(root, args.chemin);
486
+ if (!target) return "Chemin hors du projet : refusé.";
487
+ const before = await readFile(target, "utf8").catch(() => null);
488
+ if (before === null) return "Fichier illisible ou inexistant.";
489
+ const oldText = String(args.ancien ?? "");
490
+ if (!oldText) return "L’extrait à remplacer est vide.";
491
+ const first = before.indexOf(oldText);
492
+ if (first < 0)
493
+ return "L’extrait n’existe plus dans le fichier. Relis-le avant de modifier.";
494
+ if (before.indexOf(oldText, first + oldText.length) >= 0)
495
+ return "L’extrait apparaît plusieurs fois. Fournis plus de contexte.";
496
+ const after =
497
+ before.slice(0, first) +
498
+ String(args.nouveau ?? "") +
499
+ before.slice(first + oldText.length);
500
+ await writeFile(target, after, "utf8");
501
+ return `${relativeName(root, target)} modifié.`;
502
+ }
503
+
187
504
  if (name === "ecrire_fichier") {
188
505
  if (!approved) return "L’utilisateur a refusé cette modification.";
189
- const target = inside(root, args.chemin);
506
+ const target = await safePath(root, args.chemin);
190
507
  if (!target) return "Chemin hors du projet : refusé.";
508
+ await mkdir(path.dirname(target), { recursive: true });
191
509
  await writeFile(target, String(args.contenu ?? ""), "utf8");
192
510
  return `${args.chemin} enregistré.`;
193
511
  }
194
512
 
195
513
  if (name === "executer") {
196
514
  if (!approved) return "L’utilisateur a refusé cette commande.";
515
+ if (args.arriere_plan) {
516
+ const job = startJob(String(args.commande), root);
517
+ return `Commande lancée en arrière-plan : ${job.id}. Lis sa sortie avec sortie_commande et arrête-la avec arreter_commande.`;
518
+ }
197
519
  try {
198
520
  const { stdout, stderr } = await run(String(args.commande), {
199
521
  cwd: root,
package/src/ui.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createInterface } from "node:readline/promises";
2
2
  import { readFile } from "node:fs/promises";
3
- import path from "node:path";
3
+ import { safePath } from "./tools.js";
4
4
 
5
5
  const plain = !process.stdout.isTTY || process.env.NO_COLOR;
6
6
  const paint = (code, text) =>
@@ -53,23 +53,75 @@ export function activity(name, args) {
53
53
  lire_fichier: args.chemin,
54
54
  lister_fichiers: args.dossier || ".",
55
55
  chercher: `« ${args.motif} »`,
56
+ trouver_fichiers: args.motif,
56
57
  ecrire_fichier: args.chemin,
58
+ editer_fichier: args.chemin,
59
+ etat_git: "du dépôt",
60
+ diff_git: args.chemin || "du dépôt",
57
61
  executer: args.commande,
62
+ recherche_web: `« ${args.requete} »`,
63
+ lire_une_page: args.url,
64
+ sortie_commande: args.id,
65
+ arreter_commande: args.id,
58
66
  }[name];
59
67
  const label =
60
68
  {
61
69
  lire_fichier: "Lecture",
62
70
  lister_fichiers: "Exploration",
63
71
  chercher: "Recherche",
72
+ trouver_fichiers: "Fichiers",
64
73
  ecrire_fichier: "Écriture",
74
+ editer_fichier: "Modification",
75
+ etat_git: "État Git",
76
+ diff_git: "Diff Git",
65
77
  executer: "Commande",
78
+ recherche_web: "Web",
79
+ lire_une_page: "Page",
80
+ sortie_commande: "Sortie",
81
+ arreter_commande: "Arrêt",
66
82
  }[name] || name;
67
- say(style.dim(` ${label} ${detail ?? ""}`.trimEnd()));
83
+ say(
84
+ `${style.olive(" ◇")} ${style.dim(`${label} ${detail ?? ""}`.trimEnd())}`,
85
+ );
86
+ }
87
+
88
+ export async function previewEdit(root, relative, oldText, newText) {
89
+ const target = await safePath(root, relative);
90
+ if (!target) {
91
+ say(style.red(" Chemin hors du projet : refusé."));
92
+ return false;
93
+ }
94
+ const current = await readFile(target, "utf8").catch(() => null);
95
+ const oldPart = String(oldText ?? "");
96
+ if (current === null || !oldPart || !current.includes(oldPart)) {
97
+ say(
98
+ style.red(
99
+ " Aperçu indisponible : relire le fichier avant modification.",
100
+ ),
101
+ );
102
+ return false;
103
+ }
104
+ if (
105
+ current.indexOf(oldPart, current.indexOf(oldPart) + oldPart.length) >= 0
106
+ ) {
107
+ say(style.red(" Extrait ambigu : il apparaît plusieurs fois."));
108
+ return false;
109
+ }
110
+ await preview(
111
+ root,
112
+ relative,
113
+ current.replace(oldPart, String(newText ?? "")),
114
+ );
115
+ return true;
68
116
  }
69
117
 
70
118
  // Shows what would change before anything is written, the way a diff does.
71
119
  export async function preview(root, relative, next) {
72
- const target = path.resolve(root, relative);
120
+ const target = await safePath(root, relative);
121
+ if (!target) {
122
+ say(style.red(" Chemin hors du projet : refusé."));
123
+ return false;
124
+ }
73
125
  const current = await readFile(target, "utf8").catch(() => null);
74
126
  if (current === null) {
75
127
  const lines = next.split("\n");
@@ -117,11 +169,19 @@ export async function confirm(question) {
117
169
  }
118
170
  }
119
171
 
172
+ let inputHistory = [];
173
+
120
174
  export async function prompt(question) {
121
175
  const rl = createInterface({ input: process.stdin, output: process.stdout });
176
+ const decorated = process.stdout.isTTY;
177
+ if (decorated) rl.history = [...inputHistory];
178
+ const rule = ` ${style.dim("─".repeat(Math.max(20, Math.min(58, (process.stdout.columns || 80) - 6))))}`;
122
179
  try {
123
- return (await rl.question(question)).trim();
180
+ if (decorated) say(rule);
181
+ return (await rl.question(decorated ? ` ${question}` : question)).trim();
124
182
  } finally {
183
+ if (decorated) inputHistory = rl.history.slice(0, 100);
125
184
  rl.close();
185
+ if (decorated) say(rule);
126
186
  }
127
187
  }