henergyqueai 0.4.2 → 0.8.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/src/compact.js ADDED
@@ -0,0 +1,56 @@
1
+ import { ask } from "./client.js";
2
+
3
+ export const historySize = (messages) =>
4
+ messages.reduce(
5
+ (size, message) => size + String(message.content || "").length,
6
+ 0,
7
+ );
8
+
9
+ export function needsCompaction(messages) {
10
+ return messages.length > 55 || historySize(messages) > 240000;
11
+ }
12
+
13
+ export async function compactHistory(
14
+ session,
15
+ messages,
16
+ { force = false, onStatus } = {},
17
+ ) {
18
+ if (!messages.length || (!force && !needsCompaction(messages))) return false;
19
+ let keepFrom = Math.max(1, messages.length - 20);
20
+ while (keepFrom < messages.length && messages[keepFrom].role !== "user")
21
+ keepFrom += 1;
22
+ if (keepFrom >= messages.length) keepFrom = messages.length;
23
+ const older = messages.slice(0, keepFrom);
24
+ if (!older.length) return false;
25
+ onStatus?.("Compression du contexte");
26
+ const transcript = JSON.stringify(older).slice(-150000);
27
+ const response = await ask({
28
+ base: session.base,
29
+ key: session.key,
30
+ modelId: session.modelId,
31
+ tools: [],
32
+ messages: [
33
+ {
34
+ role: "user",
35
+ content: `Résume fidèlement cette conversation de travail pour reprendre la suite. Garde les demandes de l’utilisateur, les décisions, les fichiers lus ou modifiés, les vérifications et ce qui reste à faire. Écarte les détails redondants. N’invente rien. Réponds avec un résumé structuré de moins de 2500 mots.\n\n${transcript}`,
36
+ },
37
+ ],
38
+ });
39
+ const summary = String(response.content || "").trim();
40
+ if (!summary)
41
+ throw new Error("Compression du contexte impossible : résumé vide.");
42
+ messages.splice(
43
+ 0,
44
+ keepFrom,
45
+ {
46
+ role: "user",
47
+ content: `Contexte résumé de la conversation précédente :\n${summary}`,
48
+ },
49
+ {
50
+ role: "assistant",
51
+ content:
52
+ "Contexte reçu. Je poursuis la tâche en tenant compte de ce résumé.",
53
+ },
54
+ );
55
+ return true;
56
+ }
package/src/confiance.js CHANGED
@@ -4,16 +4,30 @@ import { emitKeypressEvents } from "node:readline";
4
4
  // option, Entrée to confirm, Échap to back out.
