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/package.json CHANGED
@@ -1,18 +1,21 @@
1
1
  {
2
2
  "name": "henergyqueai",
3
- "version": "0.4.2",
3
+ "version": "0.8.0",
4
4
  "description": "L’assistant HenergyqueAI dans votre terminal : il lit votre projet, propose des modifications et lance des commandes, avec votre accord.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "henergyqueai": "bin/henergyqueai.js"
8
8
  },
9
+ "scripts": {
10
+ "test": "node --test test/*.test.js"
11
+ },
9
12
  "files": [
10
13
  "bin",
11
14
  "src",
12
15
  "README.md"
13
16
  ],
14
17
  "engines": {
15
- "node": ">=20"
18
+ "node": ">=22"
16
19
  },
17
20
  "license": "UNLICENSED",
18
21
  "keywords": [
@@ -21,5 +24,14 @@
21
24
  "assistant",
22
25
  "ia"
23
26
  ],
24
- "homepage": "https://henergyqueai.fr"
27
+ "homepage": "https://henergyqueai.fr",
28
+ "dependencies": {
29
+ "@modelcontextprotocol/client": "^2.1.0",
30
+ "ink": "^7.1.1",
31
+ "react": "^19.3.0",
32
+ "react-devtools-core": "^6.1.5"
33
+ },
34
+ "devDependencies": {
35
+ "@modelcontextprotocol/server": "^2.1.0"
36
+ }
25
37
  }
