henergyqueai 0.9.5 → 0.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ide-server.js CHANGED
@@ -1,406 +1,425 @@
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
- session.surface = "vscode";
86
- const known = new Set(session.tools.map((tool) => tool.function?.name));
87
- session.tools = [...session.tools, ...interactiveDefinitions.filter((tool) => !known.has(tool.function.name))];
88
- let checkpoints = createCheckpoints(session.root);
89
- let controller = null;
90
- let busy = false;
91
- const pending = new Map();
92
- const notes = [];
93
-
94
- const contextLeft = () =>
95
- Math.max(0, 1 - Math.max(messages.length / 55, historySize(messages) / 240000));
96
- const state = () => ({
97
- type: "state",
98
- version,
99
- root: session.root,
100
- model: session.modelId,
101
- mode: session.mode,
102
- models: Object.entries(MODELS).map(([id, label]) => ({ id, label })),
103
- modes: Object.entries(MODES).map(([id, detail]) => ({ id, detail })),
104
- connected: Boolean(session.key),
105
- busy,
106
- contextLeft: contextLeft(),
107
- mcp: session.mcp?.servers?.length || 0,
108
- });
109
-
110
- const wait = (id, event) =>
111
- new Promise((resolve) => {
112
- pending.set(id, resolve);
113
- send(event);
114
- });
115
- const settleAll = () => {
116
- for (const resolve of pending.values()) resolve(null);
117
- pending.clear();
118
- };
119
-
120
- const requestApproval = async (request) => {
121
- const choice = await wait(request.id, { type: "approval", ...request });
122
- if (choice === 1) {
123
- if (request.name === "executer" || request.name.startsWith("mcp_")) {
124
- const rule =
125
- request.name === "executer"
126
- ? `Executer(${String(request.args?.commande || "").replace(/[()]/g, "")})`
127
- : `Mcp(${request.name.slice(4)})`;
128
- session.permissions = {
129
- ...session.permissions,
130
- autoriser: [...(session.permissions?.autoriser || []), rule],
131
- };
132
- } else session.mode = "accepter-modifications";
133
- send(state());
134
- }
135
- if (choice === 2 || choice === null) controller?.abort();
136
- return choice === 0 || choice === 1;
137
- };
138
- const requestChoice = ({ id, question, options }) =>
139
- wait(id, { type: "question", id, question, options });
140
- const requestPlan = async ({ id, plan }) => {
141
- const value = await wait(id, { type: "plan", id, plan });
142
- queueMicrotask(() => send(state()));
143
- return value;
144
- };
145
-
146
- const run = async ({ text, display, images = [], editor }) => {
147
- if (busy) return send({ type: "error", message: "Une réponse est déjà en cours." });
148
- if (!session.key) return send({ type: "auth-required" });
149
- busy = true;
150
- controller = new AbortController();
151
- const started = Date.now();
152
- send({ type: "turn-start", display: display || text });
153
- send(state());
154
- let aborted = false;
155
- try {
156
- const compacted = await compactHistory(session, messages, {
157
- onStatus: (phase) => send({ type: "phase", text: phase }),
158
- });
159
- if (compacted) {
160
- checkpoints.forgetConversation();
161
- send({ type: "notice", text: "Contexte précédent résumé pour poursuivre la conversation." });
162
- }
163
- checkpoints.begin({ text: display || text, messageCount: messages.length });
164
- send({ type: "checkpoint", index: checkpoints.list().length - 1 });
165
- const expanded = await expandReferences(session.root, text);
166
- const editorBlock = editor ? `${expanded.includes(REFERENCE_MARKER) ? "\n\n" : REFERENCE_MARKER}${editor}` : "";
167
- const added = notes.splice(0);
168
- const content = taskContent(
169
- `${expanded}${editorBlock}${added.length ? `${NOTE_MARKER}${added.join("\n")}` : ""}`,
170
- session,
171
- );
172
- const referenced = await referencedImages(session.root, text);
173
- const pictures = [...images, ...referenced.map((image) => image.url)].slice(0, 4);
174
- messages.push({
175
- role: "user",
176
- content: pictures.length
177
- ? [{ type: "text", text: content }, ...pictures.map((url) => ({ type: "image_url", image_url: { url } }))]
178
- : content,
179
- });
180
- session.projectContextSent = true;
181
- await runAgentTurn(session, messages, {
182
- emit: send,
183
- requestApproval,
184
- requestChoice,
185
- requestPlan,
186
- checkpoints,
187
- signal: controller.signal,
188
- });
189
- } catch (error) {
190
- aborted = controller.signal.aborted;
191
- // Connexion révoquée depuis le site : on oublie la clé et l'extension
192
- // affiche son bouton « Se connecter », sans renvoyer vers le terminal.
193
- if (!aborted && error.status === 401) {
194
- session.key = null;
195
- await saveConfig({ key: undefined }).catch(() => {});
196
- send({ type: "auth-required", reason: "revoked" });
197
- } else send(aborted ? { type: "interrupted" } : { type: "error", message: error.message });
198
- } finally {
199
- settleAll();
200
- for (const message of messages)
201
- if (Array.isArray(message.content)) {
202
- const count = message.content.filter((part) => part.type === "image_url").length;
203
- message.content = `${textContent(message.content)}\n[${count} image${count > 1 ? "s jointes" : " jointe"}]`;
204
- }
205
- session.projectContext = await projectContext(session.root).catch(() => session.projectContext);
206
- await saveSession(session.root, messages, session.conversationId).catch((error) =>
207
- send({ type: "error", message: `Enregistrement impossible : ${error.message}` }),
208
- );
209
- busy = false;
210
- controller = null;
211
- send({ type: "turn-end", seconds: Math.max(1, Math.round((Date.now() - started) / 1000)), aborted });
212
- send(state());
213
- }
214
- };
215
-
216
- const reset = () => {
217
- messages.length = 0;
218
- session.conversationId = randomUUID();
219
- session.projectContextSent = false;
220
- checkpoints = createCheckpoints(session.root);
221
- };
222
-
223
- const handlers = {
224
- hello: () => send(state()),
225
- send: (command) => run(command),
226
- init: () => run({ text: INIT_PROMPT, display: "Préparer HENERGYQUEAI.md" }),
227
- interrupt: () => {
228
- settleAll();
229
- controller?.abort();
230
- },
231
- approval: ({ id, choice }) => {
232
- pending.get(id)?.(choice);
233
- pending.delete(id);
234
- },
235
- answer: ({ id, value }) => {
236
- pending.get(id)?.(value ?? null);
237
- pending.delete(id);
238
- },
239
- model: async ({ value }) => {
240
- if (!MODELS[value]) return;
241
- session.modelId = value;
242
- await saveConfig({ modelId: value });
243
- send(state());
244
- },
245
- mode: ({ value }) => {
246
- if (!MODES[value]) return;
247
- session.mode = value;
248
- send(state());
249
- },
250
- new: () => {
251
- if (busy) return;
252
- reset();
253
- send({ type: "transcript", items: [] });
254
- send(state());
255
- },
256
- sessions: async () => {
257
- const list = await listSessions(session.root).catch(() => []);
258
- send({
259
- type: "sessions",
260
- items: list.map((saved) => ({
261
- id: saved.id,
262
- title: sessionTitle(saved),
263
- date: saved.date,
264
- count: saved.messages.filter((message) => message.role === "user").length,
265
- current: saved.id === session.conversationId,
266
- })),
267
- });
268
- },
269
- resume: async ({ id }) => {
270
- if (busy) return;
271
- const saved = (await listSessions(session.root).catch(() => [])).find((item) => item.id === id);
272
- if (!saved) return send({ type: "error", message: "Conversation introuvable." });
273
- reset();
274
- messages.push(...saved.messages);
275
- session.conversationId = saved.id || randomUUID();
276
- session.projectContextSent = true;
277
- send({ type: "transcript", items: transcript(messages) });
278
- send(state());
279
- },
280
- rewind: async ({ index, code }) => {
281
- if (busy) return;
282
- const point = checkpoints.point(index);
283
- if (!point) return;
284
- const restored = code ? await checkpoints.restoreCode(index) : 0;
285
- if (point.messageCount !== null) {
286
- messages.splice(point.messageCount);
287
- if (!messages.length) session.projectContextSent = false;
288
- }
289
- checkpoints.truncate(index);
290
- await saveSession(session.root, messages, session.conversationId).catch(() => {});
291
- send({ type: "rewound", index, text: point.text, restored, conversation: point.messageCount !== null });
292
- send(state());
293
- },
294
- compact: async () => {
295
- if (busy || !messages.length) return;
296
- busy = true;
297
- send(state());
298
- try {
299
- send({ type: "phase", text: "Compression du contexte" });
300
- if (await compactHistory(session, messages, { force: true })) {
301
- checkpoints.forgetConversation();
302
- await saveSession(session.root, messages, session.conversationId);
303
- send({ type: "notice", text: "Conversation résumée : le contexte est libéré." });
304
- }
305
- } catch (error) {
306
- send({ type: "error", message: error.message });
307
- } finally {
308
- busy = false;
309
- send({ type: "phase", text: "" });
310
- send(state());
311
- }
312
- },
313
- note: async ({ text }) => {
314
- const { appendFile, readFile, writeFile } = await import("node:fs/promises");
315
- const path = (await import("node:path")).default;
316
- const file = path.join(session.root, "HENERGYQUEAI.md");
317
- const current = await readFile(file, "utf8").catch(() => null);
318
- if (current === null) await writeFile(file, `# Consignes du projet\n\n- ${text}\n`, "utf8");
319
- else await appendFile(file, `${current.endsWith("\n") ? "" : "\n"}- ${text}\n`, "utf8");
320
- session.projectContext = await projectContext(session.root).catch(() => session.projectContext);
321
- if (session.projectContextSent) notes.push(text);
322
- send({ type: "notice", text: `Consigne ajoutée à HENERGYQUEAI.md : ${text}` });
323
- },
324
- usage: async () => {
325
- try {
326
- const { plan, usage } = await getUsage(session);
327
- send({ type: "usage", plan, used: usage.used, limit: usage.limit });
328
- } catch (error) {
329
- send({ type: "usage", error: error.message });
330
- }
331
- },
332
- files: async ({ query = "" }) => {
333
- const listing = await execute("trouver_fichiers", { motif: "**/*" }, { root: session.root, approved: true }).catch(
334
- () => "",
335
- );
336
- const needle = String(query).toLowerCase();
337
- const files = String(listing)
338
- .split("\n")
339
- .filter((file) => file && !file.startsWith("Aucun"))
340
- .map((file) => file.replaceAll("\\", "/"));
341
- const scored = needle
342
- ? files
343
- .map((file) => {
344
- const name = file.toLowerCase();
345
- const base = name.split("/").at(-1);
346
- const score = base.startsWith(needle) ? 0 : base.includes(needle) ? 1 : name.includes(needle) ? 2 : -1;
347
- return [score, file];
348
- })
349
- .filter(([score]) => score >= 0)
350
- .sort((a, b) => a[0] - b[0] || a[1].length - b[1].length)
351
- .map(([, file]) => file)
352
- : files;
353
- send({ type: "files", query, items: scored.slice(0, 40) });
354
- },
355
- export: () =>
356
- send({
357
- type: "export",
358
- markdown: conversationMarkdown(messages, { model: MODELS[session.modelId] }),
359
- }),
360
- login: async () => {
361
- try {
362
- const key = await awaitAuthorization({
363
- base: session.base,
364
- onUrl: (url) => send({ type: "auth-url", url }),
365
- });
366
- session.key = key;
367
- await saveConfig({ key });
368
- send({ type: "notice", text: "Connecté." });
369
- send(state());
370
- } catch (error) {
371
- send({ type: "error", message: error.message });
372
- }
373
- },
374
- };
375
-
376
- send(state());
377
- if (messages.length) send({ type: "transcript", items: transcript(messages) });
378
-
379
- await new Promise((resolve) => {
380
- let buffer = "";
381
- process.stdin.setEncoding("utf8");
382
- process.stdin.on("data", (chunk) => {
383
- buffer += chunk;
384
- let at;
385
- while ((at = buffer.indexOf("\n")) >= 0) {
386
- const line = buffer.slice(0, at).trim();
387
- buffer = buffer.slice(at + 1);
388
- if (!line) continue;
389
- let command;
390
- try {
391
- command = JSON.parse(line);
392
- } catch {
393
- continue;
394
- }
395
- Promise.resolve(handlers[command.type]?.(command)).catch((error) =>
396
- send({ type: "error", message: error.message }),
397
- );
398
- }
399
- });
400
- process.stdin.on("end", resolve);
401
- process.stdin.on("close", resolve);
402
- });
403
- settleAll();
404
- controller?.abort();
405
- stopAll();
406
- }
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
+ import { createWarmer } from "./warm.js";
15
+
16
+ // Mode « --ide » : l'extension VS Code dessine l'interface, ce processus garde
17
+ // le moteur. Chaque ligne reçue sur l'entrée standard est une commande JSON,
18
+ // chaque ligne écrite sur la sortie standard un événement JSON.
19
+
20
+ const MODELS = {
21
+ velys: "Velys 3.0",
22
+ oryne: "Oryne 2.6",
23
+ aelyr: "Aelyr 4.2 Pro",
24
+ "aelyr-4": "Aelyr 4.0",
25
+ };
26
+ const SHELL_MARKER = "\n\n--- Commandes lancées par l’utilisateur ---\n";
27
+ const NOTE_MARKER = "\n\n--- Consignes ajoutées au projet ---\n";
28
+ const INIT_PROMPT =
29
+ "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.";
30
+
31
+ const textContent = (content) =>
32
+ Array.isArray(content)
33
+ ? content.filter((part) => part.type === "text").map((part) => part.text).join("\n")
34
+ : String(content || "");
35
+ const cleanQuestion = (content) =>
36
+ visibleQuestion(textContent(content).split(SHELL_MARKER)[0].split(NOTE_MARKER)[0]);
37
+
38
+ const taskContent = (content, session) => {
39
+ const task =
40
+ session.mode === "plan"
41
+ ? `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}`
42
+ : content;
43
+ return session.projectContextSent || !session.projectContext
44
+ ? task
45
+ : `Consignes locales du projet :\n\n${session.projectContext}\n\n---\nDemande actuelle :\n${task}`;
46
+ };
47
+
48
+ // La conversation enregistrée, rejouée sous forme d'éléments affichables.
49
+ export function transcript(messages) {
50
+ const items = [];
51
+ const tools = new Map();
52
+ for (const message of messages) {
53
+ if (message.role === "user") {
54
+ const raw = textContent(message.content);
55
+ if (raw.startsWith("Contexte résumé de la conversation précédente"))
56
+ items.push({ kind: "notice", text: "Contexte précédent résumé." });
57
+ else if (raw.startsWith("[Vérification automatique"))
58
+ items.push({ kind: "notice", text: "Vérification automatique relancée par un hook." });
59
+ else items.push({ kind: "user", text: cleanQuestion(message.content) });
60
+ } else if (message.role === "assistant") {
61
+ const text = String(message.content || "").trim();
62
+ if (text && !text.startsWith("Contexte reçu. Je poursuis")) items.push({ kind: "assistant", text });
63
+ for (const call of message.tool_calls || []) {
64
+ let args = {};
65
+ try {
66
+ args = JSON.parse(call.function?.arguments || "{}");
67
+ } catch {}
68
+ const item = { kind: "tool", id: call.id, name: call.function?.name, args, status: "done" };
69
+ tools.set(call.id, item);
70
+ items.push(item);
71
+ }
72
+ } else if (message.role === "tool") {
73
+ const item = tools.get(message.tool_call_id);
74
+ if (item) item.result = String(message.content || "").slice(0, 6000);
75
+ }
76
+ }
77
+ return items;
78
+ }
79
+
80
+ const sessionTitle = (saved) => {
81
+ const first = saved.messages.find((message) => message.role === "user");
82
+ return cleanQuestion(first?.content || "").slice(0, 90) || "Conversation";
83
+ };
84
+
85
+ export async function runIdeServer(session, messages, { saveConfig, version }) {
86
+ const send = (event) => process.stdout.write(`${JSON.stringify(event)}\n`);
87
+ // Rien d'autre que le protocole ne doit partir sur la sortie standard.
88
+ console.log = (...args) => console.error(...args);
89
+ console.info = console.log;
90
+
91
+ session.surface = "vscode";
92
+ const known = new Set(session.tools.map((tool) => tool.function?.name));
93
+ session.tools = [...session.tools, ...interactiveDefinitions.filter((tool) => !known.has(tool.function.name))];
94
+ let checkpoints = createCheckpoints(session.root);
95
+ let controller = null;
96
+ let busy = false;
97
+ // Le cache reste au chaud pendant les pauses, sans rien afficher.
98
+ const warmer = createWarmer(session, () => messages);
99
+ const pending = new Map();
100
+ const notes = [];
101
+
102
+ const contextLeft = () =>
103
+ Math.max(0, 1 - Math.max(messages.length / 55, historySize(messages) / 240000));
104
+ const state = () => ({
105
+ type: "state",
106
+ version,
107
+ root: session.root,
108
+ model: session.modelId,
109
+ mode: session.mode,
110
+ models: Object.entries(MODELS).map(([id, label]) => ({ id, label })),
111
+ modes: Object.entries(MODES).map(([id, detail]) => ({ id, detail })),
112
+ connected: Boolean(session.key),
113
+ busy,
114
+ contextLeft: contextLeft(),
115
+ mcp: session.mcp?.servers?.length || 0,
116
+ });
117
+
118
+ const wait = (id, event) =>
119
+ new Promise((resolve) => {
120
+ pending.set(id, resolve);
121
+ send(event);
122
+ });
123
+ const settleAll = () => {
124
+ for (const resolve of pending.values()) resolve(null);
125
+ pending.clear();
126
+ };
127
+
128
+ const requestApproval = async (request) => {
129
+ const choice = await wait(request.id, { type: "approval", ...request });
130
+ if (choice === 1) {
131
+ if (request.name === "executer" || request.name.startsWith("mcp_")) {
132
+ const rule =
133
+ request.name === "executer"
134
+ ? `Executer(${String(request.args?.commande || "").replace(/[()]/g, "")})`
135
+ : `Mcp(${request.name.slice(4)})`;
136
+ session.permissions = {
137
+ ...session.permissions,
138
+ autoriser: [...(session.permissions?.autoriser || []), rule],
139
+ };
140
+ } else session.mode = "accepter-modifications";
141
+ send(state());
142
+ }
143
+ if (choice === 2 || choice === null) controller?.abort();
144
+ return choice === 0 || choice === 1;
145
+ };
146
+ const requestChoice = ({ id, question, options }) =>
147
+ wait(id, { type: "question", id, question, options });
148
+ const requestPlan = async ({ id, plan }) => {
149
+ const value = await wait(id, { type: "plan", id, plan });
150
+ queueMicrotask(() => send(state()));
151
+ return value;
152
+ };
153
+
154
+ const run = async ({ text, display, images = [], editor }) => {
155
+ if (busy) return send({ type: "error", message: "Une réponse est déjà en cours." });
156
+ if (!session.key) return send({ type: "auth-required" });
157
+ busy = true;
158
+ warmer.stop();
159
+ controller = new AbortController();
160
+ const started = Date.now();
161
+ send({ type: "turn-start", display: display || text });
162
+ send(state());
163
+ let aborted = false;
164
+ try {
165
+ const compacted = await compactHistory(session, messages, {
166
+ onStatus: (phase) => send({ type: "phase", text: phase }),
167
+ });
168
+ if (compacted) {
169
+ checkpoints.forgetConversation();
170
+ send({ type: "notice", text: "Contexte précédent résumé pour poursuivre la conversation." });
171
+ }
172
+ checkpoints.begin({ text: display || text, messageCount: messages.length });
173
+ send({ type: "checkpoint", index: checkpoints.list().length - 1 });
174
+ const expanded = await expandReferences(session.root, text);
175
+ const editorBlock = editor ? `${expanded.includes(REFERENCE_MARKER) ? "\n\n" : REFERENCE_MARKER}${editor}` : "";
176
+ const added = notes.splice(0);
177
+ const content = taskContent(
178
+ `${expanded}${editorBlock}${added.length ? `${NOTE_MARKER}${added.join("\n")}` : ""}`,
179
+ session,
180
+ );
181
+ const referenced = await referencedImages(session.root, text);
182
+ const pictures = [...images, ...referenced.map((image) => image.url)].slice(0, 4);
183
+ messages.push({
184
+ role: "user",
185
+ content: pictures.length
186
+ ? [{ type: "text", text: content }, ...pictures.map((url) => ({ type: "image_url", image_url: { url } }))]
187
+ : content,
188
+ });
189
+ session.projectContextSent = true;
190
+ await runAgentTurn(session, messages, {
191
+ emit: send,
192
+ requestApproval,
193
+ requestChoice,
194
+ requestPlan,
195
+ checkpoints,
196
+ signal: controller.signal,
197
+ });
198
+ } catch (error) {
199
+ aborted = controller.signal.aborted;
200
+ // Connexion révoquée depuis le site : on oublie la clé et l'extension
201
+ // affiche son bouton « Se connecter », sans renvoyer vers le terminal.
202
+ if (!aborted && error.status === 401) {
203
+ session.key = null;
204
+ await saveConfig({ key: undefined }).catch(() => {});
205
+ send({ type: "auth-required", reason: "revoked" });
206
+ } else send(aborted ? { type: "interrupted" } : { type: "error", message: error.message });
207
+ } finally {
208
+ settleAll();
209
+ for (const message of messages)
210
+ if (Array.isArray(message.content)) {
211
+ const count = message.content.filter((part) => part.type === "image_url").length;
212
+ message.content = `${textContent(message.content)}\n[${count} image${count > 1 ? "s jointes" : " jointe"}]`;
213
+ }
214
+ session.projectContext = await projectContext(session.root).catch(() => session.projectContext);
215
+ await saveSession(session.root, messages, session.conversationId).catch((error) =>
216
+ send({ type: "error", message: `Enregistrement impossible : ${error.message}` }),
217
+ );
218
+ busy = false;
219
+ controller = null;
220
+ if (!aborted) warmer.arm();
221
+ send({ type: "turn-end", seconds: Math.max(1, Math.round((Date.now() - started) / 1000)), aborted });
222
+ send(state());
223
+ }
224
+ };
225
+
226
+ const reset = () => {
227
+ warmer.stop();
228
+ messages.length = 0;
229
+ session.conversationId = randomUUID();
230
+ session.projectContextSent = false;
231
+ checkpoints = createCheckpoints(session.root);
232
+ };
233
+
234
+ const handlers = {
235
+ hello: () => send(state()),
236
+ send: (command) => run(command),
237
+ init: () => run({ text: INIT_PROMPT, display: "Préparer HENERGYQUEAI.md" }),
238
+ interrupt: () => {
239
+ settleAll();
240
+ controller?.abort();
241
+ },
242
+ approval: ({ id, choice }) => {
243
+ pending.get(id)?.(choice);
244
+ pending.delete(id);
245
+ },
246
+ answer: ({ id, value }) => {
247
+ pending.get(id)?.(value ?? null);
248
+ pending.delete(id);
249
+ },
250
+ model: async ({ value }) => {
251
+ if (!MODELS[value]) return;
252
+ session.modelId = value;
253
+ await saveConfig({ modelId: value });
254
+ send(state());
255
+ },
256
+ mode: ({ value }) => {
257
+ if (!MODES[value]) return;
258
+ session.mode = value;
259
+ send(state());
260
+ },
261
+ new: () => {
262
+ if (busy) return;
263
+ reset();
264
+ send({ type: "transcript", items: [] });
265
+ send(state());
266
+ },
267
+ sessions: async () => {
268
+ const list = await listSessions(session.root).catch(() => []);
269
+ send({
270
+ type: "sessions",
271
+ items: list.map((saved) => ({
272
+ id: saved.id,
273
+ title: sessionTitle(saved),
274
+ date: saved.date,
275
+ count: saved.messages.filter((message) => message.role === "user").length,
276
+ current: saved.id === session.conversationId,
277
+ })),
278
+ });
279
+ },
280
+ resume: async ({ id }) => {
281
+ if (busy) return;
282
+ const saved = (await listSessions(session.root).catch(() => [])).find((item) => item.id === id);
283
+ if (!saved) return send({ type: "error", message: "Conversation introuvable." });
284
+ reset();
285
+ messages.push(...saved.messages);
286
+ session.conversationId = saved.id || randomUUID();
287
+ session.projectContextSent = true;
288
+ send({ type: "transcript", items: transcript(messages) });
289
+ send(state());
290
+ },
291
+ rewind: async ({ index, code }) => {
292
+ if (busy) return;
293
+ const point = checkpoints.point(index);
294
+ if (!point) return;
295
+ const restored = code ? await checkpoints.restoreCode(index) : 0;
296
+ if (point.messageCount !== null) {
297
+ messages.splice(point.messageCount);
298
+ if (!messages.length) session.projectContextSent = false;
299
+ }
300
+ checkpoints.truncate(index);
301
+ await saveSession(session.root, messages, session.conversationId).catch(() => {});
302
+ send({ type: "rewound", index, text: point.text, restored, conversation: point.messageCount !== null });
303
+ send(state());
304
+ },
305
+ compact: async () => {
306
+ if (busy || !messages.length) return;
307
+ busy = true;
308
+ send(state());
309
+ try {
310
+ send({ type: "phase", text: "Compression du contexte" });
311
+ if (await compactHistory(session, messages, { force: true })) {
312
+ checkpoints.forgetConversation();
313
+ await saveSession(session.root, messages, session.conversationId);
314
+ send({ type: "notice", text: "Conversation résumée : le contexte est libéré." });
315
+ }
316
+ } catch (error) {
317
+ send({ type: "error", message: error.message });
318
+ } finally {
319
+ busy = false;
320
+ send({ type: "phase", text: "" });
321
+ send(state());
322
+ }
323
+ },
324
+ note: async ({ text }) => {
325
+ const { appendFile, readFile, writeFile } = await import("node:fs/promises");
326
+ const path = (await import("node:path")).default;
327
+ const file = path.join(session.root, "HENERGYQUEAI.md");
328
+ const current = await readFile(file, "utf8").catch(() => null);
329
+ if (current === null) await writeFile(file, `# Consignes du projet\n\n- ${text}\n`, "utf8");
330
+ else await appendFile(file, `${current.endsWith("\n") ? "" : "\n"}- ${text}\n`, "utf8");
331
+ session.projectContext = await projectContext(session.root).catch(() => session.projectContext);
332
+ if (session.projectContextSent) notes.push(text);
333
+ send({ type: "notice", text: `Consigne ajoutée à HENERGYQUEAI.md : ${text}` });
334
+ },
335
+ usage: async () => {
336
+ try {
337
+ const { plan, usage } = await getUsage(session);
338
+ send({
339
+ type: "usage",
340
+ plan,
341
+ used: usage.used,
342
+ limit: usage.limit,
343
+ day: usage.day?.percent,
344
+ week: usage.week?.percent,
345
+ relay: !!usage.relay,
346
+ });
347
+ } catch (error) {
348
+ send({ type: "usage", error: error.message });
349
+ }
350
+ },
351
+ files: async ({ query = "" }) => {
352
+ const listing = await execute("trouver_fichiers", { motif: "**/*" }, { root: session.root, approved: true }).catch(
353
+ () => "",
354
+ );
355
+ const needle = String(query).toLowerCase();
356
+ const files = String(listing)
357
+ .split("\n")
358
+ .filter((file) => file && !file.startsWith("Aucun"))
359
+ .map((file) => file.replaceAll("\\", "/"));
360
+ const scored = needle
361
+ ? files
362
+ .map((file) => {
363
+ const name = file.toLowerCase();
364
+ const base = name.split("/").at(-1);
365
+ const score = base.startsWith(needle) ? 0 : base.includes(needle) ? 1 : name.includes(needle) ? 2 : -1;
366
+ return [score, file];
367
+ })
368
+ .filter(([score]) => score >= 0)
369
+ .sort((a, b) => a[0] - b[0] || a[1].length - b[1].length)
370
+ .map(([, file]) => file)
371
+ : files;
372
+ send({ type: "files", query, items: scored.slice(0, 40) });
373
+ },
374
+ export: () =>
375
+ send({
376
+ type: "export",
377
+ markdown: conversationMarkdown(messages, { model: MODELS[session.modelId] }),
378
+ }),
379
+ login: async () => {
380
+ try {
381
+ const key = await awaitAuthorization({
382
+ base: session.base,
383
+ onUrl: (url) => send({ type: "auth-url", url }),
384
+ });
385
+ session.key = key;
386
+ await saveConfig({ key });
387
+ send({ type: "notice", text: "Connecté." });
388
+ send(state());
389
+ } catch (error) {
390
+ send({ type: "error", message: error.message });
391
+ }
392
+ },
393
+ };
394
+
395
+ send(state());
396
+ if (messages.length) send({ type: "transcript", items: transcript(messages) });
397
+
398
+ await new Promise((resolve) => {
399
+ let buffer = "";
400
+ process.stdin.setEncoding("utf8");
401
+ process.stdin.on("data", (chunk) => {
402
+ buffer += chunk;
403
+ let at;
404
+ while ((at = buffer.indexOf("\n")) >= 0) {
405
+ const line = buffer.slice(0, at).trim();
406
+ buffer = buffer.slice(at + 1);
407
+ if (!line) continue;
408
+ let command;
409
+ try {
410
+ command = JSON.parse(line);
411
+ } catch {
412
+ continue;
413
+ }
414
+ Promise.resolve(handlers[command.type]?.(command)).catch((error) =>
415
+ send({ type: "error", message: error.message }),
416
+ );
417
+ }
418
+ });
419
+ process.stdin.on("end", resolve);
420
+ process.stdin.on("close", resolve);
421
+ });
422
+ settleAll();
423
+ controller?.abort();
424
+ stopAll();
425
+ }