poad 2.41.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.
- package/global/ai/index.js +279 -0
- package/global/ai/list.js +5 -0
- package/global/ai/login.js +5 -0
- package/global/ai/logout.js +5 -0
- package/global/ai/models.js +5 -0
- package/global/ai/use.js +5 -0
- package/global/cli.js +8 -0
- package/global/run.js +7 -0
- package/global/start.js +17 -0
- package/global/stop.js +1 -0
- package/package.json +1 -1
- package/poad.js +12 -8
- package/project/cli.js +1 -1
- package/project/logs.js +29 -7
- package/project/setup.js +2 -0
- package/test/ai-catalog.test.js +117 -0
- package/test/ai.test.js +187 -0
- package/test/console-services.test.js +90 -0
- package/test/fixtures-permalink-ai.json +233 -0
- package/test/help.test.js +7 -0
- package/test/logs.test.js +192 -0
- package/utils/ai-catalog.js +148 -0
- package/utils/ai.js +178 -0
- package/utils/console-services.js +70 -0
- package/utils/keycloak.js +46 -0
- package/utils/logline.js +169 -7
- package/utils/mail.js +1 -0
|
@@ -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;
|
package/global/ai/use.js
ADDED
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
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
|
|
162
|
-
description = cli[el].description.
|
|
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]
|
|
188
|
-
description = cli[el].
|
|
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
|
|
233
|
-
description = cli[el].description.
|
|
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]
|
|
259
|
-
description = cli[el].
|
|
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> 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
|
@@ -12,6 +12,15 @@
|
|
|
12
12
|
// 8 caractères au moins)
|
|
13
13
|
// poad logs step=appel une étape (avec flow= ou run= le plus souvent)
|
|
14
14
|
// poad logs function=demo-stats une fonction : ses appels et ses console.log
|
|
15
|
+
// poad logs token="Claude Code" un jeton du serveur MCP (engine 0.29+) : par son
|
|
16
|
+
// nom, son id (ou son début) ou son préfixe ; ses
|
|
17
|
+
// appels (mcp) et les changements de ses droits (meta)
|
|
18
|
+
// poad logs tool=select_rows un outil du serveur MCP
|
|
19
|
+
// poad logs outcome=refused un résultat d'appel MCP (ok, error, refused,
|
|
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)
|
|
15
24
|
// poad logs limit=500 nombre de lignes (100 par défaut)
|
|
16
25
|
// poad logs -f | --follow suivi en direct
|
|
17
26
|
// poad logs --json une ligne JSON par entrée (pour jq)
|
|
@@ -21,14 +30,14 @@
|
|
|
21
30
|
// dit pas. Le CLI lit _logs.entries dans la base du projet : ces filtres
|
|
22
31
|
// portent sur la colonne attrs et valent pour tout engine qui a le collecteur
|
|
23
32
|
// (les index qui les accélèrent arrivent avec l'engine 0.18.1).
|
|
24
|
-
module.exports = async (args = {}) => {
|
|
33
|
+
module.exports = async (args = {}, raw = []) => {
|
|
25
34
|
const chalk = require('chalk-v2');
|
|
26
35
|
const { findPoadDir } = require('../utils/findpoad');
|
|
27
36
|
const { isDockerExist } = require('../utils/docker');
|
|
28
37
|
const { readConfig } = require('../utils/config');
|
|
29
38
|
const { supportsLogs } = require('../utils/logs');
|
|
30
39
|
const { connect } = require('../utils/migrations');
|
|
31
|
-
const { LEVELS, ATTR_OPTIONS, attrConditions, fromClause, formatLine } = require('../utils/logline');
|
|
40
|
+
const { LEVELS, ATTR_OPTIONS, attrConditions, fromClause, formatLine, parseToken, resolveTokenIds, tokenCondition } = require('../utils/logline');
|
|
32
41
|
|
|
33
42
|
const root = findPoadDir(process.cwd());
|
|
34
43
|
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
@@ -42,7 +51,7 @@ module.exports = async (args = {}) => {
|
|
|
42
51
|
return console.log(chalk.redBright('The project is not started: run "poad start".'));
|
|
43
52
|
}
|
|
44
53
|
|
|
45
|
-
const OPTIONS = ['level', 'since', 'request', 'grep', 'limit', 'run', ...Object.keys(ATTR_OPTIONS), '-f', '--follow', 'follow', '--json', 'json'];
|
|
54
|
+
const OPTIONS = ['level', 'since', 'request', 'grep', 'limit', 'run', 'token', ...Object.keys(ATTR_OPTIONS), '-f', '--follow', 'follow', '--json', 'json'];
|
|
46
55
|
const flag = (...names) => names.some((n) => args[n] === true);
|
|
47
56
|
const follow = flag('-f', '--follow', 'follow');
|
|
48
57
|
const asJson = flag('--json', 'json');
|
|
@@ -74,25 +83,38 @@ module.exports = async (args = {}) => {
|
|
|
74
83
|
process.exitCode = 1;
|
|
75
84
|
return console.log(chalk.redBright(attrs.error));
|
|
76
85
|
}
|
|
86
|
+
// token= : la valeur telle que tapée (parseArgs ferait d'un préfixe tout en chiffres un nombre)
|
|
87
|
+
const typed = raw.find((w) => typeof w === 'string' && w.startsWith('token='));
|
|
88
|
+
const token = parseToken(typed !== undefined ? typed.slice('token='.length) : args.token);
|
|
89
|
+
if (token && token.error) {
|
|
90
|
+
process.exitCode = 1;
|
|
91
|
+
return console.log(chalk.redBright(token.error));
|
|
92
|
+
}
|
|
77
93
|
const limit = Math.min(Number(args.limit) || (args.request ? 1000 : 100), 10000);
|
|
78
94
|
|
|
79
95
|
// Conditions communes à la première lecture et au suivi
|
|
80
96
|
const where = [];
|
|
81
97
|
const values = [];
|
|
82
|
-
const add = (sql,
|
|
83
|
-
|
|
84
|
-
|
|
98
|
+
const add = (sql, ...vs) => {
|
|
99
|
+
where.push(
|
|
100
|
+
sql.replace(/\?/g, () => {
|
|
101
|
+
values.push(vs.shift());
|
|
102
|
+
return `$${values.length}`;
|
|
103
|
+
}),
|
|
104
|
+
);
|
|
85
105
|
};
|
|
86
106
|
if (services.length) add('service = any(?)', services);
|
|
87
107
|
if (level) add('level = any(?)', LEVELS.slice(LEVELS.indexOf(level)));
|
|
88
108
|
if (since) add("ts >= now() - ?::interval", since);
|
|
89
109
|
if (args.request) add('request_id like ?', `${String(args.request).replace(/[%_]/g, '')}%`);
|
|
90
110
|
if (args.grep) add('msg ilike ?', `%${String(args.grep).replace(/[%_\\]/g, (c) => `\\${c}`)}%`);
|
|
91
|
-
for (const [sql, v] of attrs.conditions) add(sql, v);
|
|
111
|
+
for (const [sql, ...v] of attrs.conditions) add(sql, ...v);
|
|
92
112
|
|
|
93
113
|
const print = (r) => console.log(asJson ? JSON.stringify(r) : formatLine(r, chalk));
|
|
94
114
|
|
|
95
115
|
const client = await connect(config);
|
|
116
|
+
// Le jeton par son nom actuel, son préfixe ou le début de son id : ses lignes, même sous un ancien nom
|
|
117
|
+
if (token) add(...tokenCondition(token, await resolveTokenIds(client, token)));
|
|
96
118
|
const from = (extra) => fromClause([...where, ...(extra ? [extra] : [])].join(' and ') || 'true', attrs.prefix);
|
|
97
119
|
let lastId = 0;
|
|
98
120
|
try {
|
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.'));
|