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/utils/logline.js CHANGED
@@ -5,7 +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' };
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' };
9
10
  // Identifiant d'exécution (UUID) entier, ou son début : 8 caractères au moins
10
11
  const RUN_RE = /^[0-9a-f-]{8,36}$/;
11
12
 
@@ -22,7 +23,7 @@ const attrConditions = (args = {}) => {
22
23
  for (const [option, attr] of Object.entries(ATTR_OPTIONS)) {
23
24
  const value = args[option];
24
25
  if (value === undefined) continue;
25
- if (value === true || value === '') return { error: `${option}=<name>: a value is expected, such as ${option}=${option === 'function' ? 'demo-stats' : option === 'step' ? 'appel' : 'demo-flux'}` };
26
+ if (value === true || value === '') return { error: `${option}=<${option === 'outcome' ? 'outcome' : 'name'}>: a value is expected, such as ${option}=${EXAMPLES[option]}` };
26
27
  conditions.push([`attrs->>'${attr}' = ?`, String(value)]);
27
28
  }
28
29
  if (args.run !== undefined) {
@@ -44,6 +45,79 @@ const attrConditions = (args = {}) => {
44
45
  */
45
46
  const fromClause = (cond, prefix) => (prefix ? `(select * from _logs.entries where ${cond} offset 0) e` : `_logs.entries where ${cond}`);
46
47
 
48
+ // Jeton du serveur MCP (engine 0.29+) : poad_mcp_<préfixe de 8>_<secret>.
49
+ // Le préfixe et l'id se montrent (console, lignes du puits), jamais le secret.
50
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
51
+ const ID_START_RE = /^[0-9a-f][0-9a-f-]{7,34}$/;
52
+ const PREFIX_RE = /^[a-z0-9]{8}$/;
53
+
54
+ /**
55
+ * Ce que désigne token=<valeur> : un nom, un id (entier ou son début, 8
56
+ * caractères au moins) ou le préfixe du jeton (8 caractères, ou poad_mcp_<préfixe>).
57
+ * Un jeton entier est refusé, sans le répéter : il n'a rien à faire sur une
58
+ * ligne de commande ni dans l'historique du shell.
59
+ */
60
+ const parseToken = (value) => {
61
+ if (value === undefined) return null;
62
+ if (value === true || String(value).trim() === '') return { error: 'token=<name>: a value is expected, the name, id or prefix of an MCP token, such as token="Claude Code"' };
63
+ const v = String(value).trim();
64
+ if (/^poad_mcp_[a-z0-9]{8}_/i.test(v)) return { error: 'token=: this is an MCP token itself. Give its name, its id or its prefix (poad_mcp_<prefix>), never the token: revoke it if it was shared.' };
65
+ const m = /^poad_mcp_([a-z0-9]{8})$/.exec(v);
66
+ const lower = v.toLowerCase();
67
+ return {
68
+ name: v,
69
+ prefix: m ? m[1] : PREFIX_RE.test(v) ? v : null,
70
+ id: UUID_RE.test(lower) ? lower : null,
71
+ idStart: !UUID_RE.test(lower) && ID_START_RE.test(lower) ? lower : null,
72
+ };
73
+ };
74
+
75
+ /**
76
+ * Ids des jetons de _poad.mcp_tokens que désigne token= : par le nom actuel,
77
+ * le préfixe ou le début de l'id. Couvre les lignes écrites sous un ancien nom.
78
+ * Sans la table (engine avant 0.29) ou sans droit de la lire : aucun.
79
+ */
80
+ const resolveTokenIds = async (client, t) => {
81
+ if (!t || t.error) return [];
82
+ try {
83
+ const exists = await client.query(
84
+ "select to_regclass('_poad.mcp_tokens') is not null as ok, to_regclass('_poad.mcp_token_changes') is not null as changes",
85
+ );
86
+ if (!exists.rows[0] || !exists.rows[0].ok) return [];
87
+ // Un ancien nom (renommage, engine 0.29.1+) : l'historique des droits le garde
88
+ const former = exists.rows[0].changes ? ' union select token_id::text from _poad.mcp_token_changes where name_before = $1 or name_after = $1' : '';
89
+ const r = await client.query(
90
+ `select id::text as id from _poad.mcp_tokens where name = $1 or prefix = $2 or id::text like $3${former}`,
91
+ [t.name, t.prefix || '', t.id || (t.idStart ? `${t.idStart}%` : '')],
92
+ );
93
+ return [...new Set(r.rows.map((row) => row.id))];
94
+ } catch {
95
+ return [];
96
+ }
97
+ };
98
+
99
+ /**
100
+ * Condition de token= sur les lignes de mcp (token_id, token_name, et
101
+ * token_prefix d'un appel refusé) et de meta (mcp_token_updated, mcp_token_revoked).
102
+ * Renvoie [sql avec des ?, ...valeurs].
103
+ */
104
+ const tokenCondition = (t, ids = []) => {
105
+ const all = [...new Set([...ids, ...(t.id ? [t.id] : [])])];
106
+ // name_before : la ligne de meta d'un renommage, sous l'ancien nom
107
+ const parts = ["attrs->>'token_name' = ?", "attrs->>'name_before' = ?", "attrs->>'token_id' = any(?)"];
108
+ const values = [t.name, t.name, all];
109
+ if (t.prefix) {
110
+ parts.push("attrs->>'token_prefix' = ?");
111
+ values.push(t.prefix);
112
+ }
113
+ if (t.idStart) {
114
+ // Ni % ni _ possibles (ID_START_RE) : rien à échapper
115
+ parts.push("attrs->>'token_id' like ?");
116
+ values.push(`${t.idStart}%`);
117
+ }
118
+ return [`(${parts.join(' or ')})`, ...values];
119
+ };
120
+
47
121
  const COLORS = ['cyanBright', 'magentaBright', 'blueBright', 'greenBright', 'yellow', 'cyan', 'magenta', 'blue'];
48
122
  const colorOf = (s) => COLORS[[...s].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7) % COLORS.length];
49
123
  const WIDTH = 8;
@@ -60,9 +134,93 @@ const origin = (r, chalk) => {
60
134
  return a.stream === 'stderr' ? chalk.yellow(`[${a.step}!]`) : chalk.cyan(`[${a.step}]`);
61
135
  }
62
136
  if (a.function && !String(r.msg).includes(String(a.function))) return chalk.cyan(`[${a.function}]`);
137
+ // Appel au serveur MCP : le jeton, par son nom, quand le message ne le dit pas
138
+ // (engine 0.29.0 : « tools/call list_tables ok [nom] » ; meta le dit aussi)
139
+ if (r.service === 'mcp') {
140
+ if (a.token_name) return String(r.msg).includes(String(a.token_name)) ? '' : chalk.cyan(`[${a.token_name}]`);
141
+ if (a.token_prefix) return chalk.yellow(`[poad_mcp_${a.token_prefix}…]`);
142
+ }
63
143
  return '';
64
144
  };
65
145
 
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
+ };
160
+ const styleOutcome = (o, chalk) => chalk[OUTCOME_STYLE[o] || 'white'](o);
161
+
162
+ /**
163
+ * Message d'une ligne du service mcp : outil, résultat (en couleur) et durée de
164
+ * l'outil, que le message les dise déjà (« tools/call select_rows ok (12.4 ms) »)
165
+ * ou non. Renvoie { msg, extra, ms } ; ms : la durée est dite, pas de duration_ms en plus.
166
+ */
167
+ const mcpParts = (r, chalk) => {
168
+ const a = r.attrs || {};
169
+ let msg = String(r.msg);
170
+ const extra = [];
171
+ if (a.tool && !msg.includes(String(a.tool))) extra.push(chalk.cyan(String(a.tool)));
172
+ if (a.outcome) {
173
+ const o = String(a.outcome);
174
+ const re = /^[a-z_]+$/i.test(o) ? new RegExp(`(^|\\s)${o}(?=\\s|$|\\))`) : null;
175
+ if (re && re.test(msg)) msg = msg.replace(re, (all, sp) => `${sp}${styleOutcome(o, chalk)}`);
176
+ else extra.push(styleOutcome(o, chalk));
177
+ }
178
+ const hasMs = /\d ms\)?$/.test(msg) || /\(\d+(\.\d+)? ms\)/.test(msg);
179
+ if (a.tool_ms !== undefined && !hasMs) extra.push(`${a.tool_ms} ms`);
180
+ // La raison d'un refus, sauf si le message la dit (« POST /mcp/v1 401 revoked »)
181
+ const reason = a.reason ? String(a.reason) : '';
182
+ if (reason && !(/^[a-z_]+$/i.test(reason) && new RegExp(`(^|\\s)${reason}(\\s|$)`).test(msg))) extra.push(chalk.yellow(reason));
183
+ // Les noms des arguments (jamais leur valeur), en dernier
184
+ const tail = Array.isArray(a.arg_keys) && a.arg_keys.length ? [chalk.grey(`args: ${a.arg_keys.join(',')}`)] : [];
185
+ return { msg, extra, tail, ms: hasMs || a.tool_ms !== undefined };
186
+ };
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
+
214
+ // Droits d'un jeton MCP modifiés (service meta) : les scopes gagnés et perdus
215
+ const tokenChange = (a, chalk) => {
216
+ const out = [];
217
+ if (a.name_before && a.token_name && a.name_before !== a.token_name) out.push(chalk.grey(`renamed from « ${a.name_before} »`));
218
+ if (Array.isArray(a.scopes_added) && a.scopes_added.length) out.push(chalk.yellow(a.scopes_added.map((s) => `+${s}`).join(' ')));
219
+ if (Array.isArray(a.scopes_removed) && a.scopes_removed.length) out.push(chalk.grey(a.scopes_removed.map((s) => `-${s}`).join(' ')));
220
+ if (a.expiry && a.expiry !== 'unchanged') out.push(`expiry ${a.expiry}${a.expires_at_after ? ` ${String(a.expires_at_after).slice(0, 10)}` : ''}`);
221
+ return out;
222
+ };
223
+
66
224
  /** Texte d'une entrée de _logs.entries (une ligne, plus la pile d'une erreur) */
