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.
@@ -0,0 +1,399 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { interactiveDefinitions, runAgentTurn } from "./agent-loop.js";
3
+ import { compactHistory, historySize } from "./compact.js";
4
+ import { projectContext } from "./contexte.js";
5
+ import { createCheckpoints } from "./checkpoints.js";
6
+ import { listSessions, saveSession } from "./sessions.js";
7
+ import { REFERENCE_MARKER, expandReferences, referencedImages, visibleQuestion } from "./references.js";
8
+ import { execute } from "./tools.js";
9
+ import { getUsage } from "./client.js";
10
+ import { awaitAuthorization } from "./connexion.js";
11
+ import { MODES } from "./reglages.js";
12
+ import { stopAll } from "./background.js";
13
+ import { conversationMarkdown } from "./export.js";
14
+
15
+ // Mode « --ide » : l'extension VS Code dessine l'interface, ce processus garde
16
+ // le moteur. Chaque ligne reçue sur l'entrée standard est une commande JSON,
17
+ // chaque ligne écrite sur la sortie standard un événement JSON.
18
+
19
+ const MODELS = { velys: "Velys", oryne: "Oryne", aelyr: "Aelyr" };
20
+ const SHELL_MARKER = "\n\n--- Commandes lancées par l’utilisateur ---\n";
21
+ const NOTE_MARKER = "\n\n--- Consignes ajoutées au projet ---\n";
22
+ const INIT_PROMPT =
23
+ "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.";
24
+
25
+ const textContent = (content) =>
26
+ Array.isArray(content)
27
+ ? content.filter((part) => part.type === "text").map((part) => part.text).join("\n")
28
+ : String(content || "");
29
+ const cleanQuestion = (content) =>
30
+ visibleQuestion(textContent(content).split(SHELL_MARKER)[0].split(NOTE_MARKER)[0]);
31
+
32
+ const taskContent = (content, session) => {
33
+ const task =
34
+ session.mode === "plan"
35
+ ? `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}`
36
+ : content;
37
+ return session.projectContextSent || !session.projectContext
38
+ ? task
39
+ : `Consignes locales du projet :\n\n${session.projectContext}\n\n---\nDemande actuelle :\n${task}`;
40
+ };
41
+
42
+ // La conversation enregistrée, rejouée sous forme d'éléments affichables.
43
+ export function transcript(messages) {
44
+ const items = [];
45
+ const tools = new Map();
46
+ for (const message of messages) {
47
+ if (message.role === "user") {
48
+ const raw = textContent(message.content);
49
+ if (raw.startsWith("Contexte résumé de la conversation précédente"))
50
+ items.push({ kind: "notice", text: "Contexte précédent résumé." });
51
+ else if (raw.startsWith("[Vérification automatique"))
52
+ items.push({ kind: "notice", text: "Vérification automatique relancée par un hook." });
53
+ else items.push({ kind: "user", text: cleanQuestion(message.content) });
54
+ } else if (message.role === "assistant") {
55
+ const text = String(message.content || "").trim();
56
+ if (text && !text.startsWith("Contexte reçu. Je poursuis")) items.push({ kind: "assistant", text });
57
+ for (const call of message.tool_calls || []) {
58
+ let args = {};
59
+ try {
60
+ args = JSON.parse(call.function?.arguments || "{}");
61
+ } catch {}
62
+ const item = { kind: "tool", id: call.id, name: call.function?.name, args, status: "done" };
63
+ tools.set(call.id, item);
64
+ items.push(item);
65
+ }
66
+ } else if (message.role === "tool") {
67
+ const item = tools.get(message.tool_call_id);
68
+ if (item) item.result = String(message.content || "").slice(0, 6000);
69
+ }
70
+ }
71
+ return items;
72
+ }
73
+
74
+ const sessionTitle = (saved) => {
75
+ const first = saved.messages.find((message) => message.role === "user");
76
+ return cleanQuestion(first?.content || "").slice(0, 90) || "Conversation";
77
+ };
78
+
79
+ export async function runIdeServer(session, messages, { saveConfig, version }) {
80
+ const send = (event) => process.stdout.write(`${JSON.stringify(event)}\n`);
81
+ // Rien d'autre que le protocole ne doit partir sur la sortie standard.
82
+ console.log = (...args) => console.error(...args);
83
+ console.info = console.log;
84
+
85
+ const known = new Set(session.tools.map((tool) => tool.function?.name));
86
+ session.tools = [...session.tools, ...interactiveDefinitions.filter((tool) => !known.has(tool.function.name))];
87
+ let checkpoints = createCheckpoints(session.root);
88
+ let controller = null;
89
+ let busy = false;
90
+ const pending = new Map();
91
+ const notes = [];
92
+
93
+ const contextLeft = () =>
94
+ Math.max(0, 1 - Math.max(messages.length / 55, historySize(messages) / 240000));
95
+ const state = () => ({
96
+ type: "state",
97
+ version,
98
+ root: session.root,
99
+ model: session.modelId,
100
+ mode: session.mode,
101
+ models: Object.entries(MODELS).map(([id, label]) => ({ id, label })),
102
+ modes: Object.entries(MODES).map(([id, detail]) => ({ id, detail })),
103
+ connected: Boolean(session.key),
104
+ busy,
105
+ contextLeft: contextLeft(),
106
+ mcp: session.mcp?.servers?.length || 0,
107
+ });
108
+
109
+ const wait = (id, event) =>
110
+ new Promise((resolve) => {
111
+ pending.set(id, resolve);
112
+ send(event);
113
+ });
114
+ const settleAll = () => {
115
+ for (const resolve of pending.values()) resolve(null);
116
+ pending.clear();
117
+ };
118
+
119
+ const requestApproval = async (request) => {
120
+ const choice = await wait(request.id, { type: "approval", ...request });
121
+ if (choice === 1) {
122
+ if (request.name === "executer" || request.name.startsWith("mcp_")) {
123
+ const rule =
124
+ request.name === "executer"
125
+ ? `Executer(${String(request.args?.commande || "").replace(/[()]/g, "")})`
126
+ : `Mcp(${request.name.slice(4)})`;
127
+ session.permissions = {
128
+ ...session.permissions,
129
+ autoriser: [...(session.permissions?.autoriser || []), rule],
130
+ };
131
+ } else session.mode = "accepter-modifications";
132
+ send(state());
133
+ }
134
+ if (choice === 2 || choice === null) controller?.abort();
135
+ return choice === 0 || choice === 1;
136
+ };
137
+ const requestChoice = ({ id, question, options }) =>
138
+ wait(id, { type: "question", id, question, options });
139
+ const requestPlan = async ({ id, plan }) => {
140
+ const value = await wait(id, { type: "plan", id, plan });
141
+ queueMicrotask(() => send(state()));
142
+ return value;
143
+ };
144
+
145
+ const run = async ({ text, display, images = [], editor }) => {
146
+ if (busy) return send({ type: "error", message: "Une réponse est déjà en cours." });
147
+ if (!session.key) return send({ type: "auth-required" });
148
+ busy = true;
149
+ controller = new AbortController();
150
+ const started = Date.now();
151
+ send({ type: "turn-start", display: display || text });
152
+ send(state());
153
+ let aborted = false;
154
+ try {
155
+ const compacted = await compactHistory(session, messages, {
156
+ onStatus: (phase) => send({ type: "phase", text: phase }),
157
+ });
158
+ if (compacted) {
159
+ checkpoints.forgetConversation();
160
+ send({ type: "notice", text: "Contexte précédent résumé pour poursuivre la conversation." });
161
+ }
162
+ checkpoints.begin({ text: display || text, messageCount: messages.length });
163
+ send({ type: "checkpoint", index: checkpoints.list().length - 1 });
164
+ const expanded = await expandReferences(session.root, text);
165
+ const editorBlock = editor ? `${expanded.includes(REFERENCE_MARKER) ? "\n\n" : REFERENCE_MARKER}${editor}` : "";
166
+ const added = notes.splice(0);
167
+ const content = taskContent(
168
+ `${expanded}${editorBlock}${added.length ? `${NOTE_MARKER}${added.join("\n")}` : ""}`,
169
+ session,
170
+ );
171
+ const referenced = await referencedImages(session.root, text);
172
+ const pictures = [...images, ...referenced.map((image) => image.url)].slice(0, 4);
173
+ messages.push({
174
+ role: "user",
175
+ content: pictures.length
176
+ ? [{ type: "text", text: content }, ...pictures.map((url) => ({ type: "image_url", image_url: { url } }))]
177
+ : content,
178
+ });
179
+ session.projectContextSent = true;
180
+ await runAgentTurn(session, messages, {
181
+ emit: send,
182
+ requestApproval,
183
+ requestChoice,
184
+ requestPlan,
185
+ checkpoints,
186
+ signal: controller.signal,
187
+ });
188
+ } catch (error) {
189
+ aborted = controller.signal.aborted;
190
+ send(aborted ? { type: "interrupted" } : { type: "error", message: error.message });
191
+ } finally {
192
+ settleAll();
193
+ for (const message of messages)
194
+ if (Array.isArray(message.content)) {
195
+ const count = message.content.filter((part) => part.type === "image_url").length;
196
+ message.content = `${textContent(message.content)}\n[${count} image${count > 1 ? "s jointes" : " jointe"}]`;
197
+ }
198
+ session.projectContext = await projectContext(session.root).catch(() => session.projectContext);
199
+ await saveSession(session.root, messages, session.conversationId).catch((error) =>
200
+ send({ type: "error", message: `Enregistrement impossible : ${error.message}` }),
201
+ );
202
+ busy = false;
203
+ controller = null;
204
+ send({ type: "turn-end", seconds: Math.max(1, Math.round((Date.now() - started) / 1000)), aborted });
205
+ send(state());
206
+ }
207
+ };
208
+
209
+ const reset = () => {
210
+ messages.length = 0;
211
+ session.conversationId = randomUUID();
212
+ session.projectContextSent = false;
213
+ checkpoints = createCheckpoints(session.root);
214
+ };
215
+
216
+ const handlers = {
217
+ hello: () => send(state()),
218
+ send: (command) => run(command),
219
+ init: () => run({ text: INIT_PROMPT, display: "Préparer HENERGYQUEAI.md" }),
220
+ interrupt: () => {
221
+ settleAll();
222
+ controller?.abort();
223
+ },
224
+ approval: ({ id, choice }) => {
225
+ pending.get(id)?.(choice);
226
+ pending.delete(id);
227
+ },
228
+ answer: ({ id, value }) => {
229
+ pending.get(id)?.(value ?? null);
230
+ pending.delete(id);
231
+ },
232
+ model: async ({ value }) => {
233
+ if (!MODELS[value]) return;
234
+ session.modelId = value;
235
+ await saveConfig({ modelId: value });
236
+ send(state());
237
+ },
238
+ mode: ({ value }) => {
239
+ if (!MODES[value]) return;
240
+ session.mode = value;
241
+ send(state());
242
+ },
243
+ new: () => {
244
+ if (busy) return;
245
+ reset();
246
+ send({ type: "transcript", items: [] });
247
+ send(state());
248
+ },
249
+ sessions: async () => {
250
+ const list = await listSessions(session.root).catch(() => []);
251
+ send({
252
+ type: "sessions",
253
+ items: list.map((saved) => ({
254
+ id: saved.id,
255
+ title: sessionTitle(saved),
256
+ date: saved.date,
257
+ count: saved.messages.filter((message) => message.role === "user").length,
258
+ current: saved.id === session.conversationId,
259
+ })),
260
+ });
261
+ },
262
+ resume: async ({ id }) => {
263
+ if (busy) return;
264
+ const saved = (await listSessions(session.root).catch(() => [])).find((item) => item.id === id);
265
+ if (!saved) return send({ type: "error", message: "Conversation introuvable." });
266
+ reset();
267
+ messages.push(...saved.messages);
268
+ session.conversationId = saved.id || randomUUID();
269
+ session.projectContextSent = true;
270
+ send({ type: "transcript", items: transcript(messages) });
271
+ send(state());
272
+ },
273
+ rewind: async ({ index, code }) => {
274
+ if (busy) return;
275
+ const point = checkpoints.point(index);
276
+ if (!point) return;
277
+ const restored = code ? await checkpoints.restoreCode(index) : 0;
278
+ if (point.messageCount !== null) {
279
+ messages.splice(point.messageCount);
280
+ if (!messages.length) session.projectContextSent = false;
281
+ }
282
+ checkpoints.truncate(index);
283
+ await saveSession(session.root, messages, session.conversationId).catch(() => {});
284
+ send({ type: "rewound", index, text: point.text, restored, conversation: point.messageCount !== null });
285
+ send(state());
286
+ },
287
+ compact: async () => {
288
+ if (busy || !messages.length) return;
289
+ busy = true;
290
+ send(state());
291
+ try {
292
+ send({ type: "phase", text: "Compression du contexte" });
293
+ if (await compactHistory(session, messages, { force: true })) {
294
+ checkpoints.forgetConversation();
295
+ await saveSession(session.root, messages, session.conversationId);
296
+ send({ type: "notice", text: "Conversation résumée : le contexte est libéré." });
297
+ }
298
+ } catch (error) {
299
+ send({ type: "error", message: error.message });
300
+ } finally {
301
+ busy = false;
302
+ send({ type: "phase", text: "" });
303
+ send(state());
304
+ }
305
+ },
306
+ note: async ({ text }) => {
307
+ const { appendFile, readFile, writeFile } = await import("node:fs/promises");
308
+ const path = (await import("node:path")).default;
309
+ const file = path.join(session.root, "HENERGYQUEAI.md");
310
+ const current = await readFile(file, "utf8").catch(() => null);
311
+ if (current === null) await writeFile(file, `# Consignes du projet\n\n- ${text}\n`, "utf8");
312
+ else await appendFile(file, `${current.endsWith("\n") ? "" : "\n"}- ${text}\n`, "utf8");
313
+ session.projectContext = await projectContext(session.root).catch(() => session.projectContext);
314
+ if (session.projectContextSent) notes.push(text);
315
+ send({ type: "notice", text: `Consigne ajoutée à HENERGYQUEAI.md : ${text}` });
316
+ },
317
+ usage: async () => {
318
+ try {
319
+ const { plan, usage } = await getUsage(session);
320
+ send({ type: "usage", plan, used: usage.used, limit: usage.limit });
321
+ } catch (error) {
322
+ send({ type: "usage", error: error.message });
323
+ }
324
+ },
325
+ files: async ({ query = "" }) => {
326
+ const listing = await execute("trouver_fichiers", { motif: "**/*" }, { root: session.root, approved: true }).catch(
327
+ () => "",
328
+ );
329
+ const needle = String(query).toLowerCase();
330
+ const files = String(listing)
331
+ .split("\n")
332
+ .filter((file) => file && !file.startsWith("Aucun"))
333
+ .map((file) => file.replaceAll("\\", "/"));
334
+ const scored = needle
335
+ ? files
336
+ .map((file) => {
337
+ const name = file.toLowerCase();
338
+ const base = name.split("/").at(-1);
339
+ const score = base.startsWith(needle) ? 0 : base.includes(needle) ? 1 : name.includes(needle) ? 2 : -1;
340
+ return [score, file];
341
+ })
342
+ .filter(([score]) => score >= 0)
343
+ .sort((a, b) => a[0] - b[0] || a[1].length - b[1].length)
344
+ .map(([, file]) => file)
345
+ : files;
346
+ send({ type: "files", query, items: scored.slice(0, 40) });
347
+ },
348
+ export: () =>
349
+ send({
350
+ type: "export",
351
+ markdown: conversationMarkdown(messages, { model: MODELS[session.modelId] }),
352
+ }),
353
+ login: async () => {
354
+ try {
355
+ const key = await awaitAuthorization({
356
+ base: session.base,
357
+ onUrl: (url) => send({ type: "auth-url", url }),
358
+ });
359
+ session.key = key;
360
+ await saveConfig({ key });
361
+ send({ type: "notice", text: "Connecté." });
362
+ send(state());
363
+ } catch (error) {
364
+ send({ type: "error", message: error.message });
365
+ }
366
+ },
367
+ };
368
+
369
+ send(state());
370
+ if (messages.length) send({ type: "transcript", items: transcript(messages) });
371
+
372
+ await new Promise((resolve) => {
373
+ let buffer = "";
374
+ process.stdin.setEncoding("utf8");
375
+ process.stdin.on("data", (chunk) => {
376
+ buffer += chunk;
377
+ let at;
378
+ while ((at = buffer.indexOf("\n")) >= 0) {
379
+ const line = buffer.slice(0, at).trim();
380
+ buffer = buffer.slice(at + 1);
381
+ if (!line) continue;
382
+ let command;
383
+ try {
384
+ command = JSON.parse(line);
385
+ } catch {
386
+ continue;
387
+ }
388
+ Promise.resolve(handlers[command.type]?.(command)).catch((error) =>
389
+ send({ type: "error", message: error.message }),
390
+ );
391
+ }
392
+ });
393
+ process.stdin.on("end", resolve);
394
+ process.stdin.on("close", resolve);
395
+ });
396
+ settleAll();
397
+ controller?.abort();
398
+ stopAll();
399
+ }
package/src/mcp.js ADDED
@@ -0,0 +1,115 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+
5
+ export const MCP_CONFIG = path.join(homedir(), ".henergyqueai", "mcp.json");
6
+
7
+ function environment(configured = {}) {
8
+ const output = {};
9
+ for (const [key, value] of Object.entries(configured)) {
10
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || typeof value !== "string")
11
+ throw new Error("Variable d’environnement MCP invalide.");
12
+ output[key] = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => {
13
+ if (process.env[name] == null)
14
+ throw new Error(`Variable ${name} absente de l’environnement.`);
15
+ return process.env[name];
16
+ });
17
+ }
18
+ return output;
19
+ }
20
+
21
+ const safeName = (value) => String(value).replace(/[^a-zA-Z0-9_]/g, "_");
22
+
23
+ async function within(promise, milliseconds) {
24
+ let timer;
25
+ try {
26
+ return await Promise.race([
27
+ promise,
28
+ new Promise((_, reject) => {
29
+ timer = setTimeout(() => reject(new Error("délai de connexion dépassé")), milliseconds);
30
+ }),
31
+ ]);
32
+ } finally {
33
+ clearTimeout(timer);
34
+ }
35
+ }
36
+
37
+ export async function connectMcp(root, { configFile = MCP_CONFIG } = {}) {
38
+ const raw = await readFile(configFile, "utf8").catch(() => null);
39
+ const result = { definitions: [], servers: [], errors: [], close: async () => {} };
40
+ if (!raw) return result;
41
+ let config;
42
+ try {
43
+ config = JSON.parse(raw);
44
+ } catch {
45
+ result.errors.push("mcp.json est illisible.");
46
+ return result;
47
+ }
48
+ const entries = Object.entries(config?.servers || {}).slice(0, 4);
49
+ if (!entries.length) return result;
50
+ const [{ Client }, { StdioClientTransport, getDefaultEnvironment }] = await Promise.all([
51
+ import("@modelcontextprotocol/client"),
52
+ import("@modelcontextprotocol/client/stdio"),
53
+ ]);
54
+ const connections = new Map();
55
+ const clients = [];
56
+ for (const [serverName, settings] of entries) {
57
+ if (!/^[a-zA-Z][a-zA-Z0-9_-]{0,31}$/.test(serverName) ||
58
+ typeof settings?.command !== "string" || !settings.command.trim() ||
59
+ !Array.isArray(settings.args) || !settings.args.every((item) => typeof item === "string")) {
60
+ result.errors.push(`${serverName} : configuration invalide.`);
61
+ continue;
62
+ }
63
+ let client;
64
+ try {
65
+ const env = { ...getDefaultEnvironment(), ...environment(settings.env) };
66
+ client = new Client({ name: "henergyqueai", version: "0.7.0" });
67
+ const transport = new StdioClientTransport({
68
+ command: settings.command,
69
+ args: settings.args,
70
+ env,
71
+ cwd: root,
72
+ stderr: "ignore",
73
+ });
74
+ await within(client.connect(transport), 8000);
75
+ const listed = await within(client.listTools(), 8000);
76
+ let count = 0;
77
+ for (const tool of listed.tools || []) {
78
+ if (count >= 32 || result.definitions.length >= 36) break;
79
+ const name = `mcp_${safeName(serverName)}_${safeName(tool.name)}`.slice(0, 64);
80
+ if (connections.has(name) || !/^[a-zA-Z0-9_-]{1,64}$/.test(name)) continue;
81
+ connections.set(name, { client, original: tool.name });
82
+ result.definitions.push({
83
+ type: "function",
84
+ function: {
85
+ name,
86
+ description: `[${serverName}] ${String(tool.description || tool.name).slice(0, 600)}`,
87
+ parameters: tool.inputSchema || { type: "object", properties: {} },
88
+ },
89
+ });
90
+ count += 1;
91
+ }
92
+ clients.push(client);
93
+ result.servers.push({ name: serverName, tools: count });
94
+ } catch (error) {
95
+ await client?.close().catch(() => {});
96
+ result.errors.push(`${serverName} : ${error.message}`);
97
+ }
98
+ }
99
+ result.call = async (name, args) => {
100
+ const connection = connections.get(name);
101
+ if (!connection) return "Outil MCP indisponible.";
102
+ const response = await connection.client.callTool({
103
+ name: connection.original,
104
+ arguments: args,
105
+ });
106
+ const text = (response.content || [])
107
+ .map((block) => block.type === "text" ? block.text : `[${block.type}]`)
108
+ .join("\n");
109
+ return `${response.isError ? "Erreur MCP : " : ""}${text || "(aucun texte)"}`.slice(0, 12000);
110
+ };
111
+ result.close = async () => {
112
+ await Promise.allSettled(clients.map((client) => client.close()));
113
+ };
114
+ return result;
115
+ }
@@ -0,0 +1,49 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { safePath } from "./tools.js";
4
+ import { IMAGE_TYPES, imageFile } from "./clipboard.js";
5
+
6
+ export const REFERENCE_MARKER = "\n\n--- Fichiers joints à cette demande ---\n";
7
+
8
+ export async function expandReferences(root, message) {
9
+ const references = [...String(message).matchAll(/(?:^|\s)@(?:\{([^}]+)\}|([a-zA-Z0-9_./\\-]+))/g)]
10
+ .map((match) => match[1] || match[2])
11
+ .filter((name, index, all) => all.indexOf(name) === index)
12
+ .slice(0, 5);
13
+ const included = [];
14
+ for (const name of references) {
15
+ const file = await safePath(root, name);
16
+ if (!file) continue;
17
+ const info = await stat(file).catch(() => null);
18
+ if (!info?.isFile() || info.size > 100_000) continue;
19
+ const content = await readFile(file, "utf8").catch(() => null);
20
+ if (content === null || content.includes("\0")) continue;
21
+ included.push(`### ${name}\n${content.slice(0, 20000)}${content.length > 20000 ? "\n[extrait limité à 20 000 caractères]" : ""}`);
22
+ }
23
+ return included.length
24
+ ? `${message}${REFERENCE_MARKER}${included.join("\n\n")}`
25
+ : message;
26
+ }
27
+
28
+ // Les images citées avec @capture.png partent comme des images, pas comme du texte.
29
+ export async function referencedImages(root, message) {
30
+ const names = [...String(message).matchAll(/(?:^|\s)@(?:\{([^}]+)\}|([a-zA-Z0-9_./\\-]+))/g)]
31
+ .map((match) => match[1] || match[2])
32
+ .filter((name, index, all) => all.indexOf(name) === index && IMAGE_TYPES[path.extname(name).toLowerCase()]);
33
+ const images = [];
34
+ for (const name of names.slice(0, 4)) {
35
+ const file = await safePath(root, name);
36
+ const url = file && (await imageFile(file));
37
+ if (url) images.push({ name, url });
38
+ }
39
+ return images;
40
+ }
41
+
42
+ export function visibleQuestion(content) {
43
+ return String(content || "")
44
+ .split("Demande actuelle :\n")
45
+ .at(-1)
46
+ .split(REFERENCE_MARKER)[0]
47
+ .replace(/\s+/g, " ")
48
+ .trim();
49
+ }
package/src/reglages.js CHANGED
@@ -91,15 +91,21 @@ const compile = (rule) => {
91
91
 
92
92
  const SUBJECT = {
93
93
  ecrire_fichier: ["ecrire", (args) => args.chemin],
94
+ editer_fichier: ["ecrire", (args) => args.chemin],
94
95
  executer: ["executer", (args) => args.commande],
95
96
  lire_fichier: ["lire", (args) => args.chemin],
96
97
  lister_fichiers: ["lister", (args) => args.dossier || "."],
97
98
  chercher: ["chercher", (args) => args.motif],
99
+ trouver_fichiers: ["lister", (args) => args.motif],
100
+ etat_git: ["git", () => "status"],
101
+ diff_git: ["git", (args) => args.chemin || "diff"],
98
102
  };
99
103
 
100
104
  // Returns "autorise", "refuse" or null when no rule has an opinion.
101
105
  export function ruling(permissions, name, args) {
102
- const known = SUBJECT[name];
106
+ const known = name.startsWith("mcp_")
107
+ ? ["mcp", () => name.slice(4)]
108
+ : SUBJECT[name];
103
109
  if (!known) return null;
104
110
  const [tool, pick] = known;
105
111
  const value = String(pick(args) ?? "");
@@ -118,5 +124,6 @@ export const MODES = {
118
124
  "accepter-modifications":
119
125
  "écrit sans demander, mais demande pour les commandes",
120
126
  "lecture-seule": "ne peut ni écrire ni exécuter",
127
+ plan: "explore et propose un plan sans modifier",
121
128
  "sans-demander": "ne demande jamais rien",
122
129
  };
package/src/sessions.js CHANGED
@@ -1,10 +1,9 @@
1
- import { readFile, writeFile, mkdir } from "node:fs/promises";
1
+ import { readFile, writeFile, mkdir, readdir } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
- import { createHash } from "node:crypto";
3
+ import { createHash, randomUUID } from "node:crypto";
4
4
  import path from "node:path";
5
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.
6
+ // Sessions stay beside the settings, never inside the project.
8
7
  const store = (root) =>
9
8
  path.join(
10
9
  homedir(),
@@ -13,13 +12,21 @@ const store = (root) =>
13
12
  `${createHash("sha256").update(root).digest("hex").slice(0, 16)}.json`,
14
13
  );
15
14
 
16
- export async function saveSession(root, messages) {
15
+ export async function saveSession(root, messages, id) {
17
16
  const file = store(root);
18
17
  await mkdir(path.dirname(file), { recursive: true });
18
+ const previous = await lastSession(root);
19
+ if (previous?.messages?.length && messages.length && previous.id !== id) {
20
+ const archive = path.join(
21
+ path.dirname(file),
22
+ `${path.basename(file, ".json")}-${previous.date || Date.now()}-${randomUUID().slice(0, 8)}.json`,
23
+ );
24
+ await writeFile(archive, JSON.stringify(previous), "utf8");
25
+ }
19
26
  await writeFile(
20
27
  file,
21
28
  JSON.stringify(
22
- { root, date: Date.now(), messages: messages.slice(-60) },
29
+ { id, root, date: Date.now(), messages: messages.slice(-60) },
23
30
  null,
24
31
  2,
25
32
  ),
@@ -27,6 +34,35 @@ export async function saveSession(root, messages) {
27
34
  );
28
35
  }
29
36
 
37
+ export async function listSessions(root) {
38
+ const current = store(root);
39
+ const prefix = `${path.basename(current, ".json")}-`;
40
+ const names = await readdir(path.dirname(current)).catch(() => []);
41
+ const files = [
42
+ current,
43
+ ...names
44
+ .filter((name) => name.startsWith(prefix) && name.endsWith(".json"))
45
+ .map((name) => path.join(path.dirname(current), name)),
46
+ ];
47
+ const sessions = [];
48
+ for (const file of files) {
49
+ const raw = await readFile(file, "utf8").catch(() => null);
50
+ if (!raw) continue;
51
+ try {
52
+ const saved = JSON.parse(raw);
53
+ if (
54
+ saved.root === root &&
55
+ Array.isArray(saved.messages) &&
56
+ saved.messages.length
57
+ )
58
+ sessions.push(saved);
59
+ } catch {
60
+ // An incomplete archive is ignored.
61
+ }
62
+ }
63
+ return sessions.sort((a, b) => (b.date || 0) - (a.date || 0)).slice(0, 30);
64
+ }
65
+
30
66
  export async function lastSession(root) {
31
67
  const raw = await readFile(store(root), "utf8").catch(() => null);
32
68
  if (!raw) return null;