@@ -0,0 +1,339 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { ask } from "./client.js";
3
+ import { READ_ONLY, definitions, execute, needsApproval, safePath } from "./tools.js";
4
+ import { ruling } from "./reglages.js";
5
+ import { fileDiff } from "./diff.js";
6
+ import { runHooks } from "./hooks.js";
7
+
8
+ const summarize = (value, limit = 1600) => {
9
+ const text = String(value ?? "");
10
+ return text.length > limit ? `${text.slice(0, limit)}\n…` : text;
11
+ };
12
+
13
+ // Outils qui ont besoin de quelqu'un devant l'écran : ils ne sont proposés que
14
+ // dans l'interface interactive.
15
+ export const interactiveDefinitions = [
16
+ {
17
+ type: "function",
18
+ function: {
19
+ name: "poser_question",
20
+ description:
21
+ "Pose une question à choix à l’utilisateur quand la demande se comprend de plusieurs façons qui mènent à des travaux nettement différents. L’utilisateur peut aussi écrire sa propre réponse.",
22
+ parameters: {
23
+ type: "object",
24
+ properties: {
25
+ question: { type: "string" },
26
+ options: {
27
+ type: "array",
28
+ minItems: 2,
29
+ maxItems: 4,
30
+ items: {
31
+ type: "object",
32
+ properties: {
33
+ intitule: { type: "string", description: "Réponse courte." },
34
+ detail: { type: "string", description: "Ce que ce choix implique." },
35
+ },
36
+ required: ["intitule"],
37
+ },
38
+ },
39
+ },
40
+ required: ["question", "options"],
41
+ },
42
+ },
43
+ },
44
+ {
45
+ type: "function",
46
+ function: {
47
+ name: "proposer_plan",
48
+ description:
49
+ "En mode plan, présente le plan terminé à l’utilisateur pour qu’il l’approuve. S’il accepte, tu peux ensuite modifier les fichiers et exécuter les étapes.",
50
+ parameters: {
51
+ type: "object",
52
+ properties: {
53
+ plan: { type: "string", description: "Le plan en Markdown, étape par étape." },
54
+ },
55
+ required: ["plan"],
56
+ },
57
+ },
58
+ },
59
+ {
60
+ type: "function",
61
+ function: {
62
+ name: "deleguer",
63
+ description:
64
+ "Confie une recherche indépendante à un sous-agent qui lit le projet (et le web) sans rien modifier, puis rend un compte rendu. Plusieurs appels dans la même réponse tournent en parallèle. Chaque sous-agent consomme des requêtes : ne l’utilise que pour une exploration large.",
65
+ parameters: {
66
+ type: "object",
67
+ properties: {
68
+ description: { type: "string", description: "Titre court de la mission (3 à 6 mots)." },
69
+ consigne: {
70
+ type: "string",
71
+ description: "Consigne complète et autonome : le sous-agent ne voit pas la conversation.",
72
+ },
73
+ },
74
+ required: ["description", "consigne"],
75
+ },
76
+ },
77
+ },
78
+ ];
79
+
80
+ const INTERACTIVE = new Set(interactiveDefinitions.map((item) => item.function.name));
81
+ const PARALLEL = (name) => READ_ONLY.has(name) || name === "deleguer";
82
+
83
+ const SUBAGENT_BRIEF =
84
+ "Tu es un sous-agent chargé d’une recherche précise dans ce projet. Tu peux seulement lire (fichiers, Git, web) : ne propose pas de modification à appliquer. Travaille de façon autonome, puis termine par un compte rendu concis et factuel : ce que tu as trouvé, avec les chemins et numéros de ligne utiles.";
85
+
86
+ export async function toolPreview(root, name, args) {
87
+ if (name === "executer")
88
+ return `${String(args.commande || "")}${args.arriere_plan ? "\n(en arrière-plan)" : ""}`;
89
+ if (name.startsWith("mcp_")) return `${name}\n${summarize(JSON.stringify(args), 1200)}`;
90
+ if (!["ecrire_fichier", "editer_fichier"].includes(name)) return "";
91
+ const target = await safePath(root, args.chemin);
92
+ if (!target) throw new Error("Chemin hors du projet.");
93
+ const before = await readFile(target, "utf8").catch(() => null);
94
+ if (name === "editer_fichier") {
95
+ if (before === null) throw new Error("Fichier illisible ou inexistant.");
96
+ const oldText = String(args.ancien ?? "");
97
+ if (!oldText || !before.includes(oldText))
98
+ throw new Error(
99
+ "Extrait introuvable. Relis le fichier avant de modifier.",
100
+ );
101
+ if (before.indexOf(oldText, before.indexOf(oldText) + oldText.length) >= 0)
102
+ throw new Error(
103
+ "Extrait présent plusieurs fois. Précise la modification.",
104
+ );
105
+ return `${args.chemin}\n− ${summarize(oldText, 600)}\n+ ${summarize(args.nouveau, 600)}`;
106
+ }
107
+ return `${args.chemin}\n${before === null ? "Nouveau fichier" : "Remplacement complet"}\n+ ${summarize(args.contenu, 1000)}`;
108
+ }
109
+
110
+ const parseArgs = (raw) => {
111
+ try {
112
+ const value = JSON.parse(raw || "{}");
113
+ return value && typeof value === "object" ? value : {};
114
+ } catch {
115
+ return {};
116
+ }
117
+ };
118
+
119
+ export async function runAgentTurn(session, messages, options = {}) {
120
+ const {
121
+ emit,
122
+ requestApproval,
123
+ requestChoice,
124
+ requestPlan,
125
+ signal,
126
+ checkpoints,
127
+ maxRounds = 24,
128
+ } = options;
129
+ const send = (event) => emit?.(event);
130
+ let stopAfterRound = false;
131
+ let finChecks = 0;
132
+
133
+ const delegate = async (call, args) => {
134
+ const sub = {
135
+ ...session,
136
+ tools: definitions.filter((item) => READ_ONLY.has(item.function.name)),
137
+ mode: "lecture-seule",
138
+ hooks: null,
139
+ };
140
+ const subMessages = [
141
+ {
142
+ role: "user",
143
+ content: `${SUBAGENT_BRIEF}\n\nMission : ${String(args.consigne || args.description || "").slice(0, 20000)}`,
144
+ },
145
+ ];
146
+ let steps = 0;
147
+ try {
148
+ await runAgentTurn(sub, subMessages, {
149
+ signal,
150
+ maxRounds: 12,
151
+ emit: (event) => {
152
+ if (event.type !== "tool-start") return;
153
+ steps += 1;
154
+ send({ type: "tool-progress", id: call.id, name: event.name, args: event.args, steps });
155
+ },
156
+ });
157
+ } catch (error) {
158
+ if (signal?.aborted) throw error;
159
+ const partial = subMessages.filter((item) => item.role === "assistant" && item.content).at(-1);
160
+ return `Le sous-agent n’a pas pu terminer (${error.message}).${partial ? `\nDernières notes :\n${partial.content}` : ""}`;
161
+ }
162
+ const last = subMessages.at(-1);
163
+ return last?.role === "assistant" && last.content
164
+ ? last.content
165
+ : "Le sous-agent n’a rien rapporté.";
166
+ };
167
+
168
+ const runInteractive = async (call, args) => {
169
+ if (call.name === "poser_question") {
170
+ if (!requestChoice) return "Impossible de poser une question ici : tranche et dis ce que tu supposes.";
171
+ const choices = (Array.isArray(args.options) ? args.options : [])
172
+ .filter((item) => item && typeof item.intitule === "string")
173
+ .slice(0, 4);
174
+ if (!args.question || choices.length < 2) return "Question invalide : il faut une question et au moins deux options.";
175
+ const answer = await requestChoice({ id: call.id, question: String(args.question), options: choices });
176
+ return answer
177
+ ? `L’utilisateur a répondu : ${answer}`
178
+ : "L’utilisateur n’a pas répondu. Tranche et dis ce que tu supposes.";
179
+ }
180
+ if (call.name === "proposer_plan") {
181
+ if (!requestPlan) return "Plan noté.";
182
+ const choice = await requestPlan({ id: call.id, plan: String(args.plan || "") });
183
+ if (choice === "auto" || choice === "manuel") {
184
+ session.mode = choice === "auto" ? "accepter-modifications" : "demander";
185
+ return `Plan accepté. Tu peux maintenant modifier les fichiers${choice === "auto" ? " (les modifications sont acceptées automatiquement)" : " (chaque modification sera validée)"} : commence l’exécution.`;
186
+ }
187
+ stopAfterRound = true;
188
+ return "L’utilisateur veut retravailler le plan. Arrête-toi ici et attends ses remarques.";
189
+ }
190
+ return delegate(call, args);
191
+ };
192
+
193
+ const runCall = async (call, args) => {
194
+ if (INTERACTIVE.has(call.name)) return runInteractive(call, args);
195
+ const verdict = ruling(session.permissions, call.name, args);
196
+ if (needsApproval(call.name) && ["lecture-seule", "plan"].includes(session.mode))
197
+ return session.mode === "plan"
198
+ ? "Action refusée : mode plan. Termine le plan puis présente-le avec proposer_plan."
199
+ : "Action refusée : mode lecture seule.";
200
+ if (verdict === "refuse") return "Action refusée par les règles du projet.";
201
+ if (session.hooks) {
202
+ const before = await runHooks(session.hooks, "avant_outil", { root: session.root, name: call.name, args });
203
+ if (before.blocked) return `Bloqué par un hook : ${before.blocked}`;
204
+ }
205
+ let approved = true;
206
+ if (needsApproval(call.name)) {
207
+ try {
208
+ const preview = await toolPreview(session.root, call.name, args);
209
+ const diff = await fileDiff(session.root, call.name, args).catch(() => null);
210
+ send({ type: "tool-preview", id: call.id, name: call.name, preview, diff });
211
+ const automatic =
212
+ verdict === "autorise" ||
213
+ session.mode === "sans-demander" ||
214
+ (session.mode === "accepter-modifications" &&
215
+ ["ecrire_fichier", "editer_fichier"].includes(call.name));
216
+ approved =
217
+ automatic ||
218
+ Boolean(await requestApproval?.({ id: call.id, name: call.name, args, preview, diff }));
219
+ } catch (error) {
220
+ return `Action annulée : ${error.message}`;
221
+ }
222
+ }
223
+ let result = await execute(call.name, args, {
224
+ root: session.root,
225
+ approved,
226
+ mcp: session.mcp,
227
+ session,
228
+ signal,
229
+ checkpoints,
230
+ });
231
+ if (session.hooks && approved) {
232
+ const after = await runHooks(session.hooks, "apres_outil", {
233
+ root: session.root,
234
+ name: call.name,
235
+ args,
236
+ result: String(result).slice(0, 4000),
237
+ });
238
+ if (after.notes.length) result = `${result}\n\nHook : ${after.notes.join("\n")}`;
239
+ }
240
+ return result;
241
+ };
242
+
243
+ for (let round = 0; round < maxRounds; round += 1) {
244
+ if (signal?.aborted) throw new Error("Réponse interrompue.");
245
+ send({ type: "thinking", round, tokens: 0 });
246
+ let streamed = false;
247
+ const answer = await ask({
248
+ base: session.base,
249
+ key: session.key,
250
+ messages,
251
+ tools: session.tools,
252
+ modelId: session.modelId,
253
+ signal,
254
+ onThinking: ({ tokens } = {}) =>
255
+ send({ type: "thinking", round, tokens: Number(tokens) || 0 }),
256
+ onDelta: (text) => {
257
+ if (!text) return;
258
+ streamed = true;
259
+ send({ type: "delta", round, text });
260
+ },
261
+ });
262
+ if (!streamed && answer.content)
263
+ send({ type: "delta", round, text: answer.content });
264
+ if (!answer.toolCalls?.length) {
265
+ messages.push({ role: "assistant", content: answer.content || "" });
266
+ if (session.hooks?.fin?.length && finChecks < 2) {
267
+ const end = await runHooks(session.hooks, "fin", { root: session.root });
268
+ if (end.blocked) {
269
+ finChecks += 1;
270
+ messages.push({
271
+ role: "user",
272
+ content: `[Vérification automatique après ta réponse]\n${end.blocked}`,
273
+ });
274
+ send({ type: "hook", text: end.blocked });
275
+ continue;
276
+ }
277
+ }
278
+ send({ type: "done" });
279
+ return;
280
+ }
281
+
282
+ messages.push({
283
+ role: "assistant",
284
+ content: answer.content || "",
285
+ tool_calls: answer.toolCalls.map((call) => ({
286
+ id: call.id,
287
+ type: "function",
288
+ function: { name: call.name, arguments: call.arguments },
289
+ })),
290
+ });
291
+
292
+ // Les lectures consécutives partent ensemble ; tout ce qui modifie ou
293
+ // demande l'avis de l'utilisateur passe seul, dans l'ordre.
294
+ const calls = answer.toolCalls.map((call) => ({ call, args: parseArgs(call.arguments) }));
295
+ const groups = [];
296
+ for (const item of calls) {
297
+ const last = groups.at(-1);
298
+ if (last && PARALLEL(item.call.name) && PARALLEL(last[0].call.name)) last.push(item);
299
+ else groups.push([item]);
300
+ }
301
+ for (const group of groups) {
302
+ if (stopAfterRound) {
303
+ for (const { call } of group)
304
+ messages.push({ role: "tool", tool_call_id: call.id, content: "Non exécuté : l’utilisateur a repris la main." });
305
+ continue;
306
+ }
307
+ for (const { call, args } of group)
308
+ send({ type: "tool-start", id: call.id, name: call.name, args });
309
+ const results = await Promise.all(
310
+ group.map(({ call, args }) =>
311
+ runCall(call, args).then(
312
+ (result) => {
313
+ send({ type: "tool-end", id: call.id, name: call.name, args, result: summarize(result, 6000) });
314
+ return result;
315
+ },
316
+ (error) => {
317
+ if (signal?.aborted) throw error;
318
+ const result = `Échec de l’outil : ${error.message}`;
319
+ send({ type: "tool-end", id: call.id, name: call.name, args, result });
320
+ return result;
321
+ },
322
+ ),
323
+ ),
324
+ );
325
+ group.forEach(({ call }, index) =>
326
+ messages.push({
327
+ role: "tool",
328
+ tool_call_id: call.id,
329
+ content: String(results[index]).slice(0, 12000),
330
+ }),
331
+ );
332
+ }
333
+ if (stopAfterRound) {
334
+ send({ type: "done" });
335
+ return;
336
+ }
337
+ }
338
+ throw new Error("La limite d’étapes de cette demande a été atteinte.");
339
+ }
@@ -0,0 +1,93 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+
3
+ // Commandes longues (serveur de développement, surveillance des tests) lancées
4
+ // en arrière-plan : l'assistant continue de travailler et relit leur sortie
5
+ // quand il en a besoin.
6
+ const jobs = new Map();
7
+ let counter = 0;
8
+ const KEEP = 60000;
9
+
10
+ export function startJob(command, cwd) {
11
+ counter += 1;
12
+ const id = `fond-${counter}`;
13
+ const child = spawn(command, {
14
+ cwd,
15
+ shell: true,
16
+ windowsHide: true,
17
+ detached: process.platform !== "win32",
18
+ stdio: ["ignore", "pipe", "pipe"],
19
+ });
20
+ const job = {
21
+ id,
22
+ command,
23
+ child,
24
+ output: "",
25
+ read: 0,
26
+ running: true,
27
+ code: null,
28
+ started: Date.now(),
29
+ };
30
+ const collect = (chunk) => {
31
+ job.output += chunk.toString("utf8");
32
+ if (job.output.length > KEEP) {
33
+ const cut = job.output.length - KEEP;
34
+ job.output = job.output.slice(cut);
35
+ job.read = Math.max(0, job.read - cut);
36
+ }
37
+ };
38
+ child.stdout.on("data", collect);
39
+ child.stderr.on("data", collect);
40
+ child.on("error", (error) => {
41
+ collect(`\n${error.message}\n`);
42
+ job.running = false;
43
+ });
44
+ child.on("exit", (code) => {
45
+ job.running = false;
46
+ job.code = code;
47
+ });
48
+ jobs.set(id, job);
49
+ return job;
50
+ }
51
+
52
+ const status = (job) =>
53
+ job.running ? "en cours" : `terminée (code ${job.code ?? "?"})`;
54
+
55
+ // Rend la sortie produite depuis la dernière lecture, comme un fil qu'on suit.
56
+ export function readJob(id) {
57
+ const job = jobs.get(id);
58
+ if (!job) return `Aucune commande « ${id} ».`;
59
+ const fresh = job.output.slice(job.read);
60
+ job.read = job.output.length;
61
+ const shown = fresh.length > 8000 ? `…\n${fresh.slice(-8000)}` : fresh;
62
+ return `${job.id} · ${status(job)}\n${shown || "(pas de nouvelle sortie)"}`;
63
+ }
64
+
65
+ export function stopJob(id) {
66
+ const job = jobs.get(id);
67
+ if (!job) return `Aucune commande « ${id} ».`;
68
+ if (!job.running) return `${id} était déjà ${status(job)}.`;
69
+ try {
70
+ if (process.platform === "win32")
71
+ spawnSync("taskkill", ["/pid", String(job.child.pid), "/T", "/F"], {
72
+ windowsHide: true,
73
+ });
74
+ else process.kill(-job.child.pid, "SIGTERM");
75
+ } catch {
76
+ job.child.kill();
77
+ }
78
+ job.running = false;
79
+ return `${id} arrêtée.`;
80
+ }
81
+
82
+ export const listJobs = () =>
83
+ [...jobs.values()].map((job) => ({
84
+ id: job.id,
85
+ command: job.command,
86
+ running: job.running,
87
+ status: status(job),
88
+ started: job.started,
89
+ }));
90
+
91
+ export function stopAll() {
92
+ for (const job of jobs.values()) if (job.running) stopJob(job.id);
93
+ }
@@ -0,0 +1,57 @@
1
+ import { readFile, rm, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { safePath } from "./tools.js";
4
+
5
+ // Un point de retour par demande : l'état de la conversation au moment où elle
6
+ // part, et le contenu d'origine de chaque fichier que l'assistant modifie
7
+ // ensuite. Revenir à un point rétablit ces fichiers tels qu'ils étaient.
8
+ // Les commandes du terminal ne sont pas suivies.
9
+ export function createCheckpoints(root) {
10
+ const points = [];
11
+ return {
12
+ begin({ text, messageCount, entryId }) {
13
+ points.push({ text, messageCount, entryId, files: new Map(), date: Date.now() });
14
+ },
15
+ async remember(relative) {
16
+ const current = points.at(-1);
17
+ const target = current && (await safePath(root, relative));
18
+ if (!target || current.files.has(target)) return;
19
+ current.files.set(target, await readFile(target).catch(() => null));
20
+ },
21
+ // Après un résumé, les anciens messages n'existent plus : seul le code
22
+ // peut encore être rétabli pour les points antérieurs.
23
+ forgetConversation() {
24
+ for (const point of points) point.messageCount = null;
25
+ },
26
+ list() {
27
+ return points.map((point, index) => ({
28
+ index,
29
+ text: point.text,
30
+ date: point.date,
31
+ conversation: point.messageCount !== null,
32
+ files: [...new Set(points.slice(index).flatMap((item) => [...item.files.keys()]))].map(
33
+ (file) => path.relative(root, file).replaceAll(path.sep, "/"),
34
+ ),
35
+ }));
36
+ },
37
+ point: (index) => points[index],
38
+ async restoreCode(index) {
39
+ let restored = 0;
40
+ for (let at = points.length - 1; at >= index; at -= 1) {
41
+ for (const [file, before] of points[at].files) {
42
+ if (before === null) await rm(file, { force: true });
43
+ else await writeFile(file, before);
44
+ restored += 1;
45
+ }
46
+ points[at].files.clear();
47
+ }
48
+ return restored;
49
+ },
50
+ truncate(index) {
51
+ points.splice(index);
52
+ },
53
+ clear() {
54
+ points.length = 0;
55
+ },
56
+ };
57
+ }
package/src/client.js CHANGED
@@ -1,5 +1,33 @@
1
1
  // Talks to /api/v1/agent and turns its stream into events the terminal can
2
2
  // display as they happen.
3
+ export async function getUsage({ base, key }) {
4
+ const response = await fetch(`${base.replace(/\/$/, "")}/api/v1/agent/usage`, {
5
+ headers: { Authorization: `Bearer ${key}` },
6
+ signal: AbortSignal.timeout(10000),
7
+ });
8
+ const body = await response.json().catch(() => ({}));
9
+ if (!response.ok) throw new Error(body.error || `Erreur ${response.status}.`);
10
+ return body;
11
+ }
12
+
13
+ // Web searches go through the service, which holds the search key.
14
+ export async function webRequest({ base, key }, body, signal) {
15
+ const response = await fetch(`${base.replace(/\/$/, "")}/api/v1/agent/web`, {
16
+ method: "POST",
17
+ headers: {
18
+ "Content-Type": "application/json",
19
+ Authorization: `Bearer ${key}`,
20
+ },
21
+ body: JSON.stringify(body),
22
+ signal: signal
23
+ ? AbortSignal.any([signal, AbortSignal.timeout(30000)])
24
+ : AbortSignal.timeout(30000),
25
+ });
26
+ const data = await response.json().catch(() => ({}));
27
+ if (!response.ok) throw new Error(data.error || `Erreur ${response.status}.`);
28
+ return data;
29
+ }
30
+
3
31
  export async function ask({
4
32
  base,
5
33
  key,
@@ -0,0 +1,79 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { readFile, rm, stat } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { randomUUID } from "node:crypto";
7
+
8
+ const runFile = promisify(execFile);
9
+
10
+ export const IMAGE_TYPES = {
11
+ ".png": "image/png",
12
+ ".jpg": "image/jpeg",
13
+ ".jpeg": "image/jpeg",
14
+ ".gif": "image/gif",
15
+ ".webp": "image/webp",
16
+ };
17
+ const MAX_IMAGE = 5_000_000;
18
+
19
+ // Lit l'image du presse-papiers (capture d'écran) et la rend en data URL, ou
20
+ // null s'il n'y en a pas.
21
+ export async function clipboardImage() {
22
+ const file = path.join(tmpdir(), `henergyqueai-${randomUUID()}.png`);
23
+ try {
24
+ if (process.platform === "win32") {
25
+ const script = `Add-Type -AssemblyName System.Windows.Forms; Add-Type -AssemblyName System.Drawing; $i = [System.Windows.Forms.Clipboard]::GetImage(); if ($i -eq $null) { exit 3 }; $i.Save('${file.replaceAll("'", "''")}', [System.Drawing.Imaging.ImageFormat]::Png)`;
26
+ await runFile("powershell", ["-NoProfile", "-STA", "-Command", script], {
27
+ timeout: 10000,
28
+ windowsHide: true,
29
+ });
30
+ } else if (process.platform === "darwin") {
31
+ await runFile(
32
+ "osascript",
33
+ ["-e", `set f to open for access POSIX file "${file}" with write permission`, "-e", "write (the clipboard as «class PNGf») to f", "-e", "close access f"],
34
+ { timeout: 10000 },
35
+ );
36
+ } else {
37
+ const { stdout } = await runFile("xclip", ["-selection", "clipboard", "-t", "image/png", "-o"], {
38
+ timeout: 10000,
39
+ encoding: "buffer",
40
+ maxBuffer: MAX_IMAGE * 2,
41
+ });
42
+ if (!stdout?.length) return null;
43
+ return toDataUrl(stdout, "image/png");
44
+ }
45
+ return await imageFile(file);
46
+ } catch {
47
+ return null;
48
+ } finally {
49
+ await rm(file, { force: true }).catch(() => {});
50
+ }
51
+ }
52
+
53
+ const toDataUrl = (buffer, type) =>
54
+ buffer.length && buffer.length <= MAX_IMAGE ? `data:${type};base64,${buffer.toString("base64")}` : null;
55
+
56
+ export async function imageFile(file) {
57
+ const type = IMAGE_TYPES[path.extname(file).toLowerCase()];
58
+ if (!type) return null;
59
+ const details = await stat(file).catch(() => null);
60
+ if (!details?.isFile() || details.size > MAX_IMAGE) return null;
61
+ return toDataUrl(await readFile(file), type);
62
+ }
63
+
64
+ // Copie du texte dans le presse-papiers du système.
65
+ export function copyText(text) {
66
+ const [command, args] =
67
+ process.platform === "win32"
68
+ ? ["powershell", ["-NoProfile", "-Command", "$input | Set-Clipboard"]]
69
+ : process.platform === "darwin"
70
+ ? ["pbcopy", []]
71
+ : ["xclip", ["-selection", "clipboard"]];
72
+ return new Promise((resolve) => {
73
+ const child = spawn(command, args, { windowsHide: true, stdio: ["pipe", "ignore", "ignore"] });
74
+ child.on("error", () => resolve(false));
75
+ child.on("close", (code) => resolve(code === 0));
76
+ child.stdin.on("error", () => {});
77
+ child.stdin.end(text, "utf8");
78
+ });
79
+ }