67
225
  const formatLine = (r, chalk) => {
68
226
  const a = r.attrs || {};
@@ -70,19 +228,23 @@ const formatLine = (r, chalk) => {
70
228
  const time = new Date(r.ts).toISOString().slice(11, 23);
71
229
  const svc = chalk[colorOf(r.service)](r.service.padEnd(WIDTH).slice(0, WIDTH));
72
230
  const lvl = (levelStyle[r.level] || chalk.white)(r.level.padEnd(5));
73
- const extra = [];
74
- // La durée d'une requête lente de Postgres est déjà dans son message
75
- if (a.duration_ms !== undefined && r.service !== 'postgres') extra.push(`${a.duration_ms} ms`);
231
+ const mcp = r.service === 'mcp' ? mcpParts(r, chalk) : r.service === 'ai' ? aiParts(r, chalk) : null;
232
+ const msg = mcp ? mcp.msg : r.msg;
233
+ const extra = mcp ? [...mcp.extra] : [];
234
+ // La durée d'une requête lente de Postgres est déjà dans son message, celle d'un appel MCP aussi
235
+ if (a.duration_ms !== undefined && r.service !== 'postgres' && !(mcp && mcp.ms)) extra.push(`${a.duration_ms} ms`);
76
236
  if (a.role) extra.push(a.role);
237
+ if (r.service === 'meta' && /^mcp_token_/.test(a.event || '')) extra.push(...tokenChange(a, chalk));
77
238
  if (a.error_code || a.error) extra.push(chalk.yellow([a.error_code, a.error].filter(Boolean).join(': ')));
78
239
  if (a.err && a.err.message) extra.push(chalk.redBright(a.err.message));
79
240
  if (a.sql) extra.push(chalk.grey(String(a.sql).replace(/\s+/g, ' ').slice(0, 160)));
80
241
  if (a.statement && r.service === 'postgres') extra.push(chalk.grey(String(a.statement).replace(/\s+/g, ' ').slice(0, 160)));
242
+ if (mcp) extra.push(...mcp.tail);
81
243
  const req = r.request_id ? chalk.grey(` ·${r.request_id.slice(0, 8)}`) : '';
82
244
  const from = origin(r, chalk);
83
- let text = `${chalk.grey(time)} ${svc} ${lvl} ${from ? `${from} ` : ''}${r.msg}${extra.length ? ' ' + extra.join(' ') : ''}${req}`;
245
+ let text = `${chalk.grey(time)} ${svc} ${lvl} ${from ? `${from} ` : ''}${msg}${extra.length ? ' ' + extra.join(' ') : ''}${req}`;
84
246
  if (a.err && a.err.stack && r.level !== 'debug') text += '\n' + chalk.grey(String(a.err.stack).split('\n').slice(1, 6).join('\n'));
85
247
  return text;
86
248
  };
87
249
 
88
- module.exports = { LEVELS, ATTR_OPTIONS, attrConditions, fromClause, formatLine };
250
+ module.exports = { LEVELS, ATTR_OPTIONS, attrConditions, fromClause, formatLine, parseToken, resolveTokenIds, tokenCondition };
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,