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/keycloak.js CHANGED
@@ -332,6 +332,47 @@ const enableUserAttributes = async (port, secrets, realm) => {
332
332
  if (!res.ok) throw new Error(`user profile: ${res.status}`);
333
333
  };
334
334
 
335
+ /**
336
+ * Connexion qui dure à la console d'administration (Keycloak local, développement
337
+ * seulement) : sessions SSO du realm master de 30 jours et case « Se souvenir de
338
+ * moi ». Après une première connexion (case cochée), le lien de la console poad
339
+ * ouvre l'administration déjà connecté, tant que ce Keycloak tourne.
340
+ */
341
+ const LONG_SESSION = 30 * 24 * 3600;
342
+ const MASTER_SESSIONS = {
343
+ rememberMe: true,
344
+ ssoSessionIdleTimeout: LONG_SESSION,
345
+ ssoSessionMaxLifespan: LONG_SESSION,
346
+ ssoSessionIdleTimeoutRememberMe: LONG_SESSION,
347
+ ssoSessionMaxLifespanRememberMe: LONG_SESSION,
348
+ };
349
+ const longAdminSessions = async (port, secrets) => {
350
+ const token = await adminToken(port, secrets);
351
+ const url = `http://localhost:${port}/admin/realms/master`;
352
+ const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
353
+ const realm = await (await fetch(url, { headers })).json();
354
+ if (Object.entries(MASTER_SESSIONS).every(([k, v]) => realm[k] === v)) return false;
355
+ const res = await fetch(url, { method: 'PUT', headers, body: JSON.stringify(MASTER_SESSIONS) });
356
+ if (!res.ok) throw new Error(`master realm sessions: ${res.status}`);
357
+ return true;
358
+ };
359
+
360
+ /**
361
+ * Keycloak partagé : son mot de passe d'administration (rangé pour la machine
362
+ * dans ~/.poad) est recopié dans data/keycloak/shared-admin.json du projet,
363
+ * comme celui d'un Keycloak propre au projet l'est dans data/keycloak/users.json
364
+ * (data/ n'est jamais versionné). meta l'y lit à la demande du bouton « copier »
365
+ * de la console locale. Retiré quand le projet lâche le Keycloak partagé.
366
+ */
367
+ const sharedAdminFile = (root) => path.join(dataDir(root), 'shared-admin.json');
368
+ const writeSharedAdmin = (root, password) => {
369
+ fs.mkdirSync(dataDir(root), { recursive: true });
370
+ const file = sharedAdminFile(root);
371
+ fs.writeFileSync(file, JSON.stringify({ admin_password: password }) + '\n', { mode: 0o600 });
372
+ fs.chmodSync(file, 0o600);
373
+ };
374
+ const removeSharedAdmin = (root) => fs.rmSync(sharedAdminFile(root), { force: true });
375
+
335
376
  /**
336
377
  * Reprise : avant de recréer un Keycloak qui tourne, garde les identifiants de
337
378
  * ses utilisateurs qui n'en ont pas encore dans les secrets (projets antérieurs,
@@ -460,6 +501,11 @@ module.exports = {
460
501
  readRunningRealm,
461
502
  adoptRunningIds,
462
503
  enableUserAttributes,
504
+ longAdminSessions,
505
+ MASTER_SESSIONS,
506
+ sharedAdminFile,
507
+ writeSharedAdmin,
508
+ removeSharedAdmin,
463
509
  exportRealm,
464
510
  assertCanRegister,
465
511
  register,
@@ -0,0 +1,99 @@
1
+ // Mise en page de l'aide dans le terminal : coupure aux espaces à la largeur
2
+ // réelle du terminal, retrait suspendu (les lignes suivantes d'une description
3
+ // repartent sous la colonne des descriptions, jamais en colonne 0).
4
+ //
5
+ // Le texte se donne en segments { text, style } : la coupure se fait sur le
6
+ // texte nu, la couleur (chalk) est posée mot par mot après coup, si bien
7
+ // qu'aucun code de couleur ne compte dans la largeur ni ne déborde d'une ligne.
8
+
9
+ const FALLBACK_COLUMNS = 100; // sortie qui n'est pas un terminal (tube, fichier)
10
+ const MIN_COLUMNS = 40;
11
+ const MIN_DESCRIPTION = 30; // en dessous : la description passe sous la commande
12
+
13
+ /** Largeur utile : celle du terminal, sinon $COLUMNS, sinon 100 (au moins 40) */
14
+ function terminalColumns(stream = process.stdout, env = process.env) {
15
+ const tty = stream && stream.isTTY && Number(stream.columns);
16
+ const n = tty || Number(env.COLUMNS) || FALLBACK_COLUMNS;
17
+ return Math.max(MIN_COLUMNS, Math.floor(n));
18
+ }
19
+
20
+ const ANSI = /\x1b\[[0-9;]*m/g;
21
+ const visible = (s) => String(s).replace(ANSI, '').length;
22
+
23
+ /**
24
+ * Coupe en mots ({ word, style }), un mot plus long que la largeur étant
25
+ * découpé en morceaux de cette largeur.
26
+ */
27
+ function words(segments, width) {
28
+ const out = [];
29
+ for (const seg of segments) {
30
+ const style = seg.style || ((s) => s);
31
+ for (const w of String(seg.text).split(/\s+/).filter(Boolean)) {
32
+ if (w.length <= width) out.push({ word: w, style });
33
+ else for (let i = 0; i < w.length; i += width) out.push({ word: w.slice(i, i + width), style });
34
+ }
35
+ }
36
+ return out;
37
+ }
38
+
39
+ /** Lignes de mots ({ word, style }[][]) d'au plus `width` caractères */
40
+ function wrapWords(segments, width) {
41
+ width = Math.max(1, Math.floor(width));
42
+ const lines = [];
43
+ let line = [];
44
+ let len = 0;
45
+ for (const w of words(segments, width)) {
46
+ const add = (line.length ? 1 : 0) + w.word.length;
47
+ if (line.length && len + add > width) {
48
+ lines.push(line);
49
+ line = [];
50
+ len = 0;
51
+ }
52
+ len += (line.length ? 1 : 0) + w.word.length;
53
+ line.push(w);
54
+ }
55
+ if (line.length) lines.push(line);
56
+ return lines;
57
+ }
58
+
59
+ const paint = (line) => line.map((w) => w.style(w.word)).join(' ');
60
+
61
+ /** Texte nu coupé aux espaces : tableau de lignes d'au plus `width` caractères */
62
+ function wrap(text, width) {
63
+ return wrapWords([{ text }], width).map((l) => l.map((w) => w.word).join(' '));
64
+ }
65
+
66
+ /** Paragraphe : segments coupés à la largeur, chaque ligne précédée de `indent` espaces */
67
+ function paragraph(segments, { columns = terminalColumns(), indent = 3 } = {}) {
68
+ if (typeof segments === 'string') segments = [{ text: segments }];
69
+ const lines = wrapWords(segments, columns - indent).map(paint);
70
+ return lines.map((l) => ' '.repeat(indent) + l);
71
+ }
72
+
73
+ /**
74
+ * Une ligne de tableau : « name .... description » à deux colonnes, la
75
+ * description en retrait suspendu. Trop étroit pour deux colonnes : la
76
+ * description passe sur ses propres lignes, sous la commande, plus en retrait.
77
+ *
78
+ * name texte nu de la commande (sa largeur compte), nameStyle sa couleur
79
+ * nameWidth largeur de la colonne des commandes (points compris)
80
+ * segments description : [{ text, style }]
81
+ * dots points de conduite entre la commande et la description
82
+ */
83
+ function row({ name, nameStyle = (s) => s, dotStyle = (s) => s, segments, nameWidth, columns = terminalColumns(), indent = 3, gap = 2, dots = true }) {
84
+ if (typeof segments === 'string') segments = [{ text: segments }];
85
+ const pad = ' '.repeat(indent);
86
+ const column = indent + nameWidth + gap;
87
+ if (columns - column < MIN_DESCRIPTION || name.length > nameWidth) {
88
+ const sub = indent + 4;
89
+ // la commande elle-même se coupe si elle dépasse la largeur
90
+ return [...paragraph([{ text: name, style: nameStyle }], { columns, indent }), ...paragraph(segments, { columns, indent: sub })];
91
+ }
92
+ const filler = nameWidth - name.length;
93
+ const leader = dots && filler > 1 ? ' ' + dotStyle('.'.repeat(filler - 1)) : ' '.repeat(filler);
94
+ const lines = wrapWords(segments, columns - column).map(paint);
95
+ if (!lines.length) return [pad + nameStyle(name)];
96
+ return lines.map((l, i) => (i === 0 ? pad + nameStyle(name) + leader + ' '.repeat(gap) : ' '.repeat(column)) + l);
97
+ }
98
+
99
+ module.exports = { terminalColumns, wrap, wrapWords, paragraph, row, visible, FALLBACK_COLUMNS, MIN_COLUMNS, MIN_DESCRIPTION };
package/utils/logline.js CHANGED
@@ -5,8 +5,8 @@ const LEVELS = ['debug', 'info', 'warn', 'error', 'fatal'];
5
5
 
6
6
  // Options de filtre → attribut de la ligne (attrs). Mêmes noms et même sens
7
7
  // que les paramètres de /logs/v1 (services/logs/src/api.ts de l'infra).
8
- const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome' };
9
- const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused' };
8
+ const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome', provider: 'provider', model: 'model', event: 'event' };
9
+ const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused', provider: 'anthropic', model: 'claude-opus-5-5', event: 'ai_default_model_changed' };
10
10
  // Identifiant d'exécution (UUID) entier, ou son début : 8 caractères au moins
11
11
  const RUN_RE = /^[0-9a-f-]{8,36}$/;
12
12
 
@@ -143,8 +143,20 @@ const origin = (r, chalk) => {
143
143
  return '';
144
144
  };
145
145
 
146
- // Résultat d'un appel MCP : ok en vert, refus en jaune, échec en rouge
147
- const OUTCOME_STYLE = { ok: 'green', refused: 'yellow', invalid: 'yellow', not_found: 'yellow', rate_limited: 'yellow', unauthorized: 'redBright', error: 'redBright' };
146
+ // Résultat d'un appel MCP ou IA : ok en vert, refus en jaune, échec en rouge
147
+ const OUTCOME_STYLE = {
148
+ ok: 'green',
149
+ refused: 'yellow',
150
+ invalid: 'yellow',
151
+ not_found: 'yellow',
152
+ rate_limited: 'yellow',
153
+ forbidden: 'yellow',
154
+ no_credential: 'yellow',
155
+ budget_exceeded: 'yellow',
156
+ unauthorized: 'redBright',
157
+ provider_error: 'redBright',
158
+ error: 'redBright',
159
+ };
148
160
  const styleOutcome = (o, chalk) => chalk[OUTCOME_STYLE[o] || 'white'](o);
149
161
 
150
162
  /**
@@ -173,6 +185,32 @@ const mcpParts = (r, chalk) => {
173
185
  return { msg, extra, tail, ms: hasMs || a.tool_ms !== undefined };
174
186
  };
175
187
 
188
+ /**
189
+ * Ligne du service ai (engine 0.30+) : « chat anthropic/claude-opus-5-5 ok (812 ms) », le résultat en couleur,
190
+ * puis les jetons (entrée → sortie), le coût estimé, le statut du fournisseur s'il a refusé. Jamais de contenu
191
+ * (sauf [ai] log_content : prompt_excerpt, reply_excerpt, déjà masqués par l'engine, en gris).
192
+ */
193
+ const aiParts = (r, chalk) => {
194
+ const a = r.attrs || {};
195
+ let msg = String(r.msg);
196
+ const extra = [];
197
+ if (a.outcome) {
198
+ const o = String(a.outcome);
199
+ const re = /^[a-z_]+$/i.test(o) ? new RegExp(`(^|\\s)${o}(?=\\s|$)`) : null;
200
+ if (re && re.test(msg)) msg = msg.replace(re, (all, sp) => `${sp}${styleOutcome(o, chalk)}`);
201
+ else extra.push(styleOutcome(o, chalk));
202
+ }
203
+ if (a.input_tokens !== undefined || a.output_tokens !== undefined) extra.push(`${a.input_tokens || 0}→${a.output_tokens || 0} tok`);
204
+ if (a.cost_usd !== undefined && a.cost_usd !== null) extra.push(require('./ai').usdText(a.cost_usd));
205
+ // Modèle sans prix connu (engine 0.30+) : le coût est inconnu, jamais 0
206
+ else if (a.price === 'unknown') extra.push(chalk.yellow('cost unknown (no price: [ai.prices])'));
207
+ if (a.provider_status && a.outcome !== 'ok') extra.push(chalk.yellow(`HTTP ${a.provider_status}`));
208
+ // Modèle par défaut changé (écran IA) : qui l'a fait
209
+ if (a.event === 'ai_default_model_changed' && a.actor) extra.push(chalk.grey(`by ${a.actor}`));
210
+ const tail = [a.prompt_excerpt, a.reply_excerpt].filter(Boolean).map((t) => chalk.grey(`« ${String(t).slice(0, 120)} »`));
211
+ return { msg, extra, tail, ms: /\(\d+ ms\)$/.test(msg) };
212
+ };
213
+
176
214
  // Droits d'un jeton MCP modifiés (service meta) : les scopes gagnés et perdus
177
215
  const tokenChange = (a, chalk) => {
178
216
  const out = [];
@@ -190,7 +228,7 @@ const formatLine = (r, chalk) => {
190
228
  const time = new Date(r.ts).toISOString().slice(11, 23);
191
229
  const svc = chalk[colorOf(r.service)](r.service.padEnd(WIDTH).slice(0, WIDTH));
192
230
  const lvl = (levelStyle[r.level] || chalk.white)(r.level.padEnd(5));
193
- const mcp = r.service === 'mcp' ? mcpParts(r, chalk) : null;
231
+ const mcp = r.service === 'mcp' ? mcpParts(r, chalk) : r.service === 'ai' ? aiParts(r, chalk) : null;
194
232
  const msg = mcp ? mcp.msg : r.msg;
195
233
  const extra = mcp ? [...mcp.extra] : [];
196
234
  // La durée d'une requête lente de Postgres est déjà dans son message, celle d'un appel MCP aussi
package/utils/mail.js CHANGED
@@ -91,6 +91,7 @@ const stopMailpit = async (docker, config) => {
91
91
 
92
92
  module.exports = {
93
93
  MAILPIT_IMAGE,
94
+ MAIL_ALIAS,
94
95
  networkName,
95
96
  mailContainerName,
96
97
  mailPort,