poad 2.42.0 → 2.45.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,279 @@
1
+ // poad ai : les clés des fournisseurs d'IA (Claude, GPT, Mistral, Gemini) et leur copie dans un projet.
2
+ // poad ai login <fournisseur> enregistre la clé de cette machine (invite masquée, ou entrée standard)
3
+ // poad ai logout <fournisseur> l'oublie
4
+ // poad ai list fournisseurs et clés masquées (4 derniers caractères) ; dans un projet
5
+ // démarré, ce que l'engine a (GET /ai/v1/status)
6
+ // poad ai use <fournisseur> copie la clé de la machine dans les Credentials du projet (coffre), et la
7
+ // branche sur l'usage ai.<fournisseur> ; confirmation, ou --yes
8
+ // La clé ne passe jamais sur la ligne de commande ni dans une ligne de journal ; l'engine ne lit jamais
9
+ // ~/.poad. Voir utils/ai.js.
10
+ const ai = require('../../utils/ai');
11
+
12
+ const USAGE = {
13
+ login: 'poad ai login <anthropic|openai|mistral|gemini> (the key is asked hidden, or read from stdin: never as an argument)',
14
+ logout: 'poad ai logout <anthropic|openai|mistral|gemini>',
15
+ list: 'poad ai list',
16
+ use: 'poad ai use <anthropic|openai|mistral|gemini> [--yes] (copies this machine key into the running project credentials)',
17
+ models: 'poad ai models [anthropic|openai|mistral|gemini] [--refresh] (model catalog: default model, prices, status)',
18
+ };
19
+
20
+ const help = (sub) => {
21
+ const chalk = require('chalk-v2');
22
+ const lines = sub ? [USAGE[sub]] : Object.values(USAGE);
23
+ console.log(`${chalk.bold(' Usage :')}`);
24
+ for (const l of lines) console.log(` ${chalk.cyanBright(l)}`);
25
+ console.log(' ');
26
+ console.log(' AI providers of poad (engine 0.30.0+): Claude (anthropic), GPT (openai), Mistral (mistral), Gemini (gemini).');
27
+ console.log(` Keys of this machine: ${ai.keysFile()} (mode 0600), written only by "poad ai login". The engine never reads it:`);
28
+ console.log(' "poad ai use <provider>" copies the key into the project Credentials (vault of its database).');
29
+ console.log(' Then call POST /ai/v1/chat with the service_role key (functions, flows through a function, scripts):');
30
+ console.log(chalk.grey(' { "provider": "anthropic", "messages": [{ "role": "user", "content": "Hello" }] }'));
31
+ console.log(' Project settings, poad/config.toml: [ai] default_provider, default_model, max_tokens, monthly_budget_usd, log_content, [ai.models], [ai.prices].');
32
+ console.log(' Models: "poad ai models" lists the catalog (poadio/permalink): default model, prices, status.');
33
+ console.log(' Usage: "poad logs ai provider=openai outcome=provider_error", console > IA.');
34
+ console.log(' ');
35
+ };
36
+
37
+ const providerOf = (args, raw) => {
38
+ const words = (raw || []).filter((w) => !String(w).startsWith('-') && !String(w).includes('='));
39
+ return words.find((w) => ai.isProvider(w)) || words[0] || null;
40
+ };
41
+
42
+ const login = async (provider) => {
43
+ const chalk = require('chalk-v2');
44
+ const keys = ai.readKeys();
45
+ if (keys.broken) {
46
+ process.exitCode = 1;
47
+ return console.log(chalk.redBright(`${keys.broken}: fix or remove it, then retry.`));
48
+ }
49
+ if (process.stdin.isTTY && keys.providers[provider]) console.log(chalk.grey(` A ${provider} key is already saved (${ai.mask(keys.providers[provider].key)}): it will be replaced.`));
50
+ let key;
51
+ try {
52
+ key = await ai.readSecret(`${ai.LABELS[provider]} API key (hidden):`);
53
+ } catch (err) {
54
+ process.exitCode = 1;
55
+ return console.log(chalk.redBright(`No key read: ${err.message}`));
56
+ }
57
+ const problem = ai.keyProblem(key);
58
+ if (problem) {
59
+ process.exitCode = 1;
60
+ return console.log(chalk.redBright(`Key refused (${problem}). Nothing saved.`));
61
+ }
62
+ ai.writeKeys({ ...keys.providers, [provider]: { key, added_at: new Date().toISOString() } });
63
+ console.log(chalk.green(` ${ai.LABELS[provider]} key saved for this machine (${ai.mask(key)}) in ${ai.keysFile()}.`));
64
+ console.log(chalk.grey(` In a project: "poad ai use ${provider}" copies it into its Credentials.`));
65
+ };
66
+
67
+ const logout = (provider) => {
68
+ const chalk = require('chalk-v2');
69
+ const keys = ai.readKeys();
70
+ if (!keys.providers[provider]) return console.log(chalk.grey(` No ${provider} key on this machine.`));
71
+ const rest = { ...keys.providers };
72
+ delete rest[provider];
73
+ ai.writeKeys(rest);
74
+ console.log(chalk.green(` ${ai.LABELS[provider]} key removed from this machine.`));
75
+ console.log(chalk.grey(' Projects keep the copy made by "poad ai use": remove it in the console (Credentials).'));
76
+ };
77
+
78
+ /** Appel de l'engine du projet avec la clé service_role (jamais affichée) */
79
+ const engineCall = async (config, method, path, body) => {
80
+ const res = await fetch(`http://localhost:${config.web.port}/${path}`, {
81
+ method,
82
+ headers: { apikey: config.auth.service, authorization: `Bearer ${config.auth.service}`, ...(body ? { 'content-type': 'application/json' } : {}) },
83
+ body: body ? JSON.stringify(body) : undefined,
84
+ signal: AbortSignal.timeout(10000),
85
+ });
86
+ const text = await res.text();
87
+ let data = null;
88
+ try {
89
+ data = text ? JSON.parse(text) : null;
90
+ } catch {
91
+ data = { error: { message: text.slice(0, 200) } };
92
+ }
93
+ return { status: res.status, ok: res.ok, data };
94
+ };
95
+
96
+ const errorText = (r) => (r.data && r.data.error && (r.data.error.message || r.data.error.code)) || (r.data && r.data.message) || `HTTP ${r.status}`;
97
+
98
+ /** Le projet du dossier courant, s'il est démarré sur un engine 0.30+ ; sinon { reason } */
99
+ const runningProject = async () => {
100
+ const { findPoadDir } = require('../../utils/findpoad');
101
+ const root = findPoadDir(process.cwd());
102
+ if (!root) return { reason: 'You are not in a poad project directory.' };
103
+ const config = require('../../utils/config').readConfig(root);
104
+ if (!ai.supportsAi(config)) return { reason: `Engine ${config.engine} has no AI endpoint: "poad upgrade" to 0.30.0 or later.`, config };
105
+ const { isDockerExist } = require('../../utils/docker');
106
+ if (!(await isDockerExist(config.project_uuid))) return { reason: 'The project is not started: run "poad start".', config };
107
+ return { config, root };
108
+ };
109
+
110
+ const list = async () => {
111
+ const chalk = require('chalk-v2');
112
+ const keys = ai.readKeys();
113
+ if (keys.fixed) console.log(chalk.yellowBright(` ${ai.keysFile()} was readable by other users: set back to 0600.`));
114
+ if (keys.broken) console.log(chalk.redBright(` ${keys.broken}.`));
115
+ console.log(chalk.bold(' This machine') + chalk.grey(` (${ai.keysFile()})`));
116
+ for (const p of ai.PROVIDERS) {
117
+ const k = keys.providers[p];
118
+ console.log(` ${p.padEnd(10)} ${k ? chalk.green(ai.mask(k.key)) + chalk.grey(k.added_at ? ` saved ${k.added_at.slice(0, 10)}` : '') : chalk.grey('no key (poad ai login ' + p + ')')}`);
119
+ }
120
+ const { findPoadDir } = require('../../utils/findpoad');
121
+ if (!findPoadDir(process.cwd())) return;
122
+ const project = await runningProject();
123
+ console.log(' ');
124
+ if (!project.root) return console.log(chalk.grey(` This project: ${project.reason}`));
125
+ let r;
126
+ try {
127
+ r = await engineCall(project.config, 'GET', 'ai/v1/status');
128
+ } catch (err) {
129
+ return console.log(chalk.grey(` This project: the engine does not answer (${err.message}).`));
130
+ }
131
+ if (!r.ok) return console.log(chalk.yellowBright(` This project: ${errorText(r)}`));
132
+ const s = r.data;
133
+ console.log(chalk.bold(' This project') + chalk.grey(' (Credentials of the engine)'));
134
+ for (const p of s.providers || []) {
135
+ console.log(` ${String(p.id).padEnd(10)} ${p.configured ? chalk.green(p.key_hint || '…') + chalk.grey(` credential ${p.credential}${p.base_url ? `, ${p.base_url} address` : ''}`) : chalk.grey(`no key (poad ai use ${p.id})`)}`);
136
+ }
137
+ const d = s.defaults || {};
138
+ const m = s.month || {};
139
+ console.log(chalk.grey(` default: ${d.provider || '-'}${d.model ? ` / ${d.model}` : ''} · max_tokens ${d.max_tokens} · budget ${d.monthly_budget_usd === null || d.monthly_budget_usd === undefined ? 'none' : `${d.monthly_budget_usd} USD/month`}`));
140
+ console.log(chalk.grey(` this month: ${m.calls || 0} calls, ${m.input_tokens || 0} → ${m.output_tokens || 0} tokens, ${ai.usdText(m.cost_usd || 0)} (estimated)${m.unpriced_calls ? `, of which ${m.unpriced_calls} call${m.unpriced_calls > 1 ? 's' : ''} at unknown cost (no price: [ai.prices])` : ''}`));
141
+ };
142
+
143
+ const use = async (provider, args) => {
144
+ const chalk = require('chalk-v2');
145
+ const keys = ai.readKeys();
146
+ const k = keys.providers[provider];
147
+ if (!k) {
148
+ process.exitCode = 1;
149
+ return console.log(chalk.redBright(`No ${provider} key on this machine: "poad ai login ${provider}" first.`));
150
+ }
151
+ const project = await runningProject();
152
+ if (!project.root) {
153
+ process.exitCode = 1;
154
+ return console.log(chalk.redBright(project.reason));
155
+ }
156
+ const { config } = project;
157
+ const listing = await engineCall(config, 'GET', 'meta/v1/credentials');
158
+ if (!listing.ok) {
159
+ process.exitCode = 1;
160
+ return console.log(chalk.redBright(`Credentials not readable: ${errorText(listing)}`));
161
+ }
162
+ const slot = `ai.${provider}`;
163
+ const bound = ((listing.data.slots || []).find((s) => s.slot === slot) || {}).credential || null;
164
+ const creds = listing.data.credentials || [];
165
+ // Le credential déjà branché sur l'usage reçoit la clé ; sinon ai-<fournisseur>
166
+ const name = bound && (creds.find((c) => c.name === bound) || {}).type === provider ? bound : `ai-${provider}`;
167
+ const existing = creds.find((c) => c.name === name);
168
+ if (existing && existing.type !== provider) {
169
+ process.exitCode = 1;
170
+ return console.log(chalk.redBright(`A credential named ${name} already exists with type ${existing.type}: rename it in the console, then retry.`));
171
+ }
172
+ const yes = Boolean(args.yes || args['--yes'] || args['-y']);
173
+ const what = `${ai.LABELS[provider]} key ${ai.mask(k.key)} of this machine → credential ${name} of project ${config.project_id || config.project_uuid}${existing ? ' (its key is replaced)' : ''}, used by ${slot}`;
174
+ if (!yes) {
175
+ if (!process.stdin.isTTY) {
176
+ process.exitCode = 1;
177
+ return console.log(chalk.redBright(`Not a terminal: confirm with "poad ai use ${provider} --yes".`));
178
+ }
179
+ const { confirm } = require('@inquirer/prompts');
180
+ console.log(` ${what}.`);
181
+ console.log(chalk.grey(' The key is stored in the vault of the project database; every call to /ai/v1/chat with this provider is billed to it.'));
182
+ if (!(await confirm({ message: 'Copy the key into the project?', default: true }))) return console.log(chalk.grey(' Nothing changed.'));
183
+ }
184
+ const write = existing
185
+ ? await engineCall(config, 'PATCH', `meta/v1/credentials/${name}`, { values: { api_key: k.key } })
186
+ : await engineCall(config, 'POST', 'meta/v1/credentials', { name, type: provider, label: 'poad ai use', values: { api_key: k.key } });
187
+ if (!write.ok) {
188
+ process.exitCode = 1;
189
+ return console.log(chalk.redBright(`Key not copied: ${errorText(write)}`));
190
+ }
191
+ if (bound !== name) {
192
+ const bind = await engineCall(config, 'PUT', `meta/v1/credential-uses/${slot}`, { credential: name });
193
+ if (!bind.ok) {
194
+ process.exitCode = 1;
195
+ return console.log(chalk.redBright(`Key copied into ${name}, but not used by ${slot}: ${errorText(bind)} (console, Credentials).`));
196
+ }
197
+ }
198
+ console.log(chalk.green(` ${what}.`));
199
+ console.log(chalk.grey(` Try it: POST /ai/v1/chat { "provider": "${provider}", "messages": [{ "role": "user", "content": "Hello" }] } with the service_role key; then "poad logs ai".`));
200
+ };
201
+
202
+ /**
203
+ * poad ai models [fournisseur] : le catalogue des modèles (permalink, cache, sinon rien : la table de l'engine),
204
+ * avec le modèle par défaut du catalogue et, dans un projet, celui de [ai.models] de poad/config.toml.
205
+ */
206
+ const models = async (args, raw) => {
207
+ const chalk = require('chalk-v2');
208
+ const aiCatalog = require('../../utils/ai-catalog');
209
+ const only = (raw || []).find((w) => ai.isProvider(w));
210
+ const bad = (raw || []).find((w) => !String(w).startsWith('-') && !ai.isProvider(w) && w !== 'refresh');
211
+ if (bad) {
212
+ process.exitCode = 1;
213
+ return console.log(chalk.redBright(`Usage: ${USAGE.models}`));
214
+ }
215
+ const loaded = await aiCatalog.loadCatalog({ fresh: Boolean(args['--refresh'] || args.refresh) });
216
+ for (const w of loaded.warnings) console.log(chalk.yellowBright(` ${w}`));
217
+ if (!loaded.catalog) {
218
+ process.exitCode = 1;
219
+ return console.log(chalk.yellowBright(' No model catalog (offline, or none published yet): engines use their own model table.'));
220
+ }
221
+ // [ai.models] et [ai] default_model du projet du dossier courant, s'il y en a un
222
+ let project = {};
223
+ const { findPoadDir } = require('../../utils/findpoad');
224
+ const root = findPoadDir(process.cwd());
225
+ if (root) {
226
+ try {
227
+ const ai_ = (require('toml').parse(require('fs').readFileSync(root, 'utf8')).ai) || {};
228
+ project = { ...(ai_.default_provider && ai_.default_model ? { [ai_.default_provider]: ai_.default_model } : {}), ...(ai_.models || {}) };
229
+ } catch {
230
+ project = {};
231
+ }
232
+ }
233
+ const c = loaded.catalog;
234
+ const from = loaded.source === 'permalink' ? 'poadio/permalink' : `cache (${String(loaded.fetched_at).slice(0, 16).replace('T', ' ')})`;
235
+ console.log(chalk.grey(` Model catalog${c.checked_on ? ` of ${c.checked_on}` : ''}, from ${from}. Prices: USD per million tokens (input / output), estimated.`));
236
+ for (const p of ai.PROVIDERS) {
237
+ if (only && p !== only) continue;
238
+ const entry = c.providers[p];
239
+ console.log(' ');
240
+ console.log(` ${chalk.bold(ai.LABELS[p])} ${chalk.grey(p)}`);
241
+ if (!entry) {
242
+ console.log(chalk.grey(' not in the catalog: the engine table is used'));
243
+ continue;
244
+ }
245
+ const width = Math.max(...entry.models.map((m) => m.id.length));
246
+ for (const m of entry.models) {
247
+ const marks = [];
248
+ if (m.id === entry.default) marks.push(chalk.green('default'));
249
+ if (project[p] === m.id) marks.push(chalk.cyan('this project'));
250
+ if (m.status) marks.push(chalk.yellow(m.status));
251
+ const price = `${m.input} / ${m.output}`;
252
+ console.log(` ${m.id.padEnd(width)} ${price.padEnd(12)} ${chalk.grey(m.label !== m.id ? m.label : '')}${marks.length ? ' ' + marks.join(' ') : ''}`);
253
+ }
254
+ if (project[p] && !entry.models.some((m) => m.id === project[p])) console.log(chalk.yellowBright(` this project asks ${project[p]}, not in the catalog: give it a price in [ai.prices]`));
255
+ }
256
+ console.log(' ');
257
+ console.log(chalk.grey(' Choose per project: [ai.models] in poad/config.toml (anthropic = "…"), or in the console (AI screen, this engine only).'));
258
+ };
259
+
260
+ const run = async (sub, args = {}, raw = []) => {
261
+ const chalk = require('chalk-v2');
262
+ if (!sub || !USAGE[sub]) return help();
263
+ if (sub === 'list') return list();
264
+ if (sub === 'models') return models(args, raw);
265
+ const provider = providerOf(args, raw);
266
+ if (!provider || !ai.isProvider(provider)) {
267
+ process.exitCode = 1;
268
+ if (provider && String(provider).length > 20) return console.log(chalk.redBright(`Usage: ${USAGE[sub]}. Never pass a key as an argument: it stays in your shell history (clear it, and rotate the key).`));
269
+ return console.log(chalk.redBright(`Usage: ${USAGE[sub]}`));
270
+ }
271
+ if (sub === 'login') return login(provider);
272
+ if (sub === 'logout') return logout(provider);
273
+ return use(provider, args);
274
+ };
275
+
276
+ module.exports = (args, raw) => run(null, args, raw);
277
+ module.exports.help = () => help();
278
+ module.exports.run = run;
279
+ module.exports.subHelp = help;
@@ -0,0 +1,5 @@
1
+ // poad ai list : voir index.js
2
+ const ai = require('./index');
3
+
4
+ module.exports = (args, raw) => ai.run('list', args, raw);
5
+ module.exports.help = () => ai.subHelp('list');
@@ -0,0 +1,5 @@
1
+ // poad ai login : voir index.js
2
+ const ai = require('./index');
3
+
4
+ module.exports = (args, raw) => ai.run('login', args, raw);
5
+ module.exports.help = () => ai.subHelp('login');
@@ -0,0 +1,5 @@
1
+ // poad ai logout : voir index.js
2
+ const ai = require('./index');
3
+
4
+ module.exports = (args, raw) => ai.run('logout', args, raw);
5
+ module.exports.help = () => ai.subHelp('logout');
@@ -0,0 +1,5 @@
1
+ // poad ai models : voir index.js
2
+ const ai = require('./index');
3
+
4
+ module.exports = (args, raw) => ai.run('models', args, raw);
5
+ module.exports.help = () => ai.subHelp('models');
@@ -0,0 +1,5 @@
1
+ // poad ai use : voir index.js
2
+ const ai = require('./index');
3
+
4
+ module.exports = (args, raw) => ai.run('use', args, raw);
5
+ module.exports.help = () => ai.subHelp('use');
package/global/cli.js CHANGED
@@ -13,5 +13,13 @@ module.exports = {
13
13
  start: 'Start the project, apply migrations, start the services chosen with poad setup, then show its state, secrets hidden: poad info --secrets (--all: every configured service, --bare: engine and mail only, --quiet: nothing if it already runs). A port of poad/config.toml already used on this machine is replaced by a free one. Request bodies are limited by the gateway to [gateway] max_body of poad/config.toml (default "10m", storage uploads excepted)',
14
14
  stop: 'Stop container for poad local development (stop kc|valkey|runner: that service only)',
15
15
  run: 'Run an optional service next to the project (keycloak|kc, valkey|redis, runner, --all)',
16
+ ai: {
17
+ description: 'AI providers (engine 0.30.0+, /ai/v1): keys of this machine (~/.poad/ai.json, 0600) and their copy into a project. Then POST /ai/v1/chat with the service_role key',
18
+ login: 'Save the key of a provider for this machine: ai login anthropic|openai|mistral|gemini (hidden prompt, or stdin; never as an argument)',
19
+ logout: 'Forget the key of a provider on this machine: ai logout <provider>',
20
+ list: 'Providers and masked keys (last 4 characters); in a started project, what its engine has and the usage of the month',
21
+ use: 'Copy the machine key of a provider into the Credentials of the started project (vault) and use it for ai.<provider>: ai use <provider> [--yes]',
22
+ models: 'Model catalog (poadio/permalink, cached): default model, prices and status per provider: ai models [provider] [--refresh]',
23
+ },
16
24
  clean: 'Remove what stopped poad projects left on this machine: orphan Mailpit/Keycloak/Valkey/flows runner, networks, unused engine images (--dry-run to list, --yes without question)',
17
25
  };
