henergyqueai 0.1.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/README.md +60 -0
- package/bin/henergyqueai.js +231 -0
- package/package.json +25 -0
- package/src/butterfly.js +30 -0
- package/src/client.js +67 -0
- package/src/tools.js +212 -0
- package/src/ui.js +96 -0
package/README.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# henergyqueai
|
|
2
|
+
|
|
3
|
+
L’assistant [HenergyqueAI](https://henergyqueai.fr) dans votre terminal. Il lit votre projet, propose des modifications et lance des commandes — toujours avec votre accord.
|
|
4
|
+
|
|
5
|
+
## Installer
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -g henergyqueai
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Se connecter
|
|
12
|
+
|
|
13
|
+
Créez une clé dans **Paramètres → Clés d’API** sur [henergyqueai.fr](https://henergyqueai.fr/parametres), puis :
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
henergyqueai connexion
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
La clé est enregistrée dans `~/.henergyqueai/config.json`, lisible par vous seul.
|
|
20
|
+
|
|
21
|
+
## Utiliser
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
henergyqueai "explique-moi ce que fait src/panier.js"
|
|
25
|
+
henergyqueai "corrige le bug de date dans facture.js"
|
|
26
|
+
cat erreur.log | henergyqueai "d'où vient cette erreur ?"
|
|
27
|
+
henergyqueai # session interactive
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
L’assistant n’a accès qu’au dossier depuis lequel vous l’avez lancé.
|
|
31
|
+
|
|
32
|
+
## Options
|
|
33
|
+
|
|
34
|
+
| Option | Effet |
|
|
35
|
+
| -------------------------------- | ----------------------------------------- |
|
|
36
|
+
| `--modele <aelyr\|oryne\|velys>` | Choisit l’assistant |
|
|
37
|
+
| `--lecture-seule` | Interdit toute écriture et toute commande |
|
|
38
|
+
| `--oui` | Accepte les modifications sans demander |
|
|
39
|
+
|
|
40
|
+
## Ce qu’il fait sans demander, et ce qu’il vous soumet
|
|
41
|
+
|
|
42
|
+
Lire un fichier, explorer le projet et chercher un texte se font librement.
|
|
43
|
+
|
|
44
|
+
Écrire dans un fichier ou exécuter une commande vous est **toujours** soumis. Pour une modification, les lignes retirées et ajoutées s’affichent avant que vous répondiez.
|
|
45
|
+
|
|
46
|
+
## Variables d’environnement
|
|
47
|
+
|
|
48
|
+
| Variable | Rôle |
|
|
49
|
+
| ------------------ | ------------------------------------------------------ |
|
|
50
|
+
| `HENERGYQUEAI_KEY` | Clé d’API, prioritaire sur le fichier de configuration |
|
|
51
|
+
| `HENERGYQUEAI_URL` | Adresse du service, pour un déploiement privé |
|
|
52
|
+
| `NO_COLOR` | Désactive les couleurs |
|
|
53
|
+
|
|
54
|
+
## Votre clé
|
|
55
|
+
|
|
56
|
+
Elle donne accès à votre compte et consomme votre quota quotidien. Ne la placez jamais dans un dépôt de code. En cas de doute, révoquez-la depuis vos paramètres : l’accès est coupé immédiatement.
|
|
57
|
+
|
|
58
|
+
## Licence
|
|
59
|
+
|
|
60
|
+
Propriétaire. © HenergyqueAI.
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile, writeFile, mkdir, chmod } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { ask } from "../src/client.js";
|
|
6
|
+
import { definitions, execute, needsApproval } from "../src/tools.js";
|
|
7
|
+
import {
|
|
8
|
+
activity,
|
|
9
|
+
confirm,
|
|
10
|
+
preview,
|
|
11
|
+
prompt,
|
|
12
|
+
say,
|
|
13
|
+
style,
|
|
14
|
+
write,
|
|
15
|
+
} from "../src/ui.js";
|
|
16
|
+
import { brand, butterfly } from "../src/butterfly.js";
|
|
17
|
+
|
|
18
|
+
const CONFIG = path.join(homedir(), ".henergyqueai", "config.json");
|
|
19
|
+
const DEFAULT_BASE = process.env.HENERGYQUEAI_URL || "https://henergyqueai.fr";
|
|
20
|
+
|
|
21
|
+
async function loadConfig() {
|
|
22
|
+
const raw = await readFile(CONFIG, "utf8").catch(() => null);
|
|
23
|
+
if (!raw) return {};
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(raw);
|
|
26
|
+
} catch {
|
|
27
|
+
return {};
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function saveConfig(config) {
|
|
32
|
+
await mkdir(path.dirname(CONFIG), { recursive: true });
|
|
33
|
+
await writeFile(CONFIG, JSON.stringify(config, null, 2), "utf8");
|
|
34
|
+
// The key is a credential: keep it readable by its owner only.
|
|
35
|
+
await chmod(CONFIG, 0o600).catch(() => {});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function usage() {
|
|
39
|
+
say(`
|
|
40
|
+
${butterfly()}
|
|
41
|
+
|
|
42
|
+
${brand("henergyqueai")} — votre assistant dans le terminal
|
|
43
|
+
|
|
44
|
+
henergyqueai "corrige le bug de date dans src/facture.js"
|
|
45
|
+
henergyqueai démarre une session interactive
|
|
46
|
+
henergyqueai connexion enregistre votre clé d’API
|
|
47
|
+
henergyqueai deconnexion efface la clé enregistrée
|
|
48
|
+
|
|
49
|
+
Options
|
|
50
|
+
--modele <aelyr|oryne|velys> choisit l’assistant
|
|
51
|
+
--lecture-seule interdit toute écriture et commande
|
|
52
|
+
--oui accepte les modifications sans demander
|
|
53
|
+
|
|
54
|
+
Créez une clé depuis ${DEFAULT_BASE}/parametres`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function login() {
|
|
58
|
+
say(`\n${butterfly()}\n`);
|
|
59
|
+
say(
|
|
60
|
+
` Créez une clé sur ${brand(`${DEFAULT_BASE}/parametres`)}, puis collez-la ici.`,
|
|
61
|
+
);
|
|
62
|
+
const key = await prompt("Clé : ");
|
|
63
|
+
if (!/^hak_[A-Za-z0-9_-]{20,90}$/.test(key)) {
|
|
64
|
+
say(style.red("Cette clé n’a pas le format attendu."));
|
|
65
|
+
process.exit(1);
|
|
66
|
+
}
|
|
67
|
+
const config = await loadConfig();
|
|
68
|
+
await saveConfig({ ...config, key });
|
|
69
|
+
say(style.green(`Clé enregistrée dans ${CONFIG}.`));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// One exchange: the model answers, may ask for tools, and we loop until it
|
|
73
|
+
// stops asking. Every write or command passes through the user first.
|
|
74
|
+
async function turn(session, messages) {
|
|
75
|
+
for (let round = 0; round < 24; round += 1) {
|
|
76
|
+
let printed = false;
|
|
77
|
+
const answer = await ask({
|
|
78
|
+
base: session.base,
|
|
79
|
+
key: session.key,
|
|
80
|
+
messages,
|
|
81
|
+
tools: session.tools,
|
|
82
|
+
modelId: session.modelId,
|
|
83
|
+
onDelta: (text) => {
|
|
84
|
+
printed = true;
|
|
85
|
+
write(text);
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
if (printed) say();
|
|
89
|
+
|
|
90
|
+
if (!answer.toolCalls?.length) {
|
|
91
|
+
messages.push({ role: "assistant", content: answer.content });
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
messages.push({
|
|
96
|
+
role: "assistant",
|
|
97
|
+
content: answer.content || "",
|
|
98
|
+
tool_calls: answer.toolCalls.map((call) => ({
|
|
99
|
+
id: call.id,
|
|
100
|
+
type: "function",
|
|
101
|
+
function: { name: call.name, arguments: call.arguments },
|
|
102
|
+
})),
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
for (const call of answer.toolCalls) {
|
|
106
|
+
let args = {};
|
|
107
|
+
try {
|
|
108
|
+
args = JSON.parse(call.arguments || "{}");
|
|
109
|
+
} catch {
|
|
110
|
+
args = {};
|
|
111
|
+
}
|
|
112
|
+
activity(call.name, args);
|
|
113
|
+
|
|
114
|
+
let approved = true;
|
|
115
|
+
if (needsApproval(call.name)) {
|
|
116
|
+
if (session.readOnly) {
|
|
117
|
+
messages.push({
|
|
118
|
+
role: "tool",
|
|
119
|
+
tool_call_id: call.id,
|
|
120
|
+
content:
|
|
121
|
+
"Session en lecture seule : ni écriture ni commande. Propose la modification en texte.",
|
|
122
|
+
});
|
|
123
|
+
say(style.dim(" refusé (lecture seule)"));
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (call.name === "ecrire_fichier")
|
|
127
|
+
await preview(session.root, args.chemin, String(args.contenu ?? ""));
|
|
128
|
+
if (call.name === "executer" && args.raison)
|
|
129
|
+
say(style.dim(` ${args.raison}`));
|
|
130
|
+
approved =
|
|
131
|
+
session.yes ||
|
|
132
|
+
(await confirm(
|
|
133
|
+
call.name === "ecrire_fichier"
|
|
134
|
+
? ` Écrire ${args.chemin} ?`
|
|
135
|
+
: ` Exécuter cette commande ?`,
|
|
136
|
+
));
|
|
137
|
+
if (!approved) say(style.dim(" refusé"));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const result = await execute(call.name, args, {
|
|
141
|
+
root: session.root,
|
|
142
|
+
approved,
|
|
143
|
+
});
|
|
144
|
+
messages.push({
|
|
145
|
+
role: "tool",
|
|
146
|
+
tool_call_id: call.id,
|
|
147
|
+
content: String(result).slice(0, 30000),
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
say(style.dim(" (trop d’étapes, arrêt)"));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function main() {
|
|
155
|
+
const argv = process.argv.slice(2);
|
|
156
|
+
if (argv.includes("--aide") || argv.includes("-h") || argv.includes("--help"))
|
|
157
|
+
return usage();
|
|
158
|
+
if (argv[0] === "connexion" || argv[0] === "login") return login();
|
|
159
|
+
if (argv[0] === "deconnexion" || argv[0] === "logout") {
|
|
160
|
+
await saveConfig({ ...(await loadConfig()), key: undefined });
|
|
161
|
+
return say("Clé effacée.");
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const take = (flag) => {
|
|
165
|
+
const at = argv.indexOf(flag);
|
|
166
|
+
if (at === -1) return null;
|
|
167
|
+
const value = argv[at + 1];
|
|
168
|
+
argv.splice(at, value ? 2 : 1);
|
|
169
|
+
return value ?? null;
|
|
170
|
+
};
|
|
171
|
+
const modelId = take("--modele") || take("--model");
|
|
172
|
+
const readOnly = argv.includes("--lecture-seule");
|
|
173
|
+
const yes = argv.includes("--oui");
|
|
174
|
+
const words = argv.filter((item) => !item.startsWith("--"));
|
|
175
|
+
|
|
176
|
+
const config = await loadConfig();
|
|
177
|
+
const key = process.env.HENERGYQUEAI_KEY || config.key;
|
|
178
|
+
if (!key) {
|
|
179
|
+
say(style.red("Aucune clé enregistrée."));
|
|
180
|
+
say(`Lancez ${style.bold("henergyqueai connexion")} pour en ajouter une.`);
|
|
181
|
+
process.exit(1);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const session = {
|
|
185
|
+
base: config.base || DEFAULT_BASE,
|
|
186
|
+
key,
|
|
187
|
+
modelId: modelId || config.modelId,
|
|
188
|
+
root: process.cwd(),
|
|
189
|
+
tools: definitions,
|
|
190
|
+
readOnly,
|
|
191
|
+
yes,
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const messages = [];
|
|
195
|
+
const piped = !process.stdin.isTTY
|
|
196
|
+
? await new Promise((resolve) => {
|
|
197
|
+
let raw = "";
|
|
198
|
+
process.stdin.setEncoding("utf8");
|
|
199
|
+
process.stdin.on("data", (chunk) => (raw += chunk));
|
|
200
|
+
process.stdin.on("end", () => resolve(raw));
|
|
201
|
+
})
|
|
202
|
+
: "";
|
|
203
|
+
|
|
204
|
+
const first = [words.join(" "), piped && `\n\n${piped.slice(0, 100000)}`]
|
|
205
|
+
.filter(Boolean)
|
|
206
|
+
.join("");
|
|
207
|
+
|
|
208
|
+
try {
|
|
209
|
+
if (first) {
|
|
210
|
+
messages.push({ role: "user", content: first });
|
|
211
|
+
await turn(session, messages);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
say(`\n${butterfly()}\n`);
|
|
215
|
+
say(` ${brand("HenergyqueAI")}${style.dim(` — ${session.root}`)}`);
|
|
216
|
+
say(style.dim(" Écrivez votre demande. « quitter » pour sortir.\n"));
|
|
217
|
+
for (;;) {
|
|
218
|
+
const line = await prompt("› ");
|
|
219
|
+
if (!line) continue;
|
|
220
|
+
if (["quitter", "exit", "quit"].includes(line.toLowerCase())) return;
|
|
221
|
+
messages.push({ role: "user", content: line });
|
|
222
|
+
await turn(session, messages);
|
|
223
|
+
say();
|
|
224
|
+
}
|
|
225
|
+
} catch (error) {
|
|
226
|
+
say(style.red(error.message));
|
|
227
|
+
process.exit(1);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
main();
|
package/package.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "henergyqueai",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "L’assistant HenergyqueAI dans votre terminal : il lit votre projet, propose des modifications et lance des commandes, avec votre accord.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"henergyqueai": "bin/henergyqueai.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src",
|
|
12
|
+
"README.md"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"license": "UNLICENSED",
|
|
18
|
+
"keywords": [
|
|
19
|
+
"henergyqueai",
|
|
20
|
+
"cli",
|
|
21
|
+
"assistant",
|
|
22
|
+
"ia"
|
|
23
|
+
],
|
|
24
|
+
"homepage": "https://henergyqueai.fr"
|
|
25
|
+
}
|
package/src/butterfly.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// The HenergyqueAI butterfly, in the brand's own colours. Terminals without
|
|
2
|
+
// colour still get the shape.
|
|
3
|
+
const plain = !process.stdout.isTTY || process.env.NO_COLOR;
|
|
4
|
+
|
|
5
|
+
const rgb = (hex, text) => {
|
|
6
|
+
if (plain) return text;
|
|
7
|
+
const value = parseInt(hex.slice(1), 16);
|
|
8
|
+
return `\u001b[38;2;${(value >> 16) & 255};${(value >> 8) & 255};${value & 255}m${text}\u001b[0m`;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// Light at the wingtips, deep near the body, like the logo.
|
|
12
|
+
const WINGS = ["#edac88", "#c46c4f", "#95503f", "#95503f", "#784e3e"];
|
|
13
|
+
const BODY = "#5d3b2f";
|
|
14
|
+
|
|
15
|
+
const shape = [
|
|
16
|
+
" ▗▄▄▖ ▗▄▄▖ ",
|
|
17
|
+
" ▟███▙▓▟███▙ ",
|
|
18
|
+
"▐█████▓█████▌",
|
|
19
|
+
" ▜███▛▓▜███▛ ",
|
|
20
|
+
" ▝▀▘ ▀ ▝▀▘",
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
// The body runs down the middle, so column 6 is tinted apart from the wings.
|
|
24
|
+
const tinted = (line, wing) =>
|
|
25
|
+
rgb(wing, line.slice(0, 6)) + rgb(BODY, line[6]) + rgb(wing, line.slice(7));
|
|
26
|
+
|
|
27
|
+
export const butterfly = () =>
|
|
28
|
+
shape.map((line, index) => tinted(line, WINGS[index])).join("\n");
|
|
29
|
+
|
|
30
|
+
export const brand = (text) => rgb("#c46c4f", text);
|
package/src/client.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Talks to /api/v1/agent and turns its stream into events the terminal can
|
|
2
|
+
// display as they happen.
|
|
3
|
+
export async function ask({
|
|
4
|
+
base,
|
|
5
|
+
key,
|
|
6
|
+
messages,
|
|
7
|
+
tools,
|
|
8
|
+
modelId,
|
|
9
|
+
onDelta,
|
|
10
|
+
onThinking,
|
|
11
|
+
signal,
|
|
12
|
+
}) {
|
|
13
|
+
const response = await fetch(`${base}/api/v1/agent`, {
|
|
14
|
+
method: "POST",
|
|
15
|
+
signal,
|
|
16
|
+
headers: {
|
|
17
|
+
"Content-Type": "application/json",
|
|
18
|
+
Authorization: `Bearer ${key}`,
|
|
19
|
+
},
|
|
20
|
+
body: JSON.stringify({ messages, tools, modelId }),
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
if (
|
|
24
|
+
!String(response.headers.get("content-type")).includes("text/event-stream")
|
|
25
|
+
) {
|
|
26
|
+
const problem = await response.json().catch(() => ({}));
|
|
27
|
+
const error = new Error(problem.error || `Erreur ${response.status}.`);
|
|
28
|
+
error.status = response.status;
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const reader = response.body.getReader();
|
|
33
|
+
const decoder = new TextDecoder();
|
|
34
|
+
let buffer = "";
|
|
35
|
+
let result = null;
|
|
36
|
+
let failure = null;
|
|
37
|
+
for (;;) {
|
|
38
|
+
const { done, value } = await reader.read();
|
|
39
|
+
if (done) break;
|
|
40
|
+
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
|
|
41
|
+
let cut;
|
|
42
|
+
while ((cut = buffer.indexOf("\n\n")) !== -1) {
|
|
43
|
+
const frame = buffer.slice(0, cut);
|
|
44
|
+
buffer = buffer.slice(cut + 2);
|
|
45
|
+
let name = "";
|
|
46
|
+
let data = "";
|
|
47
|
+
for (const line of frame.split("\n")) {
|
|
48
|
+
if (line.startsWith("event:")) name = line.slice(6).trim();
|
|
49
|
+
else if (line.startsWith("data:")) data += line.slice(5).trim();
|
|
50
|
+
}
|
|
51
|
+
if (!data) continue;
|
|
52
|
+
let parsed;
|
|
53
|
+
try {
|
|
54
|
+
parsed = JSON.parse(data);
|
|
55
|
+
} catch {
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (name === "delta") onDelta?.(parsed.text || "");
|
|
59
|
+
else if (name === "thinking") onThinking?.();
|
|
60
|
+
else if (name === "done") result = parsed;
|
|
61
|
+
else if (name === "error") failure = parsed;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (failure) throw new Error(failure.error);
|
|
65
|
+
if (!result) throw new Error("Connexion interrompue avant la réponse.");
|
|
66
|
+
return result;
|
|
67
|
+
}
|
package/src/tools.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { readFile, writeFile, readdir, stat } from "node:fs/promises";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { exec } from "node:child_process";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
|
|
7
|
+
const run = promisify(exec);
|
|
8
|
+
const SKIP = new Set([
|
|
9
|
+
"node_modules",
|
|
10
|
+
".git",
|
|
11
|
+
"dist",
|
|
12
|
+
"build",
|
|
13
|
+
".next",
|
|
14
|
+
"coverage",
|
|
15
|
+
".venv",
|
|
16
|
+
"__pycache__",
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
// Everything stays inside the folder the assistant was started in. A path that
|
|
20
|
+
// climbs out of it is refused rather than quietly resolved.
|
|
21
|
+
export function inside(root, candidate) {
|
|
22
|
+
const target = path.resolve(root, candidate || ".");
|
|
23
|
+
const base = path.resolve(root);
|
|
24
|
+
if (target !== base && !target.startsWith(base + path.sep)) return null;
|
|
25
|
+
return target;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function walk(root, current, found, limit) {
|
|
29
|
+
if (found.length >= limit) return;
|
|
30
|
+
const entries = await readdir(current, { withFileTypes: true }).catch(
|
|
31
|
+
() => [],
|
|
32
|
+
);
|
|
33
|
+
for (const entry of entries) {
|
|
34
|
+
if (found.length >= limit) return;
|
|
35
|
+
if (entry.name.startsWith(".") && entry.name !== ".env.example") continue;
|
|
36
|
+
if (SKIP.has(entry.name)) continue;
|
|
37
|
+
const full = path.join(current, entry.name);
|
|
38
|
+
if (entry.isDirectory()) await walk(root, full, found, limit);
|
|
39
|
+
else found.push(path.relative(root, full).replaceAll(path.sep, "/"));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export const definitions = [
|
|
44
|
+
{
|
|
45
|
+
type: "function",
|
|
46
|
+
function: {
|
|
47
|
+
name: "lire_fichier",
|
|
48
|
+
description:
|
|
49
|
+
"Lit un fichier du projet et renvoie son contenu numéroté par ligne. À utiliser avant toute affirmation sur un fichier, et obligatoirement avant de le modifier.",
|
|
50
|
+
parameters: {
|
|
51
|
+
type: "object",
|
|
52
|
+
properties: {
|
|
53
|
+
chemin: {
|
|
54
|
+
type: "string",
|
|
55
|
+
description: "Chemin relatif à la racine du projet.",
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
required: ["chemin"],
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
type: "function",
|
|
64
|
+
function: {
|
|
65
|
+
name: "lister_fichiers",
|
|
66
|
+
description:
|
|
67
|
+
"Liste les fichiers du projet, en ignorant node_modules, .git et les dossiers de build.",
|
|
68
|
+
parameters: {
|
|
69
|
+
type: "object",
|
|
70
|
+
properties: {
|
|
71
|
+
dossier: {
|
|
72
|
+
type: "string",
|
|
73
|
+
description: "Sous-dossier à explorer. Par défaut, tout le projet.",
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
type: "function",
|
|
81
|
+
function: {
|
|
82
|
+
name: "chercher",
|
|
83
|
+
description:
|
|
84
|
+
"Cherche un texte dans les fichiers du projet et renvoie les lignes correspondantes avec leur emplacement.",
|
|
85
|
+
parameters: {
|
|
86
|
+
type: "object",
|
|
87
|
+
properties: {
|
|
88
|
+
motif: { type: "string", description: "Le texte à chercher." },
|
|
89
|
+
dossier: { type: "string", description: "Où chercher." },
|
|
90
|
+
},
|
|
91
|
+
required: ["motif"],
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
type: "function",
|
|
97
|
+
function: {
|
|
98
|
+
name: "ecrire_fichier",
|
|
99
|
+
description:
|
|
100
|
+
"Remplace le contenu d’un fichier, ou le crée. L’utilisateur voit les modifications et doit les accepter. Lis toujours le fichier avant de le réécrire.",
|
|
101
|
+
parameters: {
|
|
102
|
+
type: "object",
|
|
103
|
+
properties: {
|
|
104
|
+
chemin: { type: "string" },
|
|
105
|
+
contenu: {
|
|
106
|
+
type: "string",
|
|
107
|
+
description: "Le contenu complet du fichier après modification.",
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
required: ["chemin", "contenu"],
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
type: "function",
|
|
116
|
+
function: {
|
|
117
|
+
name: "executer",
|
|
118
|
+
description:
|
|
119
|
+
"Exécute une commande shell à la racine du projet, après accord de l’utilisateur. Sert à lancer des tests, un build ou un outil de version.",
|
|
120
|
+
parameters: {
|
|
121
|
+
type: "object",
|
|
122
|
+
properties: {
|
|
123
|
+
commande: { type: "string" },
|
|
124
|
+
raison: {
|
|
125
|
+
type: "string",
|
|
126
|
+
description: "Pourquoi cette commande est nécessaire.",
|
|
127
|
+
},
|
|
128
|
+
},
|
|
129
|
+
required: ["commande"],
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
];
|
|
134
|
+
|
|
135
|
+
// Whether a tool needs the user's explicit blessing before it runs.
|
|
136
|
+
export const needsApproval = (name) =>
|
|
137
|
+
["ecrire_fichier", "executer"].includes(name);
|
|
138
|
+
|
|
139
|
+
export async function execute(name, args, { root, approved }) {
|
|
140
|
+
if (name === "lire_fichier") {
|
|
141
|
+
const target = inside(root, args.chemin);
|
|
142
|
+
if (!target) return "Chemin hors du projet : refusé.";
|
|
143
|
+
if (!existsSync(target)) return `Le fichier ${args.chemin} n’existe pas.`;
|
|
144
|
+
const size = (await stat(target)).size;
|
|
145
|
+
if (size > 400_000) return `${args.chemin} est trop volumineux à lire.`;
|
|
146
|
+
const body = await readFile(target, "utf8").catch(() => null);
|
|
147
|
+
if (body === null) return `${args.chemin} n’est pas un fichier texte.`;
|
|
148
|
+
return body
|
|
149
|
+
.split("\n")
|
|
150
|
+
.slice(0, 2000)
|
|
151
|
+
.map((line, index) => `${index + 1}\t${line}`)
|
|
152
|
+
.join("\n");
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (name === "lister_fichiers") {
|
|
156
|
+
const target = inside(root, args.dossier || ".");
|
|
157
|
+
if (!target) return "Chemin hors du projet : refusé.";
|
|
158
|
+
const found = [];
|
|
159
|
+
await walk(root, target, found, 400);
|
|
160
|
+
return found.length ? found.join("\n") : "Aucun fichier.";
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (name === "chercher") {
|
|
164
|
+
const target = inside(root, args.dossier || ".");
|
|
165
|
+
if (!target) return "Chemin hors du projet : refusé.";
|
|
166
|
+
const files = [];
|
|
167
|
+
await walk(root, target, files, 400);
|
|
168
|
+
const needle = String(args.motif || "");
|
|
169
|
+
if (!needle) return "Motif vide.";
|
|
170
|
+
const hits = [];
|
|
171
|
+
for (const relative of files) {
|
|
172
|
+
if (hits.length >= 80) break;
|
|
173
|
+
const body = await readFile(path.join(root, relative), "utf8").catch(
|
|
174
|
+
() => null,
|
|
175
|
+
);
|
|
176
|
+
if (body === null) continue;
|
|
177
|
+
body.split("\n").forEach((line, index) => {
|
|
178
|
+
if (hits.length < 80 && line.includes(needle))
|
|
179
|
+
hits.push(`${relative}:${index + 1}: ${line.trim().slice(0, 200)}`);
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
return hits.length
|
|
183
|
+
? hits.join("\n")
|
|
184
|
+
: `Aucune occurrence de « ${needle} ».`;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (name === "ecrire_fichier") {
|
|
188
|
+
if (!approved) return "L’utilisateur a refusé cette modification.";
|
|
189
|
+
const target = inside(root, args.chemin);
|
|
190
|
+
if (!target) return "Chemin hors du projet : refusé.";
|
|
191
|
+
await writeFile(target, String(args.contenu ?? ""), "utf8");
|
|
192
|
+
return `${args.chemin} enregistré.`;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (name === "executer") {
|
|
196
|
+
if (!approved) return "L’utilisateur a refusé cette commande.";
|
|
197
|
+
try {
|
|
198
|
+
const { stdout, stderr } = await run(String(args.commande), {
|
|
199
|
+
cwd: root,
|
|
200
|
+
timeout: 120000,
|
|
201
|
+
maxBuffer: 2_000_000,
|
|
202
|
+
});
|
|
203
|
+
return (stdout + stderr).slice(0, 8000) || "(aucune sortie)";
|
|
204
|
+
} catch (error) {
|
|
205
|
+
return `Échec (${error.code ?? "erreur"}) :\n${String(
|
|
206
|
+
error.stdout || "",
|
|
207
|
+
).slice(0, 3000)}${String(error.stderr || error.message).slice(0, 3000)}`;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return `Outil inconnu : ${name}.`;
|
|
212
|
+
}
|
package/src/ui.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { createInterface } from "node:readline/promises";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
const plain = !process.stdout.isTTY || process.env.NO_COLOR;
|
|
6
|
+
const paint = (code, text) =>
|
|
7
|
+
plain ? text : `\u001b[${code}m${text}\u001b[0m`;
|
|
8
|
+
|
|
9
|
+
export const style = {
|
|
10
|
+
dim: (text) => paint("2", text),
|
|
11
|
+
bold: (text) => paint("1", text),
|
|
12
|
+
green: (text) => paint("32", text),
|
|
13
|
+
red: (text) => paint("31", text),
|
|
14
|
+
olive: (text) => paint("38;5;101", text),
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export const say = (text = "") => process.stdout.write(`${text}\n`);
|
|
18
|
+
export const write = (text) => process.stdout.write(text);
|
|
19
|
+
|
|
20
|
+
export function activity(name, args) {
|
|
21
|
+
const detail = {
|
|
22
|
+
lire_fichier: args.chemin,
|
|
23
|
+
lister_fichiers: args.dossier || ".",
|
|
24
|
+
chercher: `« ${args.motif} »`,
|
|
25
|
+
ecrire_fichier: args.chemin,
|
|
26
|
+
executer: args.commande,
|
|
27
|
+
}[name];
|
|
28
|
+
const label =
|
|
29
|
+
{
|
|
30
|
+
lire_fichier: "Lecture",
|
|
31
|
+
lister_fichiers: "Exploration",
|
|
32
|
+
chercher: "Recherche",
|
|
33
|
+
ecrire_fichier: "Écriture",
|
|
34
|
+
executer: "Commande",
|
|
35
|
+
}[name] || name;
|
|
36
|
+
say(style.dim(` ${label} ${detail ?? ""}`.trimEnd()));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Shows what would change before anything is written, the way a diff does.
|
|
40
|
+
export async function preview(root, relative, next) {
|
|
41
|
+
const target = path.resolve(root, relative);
|
|
42
|
+
const current = await readFile(target, "utf8").catch(() => null);
|
|
43
|
+
if (current === null) {
|
|
44
|
+
const lines = next.split("\n");
|
|
45
|
+
say(style.dim(` nouveau fichier, ${lines.length} lignes`));
|
|
46
|
+
for (const line of lines.slice(0, 12)) say(style.green(` + ${line}`));
|
|
47
|
+
if (lines.length > 12) say(style.dim(` … ${lines.length - 12} de plus`));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const before = current.split("\n");
|
|
51
|
+
const after = next.split("\n");
|
|
52
|
+
let start = 0;
|
|
53
|
+
while (start < before.length && before[start] === after[start]) start += 1;
|
|
54
|
+
let end = 0;
|
|
55
|
+
while (
|
|
56
|
+
end < before.length - start &&
|
|
57
|
+
end < after.length - start &&
|
|
58
|
+
before[before.length - 1 - end] === after[after.length - 1 - end]
|
|
59
|
+
)
|
|
60
|
+
end += 1;
|
|
61
|
+
const removed = before.slice(start, before.length - end);
|
|
62
|
+
const added = after.slice(start, after.length - end);
|
|
63
|
+
if (!removed.length && !added.length) {
|
|
64
|
+
say(style.dim(" aucun changement"));
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
say(style.dim(` ligne ${start + 1}`));
|
|
68
|
+
for (const line of removed.slice(0, 10)) say(style.red(` - ${line}`));
|
|
69
|
+
if (removed.length > 10)
|
|
70
|
+
say(style.dim(` … ${removed.length - 10} lignes retirées de plus`));
|
|
71
|
+
for (const line of added.slice(0, 10)) say(style.green(` + ${line}`));
|
|
72
|
+
if (added.length > 10)
|
|
73
|
+
say(style.dim(` … ${added.length - 10} lignes ajoutées de plus`));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function confirm(question) {
|
|
77
|
+
if (!process.stdin.isTTY) return false;
|
|
78
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
79
|
+
try {
|
|
80
|
+
const answer = (await rl.question(`${question} [o/N] `))
|
|
81
|
+
.trim()
|
|
82
|
+
.toLowerCase();
|
|
83
|
+
return answer === "o" || answer === "oui" || answer === "y";
|
|
84
|
+
} finally {
|
|
85
|
+
rl.close();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function prompt(question) {
|
|
90
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
91
|
+
try {
|
|
92
|
+
return (await rl.question(question)).trim();
|
|
93
|
+
} finally {
|
|
94
|
+
rl.close();
|
|
95
|
+
}
|
|
96
|
+
}
|