oft-agt 0.0.0-stage → 0.5.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.
@@ -0,0 +1,85 @@
1
+ // Public diagnostics only. Never interpolate Discord error.message, request bodies or URLs.
2
+ const ERRORS = {
3
+ MESSAGE_SEND_FAILED: ['Envoi impossible', 'Le message n’a pas pu être envoyé. Vérifiez le salon, les accès et le contenu.'],
4
+ MESSAGE_EDIT_FAILED: ['Modification impossible', 'Le message n’a pas pu être modifié. Vérifiez qu’il existe et appartient au bot.'],
5
+ MESSAGE_DELETE_FAILED: ['Suppression impossible', 'Le message n’a pas pu être supprimé. Vérifiez son existence et les permissions du bot.'],
6
+ CHANNEL_UNAVAILABLE: ['Salon inaccessible', 'Le salon est introuvable ou ne permet pas d’envoyer de messages.'],
7
+ USER_UNAVAILABLE: ['Destinataire inaccessible', 'L’utilisateur est introuvable ou ne peut pas recevoir de message privé.'],
8
+ MESSAGE_NOT_FOUND: ['Message introuvable', 'Le message cible n’existe plus ou le bloc qui devait l’envoyer n’a pas encore été exécuté.'],
9
+ MESSAGE_EMPTY: ['Message vide', 'Ajoutez du texte ou au moins un embed renseigné.'],
10
+ MESSAGE_TOO_LONG: ['Message trop long', 'Le texte du message dépasse 2 000 caractères. Réduisez-le ou utilisez un embed.'],
11
+ TOO_MANY_EMBEDS: ['Trop d’embeds', 'Un message du Builder accepte au maximum 5 embeds.'],
12
+ EMBED_TITLE_TOO_LONG: ['Titre d’embed trop long', 'Le titre d’un embed dépasse 256 caractères.'],
13
+ EMBED_DESCRIPTION_TOO_LONG: ['Description d’embed trop longue', 'La description d’un embed dépasse 4 096 caractères.'],
14
+ EMBED_AUTHOR_TOO_LONG: ['Auteur d’embed trop long', 'Le nom de l’auteur d’un embed dépasse 256 caractères.'],
15
+ EMBED_FOOTER_TOO_LONG: ['Pied de page trop long', 'Le pied de page d’un embed dépasse 2 048 caractères.'],
16
+ EMBED_FIELDS_INVALID: ['Champs d’embed invalides', 'Utilisez au maximum 25 champs par embed, avec un nom de 1 à 256 caractères et une valeur de 1 à 1 024 caractères.'],
17
+ EMBEDS_TOO_LARGE: ['Embeds trop volumineux', 'Le texte de l’ensemble des embeds dépasse 6 000 caractères.'],
18
+ MESSAGE_INVALID: ['Message invalide', 'Vérifiez les champs obligatoires, la couleur, les URL des images et les identifiants de destination.'],
19
+ INVALID_WAIT: ['Délai invalide', 'Le délai doit être un nombre compris entre 0 et 300 secondes.'],
20
+ TIMEOUT: ['Délai dépassé', 'L’action a dépassé son délai maximal. Vérifiez la connexion et réduisez les attentes.'],
21
+ NETWORK_ERROR: ['Connexion interrompue', 'La connexion à Discord a échoué. Vérifiez le réseau du serveur puis réessayez.'],
22
+ RATE_LIMITED: ['Trop de requêtes', 'Discord limite temporairement les actions du bot. Attendez avant de réessayer.'],
23
+ DISCORD_UNAVAILABLE: ['Discord indisponible', 'Discord rencontre une erreur temporaire. Réessayez dans quelques instants.'],
24
+ EXECUTION_FAILED: ['Erreur d’exécution', 'L’action n’a pas pu être effectuée. Vérifiez sa configuration et les accès du bot.'],
25
+ };
26
+ const DISCORD = {
27
+ 10003: ['Salon introuvable', 'Le salon a été supprimé ou son identifiant est incorrect.'],
28
+ 10008: ['Message introuvable', 'Le message a été supprimé ou son identifiant est incorrect.'],
29
+ 10013: ['Utilisateur introuvable', 'Vérifiez l’identifiant du destinataire.'],
30
+ 10062: ['Commande expirée', 'Le délai de réponse de la commande est dépassé.'],
31
+ 40005: ['Message trop volumineux', 'Réduisez la taille du message ou de ses pièces jointes.'],
32
+ 40058: ['Salon forum incompatible', 'Envoyez le message dans un salon textuel ou dans un fil existant du forum.'],
33
+ 40060: ['Commande déjà acquittée', 'Cette commande a déjà reçu une réponse initiale. Utilisez une modification ou une réponse supplémentaire.'],
34
+ 40094: ['Trop de réponses', 'La limite de réponses supplémentaires de cette commande est atteinte.'],
35
+ 50001: ['Accès refusé', 'Le bot ne peut pas accéder à cette ressource.'],
36
+ 50005: ['Modification interdite', 'Un bot ne peut modifier que ses propres messages.'],
37
+ 50006: ERRORS.MESSAGE_EMPTY,
38
+ 50007: ['Message privé impossible', 'Le destinataire ne peut pas recevoir de messages privés.'],
39
+ 50008: ['Salon incompatible', 'Ce salon ne permet pas l’envoi de messages textuels.'],
40
+ 50013: ['Permissions insuffisantes', 'Vérifiez les permissions Voir le salon, Envoyer des messages, Intégrer des liens et, pour une suppression, Gérer les messages.'],
41
+ 50014: ['Authentification refusée', 'Le token du bot est invalide ou révoqué. Remplacez-le depuis Paramètres.'],
42
+ 50021: ['Message système protégé', 'Discord interdit cette action sur un message système.'],
43
+ 50024: ['Action incompatible', 'Cette action n’est pas disponible dans ce type de salon.'],
44
+ 50034: ['Messages trop anciens', 'Discord refuse la suppression groupée de messages de plus de 14 jours.'],
45
+ 50035: ['Contenu refusé par Discord', 'Vérifiez la taille du message, des embeds, des champs et les formats des paramètres.'],
46
+ 50045: ['Fichier trop volumineux', 'La pièce jointe dépasse la taille autorisée par Discord.'],
47
+ 50083: ['Fil archivé', 'Désarchivez le fil avant d’y envoyer ou d’y modifier un message.'],
48
+ 200000: ['Message bloqué par AutoMod', 'Le contenu du message a été refusé par la modération automatique du serveur.'],
49
+ 240000: ['Lien bloqué', 'Discord a bloqué un lien jugé dangereux dans le message.'],
50
+ };
51
+ export function runtimeError(code, operation, cause) {
52
+ return Object.assign(new Error(code), { code, operation, cause });
53
+ }
54
+ export function errorVariables(error, action, blockId) {
55
+ let current = error, diagnostic, code;
56
+ for (let depth = 0; current && depth < 5; depth++, current = current.cause) {
57
+ if (Object.hasOwn(DISCORD, current.code)) { diagnostic = DISCORD[current.code]; code = 'DISCORD_' + current.code; break; }
58
+ if (Object.hasOwn(ERRORS, current.code)) { diagnostic = ERRORS[current.code]; code = current.code; break; }
59
+ if (current.name === 'AbortError' || current.name === 'TimeoutError') code = 'TIMEOUT';
60
+ else if (['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ETIMEDOUT', 'EAI_AGAIN', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_SOCKET'].includes(current.code)) code = current.code === 'ETIMEDOUT' ? 'TIMEOUT' : 'NETWORK_ERROR';
61
+ else if (current.status === 429) code = 'RATE_LIMITED';
62
+ else if (Number.isInteger(current.status) && current.status >= 500 && current.status <= 599) code = 'DISCORD_UNAVAILABLE';
63
+ if (code) { diagnostic = ERRORS[code]; break; }
64
+ }
65
+ const fallback = { sendMessage: 'MESSAGE_SEND_FAILED', editMessage: 'MESSAGE_EDIT_FAILED', deleteMessage: 'MESSAGE_DELETE_FAILED' };
66
+ const requested = error?.operation || action;
67
+ code ||= Object.hasOwn(fallback, requested) ? fallback[requested] : 'EXECUTION_FAILED'; diagnostic ||= ERRORS[code];
68
+ const operations = { sendMessage: 'L’envoi du message a échoué.', editMessage: 'La modification du message a échoué.', deleteMessage: 'La suppression du message a échoué.', wait: 'L’attente a été interrompue.' };
69
+ const operation = Object.hasOwn(operations, error?.operation) ? error.operation : action;
70
+ const safeBlockId = typeof blockId === 'string' && /^[\w-]{1,64}$/.test(blockId) ? blockId : '';
71
+ return { error_name: diagnostic[0], error_desc: operations[operation] || 'La commande n’a pas pu être exécutée.', error_reason: diagnostic[1], error_code: code, error_block_id: safeBlockId };
72
+ }
73
+
74
+ export function validateMessage(config) {
75
+ if ((config.text || '').length > 2000) throw runtimeError('MESSAGE_TOO_LONG');
76
+ if ((config.embeds || []).length > 5) throw runtimeError('TOO_MANY_EMBEDS');
77
+ let total = 0;
78
+ for (const embed of config.embeds || []) {
79
+ for (const [value, limit, code] of [[embed.title, 256, 'EMBED_TITLE_TOO_LONG'], [embed.description, 4096, 'EMBED_DESCRIPTION_TOO_LONG'], [embed.author?.name, 256, 'EMBED_AUTHOR_TOO_LONG'], [embed.footer?.text, 2048, 'EMBED_FOOTER_TOO_LONG']]) { if ((value || '').length > limit) throw runtimeError(code); total += (value || '').length; }
80
+ if ((embed.fields || []).length > 25 || (embed.fields || []).some(field => !field.name?.trim() || !field.value?.trim() || field.name.length > 256 || field.value.length > 1024)) throw runtimeError('EMBED_FIELDS_INVALID');
81
+ total += (embed.fields || []).reduce((sum, field) => sum + field.name.length + field.value.length, 0);
82
+ }
83
+ if (total > 6000) throw runtimeError('EMBEDS_TOO_LARGE');
84
+ if (!config.text?.trim() && !config.embeds?.length) throw runtimeError('MESSAGE_EMPTY');
85
+ }
@@ -0,0 +1,75 @@
1
+ import { matchesCondition, validateCondition } from './conditions.mjs';
2
+ import { resolveOptions, interpolateOptions } from './options.mjs';
3
+ import { FUNCTIONS } from './functions.mjs';
4
+ import { errorVariables } from './errors.mjs';
5
+ export { errorVariables } from './errors.mjs';
6
+
7
+ /** Each invocation gets its own context; no messages or secrets are shared across users. */
8
+ export async function executeCommand(command, interaction, client, options = {}) {
9
+ const registry = options.functions || FUNCTIONS;
10
+ let count = 0;
11
+ function validate(calls, depth = 0) {
12
+ if (!Array.isArray(calls) || depth > 32) throw new Error('Plan d’exécution invalide.');
13
+ for (const call of calls) {
14
+ if (++count > 500) throw new Error('Plan d’exécution trop volumineux.');
15
+ if (call.fn === 'condition') {
16
+ const { rules } = validateCondition(call.args?.kind, call.args);
17
+ if (!Array.isArray(call.branches) || call.branches.length !== rules.length || !call.otherwise) throw new Error('Branches invalides.');
18
+ rules.forEach((rule, index) => { if (call.branches[index].ruleId !== rule.id) throw new Error('Branche invalide.'); validate(call.branches[index].calls, depth + 1); });
19
+ validate(call.otherwise.calls, depth + 1);
20
+ } else if (!Object.hasOwn(registry, call.fn)) throw new Error('Fonction inconnue.');
21
+ }
22
+ }
23
+ const errorCalls = command.errorCalls || [];
24
+ validate(command.calls); validate(errorCalls);
25
+ const optionValues = { ...resolveOptions(command.options, interaction), user_id: interaction.user?.id || '', user_name: interaction.user?.username || '', channel_id: interaction.channelId || '' };
26
+ function select(calls, variables = optionValues) {
27
+ return calls.flatMap(call => {
28
+ if (call.fn !== 'condition') return [call];
29
+ const args = interpolateOptions(call.args, variables);
30
+ const index = args.rules.findIndex(rule => matchesCondition(args.kind, rule, interaction));
31
+ return select(index < 0 ? call.otherwise.calls : call.branches[index].calls, variables);
32
+ });
33
+ }
34
+ const selectedCalls = select(command.calls);
35
+ const firstReply = [...selectedCalls].find(call => call.fn === 'sendMessage' && call.args.sendMode === 'reply' && call.args.replyMode === 'command');
36
+ const privateAck = !firstReply || Boolean(firstReply.args.ephemeral);
37
+ await interaction.deferReply(privateAck ? { flags: 64 } : {});
38
+ const context = { interaction, client, messages: new Map(), hasCommandReply: false, signal: options.signal || AbortSignal.timeout(870_000) };
39
+ let failedCall;
40
+ try { for (const call of selectedCalls) {
41
+ failedCall = call;
42
+ context.signal.throwIfAborted();
43
+ const result = await registry[call.fn](context, interpolateOptions(call.args, optionValues));
44
+ if (call.fn === 'sendMessage') context.messages.set(call.id, result);
45
+ } } catch (error) {
46
+ options.onError?.();
47
+ if (!errorCalls.length) throw error;
48
+ const variables = errorVariables(error, failedCall?.fn, failedCall?.id);
49
+ // A fresh, bounded error context prevents an expired main signal from skipping the handler.
50
+ context.signal = AbortSignal.timeout(30000);
51
+ for (const call of select(errorCalls, { ...optionValues, ...variables })) {
52
+ context.signal.throwIfAborted();
53
+ const result = await registry[call.fn](context, interpolateError(interpolateOptions(call.args, optionValues), variables));
54
+ if (call.fn === 'sendMessage') context.messages.set(call.id, result);
55
+ }
56
+ }
57
+ // For commands that only send externally, remove the private loading acknowledgement.
58
+ if (!context.hasCommandReply) await interaction.deleteReply();
59
+ return context.messages;
60
+ }
61
+
62
+ export function interpolateError(args, variables) {
63
+ const result = structuredClone(args);
64
+ const replace = (value, max) => typeof value === 'string' ? value.replace(/\{(error_name|error_desc|error_reason|error_code|error_block_id)\}/g, (_, key) => variables[key] || '').slice(0, max) : value;
65
+ result.text = replace(result.text, 2000);
66
+ let remaining = 6000;
67
+ const embedText = (value, max) => { const text = replace(value, Math.min(max, remaining)); remaining -= text?.length || 0; return text; };
68
+ for (const embed of result.embeds || []) {
69
+ embed.title = embedText(embed.title, 256); embed.description = embedText(embed.description, 4096);
70
+ if (embed.author) embed.author.name = embedText(embed.author.name, 256);
71
+ if (embed.footer) embed.footer.text = embedText(embed.footer.text, 2048);
72
+ for (const field of embed.fields || []) { field.name = embedText(field.name, 256); field.value = embedText(field.value, 1024); }
73
+ }
74
+ return result;
75
+ }
@@ -0,0 +1,48 @@
1
+ import { setTimeout } from 'node:timers/promises';
2
+ import { normalizeMessageConfig, messageConfigError, discordMessagePayload } from './message-config.mjs';
3
+ import { runtimeError, validateMessage } from './errors.mjs';
4
+
5
+ async function sendMessage(context, parameters) {
6
+ const config = normalizeMessageConfig(parameters);
7
+ validateMessage(config);
8
+ const error = messageConfigError(config, undefined, false);
9
+ if (error) throw runtimeError('MESSAGE_INVALID');
10
+ const payload = discordMessagePayload(config);
11
+ const { interaction, client, messages } = context;
12
+ if (config.sendMode === 'channel') {
13
+ const channel = config.channelMode === 'id' ? await client.channels.fetch(config.channelId) : interaction.channel;
14
+ if (!channel?.send) throw runtimeError('CHANNEL_UNAVAILABLE');
15
+ return channel.send(payload);
16
+ }
17
+ if (config.sendMode === 'dm') {
18
+ const user = config.dmMode === 'id' ? await client.users.fetch(config.userId) : interaction.user;
19
+ if (!user?.send) throw runtimeError('USER_UNAVAILABLE');
20
+ return user.send(payload);
21
+ }
22
+ if (config.replyMode === 'block' || config.replyMode === 'message') {
23
+ const message = config.replyMode === 'block' ? messages.get(config.targetBlockId) : await interaction.channel?.messages.fetch(config.messageId);
24
+ if (!message?.reply) throw runtimeError('MESSAGE_NOT_FOUND');
25
+ return message.reply(payload);
26
+ }
27
+ if (!context.hasCommandReply) {
28
+ const message = await interaction.editReply(payload);
29
+ context.hasCommandReply = true;
30
+ return message;
31
+ }
32
+ return interaction.followUp({ ...payload, ...(config.ephemeral ? { flags: 64 } : {}) });
33
+ }
34
+
35
+ async function wait(context, { seconds }) {
36
+ if (!Number.isFinite(seconds) || seconds < 0 || seconds > 300) throw runtimeError('INVALID_WAIT');
37
+ await setTimeout(seconds * 1000, undefined, { signal: context.signal });
38
+ }
39
+
40
+ async function deleteMessage(context, parameters) {
41
+ if (parameters.deleteMode === 'manual' && !/^\d{17,20}$/.test(parameters.messageId || '')) throw runtimeError('MESSAGE_INVALID');
42
+ const message = parameters.deleteMode === 'block' ? context.messages.get(parameters.targetBlockId) : await context.interaction.channel?.messages.fetch(parameters.messageId);
43
+ if (!message?.delete) throw runtimeError('MESSAGE_NOT_FOUND');
44
+ await message.delete();
45
+ }
46
+
47
+ // Extend this registry together with compiler validation when adding a new block type.
48
+ export const FUNCTIONS = Object.freeze(Object.assign(Object.create(null), Object.fromEntries(Object.entries({ sendMessage, wait, deleteMessage }).map(([name, fn]) => [name, async (context, args) => { try { return await fn(context, args); } catch (error) { throw runtimeError(undefined, name, error); } }]))));
@@ -0,0 +1,124 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { readFile, writeFile, open, unlink, mkdir, rename, stat, rm, realpath, link } from 'node:fs/promises';
3
+ import { randomUUID } from 'node:crypto';
4
+ import path from 'node:path';
5
+
6
+ const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
7
+ export async function ensureLocalLauncher(home, source) {
8
+ if (path.dirname(source) !== path.join(home, 'versions')) return;
9
+ const installation = path.join(home, 'installation');
10
+ const entry = path.join(installation, 'cli.mjs');
11
+ const marker = '// Oftone stable local launcher';
12
+ const old = await readFile(entry, 'utf8');
13
+ if (old.includes(marker)) return;
14
+ // Keep the old installation runnable if an update is rolled back to it.
15
+ await writeFile(path.join(installation, 'cli-base.mjs.tmp'), old, { mode: 0o700 });
16
+ await rename(path.join(installation, 'cli-base.mjs.tmp'), path.join(installation, 'cli-base.mjs'));
17
+ const launcher = `#!/usr/bin/env node
18
+ ${marker}
19
+ import{readFile}from'node:fs/promises';import path from'node:path';import{fileURLToPath,pathToFileURL}from'node:url';
20
+ const home=path.dirname(path.dirname(fileURLToPath(import.meta.url)));
21
+ let directory='installation';try{directory=JSON.parse(await readFile(path.join(home,'agent-release.json'),'utf8')).directory;}catch{}
22
+ if(!/^(installation|versions\\/[0-9.]+-[a-f0-9]{64})$/.test(directory))throw new Error('État local de version invalide.');
23
+ await import(pathToFileURL(directory==='installation'?path.join(home,'installation','cli-base.mjs'):path.join(home,directory,'cli.mjs')).href);
24
+ `;
25
+ await writeFile(entry + '.tmp', launcher, { mode: 0o700 }); await rename(entry + '.tmp', entry);
26
+ }
27
+ export const alive = pid => {
28
+ if (!Number.isInteger(pid) || pid < 1) return false;
29
+ try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
30
+ };
31
+ async function record(home) {
32
+ try {
33
+ const value = JSON.parse(await readFile(path.join(home, 'daemon.json'), 'utf8'));
34
+ return /^[a-f0-9-]{36}$/.test(value.nonce || '') && alive(value.pid) ? value : null;
35
+ } catch (error) { if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error; return null; }
36
+ }
37
+ export async function localStatus(home) {
38
+ const daemon = await record(home);
39
+ let worker = null;
40
+ try { const pid = Number(await readFile(path.join(home, 'agent.lock'), 'utf8')); if (alive(pid)) worker = pid; } catch {}
41
+ return { running: Boolean(daemon && worker), starting: Boolean(daemon && !worker), legacy: Boolean(!daemon && worker), daemon };
42
+ }
43
+ export async function startBackground(home, fallback, { timeout = 20000, execArgv = process.execArgv } = {}) {
44
+ const status = await localStatus(home);
45
+ if (status.daemon) return status;
46
+ if (status.legacy) throw new Error('LEGACY_FOREGROUND');
47
+ await mkdir(home, { recursive: true, mode: 0o700 });
48
+ const log = path.join(home, 'agent.log');
49
+ try { if ((await stat(log)).size > 5_000_000) await rename(log, log + '.previous'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
50
+ const output = await open(log, 'a', 0o600);
51
+ const nonce = randomUUID();
52
+ let daemon;
53
+ try {
54
+ daemon = spawn(process.execPath, [...execArgv, path.join(fallback, 'cli.mjs'), 'daemon', `--run-id=${nonce}`], { detached: true, windowsHide: true, shell: false, cwd: home, env: { ...process.env, OFTONE_AGENT_HOME: home }, stdio: ['ignore', output.fd, output.fd] });
55
+ await new Promise((resolve, reject) => { daemon.once('spawn', resolve); daemon.once('error', reject); });
56
+ daemon.unref();
57
+ } finally { await output.close(); }
58
+ const deadline = Date.now() + timeout;
59
+ while (Date.now() < deadline) {
60
+ const current = await localStatus(home);
61
+ if (current.running) return current;
62
+ if (!alive(daemon.pid)) throw new Error('DAEMON_START_FAILED');
63
+ await wait(100);
64
+ }
65
+ throw new Error('DAEMON_START_TIMEOUT');
66
+ }
67
+ export async function stopBackground(home, { timeout = 90000 } = {}) {
68
+ const status = await localStatus(home);
69
+ if (status.legacy) throw new Error('LEGACY_FOREGROUND');
70
+ if (!status.daemon) return;
71
+ // A run-specific file requests graceful shutdown; never kill an unrelated reused PID.
72
+ await writeFile(path.join(home, 'daemon-stop.json'), JSON.stringify({ nonce: status.daemon.nonce }), { mode: 0o600 });
73
+ const deadline = Date.now() + timeout;
74
+ while (Date.now() < deadline) {
75
+ const current = await record(home);
76
+ if (!current || current.nonce !== status.daemon.nonce) return;
77
+ await wait(100);
78
+ }
79
+ throw new Error('DAEMON_STOP_TIMEOUT');
80
+ }
81
+ export async function managedDaemon(home, fallback, nonce, supervise) {
82
+ if (!/^[a-f0-9-]{36}$/.test(nonce || '')) throw new Error('DAEMON_INVALID');
83
+ const file = path.join(home, 'daemon.json');
84
+ const temporary = path.join(home, `daemon-${nonce}.tmp`);
85
+ await writeFile(temporary, JSON.stringify({ pid: process.pid, nonce }), { mode: 0o600, flag: 'wx' });
86
+ // Linking a complete record is atomic: concurrent starts cannot read a partial PID file.
87
+ try {
88
+ try { await link(temporary, file); }
89
+ catch (error) {
90
+ if (error.code !== 'EEXIST') throw error;
91
+ if (await record(home)) throw new Error('AGENT_ACTIVE');
92
+ await unlink(file); await link(temporary, file);
93
+ }
94
+ } finally { await unlink(temporary); }
95
+ const previousMarker = process.env.OFTONE_MANAGED_DAEMON;
96
+ process.env.OFTONE_MANAGED_DAEMON = '1';
97
+ try {
98
+ await supervise(home, fallback, { shouldStop: async () => {
99
+ try { return JSON.parse(await readFile(path.join(home, 'daemon-stop.json'), 'utf8')).nonce === nonce; } catch { return false; }
100
+ } });
101
+ } finally {
102
+ if (previousMarker === undefined) delete process.env.OFTONE_MANAGED_DAEMON; else process.env.OFTONE_MANAGED_DAEMON = previousMarker;
103
+ try { if (JSON.parse(await readFile(file, 'utf8')).nonce === nonce) await unlink(file); } catch {}
104
+ try { const stop = path.join(home, 'daemon-stop.json'); if (JSON.parse(await readFile(stop, 'utf8')).nonce === nonce) await unlink(stop); } catch {}
105
+ }
106
+ }
107
+ export async function readLogs(home) {
108
+ try {
109
+ const file = await open(path.join(home, 'agent.log'), 'r');
110
+ try { const size = (await file.stat()).size, buffer = Buffer.alloc(Math.min(size, 65536)); await file.read(buffer, 0, buffer.length, Math.max(0, size - buffer.length)); return buffer.toString('utf8').split('\n').slice(-101).join('\n'); }
111
+ finally { await file.close(); }
112
+ } catch (error) { if (error.code === 'ENOENT') return 'Aucun journal pour cette instance.\n'; throw error; }
113
+ }
114
+ export async function removeLocalInstance(home, base, config) {
115
+ await stopBackground(home);
116
+ const directory = await realpath(home), root = await realpath(base);
117
+ const scoped = path.join(root, 'instances', config.object, config.agentId);
118
+ // Scope recursive removal to the selected agent; legacy homes may contain other bots.
119
+ if (directory === scoped && /^[a-f0-9]{64}$/.test(config.object || '') && /^[a-f0-9-]{36}$/.test(config.agentId || '')) {
120
+ await rm(directory, { recursive: true }); return;
121
+ }
122
+ if (directory !== root) throw new Error('INSTANCE_INVALID');
123
+ for (const item of ['installation', 'versions', 'releases', 'agent.json', 'agent.json.tmp', 'private.pem', 'discord-secret.json', 'auth-rotation.json', 'auth-rotation.json.tmp', 'auth-operation.lock', 'private.pem.tmp', 'discord-secret.json.tmp', 'agent-release.json', 'active.json', 'paused.json', 'agent.lock', 'daemon.json', 'daemon-stop.json', 'agent.log', 'agent.log.previous', 'usage.json']) await rm(path.join(directory, item), { recursive: true, force: true });
124
+ }
@@ -0,0 +1,73 @@
1
+ export function normalizeMessageConfig(config = {}) {
2
+ const legacyChannel = !config.sendMode && config.replyMode === 'manual';
3
+ return {
4
+ ...config,
5
+ text: config.text || '',
6
+ embeds: Array.isArray(config.embeds) ? config.embeds : [],
7
+ sendMode: config.sendMode || (legacyChannel ? 'channel' : 'reply'),
8
+ replyMode: ['block', 'message'].includes(config.replyMode) ? config.replyMode : 'command',
9
+ targetBlockId: config.targetBlockId || '',
10
+ messageId: config.messageId || '',
11
+ channelMode: config.channelMode || (legacyChannel ? 'id' : 'current'),
12
+ channelId: config.channelId || (legacyChannel ? config.replyTarget || '' : ''),
13
+ dmMode: config.dmMode || 'author',
14
+ userId: config.userId || '',
15
+ ephemeral: Boolean(config.ephemeral),
16
+ };
17
+ }
18
+
19
+ export function safeMessageUrl(value) {
20
+ if (!value) return '';
21
+ try {
22
+ const url = new URL(value);
23
+ return ['https:', 'http:'].includes(url.protocol) ? url.href : '';
24
+ } catch { return ''; }
25
+ }
26
+
27
+ export function messageConfigError(raw, nodes, allowVariables = true) {
28
+ const config = normalizeMessageConfig(raw);
29
+ if (!config.text.trim() && !config.embeds.length) return 'Ajoutez du texte ou un embed au message.';
30
+ if (config.text.length > 2000) return 'Le message est limité à 2 000 caractères.';
31
+ if (config.embeds.length > 5) return 'Vous pouvez ajouter au maximum 5 embeds.';
32
+ let total = 0;
33
+ for (const [index, embed] of config.embeds.entries()) {
34
+ const fields = embed.fields || [];
35
+ const texts = [embed.title || '', embed.description || '', embed.author?.name || '', embed.footer?.text || ''];
36
+ if (!texts.some(Boolean) && !embed.image?.url && !embed.thumbnail?.url && !fields.length) return `Complétez l’embed ${index + 1} ou supprimez-le.`;
37
+ if (texts[0].length > 256 || texts[1].length > 4096 || texts[2].length > 256 || texts[3].length > 2048) return `Un texte de l’embed ${index + 1} dépasse la limite autorisée.`;
38
+ if (fields.length > 25 || fields.some(field => !field.name?.trim() || !field.value?.trim() || field.name.length > 256 || field.value.length > 1024)) return `Vérifiez les champs de l’embed ${index + 1} (nom et valeur requis).`;
39
+ if (embed.color && !/^#[a-f\d]{6}$/i.test(embed.color) && !(Number.isInteger(embed.color) && embed.color >= 0 && embed.color <= 0xffffff)) return `Vérifiez la couleur de l’embed ${index + 1}.`;
40
+ for (const url of [embed.url, embed.author?.url, embed.author?.icon_url, embed.footer?.icon_url, embed.image?.url, embed.thumbnail?.url]) {
41
+ const previewUrl = allowVariables && typeof url === 'string' ? url.replace(/\{[a-z0-9_-]+_option(?:_(?:id|name|displayName|avatar))?\}/g, 'https://example.com') : url;
42
+ if (url && !safeMessageUrl(previewUrl)) return `Utilisez une URL http ou https valide dans l’embed ${index + 1}.`;
43
+ }
44
+ if ((embed.author?.url || embed.author?.icon_url) && !embed.author?.name) return `Renseignez le nom de l’auteur dans l’embed ${index + 1}.`;
45
+ if (embed.footer?.icon_url && !embed.footer?.text) return `Renseignez le pied de page dans l’embed ${index + 1}.`;
46
+ total += texts.reduce((sum, text) => sum + text.length, 0) + fields.reduce((sum, field) => sum + field.name.length + field.value.length, 0);
47
+ }
48
+ if (total > 6000) return 'L’ensemble des embeds est limité à 6 000 caractères.';
49
+ if (config.sendMode === 'reply' && config.replyMode === 'block' && (!config.targetBlockId || (nodes && !nodes.some(node => (node.id === config.targetBlockId && (node.type === 'sendMessage' || node.data?.kind === 'message')))))) return 'Choisissez un bloc de message existant.';
50
+ const needsId = config.sendMode === 'reply' && config.replyMode === 'message' ? config.messageId : config.sendMode === 'channel' && config.channelMode === 'id' ? config.channelId : config.sendMode === 'dm' && config.dmMode === 'id' ? config.userId : null;
51
+ if (needsId !== null && !/^\d{17,20}$/.test(needsId) && !(allowVariables && /^\{[a-z0-9_-]+_option(?:_id)?\}$/.test(needsId))) return 'Renseignez un ID Discord valide (17 à 20 chiffres).';
52
+ return '';
53
+ }
54
+
55
+ export function discordMessagePayload(raw) {
56
+ const config = normalizeMessageConfig(raw);
57
+ return {
58
+ ...(config.text ? { content: config.text } : {}),
59
+ allowedMentions: { parse: [] },
60
+ embeds: config.embeds.map(embed => ({
61
+ ...(embed.title ? { title: embed.title } : {}),
62
+ ...(embed.description ? { description: embed.description } : {}),
63
+ ...(safeMessageUrl(embed.url) ? { url: safeMessageUrl(embed.url) } : {}),
64
+ ...(embed.color !== undefined && embed.color !== '' ? { color: typeof embed.color === 'number' ? embed.color : parseInt(embed.color.slice(1), 16) } : {}),
65
+ ...(embed.author?.name ? { author: { name: embed.author.name, ...(safeMessageUrl(embed.author.url) ? { url: safeMessageUrl(embed.author.url) } : {}), ...(safeMessageUrl(embed.author.icon_url) ? { icon_url: safeMessageUrl(embed.author.icon_url) } : {}) } } : {}),
66
+ ...(embed.footer?.text ? { footer: { text: embed.footer.text, ...(safeMessageUrl(embed.footer.icon_url) ? { icon_url: safeMessageUrl(embed.footer.icon_url) } : {}) } } : {}),
67
+ ...(safeMessageUrl(embed.image?.url) ? { image: { url: safeMessageUrl(embed.image.url) } } : {}),
68
+ ...(safeMessageUrl(embed.thumbnail?.url) ? { thumbnail: { url: safeMessageUrl(embed.thumbnail.url) } } : {}),
69
+ ...(embed.fields?.length ? { fields: embed.fields } : {}),
70
+ ...(embed.timestamp ? { timestamp: new Date().toISOString() } : {}),
71
+ })),
72
+ };
73
+ }
@@ -0,0 +1,33 @@
1
+ /** Resolve only declared slash options. Values stay data and are never evaluated as code. */
2
+ export function resolveOptions(options = [], interaction) {
3
+ const variables = Object.create(null);
4
+ for (const option of options) {
5
+ const key = `${option.name}_option`;
6
+ if (option.type === 3) variables[key] = interaction.options.getString(option.name) ?? '';
7
+ else if (option.type === 6) {
8
+ const user = interaction.options.getUser(option.name);
9
+ const member = user ? interaction.options.getMember(option.name) : null;
10
+ variables[key] = user ? `<@${user.id}>` : '';
11
+ variables[`${key}_id`] = user?.id || '';
12
+ variables[`${key}_name`] = user?.username || '';
13
+ variables[`${key}_displayName`] = member?.displayName || member?.nick || user?.globalName || user?.username || '';
14
+ variables[`${key}_avatar`] = user?.displayAvatarURL?.({ extension: 'png', size: 256 }) || '';
15
+ } else if (option.type === 7) {
16
+ const channel = interaction.options.getChannel(option.name);
17
+ variables[key] = channel ? `<#${channel.id}>` : '';
18
+ variables[`${key}_id`] = channel?.id || '';
19
+ variables[`${key}_name`] = channel?.name || '';
20
+ }
21
+ }
22
+ return variables;
23
+ }
24
+
25
+ export function interpolateOptions(args, variables) {
26
+ const replace = value => {
27
+ if (typeof value === 'string') return value.replace(/\{([^{}]+)\}/g, (match, key) => Object.hasOwn(variables, key) ? variables[key] : match);
28
+ if (Array.isArray(value)) return value.map(replace);
29
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, replace(item)]));
30
+ return value;
31
+ };
32
+ return replace(args);
33
+ }
package/secret.mjs ADDED
@@ -0,0 +1,16 @@
1
+ export async function acceptSecret(envelope, { decrypt, agentId, previousApplicationId, save, fetchImpl = fetch }) {
2
+ const secret = await decrypt(envelope);
3
+ try {
4
+ if (secret.agentId !== agentId || !/^\d{17,20}$/.test(secret.applicationId || '') || typeof secret.token !== 'string' || secret.token.length < 30 || secret.token.length > 300) throw new Error('SECRET_INVALID');
5
+ if (previousApplicationId && secret.applicationId !== previousApplicationId) throw new Error('APPLICATION_MISMATCH');
6
+ const options = { headers: { Authorization: 'Bot ' + secret.token }, signal: AbortSignal.timeout(15000) };
7
+ const application = await fetchImpl('https://discord.com/api/v10/oauth2/applications/@me', options);
8
+ if (!application.ok || (await application.json()).id !== secret.applicationId) throw new Error('TOKEN_INVALID');
9
+ const user = await fetchImpl('https://discord.com/api/v10/users/@me', options);
10
+ if (!user.ok) throw new Error('TOKEN_INVALID');
11
+ const profile = await user.json();
12
+ if (profile.id !== secret.applicationId) throw new Error('APPLICATION_MISMATCH');
13
+ await save(envelope);
14
+ return { id: profile.id, username: profile.username, avatar: profile.avatar };
15
+ } finally { secret.token = ''; }
16
+ }
package/supervisor.mjs ADDED
@@ -0,0 +1,34 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { readFile, writeFile, rename } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { currentDirectory } from './update.mjs';
5
+
6
+ export async function supervise(home, fallback, { shouldStop } = {}) {
7
+ let stopping = false, worker;
8
+ const stop = () => { stopping = true; if (worker?.connected) { try { worker.send({ type: 'shutdown' }, () => {}); } catch {} } else worker?.kill('SIGTERM'); };
9
+ let checking = false;
10
+ const timer = shouldStop ? setInterval(async () => { if (checking) return; if (stopping) { stop(); return; } checking = true; try { if (await shouldStop()) stop(); } catch {} finally { checking = false; } }, 250) : null;
11
+ process.on('SIGINT', stop); process.on('SIGTERM', stop);
12
+ try { while (!stopping) {
13
+ const directory = await currentDirectory(home, fallback);
14
+ let ready = false;
15
+ const code = await new Promise(resolve => {
16
+ worker = spawn(process.execPath, [...process.execArgv, path.join(directory, 'cli.mjs'), 'worker'], { env: { ...process.env, OFTONE_AGENT_HOME: home }, stdio: ['inherit', 'inherit', 'inherit', 'ipc'], windowsHide: true, shell: false });
17
+ worker.on('message', data => { if (data?.type === 'agent-ready') ready = true; });
18
+ worker.once('error', () => resolve(1)); worker.once('exit', code => resolve(code));
19
+ });
20
+ if (stopping || code === 0) return;
21
+ if (code === 75) continue;
22
+ if (!ready) {
23
+ try {
24
+ const file = path.join(home, 'agent-release.json');
25
+ const pointer = JSON.parse(await readFile(file, 'utf8'));
26
+ if (pointer.previous && pointer.previous !== pointer.directory && /^(installation|versions\/[0-9.]+-[a-f0-9]{64})$/.test(pointer.previous)) {
27
+ await writeFile(file + '.tmp', JSON.stringify({ directory: pointer.previous }), { mode: 0o600 }); await rename(file + '.tmp', file);
28
+ console.error('Échec de la nouvelle version. Retour à la version précédente.'); continue;
29
+ }
30
+ } catch {}
31
+ }
32
+ throw new Error('AGENT_WORKER_FAILED');
33
+ } } finally { clearInterval(timer); process.off('SIGINT', stop); process.off('SIGTERM', stop); }
34
+ }
@@ -0,0 +1,46 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { Client, GatewayIntentBits, REST, Routes } from 'discord.js';
3
+ import { executeCommand } from './runtime/execute.mjs';
4
+
5
+ const plan = JSON.parse(await readFile(new URL('./plan.json', import.meta.url), 'utf8'));
6
+ if (plan.schemaVersion !== 1) throw new Error('Version de plan non prise en charge.');
7
+ const token = process.env.DISCORD_TOKEN;
8
+ const applicationId = process.env.DISCORD_CLIENT_ID;
9
+ const guildId = process.env.DISCORD_GUILD_ID;
10
+ if (!token) throw new Error('DISCORD_TOKEN absent du fichier .env local.');
11
+
12
+ if (process.argv.includes('--deploy')) {
13
+ if (!/^\d{17,20}$/.test(applicationId || '')) throw new Error('DISCORD_CLIENT_ID doit être l’Application ID Discord.');
14
+ if (guildId && !/^\d{17,20}$/.test(guildId)) throw new Error('DISCORD_GUILD_ID invalide.');
15
+ const rest = new REST({ version: '10' }).setToken(token);
16
+ const route = guildId ? Routes.applicationGuildCommands(applicationId, guildId) : Routes.applicationCommands(applicationId);
17
+ await rest.put(route, { body: plan.commands.map(command => ({ name: command.name, description: command.description, type: 1, options: (command.options || []).map(({ type, name, description, required }) => ({ type, name, description, required, ...(type === 3 ? { max_length: 6000 } : {}) })) })) });
18
+ console.log(`${plan.commands.length} commande(s) enregistrée(s).`);
19
+ } else {
20
+ const client = new Client({ intents: [GatewayIntentBits.Guilds] });
21
+ const commands = new Map(plan.commands.map(command => [command.name, command]));
22
+ client.once('ready', () => console.log(`Bot connecté : ${client.user.tag}`));
23
+ client.on('interactionCreate', async interaction => {
24
+ if (!interaction.isChatInputCommand()) return;
25
+ const command = commands.get(interaction.commandName);
26
+ if (!command) { await interaction.reply({ content: 'Commande introuvable.', flags: 64 }); return; }
27
+ const started = performance.now(), hour = Math.floor(Date.now() / 3600000) * 3600000; let success = true;
28
+ try {
29
+ await executeCommand(command, interaction, client, { onError: () => { success = false; } });
30
+ } catch (error) {
31
+ success = false;
32
+ console.error(`Échec de /${command.name} (${error.name}).`);
33
+ const content = 'La commande n’a pas pu être exécutée. Vérifiez sa configuration et les permissions du bot.';
34
+ try {
35
+ if (interaction.deferred && !interaction.replied) await interaction.editReply({ content, embeds: [] });
36
+ else if (interaction.replied) await interaction.followUp({ content, flags: 64 });
37
+ else await interaction.reply({ content, flags: 64 });
38
+ } catch { console.error('Impossible de notifier l’utilisateur.'); }
39
+ } finally {
40
+ if (process.connected && process.send) try { process.send({ type: 'usage', hour, command: command.name, success, durationMs: Math.min(900000, Math.round(performance.now() - started)) }, () => {}); } catch {}
41
+ }
42
+ });
43
+ client.on('error', error => console.error(`Erreur du client Discord (${error.name}).`));
44
+ for (const event of ['SIGTERM', 'SIGINT']) process.on(event, () => { client.destroy(); process.exit(0); });
45
+ await client.login(token);
46
+ }