package/global/run.js CHANGED
@@ -86,6 +86,8 @@ module.exports = async (args = {}) => {
86
86
  await runners[service.id]();
87
87
  config = readConfig();
88
88
  }
89
+ // Groupe « Services » de la console : un premier poad run kc y ajoute Keycloak (port choisi à l'instant)
90
+ require('../utils/console-services').write(root, config);
89
91
 
90
92
  async function runKeycloak() {
91
93
  if (!(await waitForAuth())) return console.log(chalk.redBright('Keycloak not started: the auth service does not answer (poad info, docker logs).'));
@@ -171,6 +173,8 @@ module.exports = async (args = {}) => {
171
173
  await kc.enableUserAttributes(port, secrets, project.realm).catch(() => {
172
174
  /* sans effet sur la connexion : seuls les attributs ajoutés dans la console seraient perdus */
173
175
  });
176
+ // Administration : on reste connecté (30 jours, « Se souvenir de moi »)
177
+ await kc.longAdminSessions(port, secrets).catch(() => {});
174
178
  progress.succeed(chalk.bold('Keycloak started.'));
175
179
  } catch (err) {
176
180
  progress.fail(chalk.redBright(`Keycloak failed to start: ${err.message}`));
@@ -210,6 +214,9 @@ module.exports = async (args = {}) => {
210
214
  await shared.importRealm(state, { ...kc.realmOf(config, project), realm });
211
215
  kc.register(config, { ...project, realm });
212
216
  await kc.enableUserAttributes(state.port, { admin_password: state.admin_password }, realm).catch(() => {});
217
+ await kc.longAdminSessions(state.port, { admin_password: state.admin_password }).catch(() => {});
218
+ // Bouton « copier le mot de passe » de la console : lu par meta dans data/keycloak
219
+ kc.writeSharedAdmin(root, state.admin_password);
213
220
  progress.succeed(chalk.bold(`Keycloak started (shared, realm "${realm}").`));
214
221
  } catch (err) {
215
222
  progress.fail(chalk.redBright(`Keycloak failed to start: ${err.message}`));
package/global/start.js CHANGED
@@ -38,6 +38,8 @@ module.exports = async (args = {}) => {
38
38
  // Services optionnels à lancer, puis l'état complet du projet
39
39
  const finish = async () => {
40
40
  const targets = bare ? [] : all ? SERVICES.filter((s) => s.optional && s.configured(config)) : autostartServices(config);
41
+ // Groupe « Services » de la console (Mailpit, Keycloak) : ports de cette machine, après leur réattribution
42
+ require('../utils/console-services').write(root);
41
43
  if (targets.length) await require('./run')({ services: targets.map((s) => s.id), quiet: true });
42
44
  console.log(' ');
43
45
  await require('../utils/report').printReport(root, require('../utils/config').loadConfig(root));
@@ -53,6 +55,9 @@ module.exports = async (args = {}) => {
53
55
  config.engine = await offerEngineUpgrade(root, config, args);
54
56
  const gatewayWarning = gateway.maxBody(config).warning;
55
57
  if (gatewayWarning) console.log(chalk.yellowBright(gatewayWarning));
58
+ // Réglages [ai] (engine 0.30.0+) : une valeur refusée est dite, et pas transmise
59
+ const aiSettings = require('../utils/ai').engineEnv(config);
60
+ aiSettings.warnings.forEach((w) => console.log(chalk.yellowBright(w)));
56
61
  const image = 'poadio/engine:' + config.engine;
57
62
  // L'image de la version du projet n'est pas forcément là (poad install tire
58
63
  // celle du CLI, et config.toml peut en demander une autre) : on la tire.
@@ -62,6 +67,16 @@ module.exports = async (args = {}) => {
62
67
  return console.log(chalk.redBright(`No [mail] port in ${root}: add a [mail] section with a free port.`));
63
68
  }
64
69
  if (mailpit && !(await pullIfMissing(docker, mail.MAILPIT_IMAGE))) return;
70
+ // Catalogue des modèles d'IA (permalink, cache, hors ligne : le dernier connu) écrit dans poad/data/ai/ pour
71
+ // l'engine 0.31.0+, qui ne va jamais sur internet ; sans catalogue, il prend sa propre table
72
+ if (require('../utils/ai').supportsAiModels(config)) {
73
+ const aiCatalog = require('../utils/ai-catalog');
74
+ try {
75
+ aiCatalog.writeForEngine(root, await aiCatalog.loadCatalog());
76
+ } catch (err) {
77
+ console.log(chalk.grey(` AI model catalog not written (${err.message}): the engine uses its own table.`));
78
+ }
79
+ }
65
80
  // Flows (engine 0.18.0+) : leur file est sur le Valkey du projet. Le secret
66
81
  // partagé avec l'exécuteur est créé au premier démarrage qui s'en sert.
67
82
  if (require('../utils/engine').supportsFlows(config) && valkey.enabled(config)) require('../utils/config').ensureRunnerToken(root, config);
@@ -125,6 +140,8 @@ module.exports = async (args = {}) => {
125
140
  ...runner.engineEnv(config),
126
141
  // Taille maximale d'un corps de requête : [gateway] max_body (engine 0.28.2+)
127
142
  ...gateway.engineEnv(config),
143
+ // Socle IA : [ai] de poad/config.toml (engine 0.30.0+ ; un engine plus ancien les ignore)
144
+ ...aiSettings.env,
128
145
  ],
129
146
  ExposedPorts: { '5432/tcp': {}, '8000/tcp': {}, ...gelf.exposed },
130
147
  HostConfig: {
package/global/stop.js CHANGED
@@ -32,6 +32,7 @@ module.exports = async (args) => {
32
32
  kc.unregister(config);
33
33
  const project = kc.loadProject(root, config, { create: false });
34
34
  await shared.release(docker, config, project && shared.realmFor(config, project.realm));
35
+ kc.removeSharedAdmin(root);
35
36
  const left = await shared.projects(docker);
36
37
  progress.succeed(chalk.bold(left.length ? `Keycloak released (still used by ${left.length} other project(s))` : 'Keycloak stopped (no project uses it any more)'));
37
38
  return true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.42.0",
3
+ "version": "2.45.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.2.0",
6
6
  "main": "index.js",
package/poad.js CHANGED
@@ -147,6 +147,10 @@ const displayBanner = () => {
147
147
  };
148
148
 
149
149
  // Function to load project specific commands.
150
+ // « [Libellé] description » : un libellé seulement en tête du texte. Un crochet plus loin
151
+ // (« [gateway] max_body » dans la description de start) fait partie de la description.
152
+ const hasLabel = (text) => typeof text === 'string' && /^\[[^\]]*\] /.test(text);
153
+
150
154
  const loadPoadCommands = (path) => {
151
155
  let POAD_COMMANDS = {};
152
156
  try {
@@ -158,8 +162,8 @@ const loadPoadCommands = (path) => {
158
162
  if (s !== 'description') subs.push({ title: s });
159
163
  }
160
164
  let description = '';
161
- if (cli[el].description.indexOf(']') > -1) {
162
- description = cli[el].description.split('] ')[1];
165
+ if (hasLabel(cli[el].description)) {
166
+ description = cli[el].description.slice(cli[el].description.indexOf('] ') + 2);
163
167
  let lbl = cli[el].description
164
168
  .split('] ')[0]
165
169
  .replace('[', '')
@@ -184,8 +188,8 @@ const loadPoadCommands = (path) => {
184
188
  }
185
189
  } else {
186
190
  let description = '';
187
- if (cli[el].indexOf(']') > -1) {
188
- description = cli[el].split('] ')[1];
191
+ if (hasLabel(cli[el])) {
192
+ description = cli[el].slice(cli[el].indexOf('] ') + 2);
189
193
  let lbl = cli[el].split('] ')[0].replace('[', '').replace(']', '');
190
194
  POAD_COMMANDS[el] = {
191
195
  info: {
@@ -229,8 +233,8 @@ const displaySub = (path, title, description, cli) => {
229
233
  if (s !== 'description') subs.push({ title: s });
230
234
  }
231
235
  let description = '';
232
- if (cli[el].description.indexOf(']') > -1) {
233
- description = cli[el].description.split('] ')[1];
236
+ if (hasLabel(cli[el].description)) {
237
+ description = cli[el].description.slice(cli[el].description.indexOf('] ') + 2);
234
238
  let lbl = cli[el].description
235
239
  .split('] ')[0]
236
240
  .replace('[', '')
@@ -255,8 +259,8 @@ const displaySub = (path, title, description, cli) => {
255
259
  }
256
260
  } else {
257
261
  let description = '';
258
- if (cli[el].indexOf(']') > -1) {
259
- description = cli[el].split('] ')[1];
262
+ if (hasLabel(cli[el])) {
263
+ description = cli[el].slice(cli[el].indexOf('] ') + 2);
260
264
  let lbl = cli[el].split('] ')[0].replace('[', '').replace(']', '');
261
265
  POAD_COMMANDS[el] = {
262
266
  info: {
package/project/cli.js CHANGED
@@ -22,7 +22,7 @@ module.exports = {
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
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',
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…> provider=<AI provider> model=<AI model> event=<event, e.g. ai_default_model_changed> limit=100 -f --json',
26
26
  gen: {
27
27
  description: 'Generators: gen types (TypeScript types of the database), gen env (types of the public variables)',
28
28
  types: 'TypeScript types of the database for createClient<Database>() (out=src/types/database.ts)',
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
+ });