poad 2.42.0 → 2.46.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/poad.js CHANGED
@@ -116,37 +116,18 @@ const checkVersion = async () => {
116
116
  });
117
117
  };
118
118
 
119
- // Function to display the banner and the list of commands.
120
- const displayBanner = () => {
121
- figlet('poad', function (err, data) {
122
- console.log(chalk.cyan(data));
123
- console.log(chalk.white.bold(` version ${package.version}`));
124
- console.log(' ');
125
- console.log(
126
- `${chalk.bold(' Usage :')} ${chalk.cyanBright(
127
- POAD_COMMAND + ' <command>'
128
- )} ${chalk.cyan('[<args>]')}`
129
- );
130
- console.log(' ');
131
- console.log(chalk.bold(' Global commands :'));
132
- console.log(' ');
133
- display(POAD_GLOBAL_COMMANDS);
134
- console.log(' ');
135
- console.log(chalk.bold(' Project commands :'));
136
- if (!POAD_PATH) {
137
- console.log(`\n You are not in a project directory. `);
138
- console.log(' ');
139
- } else {
140
- POAD_COMMANDS = loadPoadCommands(__dirname + '/project/cli.js');
141
- console.log(' ');
142
- display(POAD_COMMANDS);
143
- console.log(' ');
144
- }
145
- console.log(' ');
146
- });
119
+ // Liste des commandes (utils/banner.js) : vue courte pour « poad », liste
120
+ // complète pour « poad --help », « poad -h » et « poad help ».
121
+ const displayBanner = ({ full = false } = {}) => {
122
+ const lines = require('./utils/banner').render({ full, inProject: Boolean(POAD_PATH), version: package.version });
123
+ console.log(lines.join('\n'));
147
124
  };
148
125
 
149
126
  // Function to load project specific commands.
127
+ // « [Libellé] description » : un libellé seulement en tête du texte. Un crochet plus loin
128
+ // (« [gateway] max_body » dans la description de start) fait partie de la description.
129
+ const hasLabel = (text) => typeof text === 'string' && /^\[[^\]]*\] /.test(text);
130
+
150
131
  const loadPoadCommands = (path) => {
151
132
  let POAD_COMMANDS = {};
152
133
  try {
@@ -158,8 +139,8 @@ const loadPoadCommands = (path) => {
158
139
  if (s !== 'description') subs.push({ title: s });
159
140
  }
160
141
  let description = '';
161
- if (cli[el].description.indexOf(']') > -1) {
162
- description = cli[el].description.split('] ')[1];
142
+ if (hasLabel(cli[el].description)) {
143
+ description = cli[el].description.slice(cli[el].description.indexOf('] ') + 2);
163
144
  let lbl = cli[el].description
164
145
  .split('] ')[0]
165
146
  .replace('[', '')
@@ -184,8 +165,8 @@ const loadPoadCommands = (path) => {
184
165
  }
185
166
  } else {
186
167
  let description = '';
187
- if (cli[el].indexOf(']') > -1) {
188
- description = cli[el].split('] ')[1];
168
+ if (hasLabel(cli[el])) {
169
+ description = cli[el].slice(cli[el].indexOf('] ') + 2);
189
170
  let lbl = cli[el].split('] ')[0].replace('[', '').replace(']', '');
190
171
  POAD_COMMANDS[el] = {
191
172
  info: {
@@ -211,102 +192,6 @@ const loadPoadCommands = (path) => {
211
192
  }
212
193
  };
213
194
 
214
- /**
215
- * Displays the subcommands and their descriptions for a given command.
216
- *
217
- * @param {string} path - The path of the command.
218
- * @param {string} title - The title of the command.
219
- * @param {string} description - The description of the command.
220
- * @param {object} cli - The command line interface object.
221
- */
222
- const displaySub = (path, title, description, cli) => {
223
- POAD_COMMANDS = {};
224
- delete cli.description;
225
- for (let el in cli) {
226
- if (cli[el].description) {
227
- let subs = [];
228
- for (let s in cli[el]) {
229
- if (s !== 'description') subs.push({ title: s });
230
- }
231
- let description = '';
232
- if (cli[el].description.indexOf(']') > -1) {
233
- description = cli[el].description.split('] ')[1];
234
- let lbl = cli[el].description
235
- .split('] ')[0]
236
- .replace('[', '')
237
- .replace(']', '');
238
- POAD_COMMANDS[el] = {
239
- info: {
240
- title: el,
241
- description: description,
242
- label: lbl.toLowerCase(),
243
- sub: subs,
244
- },
245
- };
246
- } else {
247
- description = cli[el].description;
248
- POAD_COMMANDS[el] = {
249
- info: {
250
- title: el,
251
- description: cli[el].description,
252
- sub: subs,
253
- },
254
- };
255
- }
256
- } else {
257
- let description = '';
258
- if (cli[el].indexOf(']') > -1) {
259
- description = cli[el].split('] ')[1];
260
- let lbl = cli[el].split('] ')[0].replace('[', '').replace(']', '');
261
- POAD_COMMANDS[el] = {
262
- info: {
263
- title: el,
264
- description: description,
265
- label: lbl.toLowerCase(),
266
- },
267
- };
268
- } else {
269
- POAD_COMMANDS[el] = {
270
- info: {
271
- title: el,
272
- description: cli[el],
273
- },
274
- };
275
- }
276
- }
277
- }
278
-
279
- console.log(
280
- `${chalk.bold(' Usage :')} ${chalk.cyanBright(
281
- POAD_COMMAND + ' ' + args.join(' ')
282
- )} ${chalk.cyan('[<args>]')}`
283
- );
284
- console.log(' ');
285
- display(POAD_COMMANDS);
286
- console.log(' ');
287
- };
288
-
289
- // Function to parse commands.
290
- const parseCommand = (args) => {
291
- const cli = require(__dirname + '/project/cli');
292
- let cmd = cli;
293
- let arguments = [];
294
- let title = '';
295
- let path = '';
296
- for (let i = 0; i < args.length; i++) {
297
- if (!cmd[args[i]]) arguments.push(args[i]);
298
- else {
299
- cmd = cmd[args[i]];
300
- title = args[i];
301
- path += ' ' + title;
302
- }
303
- }
304
- if (cmd.description) displaySub(path, title, cmd.description, cmd);
305
- else {
306
- ExecCommand(path.replace(/ /g, '/'), arguments);
307
- }
308
- };
309
-
310
195
  /**
311
196
  * Fonction qui vérifie si un chemin existe dans un objet donné
312
197
  * @param {object} obj - L'objet dans lequel chercher
@@ -357,8 +242,6 @@ const parseCommandArgs = (commands, args) => {
357
242
  // Function to process entered commands.
358
243
  const processCommands = (args) => {
359
244
  const command = args[0];
360
- const maxWidth = 30;
361
- const maxDescriptionLength = 50;
362
245
 
363
246
  POAD_COMMANDS = loadPoadCommands(__dirname + '/project/cli.js');
364
247
 
@@ -385,86 +268,6 @@ const processCommands = (args) => {
385
268
  }
386
269
  };
387
270
 
388
- // Function to format command labels with chalk for color coding.
389
- const label = (o) => {
390
- const caption = o.label;
391
-
392
- if (caption === 'experimental') return chalk.red(' (' + caption + ')');
393
- if (caption === 'alpha') return chalk.cyan(' (' + caption + ')');
394
- if (caption === 'beta') return chalk.magenta(' (' + caption + ')');
395
- if (caption === 'docker') return chalk.green(' (' + caption + ')');
396
- if (caption === 'ai') return chalk.yellow(' (' + caption.toUpperCase() + ')');
397
- return '';
398
- };
399
-
400
- // Function to execute commands.
401
- const ExecCommand = (p, args) => {
402
- console.log(p, args);
403
- const unit = require(__dirname + p);
404
- const params = {
405
- dir: {
406
- home: `${userHomeDir}/.cadriciel`,
407
- cadriciel: path.normalize(CADRICIEL_PATH + '/..'),
408
- root: path.normalize(CADRICIEL_PATH + '/../..'),
409
- },
410
- };
411
- unit(args, params);
412
- };
413
-
414
- // Function to format command descriptions.
415
- const formatDescription = (description, maxLength) => {
416
- if (description.length <= maxLength) return description;
417
-
418
- const breakPoint = description.lastIndexOf(' ', maxLength);
419
- const firstPart = description.substring(0, breakPoint);
420
- const secondPart = description.substring(breakPoint + 1).trim();
421
-
422
- return firstPart + '\n ' + secondPart;
423
- };
424
-
425
- // Function to display commands.
426
- const display = (commands) => {
427
- const maxWidth = 30;
428
- const maxDescriptionLength = 50;
429
-
430
- for (let el in commands) {
431
- let title = el;
432
- if (commands[el].info.title != '---') {
433
- if (commands[el].info) {
434
- let description = commands[el].info.description;
435
- if (commands[el].info.sub) {
436
- title += ' <subcommand>';
437
- const sc = [];
438
- for (let i = 0; i < commands[el].info.sub.length; i++) {
439
- sc.push(commands[el].info.sub[i].title);
440
- }
441
- description += chalk.white(' ');
442
- description += chalk.grey(' (subcommands: ');
443
- description += chalk.cyan(sc.join(', '));
444
- description += chalk.grey(')');
445
- }
446
- const dots = '.'.repeat(maxWidth - title.length);
447
-
448
- const formattedDesc = formatDescription(
449
- description,
450
- maxDescriptionLength
451
- );
452
-
453
- console.log(
454
- ' ' +
455
- chalk.cyanBright(title) +
456
- ' ' +
457
- chalk.grey(dots) +
458
- ' ' +
459
- label(commands[el].info) +
460
- ' ' +
461
- chalk.white(formattedDesc)
462
- );
463
- }
464
- }
465
- }
466
- };
467
-
468
271
  // True when version `a` is strictly newer than `b` (major.minor.patch).
469
272
  const isNewerVersion = (a, b) => {
470
273
  const pa = String(a).split('.').map(Number);
@@ -489,7 +292,7 @@ const helpGuard = () => {
489
292
  POAD_GLOBAL_COMMANDS = loadPoadCommands(__dirname + '/global/cli.js');
490
293
  const words = argv.filter((a) => !help.HELP_FLAGS.includes(a));
491
294
  if (!words.length) {
492
- displayBanner();
295
+ displayBanner({ full: true });
493
296
  return true;
494
297
  }
495
298
  if (!help.printHelp(argv)) {
package/project/cli.js CHANGED
@@ -7,33 +7,33 @@
7
7
  *
8
8
  */
9
9
  module.exports = {
10
- info: 'Information about your project: URLs, keys, migrations, services (secrets hidden; info --secrets shows the JWT secret, the service_role key and the admin passwords)',
10
+ info: 'URLs, keys, migrations and services of the running project (secrets hidden)',
11
11
  client: {
12
- description: 'Front-end of the project: client init is now poad create <app> --template t (adds apps/<app>, kept as an alias)',
12
+ description: 'Front-end of the project: client init, kept as an alias of poad create <app> --template t',
13
13
  init: 'Alias of poad create <app>: adds a front-end (angular | next | nuxt | vanilla, dir=<folder>, from=<local template>, --yes)',
14
14
  },
15
15
  console: 'Open the administration console of the running project in the browser (engine 0.11.0+, no password, this machine only)',
16
16
  kc: 'Keycloak test set of the project (poad/keycloak.json; kc export saves the running realm)',
17
- setup: 'Choose what "poad start" starts: e-mails (Mailpit/SMTP), Keycloak, Valkey, migrations (interactive, or kc=on valkey=off, kc=shared|own, --all, --none, --list)',
17
+ setup: 'Choose what "poad start" starts: e-mails (Mailpit/SMTP), Keycloak, Valkey, migrations',
18
18
  db: {
19
- description: 'Local database: db reset (erase, migrate, seed), db seed (apply poad/seed.sql)',
19
+ description: 'Local database of the project',
20
20
  reset: 'Erase the database and storage files, restart, apply migrations then poad/seed.sql (--yes outside a terminal)',
21
21
  seed: 'Apply poad/seed.sql (development data)',
22
22
  diff: 'Structure changes made outside the migrations (console SQL, psql…): diff to list them, diff <name> to write them as a migration, diff --discard to forget them',
23
23
  },
24
- upgrade: 'Upgrade the engine of the project (backs up poad/ first): upgrade, upgrade to=<version>, upgrade channel=beta (or channel = "beta" in poad/config.toml, or POAD_CHANNEL=beta), upgrade --rollback, upgrade --list (--yes outside a terminal)',
25
- logs: 'Unified logs of the project: logs [service…] level=warn since=15m request=<id> grep=<text> flow=<name> run=<id or its first 8 characters> step=<name> function=<name> token=<MCP token name, id or prefix> tool=<MCP tool> outcome=<ok, refused, error…> limit=100 -f --json',
24
+ upgrade: 'Upgrade the engine of the project (backup first), or roll back to a backup',
25
+ logs: 'Unified logs of the project, every service, with filters (level, since, request, flow, function, AI…) and -f',
26
26
  gen: {
27
- description: 'Generators: gen types (TypeScript types of the database), gen env (types of the public variables)',
27
+ description: 'Generators of TypeScript types: the database, the public variables',
28
28
  types: 'TypeScript types of the database for createClient<Database>() (out=src/types/database.ts)',
29
29
  env: 'TypeScript types of the public variables (PUBLIC_*) for poad.env (out=src/types/poad-env.ts)',
30
30
  },
31
31
  migrate: 'Apply pending migrations of poad/migrations and named queries of poad/queries (poad start does it too)',
32
32
  migration: 'Database migrations: migration new <name>, migration list',
33
- functions: 'Functions of the project (JS/TS, served on /functions/v1/<name>): functions new <name> (or create), functions list, functions types (editor autocompletion)',
34
- function: 'Same as functions: function create <name>, function list',
35
- flows: 'Flows of the project (automations in poad/flows/<name>.json, engine 0.18.0+, needs Valkey): flows new <name>, flows list, flows run <name> [key=value …] [input=<file.json>] [--no-wait], flows runs [name] [limit=20], flows show <run_id>, flows cancel <run_id>',
36
- flow: 'Same as flows: flow new <name>, flow list, flow run <name>',
33
+ functions: 'Functions of the project (JS/TS, served on /functions/v1/<name>): new, list, types',
34
+ function: 'Alias of poad functions',
35
+ flows: 'Flows of the project (automations in poad/flows/<name>.json, engine 0.18.0+, needs Valkey): new, list, run, runs, show, cancel',
36
+ flow: 'Alias of poad flows',
37
37
  /* status: `[AI] Vérification du statut de l'environnement`,
38
38
  gen: {
39
39
  description: 'Génération automatique des éléments clés pour votre projet',
package/project/logs.js CHANGED
@@ -18,6 +18,9 @@
18
18
  // poad logs tool=select_rows un outil du serveur MCP
19
19
  // poad logs outcome=refused un résultat d'appel MCP (ok, error, refused,
20
20
  // invalid, not_found, unauthorized, rate_limited)
21
+ // poad logs ai provider=openai les appels au socle IA (engine 0.30+) d'un fournisseur ;
22
+ // model=gpt-5 ; outcome= vaut aussi pour eux (ok, provider_error,
23
+ // budget_exceeded, no_credential, forbidden, invalid)
21
24
  // poad logs limit=500 nombre de lignes (100 par défaut)
22
25
  // poad logs -f | --follow suivi en direct
23
26
  // poad logs --json une ligne JSON par entrée (pour jq)
package/project/setup.js CHANGED
@@ -221,6 +221,8 @@ module.exports = async (args = {}) => {
221
221
  }
222
222
 
223
223
  config = loadConfig(root);
224
+ // Groupe « Services » de la console : Keycloak activé, Mailpit remplacé par un vrai SMTP…
225
+ require('../utils/console-services').write(root, config);
224
226
  if (!changes.length) {
225
227
  summary();
226
228
  console.log(chalk.grey(' Nothing changed.'));
@@ -0,0 +1,117 @@
1
+ // Catalogue des modèles d'IA (clé « ai » de poadio/permalink) : validation, cache, repli hors ligne, fichier
2
+ // écrit pour l'engine, [ai.models], et poad ai models. Sans réseau : la lecture de permalink est remplacée.
3
+ // test/fixtures-permalink-ai.json : le poad.json proposé pour poadio/permalink.
4
+ const test = require('node:test');
5
+ const assert = require('node:assert');
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { spawnSync } = require('child_process');
9
+ const { tmpdir } = require('./helpers');
10
+ const cat = require('../utils/ai-catalog');
11
+ const ai = require('../utils/ai');
12
+
13
+ const POAD = path.join(__dirname, '..', 'poad.js');
14
+ const STUB = path.join(__dirname, 'help-stub.js');
15
+ const FIXTURE = JSON.parse(fs.readFileSync(path.join(__dirname, 'fixtures-permalink-ai.json'), 'utf8'));
16
+
17
+ test('le poad.json proposé : un ancien CLI n’y lit que engine, le catalogue est valide et chaque défaut est listé', () => {
18
+ // Ce que lisent les CLI ≥ 2.38 (utils/latest.js) : la clé engine, inchangée
19
+ assert.deepStrictEqual(Object.keys(FIXTURE.engine), ['stable']);
20
+ const { catalog, warnings } = cat.parseCatalog(FIXTURE.ai);
21
+ assert.deepStrictEqual(warnings, []);
22
+ assert.deepStrictEqual(Object.keys(catalog.providers), ['anthropic', 'openai', 'mistral', 'gemini']);
23
+ assert.strictEqual(catalog.providers.anthropic.default, 'claude-opus-5-5');
24
+ assert.strictEqual(catalog.providers.openai.default, 'gpt-6.2-sol');
25
+ assert.strictEqual(catalog.providers.mistral.default, 'mistral-large-4');
26
+ assert.strictEqual(catalog.providers.gemini.default, 'gemini-4-neon');
27
+ assert.strictEqual(catalog.checked_on, '2026-11-25');
28
+ });
29
+
30
+ test('validation : schéma inconnu, fournisseur inconnu, modèle faux, défaut absent', () => {
31
+ assert.strictEqual(cat.parseCatalog({ ...FIXTURE.ai, schema: 2 }).catalog, null);
32
+ assert.match(cat.parseCatalog({ ...FIXTURE.ai, schema: 2 }).warnings[0], /update poad/);
33
+ const r = cat.parseCatalog({
34
+ schema: 1,
35
+ providers: {
36
+ llama: { default: 'x', models: [] },
37
+ openai: { default: 'a', models: [{ id: 'a', input: 1, output: 2 }, { id: 'b b', input: 1, output: 1 }, { id: 'c', input: -1, output: 1 }, { id: 'd', input: 1, output: 1, status: 'beta' }] },
38
+ mistral: { default: 'absent', models: [{ id: 'm', input: 1, output: 1 }] },
39
+ },
40
+ });
41
+ assert.deepStrictEqual(Object.keys(r.catalog.providers), ['openai']);
42
+ assert.deepStrictEqual(r.catalog.providers.openai.models, [{ id: 'a', label: 'a', input: 1, output: 2 }]);
43
+ assert.strictEqual(r.warnings.length, 5);
44
+ assert.strictEqual(cat.parseCatalog(undefined).catalog, null);
45
+ });
46
+
47
+ test('cache de 6 h, permalink lu au besoin, repli sur le cache hors ligne, rien sans cache', async (t) => {
48
+ const dir = tmpdir(t);
49
+ process.env.POAD_AI_CATALOG_CACHE = path.join(dir, 'ai-catalog.json');
50
+ t.after(() => delete process.env.POAD_AI_CATALOG_CACHE);
51
+ let calls = 0;
52
+ const online = async () => (calls++, FIXTURE);
53
+ const offline = async () => null;
54
+ assert.deepStrictEqual((await cat.loadCatalog({ fetcher: offline })).source, 'none');
55
+ const first = await cat.loadCatalog({ fetcher: online });
56
+ assert.strictEqual(first.source, 'permalink');
57
+ assert.strictEqual((await cat.loadCatalog({ fetcher: online })).source, 'cache');
58
+ assert.strictEqual(calls, 1);
59
+ const off = await cat.loadCatalog({ fresh: true, fetcher: offline });
60
+ assert.strictEqual(off.source, 'cache');
61
+ assert.ok(off.catalog.providers.anthropic);
62
+ // permalink sans clé ai (ou d'un schéma inconnu) : le dernier catalogue connu reste
63
+ assert.strictEqual((await cat.loadCatalog({ fresh: true, fetcher: async () => ({ engine: { stable: '0.29.1' } }) })).source, 'cache');
64
+ });
65
+
66
+ test('fichier pour l’engine : poad/data/ai/catalog.json, retiré sans catalogue', (t) => {
67
+ const dir = tmpdir(t);
68
+ fs.mkdirSync(path.join(dir, 'poad'));
69
+ const root = path.join(dir, 'poad', 'config.toml');
70
+ const file = cat.writeForEngine(root, { catalog: cat.parseCatalog(FIXTURE.ai).catalog, fetched_at: '2026-11-25T09:00:00.000Z' });
71
+ assert.strictEqual(file, path.join(dir, 'poad', 'data', 'ai', 'catalog.json'));
72
+ const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
73
+ assert.strictEqual(doc.schema, 1);
74
+ assert.strictEqual(doc.fetched_at, '2026-11-25T09:00:00.000Z');
75
+ assert.strictEqual(cat.writeForEngine(root, { catalog: null }), null);
76
+ assert.ok(!fs.existsSync(file));
77
+ });
78
+
79
+ test('[ai.models] → POAD_AI_MODELS ; entrées fausses signalées', () => {
80
+ const { env, warnings } = ai.engineEnv({ ai: { models: { anthropic: 'claude-sonnet-5-5', llama: 'x', openai: 'a b' } } });
81
+ assert.deepStrictEqual(env, ['POAD_AI_MODELS={"anthropic":"claude-sonnet-5-5"}']);
82
+ assert.strictEqual(warnings.length, 2);
83
+ assert.match(ai.engineEnv({ ai: { models: 'x' } }).warnings[0], /must be a table/);
84
+ });
85
+
86
+ test('poad ai models : le catalogue en cache, hors ligne, sans réseau ni Docker', (t) => {
87
+ const dir = tmpdir(t);
88
+ const home = path.join(dir, 'home');
89
+ fs.mkdirSync(path.join(home, '.poad'), { recursive: true });
90
+ fs.writeFileSync(path.join(home, '.poad_last_check.json'), JSON.stringify({ date: new Date(), version: require('../package.json').version }));
91
+ fs.writeFileSync(path.join(home, '.poad', 'ai-catalog.json'), JSON.stringify({ at: Date.now(), catalog: cat.parseCatalog(FIXTURE.ai).catalog }));
92
+ const r = spawnSync(process.execPath, ['--require', STUB, POAD, 'ai', 'models', 'mistral'], {
93
+ cwd: dir,
94
+ encoding: 'utf8',
95
+ input: '',
96
+ timeout: 15000,
97
+ env: { ...process.env, HOME: home, POAD_TEST_CALLS: path.join(dir, 'calls.log'), NODE_OPTIONS: '', POAD_AI_CATALOG_CACHE: '' },
98
+ });
99
+ assert.strictEqual(r.status, 0, r.stderr);
100
+ assert.match(r.stdout, /Model catalog of 2026-11-25, from cache/);
101
+ assert.match(r.stdout, /mistral-large-4\s+0\.7 \/ 2\.1\s+Mistral Large 4 default preview/);
102
+ assert.ok(!/gpt-6/.test(r.stdout), 'seulement le fournisseur demandé');
103
+ assert.ok(!fs.existsSync(path.join(dir, 'calls.log')), 'le cache suffit : aucun appel');
104
+ });
105
+
106
+ test('logs : changement du modèle par défaut (qui, avant, après)', () => {
107
+ const { formatLine } = require('../utils/logline');
108
+ const plain = new Proxy(function () {}, { get: () => plain, apply: (t, self, [s]) => String(s) });
109
+ const line = formatLine({ ts: '2026-11-25T10:00:00.000Z', level: 'info', service: 'ai', msg: 'default model of anthropic: (project setting) → claude-sonnet-5-5', attrs: { event: 'ai_default_model_changed', provider: 'anthropic', actor: 'console' } }, plain);
110
+ assert.match(line, /default model of anthropic: \(project setting\) → claude-sonnet-5-5 by console$/);
111
+ });
112
+
113
+ test('catalogue et [ai.models] : seulement pour l’engine 0.31.0 et plus', () => {
114
+ assert.strictEqual(ai.supportsAiModels({ engine: '0.31.0' }), true);
115
+ assert.strictEqual(ai.supportsAiModels({ engine: '0.30.0' }), false);
116
+ assert.strictEqual(ai.supportsAiModels({ engine: '1.0.0' }), true);
117
+ });
@@ -0,0 +1,187 @@
1
+ // poad ai : clés de la machine (~/.poad/ai.json, 0600), réglages [ai], filtres et rendu de poad logs ai.
2
+ // Sans réseau ni Docker : la commande tourne avec test/help-stub.js (tout appel à Docker, au réseau ou à un
3
+ // processus est refusé et noté) et un HOME à part. Fausses clés seulement.
4
+ const test = require('node:test');
5
+ const assert = require('node:assert');
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const { spawnSync } = require('child_process');
9
+ const { tmpdir } = require('./helpers');
10
+ const ai = require('../utils/ai');
11
+ const { attrConditions, formatLine } = require('../utils/logline');
12
+
13
+ const POAD = path.join(__dirname, '..', 'poad.js');
14
+ const STUB = path.join(__dirname, 'help-stub.js');
15
+ const FAKE = 'sk-ant-FAKE-test-key-0000000000wxyz';
16
+ const plain = new Proxy(function () {}, { get: () => plain, apply: (t, self, [s]) => String(s) });
17
+
18
+ function sandbox(t) {
19
+ const dir = tmpdir(t);
20
+ const home = path.join(dir, 'home');
21
+ fs.mkdirSync(home);
22
+ // Pas de vérification de version (npm view) pendant l'essai
23
+ fs.writeFileSync(path.join(home, '.poad_last_check.json'), JSON.stringify({ date: new Date(), version: require('../package.json').version }));
24
+ return { dir, home, calls: path.join(dir, 'calls.log'), file: path.join(home, '.poad', 'ai.json') };
25
+ }
26
+
27
+ const poad = (box, args, input = '') =>
28
+ spawnSync(process.execPath, ['--require', STUB, POAD, ...args], {
29
+ cwd: box.dir,
30
+ encoding: 'utf8',
31
+ input,
32
+ timeout: 15000,
33
+ env: { ...process.env, HOME: box.home, POAD_TEST_CALLS: box.calls, NODE_OPTIONS: '', POAD_AI_KEYS_FILE: '' },
34
+ });
35
+
36
+ test('ai login : clé lue sur l’entrée standard, fichier 0600 dans un dossier 0700, jamais affichée', (t) => {
37
+ const box = sandbox(t);
38
+ const r = poad(box, ['ai', 'login', 'anthropic'], `${FAKE}\n`);
39
+ assert.strictEqual(r.status, 0, r.stderr);
40
+ assert.match(r.stdout, /key saved for this machine \(…wxyz\)/);
41
+ assert.ok(!r.stdout.includes(FAKE) && !r.stderr.includes(FAKE), 'la clé ne s’affiche jamais');
42
+ assert.strictEqual(fs.statSync(box.file).mode & 0o777, 0o600);
43
+ assert.strictEqual(fs.statSync(path.dirname(box.file)).mode & 0o777, 0o700);
44
+ assert.strictEqual(JSON.parse(fs.readFileSync(box.file, 'utf8')).providers.anthropic.key, FAKE);
45
+ assert.ok(!fs.existsSync(box.calls), 'ni Docker, ni réseau, ni processus');
46
+
47
+ const list = poad(box, ['ai', 'list']);
48
+ assert.match(list.stdout, /anthropic\s+…wxyz/);
49
+ assert.match(list.stdout, /openai\s+no key/);
50
+ assert.ok(!list.stdout.includes(FAKE));
51
+
52
+ const out = poad(box, ['ai', 'logout', 'anthropic']);
53
+ assert.match(out.stdout, /removed/);
54
+ assert.deepStrictEqual(JSON.parse(fs.readFileSync(box.file, 'utf8')).providers, {});
55
+ });
56
+
57
+ test('ai login : refus d’une clé vide ou mal formée, d’un fournisseur inconnu ; une clé en argument est signalée', (t) => {
58
+ const box = sandbox(t);
59
+ assert.match(poad(box, ['ai', 'login', 'openai'], 'a b c d e f g h\n').stdout, /Key refused \(a key has no spaces\)/);
60
+ assert.match(poad(box, ['ai', 'login', 'openai'], '').stdout, /Key refused \(empty key\)/);
61
+ assert.ok(!fs.existsSync(box.file));
62
+ assert.match(poad(box, ['ai', 'login', 'llama']).stdout, /Usage: poad ai login/);
63
+ const arg = poad(box, ['ai', 'login', FAKE]);
64
+ assert.match(arg.stdout, /Never pass a key as an argument/);
65
+ assert.ok(!arg.stdout.includes(FAKE));
66
+ });
67
+
68
+ test('ai use : hors d’un projet, le dit sans rien appeler', (t) => {
69
+ const box = sandbox(t);
70
+ poad(box, ['ai', 'login', 'mistral'], 'mistral-fake-key-123456\n');
71
+ const r = poad(box, ['ai', 'use', 'mistral']);
72
+ assert.match(r.stdout, /not in a poad project/);
73
+ assert.ok(!fs.existsSync(box.calls));
74
+ });
75
+
76
+ test('readKeys : un fichier lisible par d’autres est ramené à 0600 ; un fichier abîmé est signalé sans contenu', (t) => {
77
+ const box = sandbox(t);
78
+ fs.mkdirSync(path.dirname(box.file), { recursive: true });
79
+ fs.writeFileSync(box.file, JSON.stringify({ providers: { gemini: { key: 'AIzaFAKEFAKEFAKE1234' } } }), { mode: 0o644 });
80
+ fs.chmodSync(box.file, 0o644);
81
+ const k = ai.readKeys(box.file);
82
+ assert.strictEqual(k.fixed, true);
83
+ assert.strictEqual(fs.statSync(box.file).mode & 0o777, 0o600);
84
+ assert.strictEqual(k.providers.gemini.key, 'AIzaFAKEFAKEFAKE1234');
85
+ fs.writeFileSync(box.file, `{ "providers": ${FAKE}`);
86
+ const broken = ai.readKeys(box.file);
87
+ assert.match(broken.broken, /not valid JSON/);
88
+ assert.ok(!broken.broken.includes(FAKE));
89
+ });
90
+
91
+ test('masque et forme des clés', () => {
92
+ assert.strictEqual(ai.mask(FAKE), '…wxyz');
93
+ assert.strictEqual(ai.mask('court'), '…');
94
+ assert.strictEqual(ai.mask(''), '');
95
+ assert.strictEqual(ai.keyProblem(FAKE), null);
96
+ assert.match(ai.keyProblem('abc'), /8 to 512/);
97
+ assert.match(ai.keyProblem('clé-é-é-é-é'), /ASCII/);
98
+ });
99
+
100
+ test('[ai] de config.toml → variables de l’engine ; une valeur fausse est dite et pas transmise', () => {
101
+ const { env, warnings } = ai.engineEnv({
102
+ ai: { default_provider: 'mistral', default_model: 'mistral-small-latest', max_tokens: 2048, monthly_budget_usd: 12.5, log_content: true, prices: { 'openai/gpt-x': { input: 1, output: 2 } } },
103
+ });
104
+ assert.deepStrictEqual(env, [
105
+ 'POAD_AI_DEFAULT_PROVIDER=mistral',
106
+ 'POAD_AI_DEFAULT_MODEL=mistral-small-latest',
107
+ 'POAD_AI_MAX_TOKENS=2048',
108
+ 'POAD_AI_MONTHLY_BUDGET_USD=12.5',
109
+ 'POAD_AI_LOG_CONTENT=true',
110
+ 'POAD_AI_PRICES={"openai/gpt-x":{"input":1,"output":2}}',
111
+ ]);
112
+ assert.deepStrictEqual(warnings, []);
113
+ const bad = ai.engineEnv({ ai: { default_provider: 'llama', max_tokens: -1, monthly_budget_usd: 'beaucoup', default_model: 'a b' } });
114
+ assert.deepStrictEqual(bad.env, []);
115
+ assert.strictEqual(bad.warnings.length, 4);
116
+ assert.deepStrictEqual(ai.engineEnv({}), { env: [], warnings: [] });
117
+ assert.strictEqual(ai.supportsAi({ engine: '0.30.0' }), true);
118
+ assert.strictEqual(ai.supportsAi({ engine: '0.30.0-ai.1' }), true);
119
+ assert.strictEqual(ai.supportsAi({ engine: '0.29.2' }), false);
120
+ });
121
+
122
+ test('logs : provider= et model= portent sur les attributs du même nom', () => {
123
+ const r = attrConditions({ provider: 'openai', model: 'gpt-5', outcome: 'budget_exceeded' });
124
+ assert.deepStrictEqual(r.conditions, [
125
+ ["attrs->>'outcome' = ?", 'budget_exceeded'],
126
+ ["attrs->>'provider' = ?", 'openai'],
127
+ ["attrs->>'model' = ?", 'gpt-5'],
128
+ ]);
129
+ assert.match(attrConditions({ provider: true }).error, /provider=<name>: a value is expected, such as provider=anthropic/);
130
+ });
131
+
132
+ test('logs : rendu d’une ligne ai (résultat, jetons, coût estimé ; une seule durée)', () => {
133
+ const line = formatLine(
134
+ {
135
+ ts: '2026-11-25T10:00:00.000Z',
136
+ level: 'info',
137
+ service: 'ai',
138
+ request_id: 'abcdef1234567890',
139
+ msg: 'chat anthropic/claude-opus-5-5 ok (812 ms)',
140
+ attrs: { provider: 'anthropic', model: 'claude-opus-5-5', outcome: 'ok', input_tokens: 1000, output_tokens: 500, cost_usd: 0.014, duration_ms: 812, function: 'resume' },
141
+ },
142
+ plain,
143
+ );
144
+ assert.match(line, /ai\s+info\s+\[resume\] chat anthropic\/claude-opus-5-5 ok \(812 ms\) 1000→500 tok ~\$0\.0140 ·abcdef12$/);
145
+ const refused = formatLine(
146
+ { ts: '2026-11-25T10:00:00.000Z', level: 'warn', service: 'ai', msg: 'chat openai/gpt-5 provider_error (40 ms)', attrs: { outcome: 'provider_error', provider_status: 401, error_code: 'provider_error', error: 'openai refused the call (HTTP 401)', duration_ms: 40 } },
147
+ plain,
148
+ );
149
+ assert.match(refused, /provider_error \(40 ms\) HTTP 401 provider_error: openai refused the call \(HTTP 401\)$/);
150
+ });
151
+
152
+ test('logs : un appel ai sans prix connu dit « cost unknown », jamais $0', () => {
153
+ const line = formatLine(
154
+ { ts: '2026-11-25T10:00:00.000Z', level: 'info', service: 'ai', msg: 'chat mistral/mistral-large-latest ok (9 ms)', attrs: { outcome: 'ok', input_tokens: 10, output_tokens: 5, cost_usd: null, price: 'unknown' } },
155
+ plain,
156
+ );
157
+ assert.match(line, /10→5 tok cost unknown \(no price: \[ai\.prices\]\)$/);
158
+ assert.ok(!line.includes('$0'));
159
+ });
160
+
161
+ test('ai login : un ~/.poad déjà là en 0755 est ramené à 0700, ses autres fichiers gardent leurs droits', (t) => {
162
+ const box = sandbox(t);
163
+ const dir = path.dirname(box.file);
164
+ fs.mkdirSync(dir, { mode: 0o755 });
165
+ fs.chmodSync(dir, 0o755);
166
+ const other = path.join(dir, 'engine-latest.json');
167
+ fs.writeFileSync(other, '{}', { mode: 0o644 });
168
+ fs.chmodSync(other, 0o644);
169
+ const r = poad(box, ['ai', 'login', 'openai'], 'sk-proj-abcdefghijklmnopqrstuvwxyz\n');
170
+ assert.strictEqual(r.status, 0, r.stderr);
171
+ assert.strictEqual(fs.statSync(dir).mode & 0o777, 0o700);
172
+ assert.strictEqual(fs.statSync(box.file).mode & 0o777, 0o600);
173
+ assert.strictEqual(fs.statSync(other).mode & 0o777, 0o644);
174
+ });
175
+
176
+ test('coût : un montant positif sous 0,0001 $ s’écrit « < $0.0001 », jamais $0.0000', () => {
177
+ assert.strictEqual(ai.usdText(0.000018), '< $0.0001');
178
+ assert.strictEqual(ai.usdText(0.0002), '~$0.0002');
179
+ assert.strictEqual(ai.usdText(0), '~$0.0000');
180
+ assert.strictEqual(ai.usdText(null), null);
181
+ const line = formatLine(
182
+ { ts: '2026-11-25T10:00:00.000Z', level: 'info', service: 'ai', msg: 'chat mistral/mistral-large-4 ok (1 ms)', attrs: { outcome: 'ok', input_tokens: 11, output_tokens: 5, cost_usd: 0.000018 } },
183
+ plain,
184
+ );
185
+ assert.match(line, /11→5 tok < \$0\.0001$/);
186
+ assert.ok(!line.includes('0.0000'));
187
+ });