poad 2.42.0 → 2.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +3 -0
- 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/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 +43 -5
- package/utils/mail.js +1 -0
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,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 };
|
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,
|
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 = {
|
|
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
|