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/utils/ai.js ADDED
@@ -0,0 +1,178 @@
1
+ // Socle IA (engine 0.30.0+, /ai/v1) : clés des fournisseurs et réglages [ai].
2
+ //
3
+ // Clés de la machine : ~/.poad/ai.json (dossier 0700, fichier 0600), écrit seulement par le CLI
4
+ // (poad ai login|logout). Une clé n'est jamais lue sur la ligne de commande (elle finirait dans l'historique du
5
+ // shell), jamais affichée : seulement ses 4 derniers caractères. L'engine ne lit jamais ce fichier : la clé d'un
6
+ // projet est copiée dans ses Credentials (coffre de la base) par poad ai use <fournisseur>.
7
+ //
8
+ // Réglages du projet, poad/config.toml (passés à l'engine par poad start, en variables POAD_AI_*) :
9
+ // [ai]
10
+ // default_provider = "anthropic" anthropic | openai | mistral | gemini
11
+ // default_model = "claude-opus-5-5" modèle du fournisseur par défaut
12
+ // max_tokens = 4096 max_tokens par défaut et plafond par requête
13
+ // monthly_budget_usd = 20 plafond mensuel estimé (dollars US) ; absent : aucun
14
+ // log_content = false true : extrait masqué des messages dans les lignes du puits
15
+ // [ai.models] (engine 0.31.0+) modèle par défaut de chaque fournisseur, pris parmi
16
+ // anthropic = "claude-sonnet-5-5" le catalogue (poad ai models) ; un choix fait dans l'écran IA de la
17
+ // console passe avant (base de l'engine)
18
+ // [ai.prices] prix du projet, en dollars par million de jetons
19
+ // "openai/gpt-5" = { input = 1.25, output = 10 }
20
+ const fs = require('fs');
21
+ const os = require('os');
22
+ const path = require('path');
23
+
24
+ const PROVIDERS = ['anthropic', 'openai', 'mistral', 'gemini'];
25
+ const LABELS = { anthropic: 'Anthropic (Claude)', openai: 'OpenAI (GPT)', mistral: 'Mistral AI', gemini: 'Google Gemini' };
26
+
27
+ /** ~/.poad/ai.json (POAD_AI_KEYS_FILE pour les essais) */
28
+ const keysFile = () => process.env.POAD_AI_KEYS_FILE || path.join(os.homedir(), '.poad', 'ai.json');
29
+
30
+ /** Fin de clé à montrer : …abcd (rien de plus, et rien du tout pour une clé trop courte) */
31
+ const mask = (key) => (key && String(key).length >= 12 ? `…${String(key).slice(-4)}` : key ? '…' : '');
32
+
33
+ const isProvider = (p) => PROVIDERS.includes(p);
34
+
35
+ /**
36
+ * Clés de la machine : { providers: { anthropic: { key, added_at } } }. Un fichier lisible par d'autres est
37
+ * ramené à 0600 (fixed : true). Absent ou illisible : aucune clé (broken : la raison, sans contenu).
38
+ */
39
+ const readKeys = (file = keysFile()) => {
40
+ const out = { providers: {}, fixed: false, broken: null };
41
+ let st;
42
+ try {
43
+ st = fs.statSync(file);
44
+ } catch {
45
+ return out;
46
+ }
47
+ if (process.platform !== 'win32' && (st.mode & 0o077) !== 0) {
48
+ fs.chmodSync(file, 0o600);
49
+ out.fixed = true;
50
+ }
51
+ try {
52
+ const doc = JSON.parse(fs.readFileSync(file, 'utf8'));
53
+ for (const p of PROVIDERS) {
54
+ const e = doc && doc.providers && doc.providers[p];
55
+ if (e && typeof e.key === 'string' && e.key) out.providers[p] = { key: e.key, added_at: typeof e.added_at === 'string' ? e.added_at : null };
56
+ }
57
+ } catch {
58
+ out.broken = `${file} is not valid JSON`;
59
+ }
60
+ return out;
61
+ };
62
+
63
+ /** Écrit les clés : dossier 0700, fichier 0600, remplacement atomique */
64
+ const writeKeys = (providers, file = keysFile()) => {
65
+ const dir = path.dirname(file);
66
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
67
+ // Un dossier déjà là (~/.poad créé par une autre commande, en 0755) est ramené à 0700 ; ses autres fichiers ne changent pas
68
+ if (process.platform !== 'win32' && (fs.statSync(dir).mode & 0o077) !== 0) fs.chmodSync(dir, 0o700);
69
+ const tmp = path.join(dir, `.ai.json.${process.pid}.tmp`);
70
+ const doc = { version: 1, note: 'AI provider keys of this machine, written by "poad ai login". Never read by the engine.', providers };
71
+ fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, { mode: 0o600 });
72
+ fs.chmodSync(tmp, 0o600);
73
+ fs.renameSync(tmp, file);
74
+ };
75
+
76
+ /** Forme plausible d'une clé (rien de plus : le fournisseur seul sait si elle vaut) ; null ou la raison */
77
+ const keyProblem = (key) => {
78
+ if (!key) return 'empty key';
79
+ if (/\s/.test(key)) return 'a key has no spaces';
80
+ if (key.length < 8 || key.length > 512) return 'a key has 8 to 512 characters';
81
+ if (!/^[\x21-\x7e]+$/.test(key)) return 'a key is plain ASCII';
82
+ return null;
83
+ };
84
+
85
+ /** Toute l'entrée standard (clé passée par un tube : echo "$KEY" | poad ai login openai) */
86
+ const readStdin = () =>
87
+ new Promise((resolve, reject) => {
88
+ let data = '';
89
+ process.stdin.setEncoding('utf8');
90
+ process.stdin.on('data', (c) => {
91
+ data += c;
92
+ if (data.length > 4096) reject(new Error('too much input on stdin'));
93
+ });
94
+ process.stdin.on('end', () => resolve(data));
95
+ process.stdin.on('error', reject);
96
+ });
97
+
98
+ /** La clé : invite masquée dans un terminal, sinon l'entrée standard. Jamais un argument. */
99
+ const readSecret = async (message) => {
100
+ if (process.stdin.isTTY) {
101
+ const { password } = require('@inquirer/prompts');
102
+ return String(await password({ message, mask: false })).trim();
103
+ }
104
+ return String(await readStdin()).trim();
105
+ };
106
+
107
+ // --- Réglages [ai] de config.toml -------------------------------------------------
108
+
109
+ const MODEL_RE = /^[A-Za-z0-9._:/-]{1,100}$/;
110
+
111
+ /**
112
+ * Variables de l'engine tirées de [ai] ; warnings : ce qui est écarté (affiché par poad start). Une valeur
113
+ * refusée n'est pas transmise (l'engine applique son défaut).
114
+ */
115
+ const engineEnv = (config) => {
116
+ const ai = (config && config.ai) || {};
117
+ const env = [];
118
+ const warnings = [];
119
+ if (ai.default_provider !== undefined) {
120
+ if (isProvider(String(ai.default_provider))) env.push(`POAD_AI_DEFAULT_PROVIDER=${ai.default_provider}`);
121
+ else warnings.push(`[ai] default_provider = "${String(ai.default_provider).slice(0, 32)}" in poad/config.toml: ${PROVIDERS.join(', ')}. Ignored.`);
122
+ }
123
+ if (ai.default_model !== undefined) {
124
+ if (MODEL_RE.test(String(ai.default_model))) env.push(`POAD_AI_DEFAULT_MODEL=${ai.default_model}`);
125
+ else warnings.push('[ai] default_model in poad/config.toml is not a model id. Ignored.');
126
+ }
127
+ if (ai.max_tokens !== undefined) {
128
+ const n = Number(ai.max_tokens);
129
+ if (Number.isInteger(n) && n >= 1 && n <= 200000) env.push(`POAD_AI_MAX_TOKENS=${n}`);
130
+ else warnings.push('[ai] max_tokens in poad/config.toml: an integer from 1 to 200000. Ignored (4096).');
131
+ }
132
+ if (ai.monthly_budget_usd !== undefined) {
133
+ const n = Number(ai.monthly_budget_usd);
134
+ if (Number.isFinite(n) && n >= 0) env.push(`POAD_AI_MONTHLY_BUDGET_USD=${n}`);
135
+ else warnings.push('[ai] monthly_budget_usd in poad/config.toml is not a number of dollars. Ignored: no budget cap.');
136
+ }
137
+ if (ai.log_content !== undefined) env.push(`POAD_AI_LOG_CONTENT=${ai.log_content === true ? 'true' : 'false'}`);
138
+ if (ai.models !== undefined) {
139
+ if (ai.models && typeof ai.models === 'object' && !Array.isArray(ai.models)) {
140
+ const ok = {};
141
+ for (const [p, m] of Object.entries(ai.models)) {
142
+ if (!isProvider(p)) warnings.push(`[ai.models] in poad/config.toml: unknown provider "${String(p).slice(0, 32)}" (${PROVIDERS.join(', ')}). Ignored.`);
143
+ else if (typeof m !== 'string' || !/^[A-Za-z0-9._:-]{1,100}$/.test(m)) warnings.push(`[ai.models] ${p} in poad/config.toml is not a model id. Ignored.`);
144
+ else ok[p] = m;
145
+ }
146
+ if (Object.keys(ok).length) env.push(`POAD_AI_MODELS=${JSON.stringify(ok)}`);
147
+ } else warnings.push('[ai.models] in poad/config.toml must be a table provider = "model". Ignored.');
148
+ }
149
+ if (ai.prices !== undefined) {
150
+ if (ai.prices && typeof ai.prices === 'object' && !Array.isArray(ai.prices)) env.push(`POAD_AI_PRICES=${JSON.stringify(ai.prices)}`);
151
+ else warnings.push('[ai.prices] in poad/config.toml must be a table "provider/model" = { input, output }. Ignored.');
152
+ }
153
+ return { env, warnings };
154
+ };
155
+
156
+ /** Engine 0.30.0 et plus : /ai/v1 et les credentials anthropic, openai, mistral, gemini */
157
+ const supportsAi = (config) => {
158
+ const [major, minor] = String((config && config.engine) || '').split('.').map(Number);
159
+ return major > 0 || (major === 0 && minor >= 30);
160
+ };
161
+
162
+ /**
163
+ * Coût estimé en dollars, 4 décimales, préfixé : « ~$0.0002 », et « < $0.0001 » pour un coût positif plus
164
+ * petit (un appel payé ne s'affiche jamais « 0.0000 »). Sans coût (null) : null.
165
+ */
166
+ const usdText = (n) => {
167
+ if (n === null || n === undefined) return null;
168
+ const v = Number(n) || 0;
169
+ return v > 0 && v < 0.0001 ? '< $0.0001' : `~$${v.toFixed(4)}`;
170
+ };
171
+
172
+ /** Engine 0.31.0 et plus : catalogue des modèles (/data/ai/catalog.json) et [ai.models] */
173
+ const supportsAiModels = (config) => {
174
+ const [major, minor] = String((config && config.engine) || '').split('.').map(Number);
175
+ return major > 0 || (major === 0 && minor >= 31);
176
+ };
177
+
178
+ module.exports = { supportsAiModels, PROVIDERS, LABELS, keysFile, mask, isProvider, readKeys, writeKeys, keyProblem, readSecret, engineEnv, supportsAi, usdText };
@@ -0,0 +1,131 @@
1
+ // Liste des commandes de « poad » :
2
+ // poad vue courte : logo, usage, les commandes de tous les jours
3
+ // (une ligne chacune), de quoi aller plus loin ; tient sur
4
+ // un écran, le logo reste visible
5
+ // poad --help, -h, liste complète : toutes les commandes de global/cli.js et
6
+ // poad help project/cli.js, avec leurs sous-commandes
7
+ // Le détail d'une commande (options, filtres) : poad <commande> --help (utils/help.js).
8
+ //
9
+ // Les commandes de la vue courte et leur ligne sont ici (SHORT) ; une commande
10
+ // absente de SHORT n'y paraît pas (flows, functions, gen, kc, migration…).
11
+
12
+ const { row, paragraph, terminalColumns } = require('./layout');
13
+
14
+ const SHORT = {
15
+ global: {
16
+ create: 'Create a project, or add a front-end to it',
17
+ init: 'Init poad/ in an existing folder',
18
+ start: 'Start the project and its services',
19
+ stop: 'Stop the project',
20
+ run: 'Run an optional service (kc, valkey, runner)',
21
+ ai: 'AI providers: keys of this machine, use in a project',
22
+ clean: 'Remove what stopped projects left on this machine',
23
+ },
24
+ project: {
25
+ info: 'URLs, keys and state of the running project',
26
+ console: 'Open the administration console in the browser',
27
+ logs: 'Logs of every service, with filters',
28
+ setup: 'Choose what poad start starts',
29
+ db: 'Local database: reset, seed, diff',
30
+ upgrade: 'Upgrade the engine of the project',
31
+ },
32
+ };
33
+
34
+ // « [Libellé] description » : un libellé seulement en tête du texte. Un crochet plus loin
35
+ // (« [gateway] max_body ») fait partie de la description.
36
+ const LABEL = /^\[([^\]]*)\] /;
37
+
38
+ /** Commandes d'une table de cli.js : [{ name, description, label, subs }] */
39
+ function entries(table) {
40
+ return Object.entries(table).map(([name, v]) => {
41
+ const text = typeof v === 'string' ? v : (v && v.description) || '';
42
+ const m = LABEL.exec(text);
43
+ const subs = v && typeof v === 'object' ? Object.keys(v).filter((k) => k !== 'description') : null;
44
+ return { name, description: m ? text.slice(m[0].length) : text, label: m ? m[1].toLowerCase() : null, subs };
45
+ });
46
+ }
47
+
48
+ function labelSegment(label, chalk) {
49
+ if (!label) return [];
50
+ const styles = { experimental: chalk.red, alpha: chalk.cyan, beta: chalk.magenta, docker: chalk.green, ai: chalk.yellow };
51
+ const style = styles[label];
52
+ if (!style) return [];
53
+ return [{ text: `(${label === 'ai' ? 'AI' : label})`, style }];
54
+ }
55
+
56
+ /** Segments de la description d'une commande : libellé, texte, sous-commandes */
57
+ function segmentsOf(e, chalk, { text = e.description, subs = true } = {}) {
58
+ const segs = [...labelSegment(e.label, chalk), { text, style: chalk.white }];
59
+ if (subs && e.subs && e.subs.length) {
60
+ segs.push({ text: '(subcommands:', style: chalk.grey });
61
+ // « login, » : la virgule en gris ; la dernière garde sa parenthèse collée
62
+ const tail = (mark) => (w) => chalk.cyan(w.slice(0, -1)) + chalk.grey(mark);
63
+ e.subs.forEach((s, i) => segs.push(i < e.subs.length - 1 ? { text: s + ',', style: tail(',') } : { text: s + ')', style: tail(')') }));
64
+ }
65
+ return segs;
66
+ }
67
+
68
+ /**
69
+ * Lignes de la liste des commandes (sans saut de ligne final).
70
+ * full true : liste complète ; false : vue courte (SHORT)
71
+ * inProject dans un projet poad (sinon les commandes de projet ne sont pas listées)
72
+ */
73
+ function render({ full = false, inProject = true, columns = terminalColumns(), version, chalk = require('chalk-v2'), tables } = {}) {
74
+ tables = tables || { global: require('../global/cli'), project: require('../project/cli') };
75
+ const pick = (scope) => {
76
+ const all = entries(tables[scope]);
77
+ if (full) return all;
78
+ return Object.keys(SHORT[scope])
79
+ .map((name) => all.find((e) => e.name === name))
80
+ .filter(Boolean)
81
+ .map((e) => ({ ...e, short: SHORT[scope][e.name] }));
82
+ };
83
+ const groups = { global: pick('global'), project: inProject ? pick('project') : [] };
84
+ const title = (e) => (full && e.subs && e.subs.length ? `${e.name} <subcommand>` : e.name);
85
+ const nameWidth = Math.max(...[...groups.global, ...groups.project].map((e) => title(e).length)) + 4;
86
+
87
+ const lines = [];
88
+ const figlet = require('figlet');
89
+ lines.push(...figlet.textSync('poad').replace(/\s+$/, '').split('\n').map((l) => chalk.cyan(l)));
90
+ lines.push(chalk.white.bold(` version ${version}`));
91
+ lines.push('');
92
+ lines.push(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad <command>')} ${chalk.cyan('[<args>]')}`);
93
+
94
+ const table = (list) => {
95
+ for (const e of list) {
96
+ lines.push(
97
+ ...row({
98
+ name: title(e),
99
+ nameStyle: chalk.cyanBright,
100
+ dotStyle: chalk.grey,
101
+ nameWidth,
102
+ columns,
103
+ segments: full ? segmentsOf(e, chalk) : segmentsOf(e, chalk, { text: e.short, subs: false }),
104
+ })
105
+ );
106
+ }
107
+ };
108
+
109
+ lines.push('');
110
+ lines.push(chalk.bold(' Global commands :'));
111
+ table(groups.global);
112
+ lines.push('');
113
+ lines.push(chalk.bold(' Project commands :'));
114
+ if (!inProject) lines.push(...paragraph([{ text: 'You are not in a project directory.' }], { columns }));
115
+ else table(groups.project);
116
+ lines.push('');
117
+ if (full) {
118
+ lines.push(...paragraph([{ text: 'poad <command> --help', style: chalk.cyanBright }, { text: ': usage, options and details of a command', style: chalk.grey }], { columns, indent: 1 }));
119
+ } else {
120
+ const more = [
121
+ ['poad --help', 'every command and its options'],
122
+ ['poad <command> --help', 'details of a command'],
123
+ ];
124
+ const w = Math.max(...more.map(([k]) => k.length)) + 2;
125
+ for (const [k, v] of more) lines.push(...row({ name: k, nameStyle: chalk.cyanBright, nameWidth: w, columns, indent: 1, dots: false, segments: [{ text: v, style: chalk.grey }] }));
126
+ }
127
+ lines.push('');
128
+ return lines;
129
+ }
130
+
131
+ module.exports = { SHORT, entries, render };
@@ -0,0 +1,70 @@
1
+ // Services du projet que la console locale montre (groupe « Services » de son
2
+ // rail, cartes de l'accueil). L'engine ne connaît pas les ports de la machine :
3
+ // le CLI écrit la liste dans poad/data/console/services.json (monté en /data
4
+ // dans l'engine, relu par meta à chaque affichage de la console, engine 0.29.2+).
5
+ //
6
+ // Seuls les services activés dans config.toml y figurent :
7
+ // - db : PostgreSQL de l'engine, toujours (port de la machine) ;
8
+ // - mail : Mailpit, sauf si [smtp] désigne un vrai serveur ;
9
+ // - keycloak : [keycloak] a un port (choisi au premier poad run kc) ou
10
+ // shared = true (port du Keycloak partagé de la machine) ;
11
+ // - valkey : [valkey] a un port.
12
+ // Qu'ils tournent ou non : la console sonde et indique la commande qui les
13
+ // lance. Jamais de secret dans ce fichier : le mot de passe admin de Keycloak
14
+ // reste dans data/keycloak (users.json, ou shared-admin.json pour le partagé),
15
+ // meta ne le lit qu'à la demande de la console locale (bouton copier).
16
+ //
17
+ // Réécrit à poad start, poad run et poad setup ; un échec n'arrête rien.
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+
21
+ const file = (root) => path.join(path.dirname(root), 'data', 'console', 'services.json');
22
+
23
+ const validPort = (p) => Number.isInteger(Number(p)) && Number(p) > 0 && Number(p) < 65536;
24
+
25
+ /** [{ id, url }] des services activés (config lue de config.toml) */
26
+ const list = (root, config) => {
27
+ const mail = require('./mail');
28
+ const kc = require('./keycloak');
29
+ const shared = require('./keycloak-shared');
30
+ const valkey = require('./valkey');
31
+ const out = [];
32
+ if (config.db && validPort(config.db.port)) out.push({ id: 'db', port: Number(config.db.port) });
33
+ if (mail.usesMailpit(config) && validPort(mail.mailPort(config))) out.push({ id: 'mail', url: `http://localhost:${Number(mail.mailPort(config))}/`, smtp: `${mail.MAIL_ALIAS}:1025` });
34
+ const kcService = require('./services').SERVICES.find((s) => s.id === 'keycloak');
35
+ if (kcService.configured(config)) {
36
+ const port = shared.isShared(config) ? (shared.readState() || {}).port : config.keycloak.port;
37
+ if (validPort(port)) {
38
+ // La console d'administration ouverte sur le realm du projet (le compte
39
+ // admin est celui du realm master : poad info --secrets)
40
+ let realm;
41
+ try {
42
+ const project = kc.loadProject(root, config, { create: false });
43
+ realm = kc.runningRealm(config, project ? project.realm : kc.realmName(config));
44
+ } catch {
45
+ realm = null;
46
+ }
47
+ const base = `http://localhost:${Number(port)}/admin/master/console/`;
48
+ out.push({ id: 'keycloak', url: realm ? `${base}#/${encodeURIComponent(realm)}` : base, ...(realm ? { realm } : {}), shared: shared.isShared(config) });
49
+ }
50
+ }
51
+ if (valkey.enabled(config) && validPort(config.valkey.port)) out.push({ id: 'valkey', port: Number(config.valkey.port), engine_url: valkey.URL });
52
+ return out;
53
+ };
54
+
55
+ /** Écrit la liste (remplacement atomique) ; renvoie la liste, ou null en cas d'échec */
56
+ const write = (root, config = require('./config').loadConfig(root)) => {
57
+ try {
58
+ const services = list(root, config);
59
+ const target = file(root);
60
+ fs.mkdirSync(path.dirname(target), { recursive: true });
61
+ const tmp = `${target}.${process.pid}.tmp`;
62
+ fs.writeFileSync(tmp, JSON.stringify(services, null, 2) + '\n', { mode: 0o644 });
63
+ fs.renameSync(tmp, target);
64
+ return services;
65
+ } catch {
66
+ return null;
67
+ }
68
+ };
69
+
70
+ module.exports = { file, list, write };
@@ -0,0 +1,163 @@
1
+ // Fiches d'aide des commandes qui n'exportent pas help() : ce que la liste
2
+ // des commandes (poad --help) ne dit pas, options et filtres compris. Rendu
3
+ // par utils/help.js (poad <commande> --help), coupé à la largeur du terminal.
4
+ //
5
+ // usage lignes « poad … » (la première après « Usage : »)
6
+ // text paragraphes avant les options (sinon la description de cli.js)
7
+ // options [option, explication]
8
+ // notes paragraphes après les options
9
+
10
+ const sheets = {
11
+ start: {
12
+ usage: ['poad start [--all | --bare | --quiet]'],
13
+ text: [
14
+ 'Start the project: the engine and Mailpit, the migrations of poad/migrations (unless "poad setup migrate=off"), the services chosen with poad setup, then show its state (as poad info).',
15
+ ],
16
+ options: [
17
+ ['--all', 'every configured optional service (Keycloak, Valkey, flows runner), autostart or not'],
18
+ ['--bare', 'the engine and Mailpit only, this time'],
19
+ ['--quiet', 'nothing if the project already runs (bun start of a front-end)'],
20
+ ],
21
+ notes: [
22
+ 'Secrets are hidden in the state shown at the end: poad info --secrets shows them.',
23
+ 'A port of poad/config.toml already used on this machine is replaced by a free one.',
24
+ 'Request bodies are limited by the gateway to [gateway] max_body of poad/config.toml (default "10m", storage uploads excepted).',
25
+ ],
26
+ },
27
+ stop: {
28
+ usage: ['poad stop [keycloak | valkey | runner]'],
29
+ text: ['Stop the project: engine, Mailpit, Keycloak, Valkey, flows runner, network. Its data stays in poad/data.'],
30
+ options: [
31
+ ['keycloak (or kc)', 'Keycloak only (a shared Keycloak is released, and stops when no project uses it any more)'],
32
+ ['valkey (or redis)', 'Valkey only'],
33
+ ['runner', 'the flows runner only'],
34
+ ],
35
+ },
36
+ clean: {
37
+ usage: ['poad clean [--dry-run | --yes]'],
38
+ text: [
39
+ 'Remove what stopped poad projects left on this machine: optional services (Mailpit, Keycloak, Valkey, flows runner) whose engine no longer runs, stopped poad containers, networks of stopped projects, a shared Keycloak no running project uses, engine images (about 3 GB each) no container uses.',
40
+ ],
41
+ options: [
42
+ ['--dry-run', 'list only'],
43
+ ['--yes', 'no question (required outside a terminal)'],
44
+ ],
45
+ notes: [
46
+ 'Nothing of a running project is touched. A stopped project loses nothing: its data is in its poad/data folder, and a removed engine image is pulled again by poad start when needed.',
47
+ ],
48
+ },
49
+ setup: {
50
+ usage: ['poad setup [<setting>=<value> …] [--all | --none | --list]'],
51
+ text: ['Choose what "poad start" starts with the project: e-mails, Keycloak, Valkey, migrations. Interactive in a terminal.'],
52
+ options: [
53
+ ['kc=on valkey=off', 'not interactive: changes only the settings given'],
54
+ ['kc=shared | kc=own', 'Keycloak shared by the local projects (one container, one realm per project), or one of its own'],
55
+ ['mail=smtp smtp.host=… smtp.port=587 smtp.user=… smtp.pass=…', 'e-mails sent through an SMTP server'],
56
+ ['mail=mailpit', 'back to Mailpit (e-mails caught locally)'],
57
+ ['migrate=off', 'migrations applied by hand (poad migrate)'],
58
+ ['--all | --none', 'every optional service in autostart, or none'],
59
+ ['--list', 'show the settings, change nothing'],
60
+ ],
61
+ notes: [
62
+ 'Everything goes to poad/config.toml, except the SMTP password (poad/secrets.toml). Turning a service off removes its autostart only: its port, data and test set stay. The flows runner is set elsewhere (poad run runner, [flows] runner).',
63
+ ],
64
+ },
65
+ upgrade: {
66
+ usage: ['poad upgrade [to=<version>] [--yes]', 'poad upgrade --rollback [file=<backup>]', 'poad upgrade --list'],
67
+ text: [
68
+ 'Upgrade the engine of the project to the latest published one: backup (poad/backups), stop, update of poad/config.toml, restart (the engine migrates poad/data) and migrations.',
69
+ ],
70
+ options: [
71
+ ['to=<version>', 'a given (newer) version'],
72
+ ['channel=beta', 'the beta channel (or channel = "beta" in poad/config.toml, or POAD_CHANNEL=beta)'],
73
+ ['--rollback', 'back to the latest backup (file=<name>: another one)'],
74
+ ['--list', 'list the backups'],
75
+ ['--yes', 'no question (required outside a terminal)'],
76
+ ],
77
+ },
78
+ logs: {
79
+ usage: ['poad logs [service …] [<filter>=<value> …] [-f] [--json]'],
80
+ text: [
81
+ 'Unified logs of the project (every service, the project functions and flow steps), the latest 100 lines by default. Services: gateway, data, auth, storage, meta, functions, flows, postgres, logs, engine, mailpit, keycloak, valkey, ai.',
82
+ ],
83
+ options: [
84
+ ['level=warn', 'warn, error and fatal'],
85
+ ['since=15m', 'since 15 minutes (s, m, h, d)'],
86
+ ['request=<id>', 'the whole path of a request (the start of the id is enough)'],
87
+ ['grep=<text>', 'messages that contain this text'],
88
+ ['flow=<name>', 'the lines of a flow (engine and steps)'],
89
+ ['run=<id>', 'one run of a flow (its id, or its first 8 characters)'],
90
+ ['step=<name>', 'one step (with flow= or run=, most often)'],
91
+ ['function=<name>', 'one function: its calls and its console.log'],
92
+ ['token=<name>', 'a token of the MCP server (engine 0.29+): its name, id (or its start) or prefix'],
93
+ ['tool=<name>', 'a tool of the MCP server'],
94
+ ['outcome=<outcome>', 'MCP: ok, error, refused, invalid, not_found, unauthorized, rate_limited; AI: ok, provider_error, budget_exceeded, no_credential, forbidden, invalid'],
95
+ ['provider=<provider>', 'calls to an AI provider (engine 0.30+), e.g. poad logs ai provider=openai'],
96
+ ['model=<model>', 'calls to an AI model'],
97
+ ['event=<event>', 'an event, e.g. ai_default_model_changed'],
98
+ ['limit=100', 'number of lines'],
99
+ ['-f, --follow', 'follow live'],
100
+ ['--json', 'one JSON line per entry (for jq)'],
101
+ ],
102
+ notes: ['Everything combines: poad logs flows run=dafb44e1 step=call level=warn -f'],
103
+ },
104
+ functions: {
105
+ usage: ['poad functions new <name>', 'poad functions list', 'poad functions types'],
106
+ text: [
107
+ 'Functions of the project: modules in poad/functions/<name>/ that export { fetch(request, env, ctx) } (Cloudflare Workers format), served by the engine on /functions/v1/<name> and reloaded on every save.',
108
+ ],
109
+ options: [
110
+ ['new <name> (or create)', 'create poad/functions/<name>/index.ts'],
111
+ ['list', 'functions of the project and their state in the running engine'],
112
+ ['types', 'types for the editor (autocompletion), read from the running engine'],
113
+ ],
114
+ notes: ['Their console.log: poad logs function=<name>'],
115
+ },
116
+ flows: {
117
+ usage: [
118
+ 'poad flows new <name>',
119
+ 'poad flows list',
120
+ 'poad flows run <name> [key=value …] [input=<file.json>] [--wait | --no-wait]',
121
+ 'poad flows runs [name] [limit=20]',
122
+ 'poad flows show <run_id>',
123
+ 'poad flows cancel <run_id>',
124
+ ],
125
+ text: [
126
+ 'Flows of the project: automations (trigger, steps, edges) described in poad/flows/<name>.json, served by the engine (0.18.0+) on /flows/v1. Their queue is on the Valkey of the project (poad run valkey); container steps are started by the runner (poad run runner).',
127
+ ],
128
+ options: [
129
+ ['new <name>', 'create poad/flows/<name>.json (minimal flow)'],
130
+ ['list', 'flows of the project, as the running engine sees them'],
131
+ ['run <name>', 'start a flow and follow its steps'],
132
+ ['runs [name]', 'latest runs'],
133
+ ['show <run_id>', 'detail of a run'],
134
+ ['cancel <run_id>', 'cancel a running run'],
135
+ ],
136
+ notes: ['Their logs: poad logs flow=<name>, poad logs run=<id>'],
137
+ },
138
+ migration: {
139
+ usage: ['poad migration new <name>', 'poad migration list'],
140
+ options: [
141
+ ['new <name>', 'create poad/migrations/<timestamp>_<name>.sql'],
142
+ ['list', 'applied and pending migrations'],
143
+ ],
144
+ notes: ['poad migrate applies the pending ones (poad start does it too).'],
145
+ },
146
+ kc: {
147
+ usage: ['poad kc', 'poad kc export'],
148
+ options: [
149
+ ['(nothing)', 'show the Keycloak test set of the project (poad/keycloak.json)'],
150
+ ['export', 'rewrite poad/keycloak.json from the running Keycloak (roles, groups, users created or changed in its console)'],
151
+ ],
152
+ },
153
+ };
154
+
155
+ const alias = (of, name) => ({
156
+ ...sheets[of],
157
+ usage: sheets[of].usage.map((u) => u.replace(`poad ${of}`, `poad ${name}`)),
158
+ text: [`Alias of poad ${of}.`, ...(sheets[of].text || [])],
159
+ });
160
+ sheets.function = alias('functions', 'function');
161
+ sheets.flow = alias('flows', 'flow');
162
+
163
+ module.exports = sheets;
package/utils/help.js CHANGED
@@ -5,9 +5,12 @@
5
5
  // connaît pas --help le prenait pour un argument quelconque et faisait son
6
6
  // travail (poad stop --help arrêtait le projet).
7
7
  //
8
- // Une commande peut exporter help() pour une aide détaillée ; sinon sa
9
- // description de global/cli.js ou project/cli.js (et ses sous-commandes).
8
+ // Une commande peut exporter help() pour une aide détaillée ; sinon sa fiche
9
+ // de utils/help-details.js (usage, options, notes), sinon sa description de
10
+ // global/cli.js ou project/cli.js ; ses sous-commandes en plus. Le tout est
11
+ // coupé à la largeur du terminal (utils/layout.js).
10
12
  const path = require('path');
13
+ const sheets = require('./help-details');
11
14
 
12
15
  const HELP_FLAGS = ['--help', '-h'];
13
16
 
@@ -64,16 +67,39 @@ function printHelp(argv = [], { tables = loadTables(), base = path.join(__dirnam
64
67
  return true;
65
68
  }
66
69
  const name = `poad ${cmd.dir.join(' ')}`;
70
+ const { row, paragraph, terminalColumns } = require('./layout');
71
+ const columns = terminalColumns();
67
72
  const subs = cmd.entry && typeof cmd.entry === 'object' ? Object.entries(cmd.entry).filter(([k]) => k !== 'description') : [];
68
- console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright(name)} ${chalk.cyan(subs.length ? '<subcommand> [<args>]' : '[<args>]')}`);
69
- console.log(' ');
70
- console.log(` ${describe(cmd.entry)}`);
73
+ const sheet = sheets[cmd.dir.join(' ')];
74
+ const out = [];
75
+ if (sheet) {
76
+ const [first, ...more] = sheet.usage;
77
+ out.push(`${chalk.bold(' Usage :')} ${chalk.cyanBright(first)}`);
78
+ for (const u of more) out.push(` ${chalk.cyanBright(u)}`);
79
+ } else {
80
+ out.push(`${chalk.bold(' Usage :')} ${chalk.cyanBright(name)} ${chalk.cyan(subs.length ? '<subcommand> [<args>]' : '[<args>]')}`);
81
+ }
82
+ out.push('');
83
+ ((sheet && sheet.text) || [describe(cmd.entry)]).forEach((p, i) => out.push(...(i ? [''] : []), ...paragraph(p, { columns })));
71
84
  if (subs.length) {
72
- console.log(' ');
73
- const width = Math.max(...subs.map(([k]) => k.length));
74
- for (const [k, v] of subs) console.log(` ${chalk.cyanBright(`${name} ${k.padEnd(width)}`)} ${describe(v)}`);
85
+ out.push('');
86
+ const titles = subs.map(([k]) => `${name} ${k}`);
87
+ const nameWidth = Math.max(...titles.map((t) => t.length)) + 2;
88
+ subs.forEach(([, v], i) => out.push(...row({ name: titles[i], nameStyle: chalk.cyanBright, nameWidth, columns, dots: false, segments: describe(v) })));
89
+ }
90
+ if (sheet && sheet.options) {
91
+ out.push('');
92
+ // une option trop longue pour la colonne passe sur sa propre ligne
93
+ const fit = sheet.options.filter(([k]) => k.length <= 24);
94
+ const nameWidth = Math.max(...fit.map(([k]) => k.length), 6) + 2;
95
+ for (const [k, v] of sheet.options) out.push(...row({ name: k, nameStyle: chalk.cyanBright, nameWidth, columns, dots: false, segments: v }));
96
+ }
97
+ for (const p of (sheet && sheet.notes) || []) {
98
+ out.push('');
99
+ out.push(...paragraph(p, { columns }));
75
100
  }
76
- console.log(' ');
101
+ out.push(' ');
102
+ console.log(out.join('\n'));
77
103
  return true;
78
104
  }
79
105