5
5
  export function choose(options, { selected = 0, paint } = {}) {
6
6
  if (!process.stdin.isTTY) return Promise.resolve(null);
7
+ if (!options.length) return Promise.resolve(null);
7
8
  return new Promise((resolve) => {
8
- let at = selected;
9
+ let at = Math.max(0, Math.min(selected, options.length - 1));
9
10
  let drawn = false;
11
+ let drawnRows = 0;
10
12
  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(""),
13
+ const visible = Math.min(
14
+ options.length,
15
+ Math.max(5, (process.stdout.rows || 24) - 16),
16
16
  );
17
+ const start = Math.max(
18
+ 0,
19
+ Math.min(at - Math.floor(visible / 2), options.length - visible),
20
+ );
21
+ const rows = options
22
+ .slice(start, start + visible)
23
+ .map((option, index) => paint(option, start + index === at));
24
+ if (options.length > visible)
25
+ rows.push(
26
+ ` ${start + 1}–${start + visible} / ${options.length} · ↑↓ pour parcourir`,
27
+ );
28
+ if (drawn) process.stdout.write(`\u001b[${drawnRows}A`);
29
+ process.stdout.write(rows.map((row) => `\u001b[2K${row}\n`).join(""));
30
+ drawnRows = rows.length;
17
31
  drawn = true;
18
32
  };
19
33
  emitKeypressEvents(process.stdin);
@@ -0,0 +1,25 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { safePath } from "./tools.js";
3
+
4
+ const SOURCES = [
5
+ "HENERGYQUEAI.md",
6
+ "AGENTS.md",
7
+ ".henergyqueai/instructions.md",
8
+ ];
9
+
10
+ export async function projectContext(root) {
11
+ const parts = [];
12
+ for (const name of SOURCES) {
13
+ const file = await safePath(root, name);
14
+ if (!file) continue;
15
+ const content = await readFile(file, "utf8").catch(() => "");
16
+ if (!content.trim()) continue;
17
+ parts.push(`### ${name}\n${content.slice(0, 8000).trim()}`);
18
+ }
19
+ return parts.join("\n\n").slice(0, 16000);
20
+ }
21
+
22
+ export function withProjectContext(content, context) {
23
+ if (!context) return content;
24
+ return `Consignes locales du projet (fichiers du dossier de travail) :\n\n${context}\n\n---\nDemande actuelle :\n${content}`;
25
+ }
@@ -0,0 +1,52 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { access } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { historySize } from "./compact.js";
6
+
7
+ const runFile = promisify(execFile);
8
+
9
+ export function contextReport(session, messages) {
10
+ const characters = historySize(messages);
11
+ const estimatedTokens = Math.ceil(characters / 4);
12
+ const file = session.projectContext ? "chargées" : "aucune";
13
+ return [
14
+ `Assistant : ${session.modelId}`,
15
+ `Mode : ${session.mode}`,
16
+ `Messages : ${messages.length}`,
17
+ `Contexte échangé : ~${estimatedTokens.toLocaleString("fr-FR")} tokens (estimation)`,
18
+ `Consignes du projet : ${file}`,
19
+ `Compression automatique : ${messages.length > 55 || characters > 240000 ? "bientôt" : "pas nécessaire"}`,
20
+ ].join("\n");
21
+ }
22
+
23
+ export async function diagnose(session) {
24
+ const checks = [];
25
+ checks.push(`Node.js : ${process.version}`);
26
+ checks.push(`Dossier : ${session.root}`);
27
+ checks.push(`Connexion : ${session.key ? "clé présente" : "aucune clé"}`);
28
+ checks.push(`Consignes : ${session.projectContext ? "chargées" : "absentes"}`);
29
+ if (session.reglages?.casses?.length)
30
+ checks.push(`Réglages invalides : ${session.reglages.casses.join(", ")}`);
31
+ try {
32
+ const { stdout } = await runFile("git", ["--version"], { cwd: session.root, timeout: 5000 });
33
+ checks.push(`Git : ${stdout.trim()}`);
34
+ } catch {
35
+ checks.push("Git : indisponible");
36
+ }
37
+ try {
38
+ await access(path.join(session.root, ".git"));
39
+ checks.push("Dépôt Git : présent");
40
+ } catch {
41
+ checks.push("Dépôt Git : absent");
42
+ }
43
+ try {
44
+ const response = await fetch(`${session.base.replace(/\/$/, "")}/api/health`, {
45
+ signal: AbortSignal.timeout(5000),
46
+ });
47
+ checks.push(`Service : ${response.ok ? "accessible" : `HTTP ${response.status}`}`);
48
+ } catch {
49
+ checks.push("Service : inaccessible");
50
+ }
51
+ return checks.join("\n");
52
+ }
package/src/diff.js ADDED
@@ -0,0 +1,121 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { safePath } from "./tools.js";
3
+
4
+ const splitLines = (text) => {
5
+ const normalized = String(text ?? "").replace(/\r\n/g, "\n");
6
+ if (!normalized) return [];
7
+ const lines = normalized.split("\n");
8
+ if (lines.at(-1) === "") lines.pop();
9
+ return lines;
10
+ };
11
+
12
+ // Line diff: the shared head and tail are set aside first, so that a small
13
+ // edit in a large file only compares the lines that actually moved.
14
+ export function diffLines(before, after) {
15
+ const a = before;
16
+ const b = after;
17
+ let start = 0;
18
+ while (start < a.length && start < b.length && a[start] === b[start])
19
+ start += 1;
20
+ let endA = a.length;
21
+ let endB = b.length;
22
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
23
+ endA -= 1;
24
+ endB -= 1;
25
+ }
26
+ const ops = [];
27
+ for (let i = 0; i < start; i += 1)
28
+ ops.push({ type: " ", a: i + 1, b: i + 1, text: a[i] });
29
+ const midA = a.slice(start, endA);
30
+ const midB = b.slice(start, endB);
31
+ const n = midA.length;
32
+ const m = midB.length;
33
+ if (n * m > 4_000_000) {
34
+ midA.forEach((text, i) => ops.push({ type: "-", a: start + i + 1, text }));
35
+ midB.forEach((text, j) => ops.push({ type: "+", b: start + j + 1, text }));
36
+ } else {
37
+ const width = m + 1;
38
+ const common = new Uint32Array((n + 1) * width);
39
+ for (let i = n - 1; i >= 0; i -= 1)
40
+ for (let j = m - 1; j >= 0; j -= 1)
41
+ common[i * width + j] =
42
+ midA[i] === midB[j]
43
+ ? common[(i + 1) * width + j + 1] + 1
44
+ : Math.max(common[(i + 1) * width + j], common[i * width + j + 1]);
45
+ let i = 0;
46
+ let j = 0;
47
+ while (i < n || j < m) {
48
+ if (i < n && j < m && midA[i] === midB[j]) {
49
+ ops.push({ type: " ", a: start + i + 1, b: start + j + 1, text: midA[i] });
50
+ i += 1;
51
+ j += 1;
52
+ } else if (
53
+ i < n &&
54
+ (j >= m || common[(i + 1) * width + j] >= common[i * width + j + 1])
55
+ ) {
56
+ ops.push({ type: "-", a: start + i + 1, text: midA[i] });
57
+ i += 1;
58
+ } else {
59
+ ops.push({ type: "+", b: start + j + 1, text: midB[j] });
60
+ j += 1;
61
+ }
62
+ }
63
+ }
64
+ for (let k = 0; k < a.length - endA; k += 1)
65
+ ops.push({ type: " ", a: endA + k + 1, b: endB + k + 1, text: a[endA + k] });
66
+ return ops;
67
+ }
68
+
69
+ // Keeps the changed lines and a little context around them; the unchanged
70
+ // stretches in between become a single "…" marker.
71
+ export function hunks(ops, context = 2) {
72
+ const keep = new Array(ops.length).fill(false);
73
+ ops.forEach((op, index) => {
74
+ if (op.type === " ") return;
75
+ for (
76
+ let k = Math.max(0, index - context);
77
+ k <= Math.min(ops.length - 1, index + context);
78
+ k += 1
79
+ )
80
+ keep[k] = true;
81
+ });
82
+ const lines = [];
83
+ let skipped = false;
84
+ ops.forEach((op, index) => {
85
+ if (!keep[index]) {
86
+ skipped = true;
87
+ return;
88
+ }
89
+ if (skipped && lines.length) lines.push({ type: "…" });
90
+ skipped = false;
91
+ lines.push(op);
92
+ });
93
+ return lines;
94
+ }
95
+
96
+ // What a file edit would change, computed before it is applied.
97
+ export async function fileDiff(root, name, args = {}) {
98
+ if (!["editer_fichier", "ecrire_fichier"].includes(name)) return null;
99
+ const target = await safePath(root, args.chemin);
100
+ if (!target) return null;
101
+ const before = await readFile(target, "utf8").catch(() => null);
102
+ let after;
103
+ if (name === "ecrire_fichier") after = String(args.contenu ?? "");
104
+ else {
105
+ const oldText = String(args.ancien ?? "");
106
+ const at = before === null || !oldText ? -1 : before.indexOf(oldText);
107
+ if (at < 0) return null;
108
+ after =
109
+ before.slice(0, at) +
110
+ String(args.nouveau ?? "") +
111
+ before.slice(at + oldText.length);
112
+ }
113
+ const ops = diffLines(splitLines(before), splitLines(after));
114
+ return {
115
+ path: String(args.chemin),
116
+ created: before === null,
117
+ added: ops.filter((op) => op.type === "+").length,
118
+ removed: ops.filter((op) => op.type === "-").length,
119
+ lines: hunks(ops),
120
+ };
121
+ }
package/src/export.js ADDED
@@ -0,0 +1,25 @@
1
+ import { REFERENCE_MARKER, visibleQuestion } from "./references.js";
2
+
3
+ const textOf = (content) =>
4
+ Array.isArray(content)
5
+ ? content
6
+ .map((part) => (part.type === "text" ? part.text : "[image]"))
7
+ .join("\n")
8
+ : String(content ?? "");
9
+
10
+ // La conversation en Markdown, sans le contexte de projet ni le contenu des
11
+ // fichiers joints, que l'utilisateur n'a pas écrits.
12
+ export function conversationMarkdown(messages, { model = "Assistant", date = new Date() } = {}) {
13
+ const lines = [`# Conversation HenergyqueAI`, "", `_${date.toLocaleString("fr-FR")} · ${model}_`, ""];
14
+ for (const message of messages) {
15
+ if (message.role === "user") {
16
+ const text = visibleQuestion(textOf(message.content).split(REFERENCE_MARKER)[0]).trim();
17
+ if (text) lines.push("## Vous", "", text, "");
18
+ } else if (message.role === "assistant") {
19
+ if (message.content) lines.push(`## ${model}`, "", String(message.content).trim(), "");
20
+ for (const call of message.tool_calls || [])
21
+ lines.push(`> Outil \`${call.function?.name}\` ${String(call.function?.arguments || "").slice(0, 200)}`, "");
22
+ }
23
+ }
24
+ return `${lines.join("\n").trim()}\n`;
25
+ }
package/src/history.js ADDED
@@ -0,0 +1,26 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+
5
+ // Les demandes envoyées, tous projets confondus, pour ↑ et Ctrl+R.
6
+ export const HISTORY_FILE = path.join(homedir(), ".henergyqueai", "historique.json");
7
+ const KEEP = 200;
8
+
9
+ export async function loadHistory(file = HISTORY_FILE) {
10
+ const raw = await readFile(file, "utf8").catch(() => null);
11
+ try {
12
+ const list = JSON.parse(raw || "[]");
13
+ return Array.isArray(list) ? list.filter((item) => typeof item === "string") : [];
14
+ } catch {
15
+ return [];
16
+ }
17
+ }
18
+
19
+ export async function remember(text, file = HISTORY_FILE) {
20
+ const value = String(text || "").trim();
21
+ if (!value) return;
22
+ const list = (await loadHistory(file)).filter((item) => item !== value);
23
+ list.push(value.slice(0, 4000));
24
+ await mkdir(path.dirname(file), { recursive: true });
25
+ await writeFile(file, JSON.stringify(list.slice(-KEEP)), "utf8").catch(() => {});
26
+ }
package/src/hooks.js ADDED
@@ -0,0 +1,111 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { USER_FILE, projectFile } from "./reglages.js";
4
+
5
+ // Des commandes à vous, lancées autour du travail de l'assistant :
6
+ // "hooks": {
7
+ // "avant_outil": [{ "outils": "ecrire_fichier|editer_fichier", "commande": "…" }],
8
+ // "apres_outil": [{ "outils": "editer_fichier", "commande": "npx prettier --write \"$HENERGYQUEAI_FICHIER\"" }],
9
+ // "fin": [{ "commande": "npm test --silent" }]
10
+ // }
11
+ // Un code de sortie 2 bloque l'outil (avant), ajoute un message au résultat
12
+ // (après) ou renvoie l'assistant au travail (fin), avec la sortie d'erreur
13
+ // comme explication. Les hooks d'un projet ne tournent que dans un dossier
14
+ // auquel vous avez fait confiance.
15
+ export const HOOK_EVENTS = ["avant_outil", "apres_outil", "fin"];
16
+
17
+ const readHooks = async (file) => {
18
+ const raw = await readFile(file, "utf8").catch(() => null);
19
+ if (!raw) return {};
20
+ try {
21
+ const hooks = JSON.parse(raw)?.hooks;
22
+ return hooks && typeof hooks === "object" ? hooks : {};
23
+ } catch {
24
+ return {};
25
+ }
26
+ };
27
+
28
+ export async function loadHooks(root, { project = true } = {}) {
29
+ const sources = [
30
+ ["vous", await readHooks(USER_FILE)],
31
+ ...(project ? [["projet", await readHooks(projectFile(root))]] : []),
32
+ ];
33
+ const hooks = {};
34
+ for (const event of HOOK_EVENTS)
35
+ hooks[event] = sources.flatMap(([scope, found]) =>
36
+ (Array.isArray(found[event]) ? found[event] : [])
37
+ .filter((hook) => typeof hook?.commande === "string" && hook.commande.trim())
38
+ .map((hook) => ({
39
+ scope,
40
+ outils: typeof hook.outils === "string" ? hook.outils : "",
41
+ commande: hook.commande,
42
+ })),
43
+ );
44
+ return hooks;
45
+ }
46
+
47
+ export const countHooks = (hooks) =>
48
+ HOOK_EVENTS.reduce((total, event) => total + (hooks?.[event]?.length || 0), 0);
49
+
50
+ const matches = (hook, name) => {
51
+ if (!hook.outils || !name) return true;
52
+ try {
53
+ return new RegExp(`^(?:${hook.outils})$`, "i").test(name);
54
+ } catch {
55
+ return false;
56
+ }
57
+ };
58
+
59
+ function runOne(command, { root, env, input }) {
60
+ return new Promise((resolve) => {
61
+ const child = spawn(command, {
62
+ cwd: root,
63
+ shell: true,
64
+ windowsHide: true,
65
+ env: { ...process.env, ...env },
66
+ stdio: ["pipe", "pipe", "pipe"],
67
+ });
68
+ let stdout = "";
69
+ let stderr = "";
70
+ const timer = setTimeout(() => child.kill(), 60000);
71
+ child.stdout.on("data", (chunk) => (stdout += chunk));
72
+ child.stderr.on("data", (chunk) => (stderr += chunk));
73
+ child.on("error", (error) => {
74
+ clearTimeout(timer);
75
+ resolve({ code: 1, stdout, stderr: error.message });
76
+ });
77
+ child.on("close", (code) => {
78
+ clearTimeout(timer);
79
+ resolve({ code, stdout, stderr });
80
+ });
81
+ child.stdin.on("error", () => {});
82
+ child.stdin.end(JSON.stringify(input));
83
+ });
84
+ }
85
+
86
+ // Renvoie { blocked, notes } : blocked est le motif d'un code 2, notes les
87
+ // messages que l'assistant doit lire.
88
+ export async function runHooks(hooks, event, { root, name = "", args = {}, result } = {}) {
89
+ const list = (hooks?.[event] || []).filter((hook) => matches(hook, name));
90
+ const notes = [];
91
+ let blocked = null;
92
+ for (const hook of list) {
93
+ const outcome = await runOne(hook.commande, {
94
+ root,
95
+ env: {
96
+ HENERGYQUEAI_EVENEMENT: event,
97
+ HENERGYQUEAI_OUTIL: name,
98
+ HENERGYQUEAI_FICHIER: String(args.chemin || ""),
99
+ HENERGYQUEAI_COMMANDE: String(args.commande || ""),
100
+ },
101
+ input: { evenement: event, outil: name, arguments: args, resultat: result ?? null },
102
+ });
103
+ if (outcome.code === 2) {
104
+ const reason = String(outcome.stderr || outcome.stdout).trim().slice(0, 2000) || "Refusé par un hook.";
105
+ if (event === "avant_outil") return { blocked: reason, notes };
106
+ blocked = blocked ? `${blocked}\n${reason}` : reason;
107
+ }
108
+ }
109
+ if (blocked && event === "apres_outil") notes.push(blocked);
110
+ return { blocked, notes };
111
+ }