refactor: move app code into Max Avatar/ subfolder (monorepo prep for backend)
Step 1 of adding a backend proxy server (API keys held server-side instead of shipped in the installer). Moves everything app-specific into "Max Avatar/" via git mv (preserves history): src/, tests/, scripts/, assets/, build/, resources/, package.json/-lock.json, electron-builder.yml, electron.vite.config.ts, eslint.config.mjs, playwright.config.ts, vitest.config.mts, sonar-project.properties, tsconfig*.json, Dockerfile, .editorconfig/.env*/.gitignore/.prettier*. CLAUDE.md, README.md, docs/, .claude/, .gitea/, .husky/, .vscode/, and the docker-compose files stay at the repo root, since they'll apply to both the app and the future backend. No application code needed changes (all its internal paths are relative to its own tree). Adjusted what referenced the old root from outside: - .husky/pre-commit: cd into "Max Avatar" before lint-staged - .gitea/workflows/*.yml: working-directory + cache-dependency-path + artifact paths + SonarQube projectBaseDir - docker-compose.yml: build context -> ./Max Avatar - Max Avatar/Dockerfile: node:20-alpine -> node:24-alpine (same node:sqlite issue already fixed elsewhere, never applied here before) - .vscode/launch.json, README.md: updated paths/instructions Verified from Max Avatar/ after the move: npm ci, typecheck, lint, test:coverage (473/473, same coverage numbers), build, and dev all work unchanged. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
60e2fb26af
commit
1c2f002eb3
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Convertit une valeur d'argument d'outil (toujours `unknown` a la frontiere function-calling) en
|
||||
* chaine, sans jamais utiliser la stringification par defaut d'un objet ("[object Object]") qui
|
||||
* masquerait silencieusement une entree invalide envoyee par le modele.
|
||||
*/
|
||||
export function asString(value: unknown, fallback = ''): string {
|
||||
return typeof value === 'string' ? value : fallback
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { clickElementByText } from '../../browser/browserWindow'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const clickBrowserElement: SkillDefinition = {
|
||||
name: 'click_browser_element',
|
||||
description:
|
||||
'Clique sur un lien ou un bouton du navigateur integre dont le texte visible correspond (ou contient) le texte donne. Ne fonctionne que sur des elements avec du texte visible.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
text: {
|
||||
type: 'string',
|
||||
description: 'Texte visible du lien/bouton a cliquer, le plus exact possible'
|
||||
}
|
||||
},
|
||||
required: ['text']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const text = asString(args.text).trim()
|
||||
if (!text) throw new Error('text manquant')
|
||||
const clicked = await clickElementByText(text)
|
||||
return clicked
|
||||
? `Clic effectue sur l'element correspondant a "${text}".`
|
||||
: `Echec : aucun lien ou bouton visible ne correspond a "${text}".`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { fillField } from '../../browser/browserWindow'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const fillBrowserField: SkillDefinition = {
|
||||
name: 'fill_browser_field',
|
||||
description:
|
||||
"Remplit un champ de formulaire (texte, recherche...) dans le navigateur integre, identifie par son nom/placeholder/label approximatif, et peut le valider. Le matching n'est pas garanti a 100% sur tous les sites.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
field: {
|
||||
type: 'string',
|
||||
description: 'Description du champ (ex: "recherche", "email", "nom")'
|
||||
},
|
||||
value: { type: 'string', description: 'Valeur a saisir' },
|
||||
submit: {
|
||||
type: 'boolean',
|
||||
description: 'Valider le formulaire apres saisie (defaut : false)'
|
||||
}
|
||||
},
|
||||
required: ['field', 'value']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const field = asString(args.field).trim()
|
||||
const value = asString(args.value)
|
||||
const submit = args.submit === true
|
||||
if (!field) throw new Error('field manquant')
|
||||
const filled = await fillField(field, value, submit)
|
||||
return filled
|
||||
? `Champ "${field}" rempli${submit ? ' et formulaire valide' : ''}.`
|
||||
: `Echec : aucun champ correspondant a "${field}" trouve sur la page.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { goBack } from '../../browser/browserWindow'
|
||||
import type { SkillDefinition } from '../types'
|
||||
|
||||
export const goBackBrowser: SkillDefinition = {
|
||||
name: 'go_back_browser',
|
||||
description: 'Revient a la page precedente dans le navigateur integre.',
|
||||
parameters: { type: 'object', properties: {} },
|
||||
execute: async () => {
|
||||
const didGoBack = await goBack()
|
||||
return didGoBack ? 'Retour a la page precedente effectue.' : 'Echec : pas de page precedente.'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { highlightText } from '../../browser/browserWindow'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const highlightBrowserText: SkillDefinition = {
|
||||
name: 'highlight_browser_text',
|
||||
description:
|
||||
'Surligne en jaune (et fait defiler jusqu a) un passage de texte exact dans la page actuellement affichee dans le navigateur integre.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
text: {
|
||||
type: 'string',
|
||||
description: 'Texte exact a surligner (doit correspondre mot pour mot au texte de la page)'
|
||||
}
|
||||
},
|
||||
required: ['text']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const text = asString(args.text).trim()
|
||||
if (!text) throw new Error('text manquant')
|
||||
const found = await highlightText(text)
|
||||
return found
|
||||
? `Passage surligne : "${text}".`
|
||||
: `Echec : le texte "${text}" n'a pas ete trouve exactement sur la page.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { navigateBrowser } from './navigateBrowser'
|
||||
import { readBrowserPage } from './readBrowserPage'
|
||||
import { clickBrowserElement } from './clickBrowserElement'
|
||||
import { goBackBrowser } from './goBackBrowser'
|
||||
import { fillBrowserField } from './fillBrowserField'
|
||||
import { translateBrowserPage } from './translateBrowserPage'
|
||||
import { highlightBrowserText } from './highlightBrowserText'
|
||||
|
||||
// Navigateur integre, independant de l'OS, commun a toutes les plateformes.
|
||||
export const browserSkills: SkillDefinition[] = [
|
||||
navigateBrowser,
|
||||
readBrowserPage,
|
||||
clickBrowserElement,
|
||||
goBackBrowser,
|
||||
fillBrowserField,
|
||||
translateBrowserPage,
|
||||
highlightBrowserText
|
||||
]
|
||||
@@ -0,0 +1,22 @@
|
||||
import { navigateTo } from '../../browser/browserWindow'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const navigateBrowser: SkillDefinition = {
|
||||
name: 'navigate_browser',
|
||||
description:
|
||||
"Ouvre une URL dans le navigateur integre que tu controles toi-meme (fenetre separee, visible par l'utilisateur). C'est le seul moyen d'ouvrir un site : utilise systematiquement cette fonction pour toute demande de consultation d'un site, que tu doives ensuite lire la page, cliquer, remplir un formulaire, traduire ou surligner du texte, ou simplement montrer le site a l'utilisateur. Ne jamais deviner l'URL d'un site inconnu : utiliser search_web d'abord.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
url: { type: 'string', description: 'URL exacte a ouvrir' }
|
||||
},
|
||||
required: ['url']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const url = asString(args.url).trim()
|
||||
if (!url) throw new Error('url manquante')
|
||||
const title = await navigateTo(url)
|
||||
return `Page ouverte : "${title}" (${url}).`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { readPageText } from '../../browser/browserWindow'
|
||||
import type { SkillDefinition } from '../types'
|
||||
|
||||
export const readBrowserPage: SkillDefinition = {
|
||||
name: 'read_browser_page',
|
||||
description:
|
||||
"Lit le texte reel actuellement affiche dans le navigateur integre (apres navigate_browser). Utilise ceci pour repondre a une question sur le contenu de la page, plutot que d'inventer.",
|
||||
parameters: { type: 'object', properties: {} },
|
||||
execute: async () => {
|
||||
const text = await readPageText()
|
||||
return text || "La page est vide ou n'a pas pu etre lue."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { applyTranslations, collectTranslatableElements } from '../../browser/browserWindow'
|
||||
import { translateTexts } from '../../ai/translate'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const translateBrowserPage: SkillDefinition = {
|
||||
name: 'translate_browser_page',
|
||||
description:
|
||||
'Traduit et remplace le texte visible de la page actuellement affichee dans le navigateur integre, dans la langue demandee (comme la traduction automatique dun navigateur).',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
language: { type: 'string', description: 'Langue cible (ex: "anglais", "espagnol")' }
|
||||
},
|
||||
required: ['language']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const language = asString(args.language).trim()
|
||||
if (!language) throw new Error('language manquante')
|
||||
|
||||
const elements = await collectTranslatableElements()
|
||||
if (elements.length === 0) return 'Aucun texte traduisible trouve sur cette page.'
|
||||
|
||||
const translated = await translateTexts(
|
||||
elements.map((el) => el.text),
|
||||
language
|
||||
)
|
||||
await applyTranslations(
|
||||
elements.map((el, i) => ({ id: el.id, text: translated.at(i) ?? el.text }))
|
||||
)
|
||||
|
||||
return `Page traduite en ${language} (${elements.length} elements remplaces).`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
import { requestWrittenAnswers } from '../../coach/exerciseWindow'
|
||||
import {
|
||||
saveAssessment,
|
||||
listModules,
|
||||
areAllModulesAcquired,
|
||||
getSubjectLevel,
|
||||
getSubjectObjective,
|
||||
allModulesHaveContent,
|
||||
modulesMissingContent
|
||||
} from '../../coach/coachStore'
|
||||
import { DONT_KNOW_ANSWER } from '../../../shared/coach'
|
||||
import type {
|
||||
ExerciseType,
|
||||
AssessmentKind,
|
||||
ExerciseDifficulty,
|
||||
ExerciseStyle
|
||||
} from '../../../shared/coach'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const VALID_TYPES: ExerciseType[] = ['free_text', 'multiple_choice', 'true_false']
|
||||
const VALID_KINDS: AssessmentKind[] = ['initial', 'module', 'final']
|
||||
const VALID_DIFFICULTIES: ExerciseDifficulty[] = ['facile', 'moyen', 'difficile']
|
||||
const VALID_STYLES: ExerciseStyle[] = [
|
||||
'prediction',
|
||||
'debogage',
|
||||
'probleme_ouvert',
|
||||
'projet',
|
||||
'qcm_cible'
|
||||
]
|
||||
const DEMANDING_STYLES: ExerciseStyle[] = ['projet', 'probleme_ouvert']
|
||||
const MAX_QUESTIONS = 12
|
||||
|
||||
/**
|
||||
* Le modele ecrit naturellement le francais avec accents ("probleme_ouvert" devient
|
||||
* "problème_ouvert"), ce qui ne correspondait a aucune valeur d'enum exacte et faisait echouer
|
||||
* l'appel pour rien (constate en test reel : un aller-retour perdu a chaque fois). Normalise avant
|
||||
* comparaison plutot que d'exiger une orthographe exacte sans accent.
|
||||
*/
|
||||
function stripAccents(text: string): string {
|
||||
return text.normalize('NFD').replace(/[̀-ͯ]/g, '')
|
||||
}
|
||||
|
||||
function normalizeStyle(raw: string): ExerciseStyle | null {
|
||||
const normalized = stripAccents(raw).toLowerCase()
|
||||
return VALID_STYLES.find((s) => stripAccents(s).toLowerCase() === normalized) ?? null
|
||||
}
|
||||
|
||||
interface ParsedQuestion {
|
||||
question: string
|
||||
type: ExerciseType
|
||||
options: string[] | null
|
||||
concept: string | null
|
||||
difficulty: ExerciseDifficulty | null
|
||||
exerciseStyle: ExerciseStyle | null
|
||||
targetsCommonError: string | null
|
||||
}
|
||||
|
||||
export const askWrittenExercise: SkillDefinition = {
|
||||
name: 'ask_written_exercise',
|
||||
description:
|
||||
"Pose TOUTES les questions d'evaluation d'un coup, dans UN SEUL formulaire a l'ecrit (jamais une par une, et JAMAIS a l'oral — ne recite jamais les questions dans ta reponse, seule la fenetre ecrite les affiche), et attend que l'utilisateur soumette l'ensemble. Un bouton \"Je ne sais pas\" est toujours propose pour chaque question : rassure l'utilisateur, ce n'est qu'une base pour savoir quoi enseigner, jamais une notation. Obligatoire avant tout jugement de maitrise (track_concept_mastery/complete_module) ou avant de fixer le niveau d'un sujet (record_subject_level). Precise 'kind' : 'initial' (evaluation de depart d'un sujet — refuse techniquement tant que generate_course_plan et write_module_content pour TOUS les modules n'ont pas ete faits avant ; exige EXACTEMENT une question par module existant, avec le champ 'concept' de chaque question egal au nom exact du module qu'elle teste — jamais de question generale non liee a un module precis), 'module' (validation d'un module du plan de cours), ou 'final' (evaluation globale de maitrise du sujet).",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage concerne" },
|
||||
concept: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Module/concept precis evalue (omettre pour une evaluation generale de niveau initial/final)'
|
||||
},
|
||||
kind: {
|
||||
type: 'string',
|
||||
enum: VALID_KINDS,
|
||||
description: "Type d'evaluation : initial, module ou final"
|
||||
},
|
||||
questions: {
|
||||
type: 'array',
|
||||
description:
|
||||
"Toutes les questions a poser EN UNE FOIS dans le meme formulaire (au moins 1, par exemple 5 a 10 pour une evaluation initiale). Varie les difficultes et les types d'exercice au sein du tableau.",
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
question: { type: 'string', description: "Question a poser a l'ecrit" },
|
||||
concept: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Pour kind="initial" UNIQUEMENT (obligatoire) : nom EXACT du module que cette question teste (une question par module, jamais de question generale). Pour kind="module"/"final", omettre (utilise le champ \'concept\' global).'
|
||||
},
|
||||
type: {
|
||||
type: 'string',
|
||||
enum: VALID_TYPES,
|
||||
description:
|
||||
'Type de question : free_text (texte libre), multiple_choice (QCM, fournir options) ou true_false'
|
||||
},
|
||||
options: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description: 'Liste des choix, obligatoire uniquement si type = multiple_choice'
|
||||
},
|
||||
difficulty: {
|
||||
type: 'string',
|
||||
enum: VALID_DIFFICULTIES,
|
||||
description:
|
||||
'Niveau de difficulte : facile (application directe), moyen (plusieurs etapes/contexte nouveau), difficile (transfert/combinaison/debogage). Varie les difficultes au sein du formulaire, jamais toutes au meme niveau.'
|
||||
},
|
||||
exerciseStyle: {
|
||||
type: 'string',
|
||||
enum: VALID_STYLES,
|
||||
description:
|
||||
"Type d'exercice (methode prof, du plus au moins efficace) : prediction, debogage (trouve l'erreur), probleme_ouvert (situation reelle), projet, qcm_cible (distracteurs = erreurs typiques)."
|
||||
},
|
||||
targetsCommonError: {
|
||||
type: 'string',
|
||||
description:
|
||||
"Si exerciseStyle = 'debogage' : quelle erreur typique (identifiee dans research_topic) cette question cible precisement"
|
||||
}
|
||||
},
|
||||
required: ['question', 'type']
|
||||
}
|
||||
}
|
||||
},
|
||||
required: ['subject', 'kind', 'questions']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const concept = typeof args.concept === 'string' ? args.concept.trim() : null
|
||||
const kind = asString(args.kind, 'module') as AssessmentKind
|
||||
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!VALID_KINDS.includes(kind)) throw new Error('kind invalide')
|
||||
|
||||
const rawQuestions = Array.isArray(args.questions) ? args.questions : []
|
||||
if (rawQuestions.length === 0) throw new Error('questions manquantes (au moins une requise)')
|
||||
|
||||
const questions: ParsedQuestion[] = rawQuestions.slice(0, MAX_QUESTIONS).map((raw, index) => {
|
||||
const q = (typeof raw === 'object' && raw !== null ? raw : {}) as Record<string, unknown>
|
||||
const question = asString(q.question).trim()
|
||||
const type = asString(q.type) as ExerciseType
|
||||
const options = Array.isArray(q.options) ? q.options.map((o) => String(o)) : null
|
||||
const questionConcept = typeof q.concept === 'string' ? q.concept.trim() : null
|
||||
const difficulty =
|
||||
typeof q.difficulty === 'string' ? (q.difficulty as ExerciseDifficulty) : null
|
||||
const exerciseStyle =
|
||||
typeof q.exerciseStyle === 'string' ? normalizeStyle(q.exerciseStyle) : null
|
||||
const targetsCommonError =
|
||||
typeof q.targetsCommonError === 'string' ? q.targetsCommonError.trim() : null
|
||||
|
||||
if (!question) throw new Error(`question manquante (item ${index + 1})`)
|
||||
if (!VALID_TYPES.includes(type)) throw new Error(`type invalide (item ${index + 1})`)
|
||||
if (type === 'multiple_choice' && (!options || options.length < 2)) {
|
||||
throw new Error(
|
||||
`options manquantes ou insuffisantes pour multiple_choice (item ${index + 1})`
|
||||
)
|
||||
}
|
||||
if (difficulty && !VALID_DIFFICULTIES.includes(difficulty)) {
|
||||
throw new Error(`difficulty invalide (item ${index + 1})`)
|
||||
}
|
||||
if (q.exerciseStyle && !exerciseStyle) {
|
||||
throw new Error(`exerciseStyle invalide (item ${index + 1}) : ${VALID_STYLES.join(', ')}`)
|
||||
}
|
||||
|
||||
return {
|
||||
question,
|
||||
type,
|
||||
options,
|
||||
concept: questionConcept,
|
||||
difficulty,
|
||||
exerciseStyle,
|
||||
targetsCommonError
|
||||
}
|
||||
})
|
||||
|
||||
// Garde-fous anti-confusion de phase. kind="initial" : (1) le plan de cours complet (objectif +
|
||||
// modules + CONTENU ECRIT de chaque module) doit exister AVANT la moindre question — exige par
|
||||
// l'utilisateur : "sans objectif final defini et mesurable pas de question a poser", "tout doit
|
||||
// etre redige a l'avance et consultable avant de verifier le niveau" ; (2) une fois le niveau
|
||||
// enregistre (record_subject_level), l'evaluation initiale est terminee, ne pas la rejouer
|
||||
// (constate en test reel par le passe). kind="final" : pas avant que tous les modules soient
|
||||
// acquis (constate en test reel : Max sautait directement a la finale).
|
||||
if (kind === 'initial') {
|
||||
if (getSubjectLevel(subject)) {
|
||||
throw new Error(
|
||||
`Le niveau de "${subject}" est deja enregistre : l'evaluation initiale est terminee, ne la relance pas. Utilise kind="module" pour le module en cours (appelle get_course_plan si besoin de verifier ou tu en es).`
|
||||
)
|
||||
}
|
||||
if (!getSubjectObjective(subject)) {
|
||||
throw new Error(
|
||||
`Aucun plan de cours ecrit pour "${subject}" : appelle d'abord generate_course_plan (avec un objectif mesurable et les modules devines a partir de la recherche), avant de poser la moindre question d'evaluation.`
|
||||
)
|
||||
}
|
||||
if (listModules(subject).length === 0) {
|
||||
throw new Error(
|
||||
`Aucun module cree pour "${subject}" : appelle generate_course_plan avant de poser la moindre question d'evaluation.`
|
||||
)
|
||||
}
|
||||
if (!allModulesHaveContent(subject)) {
|
||||
throw new Error(
|
||||
`Le contenu de certains modules de "${subject}" est absent ou ne respecte pas la structure obligatoire : ${modulesMissingContent(subject).join(', ')}. Appelle write_module_content pour CHAQUE module (il precisera exactement ce qui manque) avant de poser la moindre question d'evaluation.`
|
||||
)
|
||||
}
|
||||
// Chaque question doit tester EXACTEMENT un module, pour que la reponse (correcte ou non)
|
||||
// indique directement si ce module peut etre retire du plan (deja maitrise) ou doit etre
|
||||
// garde pour l'enseignement (demande utilisateur explicite : les questions correspondent aux
|
||||
// modules, pas des questions generales deconnectees du plan).
|
||||
const moduleNames = listModules(subject).map((m) => m.name)
|
||||
const providedConcepts = questions.map((q) => q.concept)
|
||||
const missingConcept = providedConcepts.some((c) => !c)
|
||||
const unknownConcepts = providedConcepts.filter((c) => c && !moduleNames.includes(c))
|
||||
const duplicateConcepts = providedConcepts.filter(
|
||||
(c, i) => c && providedConcepts.indexOf(c) !== i
|
||||
)
|
||||
const uncoveredModules = moduleNames.filter((name) => !providedConcepts.includes(name))
|
||||
if (
|
||||
missingConcept ||
|
||||
unknownConcepts.length ||
|
||||
duplicateConcepts.length ||
|
||||
uncoveredModules.length
|
||||
) {
|
||||
throw new Error(
|
||||
`L'evaluation initiale doit poser EXACTEMENT une question par module, avec "concept" egal au nom exact du module qu'elle teste.` +
|
||||
(missingConcept ? ' Au moins une question n\'a pas de "concept".' : '') +
|
||||
(unknownConcepts.length
|
||||
? ` Concepts invalides (aucun module correspondant) : ${unknownConcepts.join(', ')}.`
|
||||
: '') +
|
||||
(duplicateConcepts.length
|
||||
? ` Modules testes plusieurs fois : ${duplicateConcepts.join(', ')}.`
|
||||
: '') +
|
||||
(uncoveredModules.length
|
||||
? ` Modules non couverts : ${uncoveredModules.join(', ')}.`
|
||||
: '')
|
||||
)
|
||||
}
|
||||
}
|
||||
if (kind === 'final') {
|
||||
const modules = listModules(subject)
|
||||
if (modules.length === 0 || !areAllModulesAcquired(subject)) {
|
||||
throw new Error(
|
||||
`Tous les modules de "${subject}" ne sont pas encore valides : l'evaluation finale ne peut pas commencer avant (utilise kind="module" pour le module en cours).`
|
||||
)
|
||||
}
|
||||
const hasDemandingQuestion = questions.some(
|
||||
(q) =>
|
||||
q.difficulty === 'difficile' ||
|
||||
(q.exerciseStyle && DEMANDING_STYLES.includes(q.exerciseStyle))
|
||||
)
|
||||
if (!hasDemandingQuestion) {
|
||||
throw new Error(
|
||||
'L\'evaluation finale doit etre exigeante : au moins une question avec difficulty="difficile" (ou exerciseStyle="projet"/"probleme_ouvert"), jamais uniquement des rappels faciles.'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const answers = await requestWrittenAnswers(
|
||||
questions.map((q) => ({ question: q.question, type: q.type, options: q.options }))
|
||||
)
|
||||
|
||||
const summaries: string[] = []
|
||||
questions.forEach((q, index) => {
|
||||
const answer = answers.at(index)
|
||||
if (answer === null || answer === undefined) {
|
||||
summaries.push(`"${q.question}" : pas de reponse (fenetre fermee ou delai depasse)`)
|
||||
return
|
||||
}
|
||||
const dontKnow = answer === DONT_KNOW_ANSWER
|
||||
saveAssessment(
|
||||
subject,
|
||||
q.concept ?? concept,
|
||||
q.question,
|
||||
q.type,
|
||||
q.options,
|
||||
answer,
|
||||
kind,
|
||||
dontKnow,
|
||||
q.difficulty,
|
||||
q.exerciseStyle,
|
||||
q.targetsCommonError
|
||||
)
|
||||
summaries.push(
|
||||
dontKnow
|
||||
? `"${q.question}" : "Je ne sais pas" (lacune enregistree, pas un echec)`
|
||||
: `"${q.question}" : "${answer}"`
|
||||
)
|
||||
})
|
||||
|
||||
return `Formulaire soumis (${questions.length} question(s)) :\n${summaries.join('\n')}`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import {
|
||||
hasAssessment,
|
||||
hasMultipleDifficulties,
|
||||
moduleDontKnowRatio,
|
||||
upsertConceptStatus,
|
||||
getModuleOrderIndex,
|
||||
unlockNextModule
|
||||
} from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const MAX_DONT_KNOW_RATIO = 0.5
|
||||
|
||||
export const completeModule: SkillDefinition = {
|
||||
name: 'complete_module',
|
||||
description:
|
||||
"Marque un module du plan de cours comme valide/acquis et deverrouille le module suivant. Necessite qu'une evaluation ecrite (ask_written_exercise, kind='module') ait ete faite pour ce module precis, avec au moins 2 niveaux de difficulte distincts (jamais uniquement du facile), ET que l'utilisateur ait reellement reussi (moins de la moitie des reponses en \"Je ne sais pas\" — un module valide uniquement s'il y a reussite, pas juste une tentative) : echoue sinon.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" },
|
||||
module: { type: 'string', description: 'Nom du module valide' }
|
||||
},
|
||||
required: ['subject', 'module']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const module = asString(args.module).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!module) throw new Error('module manquant')
|
||||
|
||||
if (!hasAssessment(subject, module, 'module')) {
|
||||
throw new Error(
|
||||
`Aucune evaluation ecrite enregistree pour le module "${module}" (${subject}) : appelle ask_written_exercise (kind="module") avant.`
|
||||
)
|
||||
}
|
||||
if (!hasMultipleDifficulties(subject, module)) {
|
||||
throw new Error(
|
||||
`Les exercices du module "${module}" (${subject}) n'utilisent qu'un seul niveau de difficulte : pose au moins 2 niveaux distincts (ask_written_exercise, difficulty) avant de valider le module.`
|
||||
)
|
||||
}
|
||||
const dontKnowRatio = moduleDontKnowRatio(subject, module)
|
||||
if (dontKnowRatio > MAX_DONT_KNOW_RATIO) {
|
||||
throw new Error(
|
||||
`Trop de reponses "Je ne sais pas" sur les exercices du module "${module}" (${Math.round(dontKnowRatio * 100)}%) : le module n'est pas encore maitrise. Continue a l'enseigner (write_module_content si besoin) et repose des questions avant de le valider.`
|
||||
)
|
||||
}
|
||||
|
||||
const orderIndex = getModuleOrderIndex(subject, module)
|
||||
if (orderIndex === null) throw new Error(`Module "${module}" introuvable pour "${subject}"`)
|
||||
|
||||
upsertConceptStatus(subject, module, 'acquired')
|
||||
unlockNextModule(subject, orderIndex)
|
||||
|
||||
return `Module "${module}" valide. Le module suivant (s'il existe) est maintenant accessible.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { areAllModulesAcquired, hasAssessment, setSubjectStatus } from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const completeSubject: SkillDefinition = {
|
||||
name: 'complete_subject',
|
||||
description:
|
||||
"Marque un sujet comme maitrise, apres que tous ses modules sont valides ET qu'une evaluation finale globale (ask_written_exercise, kind='final') a ete faite. Echoue sinon.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" }
|
||||
},
|
||||
required: ['subject']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
|
||||
if (!areAllModulesAcquired(subject)) {
|
||||
throw new Error(`Tous les modules de "${subject}" ne sont pas encore valides.`)
|
||||
}
|
||||
if (!hasAssessment(subject, undefined, 'final')) {
|
||||
throw new Error(
|
||||
`Aucune evaluation finale enregistree pour "${subject}" : appelle ask_written_exercise (kind="final") avant.`
|
||||
)
|
||||
}
|
||||
|
||||
setSubjectStatus(subject, 'mastered')
|
||||
return `"${subject}" est maintenant maitrise !`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { renderMermaid, playCaption } from '../../coach/drawingWindow'
|
||||
import { synthesizeSpeech } from '../../ai/elevenlabs'
|
||||
import { saveModuleDiagram } from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const MAX_CAPTIONS = 12
|
||||
const CAPTION_MAX_LEN = 300
|
||||
const MERMAID_MAX_LEN = 4000
|
||||
|
||||
export const drawFlowDiagram: SkillDefinition = {
|
||||
name: 'draw_flow_diagram',
|
||||
description:
|
||||
"Dessine un cycle, une hierarchie, un flux ou un processus a etapes (ex: cycle de l'eau, organigramme) en syntaxe Mermaid (graph/flowchart), rendu par un vrai moteur de mise en page automatique — jamais de coordonnees manuelles pour ce type de diagramme, un modele economique les calcule mal. Donne aussi une liste de captions courtes, prononcees en sequence une fois le diagramme affiche, pour expliquer etape par etape.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string', description: 'Titre du diagramme' },
|
||||
subject: {
|
||||
type: 'string',
|
||||
description: "Sujet d'apprentissage concerne (pour conserver ce diagramme dans le module)"
|
||||
},
|
||||
module: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Module concerne : si fourni avec subject, le diagramme est conserve et relisible plus tard dans la page de progression'
|
||||
},
|
||||
mermaid: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Code Mermaid valide (ex: "graph LR; Evaporation --> Condensation --> Precipitation --> Infiltration --> Evaporation")'
|
||||
},
|
||||
captions: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description:
|
||||
'Phrases dites a voix haute en sequence une fois le diagramme affiche, une par etape'
|
||||
}
|
||||
},
|
||||
required: ['title', 'mermaid']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const title = asString(args.title, 'Diagramme').trim() || 'Diagramme'
|
||||
const subject = typeof args.subject === 'string' ? args.subject.trim() : null
|
||||
const module = typeof args.module === 'string' ? args.module.trim() : null
|
||||
const mermaidCode = asString(args.mermaid).trim().slice(0, MERMAID_MAX_LEN)
|
||||
if (!mermaidCode) throw new Error('mermaid manquant')
|
||||
|
||||
const captions = (Array.isArray(args.captions) ? args.captions : [])
|
||||
.map((c) => String(c).trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, MAX_CAPTIONS)
|
||||
.map((c) => c.slice(0, CAPTION_MAX_LEN))
|
||||
|
||||
if (captions.length === 0) {
|
||||
throw new Error(
|
||||
"Aucune caption fournie : un diagramme sans narration n'est jamais accepte. Donne au moins une phrase par etape importante."
|
||||
)
|
||||
}
|
||||
|
||||
await renderMermaid(title, mermaidCode)
|
||||
|
||||
for (const caption of captions) {
|
||||
try {
|
||||
const speech = await synthesizeSpeech(caption)
|
||||
const audio = speech.buffer.slice(
|
||||
speech.byteOffset,
|
||||
speech.byteOffset + speech.byteLength
|
||||
) as ArrayBuffer
|
||||
await playCaption(audio)
|
||||
} catch (error) {
|
||||
console.error('[coach] echec narration de diagramme', error)
|
||||
}
|
||||
}
|
||||
|
||||
if (subject && module) {
|
||||
saveModuleDiagram(subject, module, 'mermaid', title, { title, mermaidCode })
|
||||
}
|
||||
|
||||
return `Diagramme "${title}" affiche dans la fenetre dediee.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
import { openDrawingWindow, revealShape } from '../../coach/drawingWindow'
|
||||
import { synthesizeSpeech } from '../../ai/elevenlabs'
|
||||
import { PRESET_GENERATORS } from '../../coach/presets'
|
||||
import { saveModuleDiagram } from '../../coach/coachStore'
|
||||
import type { DrawShape, ShapeType } from '../../../shared/drawing'
|
||||
import type { Drawing } from '../../../shared/drawing'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const MANUAL_SHAPE_TYPES: ShapeType[] = ['rect', 'circle', 'line', 'arrow', 'text', 'stroke', 'arc']
|
||||
const PRESET_NAMES = [...PRESET_GENERATORS.keys()]
|
||||
const DEFAULT_WIDTH = 700
|
||||
const DEFAULT_HEIGHT = 500
|
||||
const NO_CAPTION_DELAY_MS = 500
|
||||
const CAPTION_MAX_LEN = 300
|
||||
const TEXT_MAX_LEN = 200
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(Math.max(value, min), max)
|
||||
}
|
||||
|
||||
function sanitizeNumber(value: unknown, fallback: number, min: number, max: number): number {
|
||||
const n = Number(value)
|
||||
if (!Number.isFinite(n)) return fallback
|
||||
return clamp(n, min, max)
|
||||
}
|
||||
|
||||
function clampCommonFields(shape: DrawShape): DrawShape {
|
||||
return {
|
||||
...shape,
|
||||
caption: shape.caption ? shape.caption.trim().slice(0, CAPTION_MAX_LEN) : undefined,
|
||||
content: shape.content ? shape.content.slice(0, TEXT_MAX_LEN) : shape.content
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerce et borne une forme manuelle venue du modele dans les limites du canvas : jamais de markup
|
||||
* possible ici, uniquement des nombres/chaines simples passes en parametres a roughjs/canvas.
|
||||
*/
|
||||
function sanitizeManualShape(
|
||||
raw: Record<string, unknown>,
|
||||
type: ShapeType,
|
||||
width: number,
|
||||
height: number
|
||||
): DrawShape | null {
|
||||
const num = (key: string, fallback = 0): number =>
|
||||
sanitizeNumber(Reflect.get(raw, key), fallback, 0, Math.max(width, height))
|
||||
const caption =
|
||||
typeof raw.caption === 'string' && raw.caption.trim() ? raw.caption.trim() : undefined
|
||||
|
||||
if (type === 'stroke') {
|
||||
const rawPoints = Array.isArray(raw.points) ? raw.points : []
|
||||
const points = rawPoints
|
||||
.filter((p): p is { x: unknown; y: unknown } => typeof p === 'object' && p !== null)
|
||||
.map((p) => ({
|
||||
x: sanitizeNumber((p as Record<string, unknown>).x, 0, 0, width),
|
||||
y: sanitizeNumber((p as Record<string, unknown>).y, 0, 0, height)
|
||||
}))
|
||||
if (points.length < 2) return null
|
||||
return { type, points, caption, color: typeof raw.color === 'string' ? raw.color : undefined }
|
||||
}
|
||||
|
||||
const base: DrawShape = {
|
||||
type,
|
||||
x: num('x'),
|
||||
y: num('y'),
|
||||
caption,
|
||||
color: typeof raw.color === 'string' ? raw.color : undefined,
|
||||
label: typeof raw.label === 'string' ? raw.label : undefined
|
||||
}
|
||||
|
||||
if (type === 'rect') {
|
||||
base.width = num('width', 50)
|
||||
base.height = num('height', 50)
|
||||
} else if (type === 'circle') {
|
||||
base.radius = num('radius', 25)
|
||||
} else if (type === 'line' || type === 'arrow') {
|
||||
base.x2 = num('x2')
|
||||
base.y2 = num('y2')
|
||||
} else if (type === 'arc') {
|
||||
base.radius = num('radius', 25)
|
||||
base.startAngle = sanitizeNumber(raw.startAngle, 0, -360, 360)
|
||||
base.endAngle = sanitizeNumber(raw.endAngle, 90, -360, 360)
|
||||
base.closed = raw.closed === true
|
||||
} else if (type === 'text') {
|
||||
base.content = typeof raw.content === 'string' ? raw.content : ''
|
||||
if (!base.content) return null
|
||||
}
|
||||
|
||||
return base
|
||||
}
|
||||
|
||||
/** Expand un preset (geometrie calculee par le code) en une liste de formes reelles. */
|
||||
function expandPreset(raw: Record<string, unknown>): DrawShape[] {
|
||||
const presetName = asString(raw.preset)
|
||||
const generator = PRESET_GENERATORS.get(presetName)
|
||||
if (!generator) {
|
||||
throw new Error(
|
||||
`Preset inconnu: "${presetName}". Presets disponibles: ${PRESET_NAMES.join(', ')}`
|
||||
)
|
||||
}
|
||||
const params =
|
||||
typeof raw.presetParams === 'object' && raw.presetParams !== null
|
||||
? (raw.presetParams as Record<string, unknown>)
|
||||
: raw
|
||||
return generator(params)
|
||||
}
|
||||
|
||||
export const drawSchema: SkillDefinition = {
|
||||
name: 'draw_schema',
|
||||
description:
|
||||
"Dessine et NARRE un schema pas a pas, forme par forme, dans une fenetre dediee (jamais une image figee d'un coup). Pour toute figure geometrique/mathematique (triangle, polygone, camembert, Venn, axes...), utilise OBLIGATOIREMENT un preset (type: 'preset') plutot que des formes manuelles : le code calcule les vraies coordonnees, toi tu ne donnes que des labels/captions. Les formes manuelles (rect/circle/line/arrow/text/arc/stroke) sont reservees a de l'annotation simple et independante, jamais a une figure a plusieurs sommets relies (un modele economique calcule mal ce genre de coordonnees). Donne a chaque forme/preset une 'caption' : c'est le mecanisme de narration synchronisee, pas le texte de ta reponse.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string', description: 'Titre du dessin' },
|
||||
subject: {
|
||||
type: 'string',
|
||||
description: "Sujet d'apprentissage concerne (pour conserver ce dessin dans le module)"
|
||||
},
|
||||
module: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Module concerne : si fourni avec subject, le dessin est conserve et relisible plus tard dans la page de progression'
|
||||
},
|
||||
width: { type: 'number', description: 'Largeur du canvas en pixels (defaut 700)' },
|
||||
height: { type: 'number', description: 'Hauteur du canvas en pixels (defaut 500)' },
|
||||
shapes: {
|
||||
type: 'array',
|
||||
description:
|
||||
"Formes a dessiner dans l'ordre (ou presets a expand). Chacune peut porter une 'caption' dite a voix haute au moment ou elle apparait.",
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
type: {
|
||||
type: 'string',
|
||||
enum: [...MANUAL_SHAPE_TYPES, 'preset'],
|
||||
description:
|
||||
"'preset' pour une figure geometrique (voir 'preset'/'presetParams'), sinon rect/circle/line/arrow/text/arc/stroke pour de l'annotation simple"
|
||||
},
|
||||
preset: {
|
||||
type: 'string',
|
||||
enum: PRESET_NAMES,
|
||||
description: `Nom du preset si type='preset' : ${PRESET_NAMES.join(', ')}`
|
||||
},
|
||||
presetParams: {
|
||||
type: 'object',
|
||||
description:
|
||||
'Parametres semantiques du preset (labels, captions, tailles...) — jamais de coordonnees de sommets, le code les calcule'
|
||||
},
|
||||
x: { type: 'number' },
|
||||
y: { type: 'number' },
|
||||
x2: { type: 'number', description: "Point d'arrivee pour line/arrow" },
|
||||
y2: { type: 'number', description: "Point d'arrivee pour line/arrow" },
|
||||
width: { type: 'number', description: 'Pour rect' },
|
||||
height: { type: 'number', description: 'Pour rect' },
|
||||
radius: { type: 'number', description: 'Pour circle/arc' },
|
||||
startAngle: { type: 'number', description: 'Pour arc, en degres' },
|
||||
endAngle: { type: 'number', description: 'Pour arc, en degres' },
|
||||
content: { type: 'string', description: 'Texte affiche pour type text' },
|
||||
label: {
|
||||
type: 'string',
|
||||
description: 'Legende visuelle optionnelle sur rect/circle/line/arrow'
|
||||
},
|
||||
caption: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Ce que tu dis a voix haute pendant que cette forme apparait (narration pas-a-pas)'
|
||||
},
|
||||
color: { type: 'string', description: 'Couleur CSS simple (ex: "red", "#3366ff")' },
|
||||
points: {
|
||||
type: 'array',
|
||||
description: 'Liste de points {x, y} pour un trait libre (type stroke)',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: { x: { type: 'number' }, y: { type: 'number' } },
|
||||
required: ['x', 'y']
|
||||
}
|
||||
}
|
||||
},
|
||||
required: ['type']
|
||||
}
|
||||
}
|
||||
},
|
||||
required: ['title', 'shapes']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const title = asString(args.title, 'Schema').trim() || 'Schema'
|
||||
const subject = typeof args.subject === 'string' ? args.subject.trim() : null
|
||||
const module = typeof args.module === 'string' ? args.module.trim() : null
|
||||
const width = sanitizeNumber(args.width, DEFAULT_WIDTH, 200, 2000)
|
||||
const height = sanitizeNumber(args.height, DEFAULT_HEIGHT, 200, 2000)
|
||||
const rawShapes = Array.isArray(args.shapes) ? args.shapes : []
|
||||
|
||||
const shapes: DrawShape[] = []
|
||||
for (const raw of rawShapes) {
|
||||
if (typeof raw !== 'object' || raw === null) continue
|
||||
const entry = raw as Record<string, unknown>
|
||||
const type = asString(entry.type) as ShapeType
|
||||
|
||||
if (type === 'preset') {
|
||||
shapes.push(...expandPreset(entry).map(clampCommonFields))
|
||||
continue
|
||||
}
|
||||
if (MANUAL_SHAPE_TYPES.includes(type)) {
|
||||
const shape = sanitizeManualShape(entry, type, width, height)
|
||||
if (shape) shapes.push(clampCommonFields(shape))
|
||||
}
|
||||
}
|
||||
|
||||
if (shapes.length === 0) throw new Error('Aucune forme valide a dessiner')
|
||||
if (shapes.every((s) => !s.caption)) {
|
||||
throw new Error(
|
||||
"Aucune caption fournie : un dessin sans narration n'est jamais accepte. Donne une caption a au moins les formes importantes pour expliquer ce que tu dessines."
|
||||
)
|
||||
}
|
||||
|
||||
await openDrawingWindow(title, width, height)
|
||||
|
||||
for (const shape of shapes) {
|
||||
if (shape.caption) {
|
||||
try {
|
||||
const speech = await synthesizeSpeech(shape.caption)
|
||||
const audio = speech.buffer.slice(
|
||||
speech.byteOffset,
|
||||
speech.byteOffset + speech.byteLength
|
||||
) as ArrayBuffer
|
||||
await revealShape(shape, audio)
|
||||
continue
|
||||
} catch (error) {
|
||||
console.error('[coach] echec narration d’une forme', error)
|
||||
}
|
||||
}
|
||||
await revealShape(shape, null)
|
||||
await new Promise((resolve) => setTimeout(resolve, NO_CAPTION_DELAY_MS))
|
||||
}
|
||||
|
||||
if (subject && module) {
|
||||
const drawing: Drawing = { title, width, height, shapes }
|
||||
saveModuleDiagram(subject, module, 'shapes', title, drawing)
|
||||
}
|
||||
|
||||
return `Dessin "${title}" termine (${shapes.length} forme(s)) dans la fenetre dediee.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { getResearchSummary, createModules, setSubjectObjective } from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const MAX_MODULES = 12
|
||||
|
||||
export const generateCoursePlan: SkillDefinition = {
|
||||
name: 'generate_course_plan',
|
||||
description:
|
||||
"Cree (ou REVISE : ajoute/supprime/modifie des modules) le plan de cours. Premier appel : juste apres research_topic, AVANT toute question d'evaluation — les modules sont devines a partir de la recherche (concepts cles), pas encore de l'evaluation puisqu'elle n'a pas eu lieu. Deuxieme appel (revision), apres l'evaluation initiale et record_subject_level : ajuste les modules (ajoute/supprime/modifie) selon les lacunes reellement identifiees - un module absent de la nouvelle liste est supprime (sauf s'il est deja acquis ou deja evalue, protege automatiquement). Necessite qu'une recherche (research_topic) ait deja ete faite pour ce sujet : echoue sinon. Exige un objectif final mesurable (methode Backward Design) : une phrase concrete du type \"Tu seras capable de [faire X] dans [situation Y]\", jamais \"comprendre\" ou \"savoir\". Seul le premier module est accessible au depart, les suivants se deverrouillent au fur et a mesure. IMPORTANT : chaque module cree ou modifie doit ensuite recevoir son contenu complet via write_module_content avant de pouvoir commencer l'evaluation initiale (ask_written_exercise refuse techniquement sinon).",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" },
|
||||
objective: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Objectif final mesurable et concret : "Tu seras capable de [faire X] dans [situation Y]"'
|
||||
},
|
||||
modules: {
|
||||
type: 'array',
|
||||
description:
|
||||
"Modules dans l'ordre d'enseignement souhaite. SEUL le nom est fourni ici : le contenu complet (6 sections, voir write_module_content) est redige SEPAREMENT par write_module_content, jamais ici — tout champ de contenu passe a cet outil est ignore.",
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string', description: 'Nom court du module/concept' }
|
||||
},
|
||||
required: ['name']
|
||||
}
|
||||
}
|
||||
},
|
||||
required: ['subject', 'objective', 'modules']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const objective = asString(args.objective).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!objective) throw new Error('objective manquant')
|
||||
|
||||
if (!getResearchSummary(subject)) {
|
||||
throw new Error(
|
||||
`Aucune recherche enregistree pour "${subject}" : appelle research_topic d'abord.`
|
||||
)
|
||||
}
|
||||
|
||||
const rawModules = Array.isArray(args.modules) ? args.modules : []
|
||||
const modules = rawModules
|
||||
.filter((m): m is Record<string, unknown> => typeof m === 'object' && m !== null)
|
||||
.map((m) => ({ name: asString(m.name).trim() }))
|
||||
.filter((m) => m.name)
|
||||
.slice(0, MAX_MODULES)
|
||||
|
||||
if (modules.length === 0) throw new Error('Aucun module valide fourni')
|
||||
|
||||
createModules(subject, modules)
|
||||
setSubjectObjective(subject, objective)
|
||||
|
||||
return `Plan de cours enregistre pour "${subject}" : ${modules.length} module(s) (${modules.map((m) => m.name).join(', ')}). Appelle maintenant write_module_content pour CHAQUE module afin d'ecrire son contenu complet avant de commencer l'evaluation initiale (ask_written_exercise refuse sinon).`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import {
|
||||
getResearchSummary,
|
||||
listModules,
|
||||
getProgress,
|
||||
getModuleDetail
|
||||
} from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const getCoursePlan: SkillDefinition = {
|
||||
name: 'get_course_plan',
|
||||
description:
|
||||
"Lit l'etat actuel d'un sujet (recherche deja faite, niveau evalue, modules et leur statut/verrouillage, contenu complet du module en cours). A appeler en debut de session si l'utilisateur mentionne un sujet deja entame (pour reprendre exactement la ou le plan de cours en etait reste), ou avant d'enseigner/evaluer un module pour relire ce qui a deja ete ecrit et rester coherent.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" }
|
||||
},
|
||||
required: ['subject']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
|
||||
const research = getResearchSummary(subject)
|
||||
const modules = listModules(subject)
|
||||
const progress = getProgress(subject)[0]
|
||||
|
||||
if (!research && modules.length === 0) {
|
||||
return `Aucun plan de cours existant pour "${subject}" : commence par research_topic.`
|
||||
}
|
||||
|
||||
const modulesText = modules.length
|
||||
? modules.map((m) => `- ${m.name} : ${m.status}${m.locked ? ' (verrouille)' : ''}`).join('\n')
|
||||
: "Aucun module cree pour l'instant (fais generate_course_plan apres l'evaluation initiale)."
|
||||
|
||||
const currentModule = modules.find((m) => !m.locked && m.status !== 'acquired')
|
||||
const currentModuleDetail = currentModule ? getModuleDetail(subject, currentModule.name) : null
|
||||
|
||||
const lines = [
|
||||
`Sujet "${subject}" — statut: ${progress?.status ?? 'inconnu'}, niveau: ${progress?.level ?? 'non evalue'}.`,
|
||||
research ? 'Recherche deja effectuee.' : 'Recherche pas encore faite.',
|
||||
'Modules:',
|
||||
modulesText
|
||||
]
|
||||
|
||||
if (currentModuleDetail) {
|
||||
lines.push(
|
||||
`\nModule en cours : "${currentModuleDetail.name}" (${currentModuleDetail.status}).`
|
||||
)
|
||||
lines.push(
|
||||
currentModuleDetail.theorySummary
|
||||
? `Contenu deja ecrit pour ce module :\n${currentModuleDetail.theorySummary}`
|
||||
: "Aucun contenu ecrit pour ce module pour l'instant : appelle write_module_content avant de l'enseigner."
|
||||
)
|
||||
}
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { trackConceptMastery } from './trackConceptMastery'
|
||||
import { askWrittenExercise } from './askWrittenExercise'
|
||||
import { recordSubjectLevel } from './recordSubjectLevel'
|
||||
import { drawSchema } from './drawSchema'
|
||||
import { drawFlowDiagram } from './drawFlowDiagram'
|
||||
import { researchTopic } from './researchTopic'
|
||||
import { getCoursePlan } from './getCoursePlan'
|
||||
import { generateCoursePlan } from './generateCoursePlan'
|
||||
import { completeModule } from './completeModule'
|
||||
import { completeSubject } from './completeSubject'
|
||||
import { writeModuleContent } from './writeModuleContent'
|
||||
import { openModuleForUser } from './openModuleForUser'
|
||||
|
||||
export const coachSkills: SkillDefinition[] = [
|
||||
trackConceptMastery,
|
||||
askWrittenExercise,
|
||||
recordSubjectLevel,
|
||||
drawSchema,
|
||||
drawFlowDiagram,
|
||||
researchTopic,
|
||||
getCoursePlan,
|
||||
generateCoursePlan,
|
||||
completeModule,
|
||||
completeSubject,
|
||||
writeModuleContent,
|
||||
openModuleForUser
|
||||
]
|
||||
@@ -0,0 +1,41 @@
|
||||
import { getModuleDetail } from '../../coach/coachStore'
|
||||
import { openCoachProgressWindow } from '../../coach/progressWindow'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const openModuleForUser: SkillDefinition = {
|
||||
name: 'open_module_for_user',
|
||||
description:
|
||||
"Ouvre directement la page du module dans la fenetre de progression, pour que l'utilisateur l'etudie par lui-meme (texte complet + schemas deja prets) — Max ne fait plus de cours a l'oral (demande utilisateur explicite) : annonce l'ouverture en une phrase courte, appelle cet outil, puis ARRETE-TOI LA. Si l'utilisateur pose une question orale ensuite, reponds-y normalement ; si elle revele un trou dans le contenu, enrichis-le via write_module_content.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" },
|
||||
module: { type: 'string', description: 'Module a ouvrir (deja deverrouille et ecrit)' }
|
||||
},
|
||||
required: ['subject', 'module']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const module = asString(args.module).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!module) throw new Error('module manquant')
|
||||
|
||||
const detail = getModuleDetail(subject, module)
|
||||
if (!detail) throw new Error(`Module "${module}" introuvable pour "${subject}"`)
|
||||
if (detail.locked) {
|
||||
throw new Error(
|
||||
`Le module "${module}" est encore verrouille : le module precedent doit etre valide avant.`
|
||||
)
|
||||
}
|
||||
if (!detail.theorySummary || !detail.theorySummary.trim()) {
|
||||
throw new Error(
|
||||
`Le contenu du module "${module}" n'est pas encore ecrit : appelle write_module_content avant de l'ouvrir.`
|
||||
)
|
||||
}
|
||||
|
||||
openCoachProgressWindow({ subject, module })
|
||||
|
||||
return `Module "${module}" ouvert pour l'utilisateur dans la page de progression.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { hasAssessment, setSubjectLevel, setSubjectStatus } from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const recordSubjectLevel: SkillDefinition = {
|
||||
name: 'record_subject_level',
|
||||
description:
|
||||
"Enregistre le niveau evalue de l'utilisateur sur un sujet (debutant/intermediaire/avance), a l'issue de l'evaluation initiale. Necessite qu'au moins une question ait ete posee a l'ecrit via ask_written_exercise pour ce sujet : echoue sinon.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" },
|
||||
level: {
|
||||
type: 'string',
|
||||
description: 'Niveau evalue (ex: "debutant", "intermediaire", "avance")'
|
||||
}
|
||||
},
|
||||
required: ['subject', 'level']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const level = asString(args.level).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!level) throw new Error('level manquant')
|
||||
|
||||
if (!hasAssessment(subject)) {
|
||||
throw new Error(
|
||||
`Aucune evaluation ecrite enregistree pour "${subject}" : appelle ask_written_exercise avant de fixer un niveau.`
|
||||
)
|
||||
}
|
||||
|
||||
setSubjectLevel(subject, level)
|
||||
setSubjectStatus(subject, 'in_progress')
|
||||
return `Niveau de "${subject}" enregistre : ${level}.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { setResearchSummary, setSubjectStatus } from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
/** Limite chaque section pour eviter un stockage demesure, sans etre restrictif pour une vraie synthese. */
|
||||
const SECTION_MAX_LEN = 2000
|
||||
|
||||
function clamp(value: unknown): string {
|
||||
return asString(value).trim().slice(0, SECTION_MAX_LEN)
|
||||
}
|
||||
|
||||
const MIN_KEY_CONCEPTS = 5
|
||||
const MAX_KEY_CONCEPTS = 10
|
||||
const MIN_COMMON_ERRORS = 3
|
||||
|
||||
function clampList(value: unknown, max: number): string[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
return value
|
||||
.map((v) => asString(v).trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, max)
|
||||
}
|
||||
|
||||
// RÈGLE 2 de docs/Max_Recherche_Sources_Coach.md : minimum de sources selon le type de sujet
|
||||
// (borne basse retenue pour chaque plage, ex. "6 a 8" -> 6).
|
||||
const DOMAIN_MIN_SOURCES = new Map<string, number>([
|
||||
['math_science', 5],
|
||||
['computer_science', 6],
|
||||
['humanities', 7],
|
||||
['medicine_law_finance', 10],
|
||||
['specialized_rare', 5]
|
||||
])
|
||||
const VALID_DOMAINS = [...DOMAIN_MIN_SOURCES.keys()]
|
||||
const VALID_LEVELS = [1, 2, 3, 4]
|
||||
const MAX_SOURCES = 20
|
||||
|
||||
interface ParsedSource {
|
||||
title: string
|
||||
url: string
|
||||
level: number
|
||||
}
|
||||
|
||||
export const researchTopic: SkillDefinition = {
|
||||
name: 'research_topic',
|
||||
description:
|
||||
"Premiere etape OBLIGATOIRE quand l'utilisateur veut apprendre un sujet. Suit docs/Max_Recherche_Sources_Coach.md : Max ne genere JAMAIS un cours depuis sa seule memoire. Avant cet appel, mene une vraie recherche web avec search_web sur 5 axes (histoire/contexte, definition/theorie, applications concretes, erreurs typiques, ressources pedagogiques existantes), EN SILENCE (resultats texte uniquement, jamais annonce a l'oral). Compile ensuite les sources trouvees dans le champ 'sources' (titre, URL exacte renvoyee par search_web, niveau de fiabilite 1 a 4). Nombre minimum de sources selon le sujet : maths/sciences 5, informatique 6 a 8, sciences humaines 7 a 10, medecine/droit/finance 10, sujet rare 5 minimum + signalement explicite dans notDocumented. Jamais une source niveau 4 seule (Wikipedia, forums, blogs non identifies) : au moins une source niveau 1, 2 ou 3 requise. Precise aussi 5 a 10 concepts cles, les 3 erreurs typiques les plus frequentes, et une explication 'methode Feynman' (comme a un enfant de 12 ans, sans jargon) prouvant que tu maitrises le sujet avant de l'enseigner — si tu ne peux pas l'ecrire simplement, cherche davantage avant d'appeler cet outil.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" },
|
||||
subjectDomain: {
|
||||
type: 'string',
|
||||
enum: VALID_DOMAINS,
|
||||
description:
|
||||
'Categorie du sujet, determine le nombre minimum de sources exige : math_science, computer_science, humanities, medicine_law_finance, specialized_rare'
|
||||
},
|
||||
sources: {
|
||||
type: 'array',
|
||||
description:
|
||||
"Sources reellement consultees via search_web (titre + URL exacte renvoyee par l'outil, jamais inventee). Niveau 1 = reference absolue (universites, documentation officielle, revues scientifiques, institutions) ; 2 = pedagogique fiable (Khan Academy, OpenStax, Eduscol) ; 3 = complementaire (blogs d'experts identifies, tutoriels officiels) ; 4 = a utiliser avec precaution (Wikipedia, forums) — jamais seul.",
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string', description: 'Titre de la page/source' },
|
||||
url: { type: 'string', description: 'URL exacte renvoyee par search_web' },
|
||||
level: { type: 'number', enum: VALID_LEVELS, description: 'Niveau de fiabilite 1 a 4' }
|
||||
},
|
||||
required: ['title', 'url', 'level']
|
||||
}
|
||||
},
|
||||
definition: { type: 'string', description: "Definition claire : qu'est-ce que c'est ?" },
|
||||
usageToday: { type: 'string', description: "A quoi ca sert aujourd'hui ?" },
|
||||
whyUsedToday: { type: 'string', description: "Pourquoi on s'en sert aujourd'hui ?" },
|
||||
practicalCases: { type: 'string', description: 'Quels sont les cas pratiques ?' },
|
||||
application: { type: 'string', description: 'Comment mettre en application le sujet ?' },
|
||||
prerequisites: {
|
||||
type: 'string',
|
||||
description:
|
||||
"Prerequis necessaires avant de commencer ce sujet (ce que l'eleve doit deja savoir)"
|
||||
},
|
||||
keyConcepts: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description: '5 a 10 concepts cles du sujet, du plus simple au plus complexe'
|
||||
},
|
||||
commonErrors: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description: 'Les 3 erreurs typiques les plus frequentes sur ce sujet'
|
||||
},
|
||||
feynmanExplanation: {
|
||||
type: 'string',
|
||||
description:
|
||||
"Explication du sujet en langage simple, comme a un enfant de 12 ans, avec une analogie : preuve que tu maitrises le sujet avant de l'enseigner (technique Feynman)"
|
||||
},
|
||||
wellDocumented: {
|
||||
type: 'string',
|
||||
description: 'Aspects du sujet bien documentes par au moins 2 sources independantes'
|
||||
},
|
||||
partiallyDocumented: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Aspects documentes par une seule source (a mentionner avec nuance) — laisser vide si aucun'
|
||||
},
|
||||
notDocumented: {
|
||||
type: 'string',
|
||||
description:
|
||||
"Aspects pour lesquels aucune source fiable n'a ete trouvee, ou signalement si le sujet est rare/peu documente — laisser vide si aucun"
|
||||
}
|
||||
},
|
||||
required: [
|
||||
'subject',
|
||||
'subjectDomain',
|
||||
'sources',
|
||||
'definition',
|
||||
'usageToday',
|
||||
'whyUsedToday',
|
||||
'practicalCases',
|
||||
'application',
|
||||
'prerequisites',
|
||||
'keyConcepts',
|
||||
'commonErrors',
|
||||
'feynmanExplanation'
|
||||
]
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
|
||||
const subjectDomain = asString(args.subjectDomain).trim()
|
||||
if (!VALID_DOMAINS.includes(subjectDomain)) {
|
||||
throw new Error(`subjectDomain invalide : ${VALID_DOMAINS.join(', ')}`)
|
||||
}
|
||||
|
||||
const rawSources = Array.isArray(args.sources) ? args.sources : []
|
||||
const sources: ParsedSource[] = rawSources.slice(0, MAX_SOURCES).map((raw, index) => {
|
||||
const s = (typeof raw === 'object' && raw !== null ? raw : {}) as Record<string, unknown>
|
||||
const title = asString(s.title).trim()
|
||||
const url = asString(s.url).trim()
|
||||
const level = Number(s.level)
|
||||
if (!title) throw new Error(`source sans titre (item ${index + 1})`)
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
throw new Error(`source sans URL valide (item ${index + 1}) : "${url}"`)
|
||||
}
|
||||
if (!VALID_LEVELS.includes(level)) {
|
||||
throw new Error(`niveau de source invalide (item ${index + 1}) : doit etre 1, 2, 3 ou 4`)
|
||||
}
|
||||
return { title, url, level }
|
||||
})
|
||||
|
||||
const minSources = DOMAIN_MIN_SOURCES.get(subjectDomain) ?? 5
|
||||
if (sources.length < minSources) {
|
||||
throw new Error(
|
||||
`Au moins ${minSources} sources requises pour un sujet "${subjectDomain}" (${sources.length} fournie(s)). Utilise search_web sur les 5 axes (histoire, definition/theorie, applications, erreurs typiques, ressources pedagogiques) avant d'appeler research_topic.`
|
||||
)
|
||||
}
|
||||
if (!sources.some((s) => s.level <= 3)) {
|
||||
throw new Error(
|
||||
'Au moins une source de niveau 1, 2 ou 3 est requise : impossible de se baser uniquement sur des sources de niveau 4 (Wikipedia, forums, blogs non identifies).'
|
||||
)
|
||||
}
|
||||
|
||||
const keyConcepts = clampList(args.keyConcepts, MAX_KEY_CONCEPTS)
|
||||
const commonErrors = clampList(args.commonErrors, MIN_COMMON_ERRORS + 2)
|
||||
|
||||
const textSections = {
|
||||
definition: clamp(args.definition),
|
||||
usageToday: clamp(args.usageToday),
|
||||
whyUsedToday: clamp(args.whyUsedToday),
|
||||
practicalCases: clamp(args.practicalCases),
|
||||
application: clamp(args.application),
|
||||
prerequisites: clamp(args.prerequisites),
|
||||
feynmanExplanation: clamp(args.feynmanExplanation)
|
||||
}
|
||||
const sections = {
|
||||
...textSections,
|
||||
subjectDomain,
|
||||
sources,
|
||||
keyConcepts,
|
||||
commonErrors,
|
||||
wellDocumented: clamp(args.wellDocumented),
|
||||
partiallyDocumented: clamp(args.partiallyDocumented),
|
||||
notDocumented: clamp(args.notDocumented)
|
||||
}
|
||||
if (Object.values(textSections).some((s) => !s)) {
|
||||
throw new Error('Toutes les sections textuelles de la recherche sont requises')
|
||||
}
|
||||
if (keyConcepts.length < MIN_KEY_CONCEPTS) {
|
||||
throw new Error(`keyConcepts doit contenir au moins ${MIN_KEY_CONCEPTS} concepts`)
|
||||
}
|
||||
if (commonErrors.length < MIN_COMMON_ERRORS) {
|
||||
throw new Error(`commonErrors doit contenir au moins ${MIN_COMMON_ERRORS} erreurs typiques`)
|
||||
}
|
||||
|
||||
setResearchSummary(subject, JSON.stringify(sections))
|
||||
setSubjectStatus(subject, 'assessing')
|
||||
|
||||
return `Recherche sur "${subject}" enregistree (${sources.length} sources, prerequis, ${keyConcepts.length} concepts cles, ${commonErrors.length} erreurs typiques, explication Feynman). Passe maintenant au plan de cours (generate_course_plan).`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { upsertConceptStatus, hasAssessment, type ConceptStatus } from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const VALID_STATUSES: ConceptStatus[] = ['not_started', 'in_progress', 'acquired', 'to_review']
|
||||
const EVALUATED_STATUSES: ConceptStatus[] = ['acquired', 'to_review']
|
||||
|
||||
export const trackConceptMastery: SkillDefinition = {
|
||||
name: 'track_concept_mastery',
|
||||
description:
|
||||
"Enregistre l'etat de maitrise d'un concept pour un sujet d'apprentissage en cours (not_started, in_progress, acquired, to_review). not_started/in_progress sont de simples marqueurs de progression pendant l'enseignement. acquired/to_review sont des jugements d'evaluation : ils exigent qu'une question ait ete posee a l'ecrit via ask_written_exercise pour ce concept au prealable, sinon l'appel echoue.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: {
|
||||
type: 'string',
|
||||
description: 'Sujet d’apprentissage en cours (ex: "trigonometrie")'
|
||||
},
|
||||
concept: { type: 'string', description: 'Nom du concept precis' },
|
||||
status: {
|
||||
type: 'string',
|
||||
enum: VALID_STATUSES,
|
||||
description: 'Etat de maitrise du concept'
|
||||
}
|
||||
},
|
||||
required: ['subject', 'concept', 'status']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const concept = asString(args.concept).trim()
|
||||
const status = asString(args.status) as ConceptStatus
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!concept) throw new Error('concept manquant')
|
||||
if (!VALID_STATUSES.includes(status)) throw new Error('status invalide')
|
||||
|
||||
if (EVALUATED_STATUSES.includes(status) && !hasAssessment(subject, concept)) {
|
||||
throw new Error(
|
||||
`Aucune evaluation ecrite enregistree pour "${concept}" (${subject}) : appelle ask_written_exercise avant de juger ce statut.`
|
||||
)
|
||||
}
|
||||
|
||||
upsertConceptStatus(subject, concept, status)
|
||||
return `Concept "${concept}" (${subject}) marque comme "${status}".`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import {
|
||||
setModuleTheory,
|
||||
validateModuleContent,
|
||||
canWriteModuleContent,
|
||||
REQUIRED_CONTENT_SECTIONS
|
||||
} from '../../coach/coachStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
// Releve de 8000 a 20000 : la structure imposee par docs/Max_Regles_Strictes_Module_Coach.md
|
||||
// (6 sections, ~800 mots minimum, 6 exercices detailles + un exercice de debogage) depasse
|
||||
// largement l'ancienne limite pensee pour une structure plus sommaire a 5 sections.
|
||||
const CONTENT_MAX_LEN = 20000
|
||||
|
||||
export const writeModuleContent: SkillDefinition = {
|
||||
name: 'write_module_content',
|
||||
description: `Redige ou met a jour le contenu COMPLET d'un module existant : c'est ce que l'utilisateur va lire lui-meme pour apprendre (Max n'enseigne plus a l'oral). A appeler pour CHAQUE module juste apres generate_course_plan, avant la moindre question d'evaluation, puis a nouveau a tout moment pour l'enrichir si une question de l'utilisateur revele un trou. Structure OBLIGATOIRE, dans cet ordre, chaque section introduite par son titre en clair : ${REQUIRED_CONTENT_SECTIONS.join(', ')}. Avant d'ecrire, VERIFIE deux fois chaque calcul/definition/analogie (une erreur factuelle invalide le module). Refuse techniquement si une section manque, est hors ordre, trop courte, ou si un module ANTERIEUR n'est pas encore acquis (interdiction de rediger un module plus loin avant que le precedent soit valide, une fois le parcours commence).`,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string', description: "Sujet d'apprentissage" },
|
||||
module: { type: 'string', description: 'Nom du module' },
|
||||
content: {
|
||||
type: 'string',
|
||||
description:
|
||||
"Contenu complet et structure du module (voir description de l'outil pour les 6 sections obligatoires et leurs exigences : longueurs minimales, phase guidee avec etapes numerotees, 6 exercices numerotes repartis sur 3 niveaux de difficulte, exercice de debogage)."
|
||||
}
|
||||
},
|
||||
required: ['subject', 'module', 'content']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const subject = asString(args.subject).trim()
|
||||
const module = asString(args.module).trim()
|
||||
const content = asString(args.content).trim().slice(0, CONTENT_MAX_LEN)
|
||||
if (!subject) throw new Error('subject manquant')
|
||||
if (!module) throw new Error('module manquant')
|
||||
if (!content) throw new Error('content manquant')
|
||||
|
||||
const { ok, blockedBy } = canWriteModuleContent(subject, module)
|
||||
if (!ok) {
|
||||
throw new Error(
|
||||
`Le module "${blockedBy}" n'est pas encore acquis : interdit de rediger/modifier le contenu de "${module}" avant de l'avoir valide (complete_module). Concentre-toi sur "${blockedBy}".`
|
||||
)
|
||||
}
|
||||
|
||||
const violations = validateModuleContent(content)
|
||||
if (violations.length > 0) {
|
||||
throw new Error(
|
||||
`Contenu invalide, corrige avant d'enregistrer :\n- ${violations.join('\n- ')}`
|
||||
)
|
||||
}
|
||||
|
||||
const updated = setModuleTheory(subject, module, content)
|
||||
if (!updated) throw new Error(`Module "${module}" introuvable pour "${subject}"`)
|
||||
|
||||
return `Contenu du module "${module}" enregistre (${content.length} caracteres, structure conforme).`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { readFile } from 'fs/promises'
|
||||
import { extname, basename } from 'path'
|
||||
import mammoth from 'mammoth'
|
||||
import pdfParse from 'pdf-parse'
|
||||
|
||||
// Garde le contenu dans une taille raisonnable pour le contexte de conversation (cout/latence).
|
||||
const MAX_CHARS = 12000
|
||||
|
||||
export interface ExtractedDocument {
|
||||
name: string
|
||||
text: string
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
export async function extractText(filePath: string): Promise<ExtractedDocument> {
|
||||
const name = basename(filePath)
|
||||
const ext = extname(filePath).toLowerCase()
|
||||
|
||||
let text: string
|
||||
switch (ext) {
|
||||
case '.txt':
|
||||
case '.md':
|
||||
case '.csv':
|
||||
text = await readFile(filePath, 'utf-8')
|
||||
break
|
||||
case '.docx': {
|
||||
const buffer = await readFile(filePath)
|
||||
const result = await mammoth.extractRawText({ buffer })
|
||||
text = result.value
|
||||
break
|
||||
}
|
||||
case '.pdf': {
|
||||
const buffer = await readFile(filePath)
|
||||
const result = await pdfParse(buffer)
|
||||
text = result.text
|
||||
break
|
||||
}
|
||||
default:
|
||||
throw new Error(`Format de fichier non supporte : ${ext || '(sans extension)'}`)
|
||||
}
|
||||
|
||||
const truncated = text.length > MAX_CHARS
|
||||
return { name, text: truncated ? text.slice(0, MAX_CHARS) : text, truncated }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { SkillDefinition } from './types'
|
||||
import type { Mode } from '../mode/modeState'
|
||||
import { getModesForSkill } from './modeMap'
|
||||
import { windowsSkills } from './windows'
|
||||
import { macSkills } from './mac'
|
||||
import { visionSkills } from './vision'
|
||||
import { memorySkills } from './memory'
|
||||
import { webSkills } from './web'
|
||||
import { browserSkills } from './browser'
|
||||
import { meetingSkills } from './meeting'
|
||||
import { coachSkills } from './coach'
|
||||
|
||||
export type { SkillDefinition } from './types'
|
||||
|
||||
export function loadSkills(): SkillDefinition[] {
|
||||
const platformSkills = process.platform === 'darwin' ? macSkills : windowsSkills
|
||||
return [
|
||||
...platformSkills,
|
||||
...visionSkills,
|
||||
...memorySkills,
|
||||
...webSkills,
|
||||
...browserSkills,
|
||||
...meetingSkills,
|
||||
...coachSkills
|
||||
]
|
||||
}
|
||||
|
||||
/** Filtre les skills exposes a l'IA selon le mode actif (voir docs/skills.md). */
|
||||
export function getSkillsForMode(mode: Mode): SkillDefinition[] {
|
||||
return loadSkills().filter((skill) => getModesForSkill(skill.name).includes(mode))
|
||||
}
|
||||
|
||||
export function findSkill(name: string): SkillDefinition | undefined {
|
||||
return loadSkills().find((skill) => skill.name === name)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import type { SkillDefinition } from '../types'
|
||||
|
||||
// A completer : equivalents macOS des competences Windows (osascript / open / etc.).
|
||||
export const macSkills: SkillDefinition[] = []
|
||||
@@ -0,0 +1,15 @@
|
||||
import { getLastMeetingSummary } from '../../meeting/meetingStore'
|
||||
import type { SkillDefinition } from '../types'
|
||||
|
||||
export const getLastMeetingSummarySkill: SkillDefinition = {
|
||||
name: 'get_last_meeting_summary',
|
||||
description:
|
||||
"Renvoie le resume de la derniere session de transcription (reunion ou cours) enregistree via le menu contextuel de l'avatar (clic droit).",
|
||||
parameters: { type: 'object', properties: {}, required: [] },
|
||||
execute: async () => {
|
||||
const summary = getLastMeetingSummary()
|
||||
return summary
|
||||
? `Resume de la derniere session enregistree :\n${summary}`
|
||||
: "Aucune session de transcription n'a encore ete enregistree."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { getLastMeetingSummarySkill } from './getLastMeetingSummary'
|
||||
|
||||
export const meetingSkills: SkillDefinition[] = [getLastMeetingSummarySkill]
|
||||
@@ -0,0 +1,26 @@
|
||||
import { adjustMood } from '../../memory/store'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const adjustMoodSkill: SkillDefinition = {
|
||||
name: 'adjust_mood',
|
||||
description:
|
||||
"Ajuste ton humeur suite a l'interaction en cours. Appelle cette fonction avec 'positif' si l'echange est agreable, chaleureux, ou qu'une bonne nouvelle est partagee ; avec 'negatif' si l'utilisateur est frustre, enerve, ou que l'echange est tendu. N'appelle rien pour un echange neutre ou purement factuel.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
change: {
|
||||
type: 'string',
|
||||
enum: ['positif', 'negatif'],
|
||||
description: "Sens du changement d'humeur"
|
||||
}
|
||||
},
|
||||
required: ['change']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const change = asString(args.change)
|
||||
const delta = change === 'positif' ? 1 : change === 'negatif' ? -1 : 0
|
||||
const mood = adjustMood(delta)
|
||||
return `Humeur ajustee (score actuel : ${mood}).`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { clearAllMemories, forgetMemory } from '../../memory/store'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const forgetInfo: SkillDefinition = {
|
||||
name: 'forget_info',
|
||||
description:
|
||||
'Supprime une information precedemment memorisee sur l\'utilisateur, ou efface toute la memoire si demande explicitement ("tout").',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: {
|
||||
type: 'string',
|
||||
description: 'Mots-cles de l\'information a oublier, ou "tout" pour tout effacer'
|
||||
}
|
||||
},
|
||||
required: ['query']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const query = asString(args.query).trim()
|
||||
if (!query) throw new Error('recherche manquante')
|
||||
|
||||
if (query.toLowerCase() === 'tout') {
|
||||
clearAllMemories()
|
||||
return 'Toute la memoire a ete effacee.'
|
||||
}
|
||||
|
||||
const removed = forgetMemory(query)
|
||||
return removed
|
||||
? `Information oubliee : ${query}`
|
||||
: `Aucune information correspondant a "${query}" trouvee.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { rememberInfo } from './rememberInfo'
|
||||
import { forgetInfo } from './forgetInfo'
|
||||
import { adjustMoodSkill } from './adjustMood'
|
||||
|
||||
// Memoire et humeur sont independantes de l'OS, communes a toutes les plateformes.
|
||||
export const memorySkills: SkillDefinition[] = [rememberInfo, forgetInfo, adjustMoodSkill]
|
||||
@@ -0,0 +1,25 @@
|
||||
import { addMemory } from '../../memory/store'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const rememberInfo: SkillDefinition = {
|
||||
name: 'remember_info',
|
||||
description:
|
||||
"Memorise durablement une information sur l'utilisateur (preference, habitude, fait personnel important) pour s'en souvenir dans les conversations futures, meme apres redemarrage.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
info: {
|
||||
type: 'string',
|
||||
description: 'Information a retenir, formulee clairement (ex: "aime le cafe sans sucre")'
|
||||
}
|
||||
},
|
||||
required: ['info']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const info = asString(args.info).trim()
|
||||
if (!info) throw new Error('information manquante')
|
||||
addMemory(info)
|
||||
return `Retenu : ${info}`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { Mode } from '../mode/modeState'
|
||||
|
||||
// Repartition verrouillee dans docs/skills.md. Un skill absent de cette table n'est expose dans
|
||||
// aucun mode (voir l'avertissement dans getSkillsForMode) : toute nouvelle competence doit y etre
|
||||
// ajoutee explicitement.
|
||||
export const SKILL_MODES: Record<string, Mode[]> = {
|
||||
// Transversal : disponible dans les 3 modes, y compris Coach (aucun effet de bord systeme).
|
||||
search_web: ['basic', 'coach', 'assistant'],
|
||||
navigate_browser: ['basic', 'coach', 'assistant'],
|
||||
read_browser_page: ['basic', 'coach', 'assistant'],
|
||||
click_browser_element: ['basic', 'coach', 'assistant'],
|
||||
go_back_browser: ['basic', 'coach', 'assistant'],
|
||||
translate_browser_page: ['basic', 'coach', 'assistant'],
|
||||
highlight_browser_text: ['basic', 'coach', 'assistant'],
|
||||
adjust_mood: ['basic', 'coach', 'assistant'],
|
||||
|
||||
// Basic + herite par Coach (lecture seule, sans effet de bord).
|
||||
check_system_memory: ['basic', 'coach', 'assistant'],
|
||||
check_storage: ['basic', 'coach', 'assistant'],
|
||||
check_battery_and_cpu: ['basic', 'coach', 'assistant'],
|
||||
check_internet_connection: ['basic', 'coach', 'assistant'],
|
||||
|
||||
// Basic uniquement (herite par Assistant, jamais par Coach : actions avec effet de bord reel).
|
||||
play_music: ['basic', 'assistant'],
|
||||
open_app: ['basic', 'assistant'],
|
||||
close_app: ['basic', 'assistant'],
|
||||
open_notepad: ['basic', 'assistant'],
|
||||
create_document: ['basic', 'assistant'],
|
||||
create_powerpoint: ['basic', 'assistant'],
|
||||
control_volume: ['basic', 'assistant'],
|
||||
control_media_playback: ['basic', 'assistant'],
|
||||
take_screenshot: ['basic', 'assistant'],
|
||||
clipboard: ['basic', 'assistant'],
|
||||
search_file: ['basic', 'assistant'],
|
||||
set_reminder: ['basic', 'assistant'],
|
||||
lock_screen: ['basic', 'assistant'],
|
||||
empty_recycle_bin: ['basic', 'assistant'],
|
||||
show_notification: ['basic', 'assistant'],
|
||||
print_file: ['basic', 'assistant'],
|
||||
create_folder: ['basic', 'assistant'],
|
||||
create_file: ['basic', 'assistant'],
|
||||
delete_file: ['basic', 'assistant'],
|
||||
fill_browser_field: ['basic', 'assistant'],
|
||||
|
||||
// Exclusif Coach : mecanisme central de detection des blocages.
|
||||
analyze_screen: ['coach'],
|
||||
watch_camera: ['coach'],
|
||||
track_concept_mastery: ['coach'],
|
||||
ask_written_exercise: ['coach'],
|
||||
record_subject_level: ['coach'],
|
||||
draw_schema: ['coach'],
|
||||
draw_flow_diagram: ['coach'],
|
||||
research_topic: ['coach'],
|
||||
get_course_plan: ['coach'],
|
||||
generate_course_plan: ['coach'],
|
||||
complete_module: ['coach'],
|
||||
complete_subject: ['coach'],
|
||||
write_module_content: ['coach'],
|
||||
open_module_for_user: ['coach'],
|
||||
|
||||
// Exclusif Assistant.
|
||||
get_last_meeting_summary: ['assistant'],
|
||||
remember_info: ['assistant'],
|
||||
forget_info: ['assistant']
|
||||
}
|
||||
|
||||
export function getModesForSkill(skillName: string): Mode[] {
|
||||
const modes = Object.hasOwn(SKILL_MODES, skillName)
|
||||
? Reflect.get(SKILL_MODES, skillName)
|
||||
: undefined
|
||||
if (!modes) {
|
||||
console.warn(`[mode] skill "${skillName}" absent de SKILL_MODES : expose dans aucun mode.`)
|
||||
return []
|
||||
}
|
||||
return modes
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export interface SkillDefinition {
|
||||
/** Nom de la fonction tel qu'expose a l'IA (function calling). */
|
||||
name: string
|
||||
description: string
|
||||
/** JSON Schema des parametres acceptes par la fonction. */
|
||||
parameters: object
|
||||
/** Execute l'action et renvoie un texte resume que l'IA pourra lire/relayer. */
|
||||
execute: (args: Record<string, unknown>) => Promise<string>
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { desktopCapturer, screen } from 'electron'
|
||||
import { analyzeImage } from '../../ai/vision'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const analyzeScreen: SkillDefinition = {
|
||||
name: 'analyze_screen',
|
||||
description:
|
||||
"Regarde ce qui s'affiche actuellement a l'ecran et repond a une question dessus (expliquer une erreur affichee, commenter un jeu ou une image, lire du texte affiche, decrire une interface...).",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
question: {
|
||||
type: 'string',
|
||||
description: "Ce que l'utilisateur veut savoir sur ce qui s'affiche"
|
||||
}
|
||||
},
|
||||
required: ['question']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const question = asString(args.question, "Decris ce que tu vois a l'ecran.")
|
||||
|
||||
const display = screen.getPrimaryDisplay()
|
||||
const sources = await desktopCapturer.getSources({
|
||||
types: ['screen'],
|
||||
thumbnailSize: display.size
|
||||
})
|
||||
const source = sources[0]
|
||||
if (!source) throw new Error('Aucun ecran detecte')
|
||||
|
||||
const base64 = source.thumbnail.toPNG().toString('base64')
|
||||
return await analyzeImage(`data:image/png;base64,${base64}`, question)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { analyzeScreen } from './analyzeScreen'
|
||||
import { watchCamera } from './watchCamera'
|
||||
|
||||
// Competences communes a toutes les plateformes (Electron fournit desktopCapturer et
|
||||
// getUserMedia de maniere identique sur Windows/Mac).
|
||||
export const visionSkills: SkillDefinition[] = [analyzeScreen, watchCamera]
|
||||
@@ -0,0 +1,25 @@
|
||||
import { requestCameraFrame } from '../../windowBridge'
|
||||
import { analyzeImage } from '../../ai/vision'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const watchCamera: SkillDefinition = {
|
||||
name: 'watch_camera',
|
||||
description:
|
||||
"Prend une photo instantanee via la webcam de l'utilisateur et repond a une question sur ce qu'elle montre (ex: 'que vois-tu ?', 'comment je suis habille ?', 'montre-moi cet objet'). Ne filme pas en continu, une seule photo a chaque appel.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
question: {
|
||||
type: 'string',
|
||||
description: "Ce que l'utilisateur veut savoir sur ce que montre la camera"
|
||||
}
|
||||
},
|
||||
required: ['question']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const question = asString(args.question, 'Decris ce que tu vois.')
|
||||
const dataUrl = await requestCameraFrame()
|
||||
return await analyzeImage(dataUrl, question)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { searchWeb } from './searchWeb'
|
||||
|
||||
// Recherche web, independante de l'OS, commune a toutes les plateformes.
|
||||
export const webSkills: SkillDefinition[] = [searchWeb]
|
||||
@@ -0,0 +1,57 @@
|
||||
import * as cheerio from 'cheerio'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
function resolveRealUrl(ddgHref: string | undefined): string | null {
|
||||
if (!ddgHref) return null
|
||||
try {
|
||||
const url = new URL(ddgHref.startsWith('//') ? `https:${ddgHref}` : ddgHref)
|
||||
return url.searchParams.get('uddg') ?? ddgHref
|
||||
} catch {
|
||||
return ddgHref
|
||||
}
|
||||
}
|
||||
|
||||
export const searchWeb: SkillDefinition = {
|
||||
name: 'search_web',
|
||||
description:
|
||||
"Fait une vraie recherche web et renvoie les premiers resultats reels (titre, extrait et URL exacte) que tu peux lire et resumer. A utiliser pour toute information recente/actuelle que tu ne connais pas avec certitude, et pour trouver l'URL exacte d'un site avant de l'ouvrir avec navigate_browser (ne jamais deviner un nom de domaine). Ne jamais decrire un faux processus de recherche ou inventer un resultat : appelle cette fonction et base ta reponse uniquement sur ce qu'elle renvoie.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: 'Termes de recherche' }
|
||||
},
|
||||
required: ['query']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const query = asString(args.query).trim()
|
||||
if (!query) throw new Error('query manquante')
|
||||
|
||||
const response = await fetch(
|
||||
`https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`,
|
||||
{
|
||||
headers: {
|
||||
'User-Agent':
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36'
|
||||
}
|
||||
}
|
||||
)
|
||||
if (!response.ok) throw new Error(`Recherche web echouee (${response.status})`)
|
||||
|
||||
const $ = cheerio.load(await response.text())
|
||||
const results: string[] = []
|
||||
|
||||
$('.result.web-result .result__body').each((_, el) => {
|
||||
if (results.length >= 5) return
|
||||
const title = $(el).find('.result__title').text().trim().replace(/\s+/g, ' ')
|
||||
const snippet = $(el).find('.result__snippet').text().trim().replace(/\s+/g, ' ')
|
||||
const url = resolveRealUrl($(el).find('.result__a').attr('href'))
|
||||
if (!title) return
|
||||
const parts = [title, url, snippet].filter(Boolean)
|
||||
results.push(parts.join(' — '))
|
||||
})
|
||||
|
||||
if (results.length === 0) return 'Aucun resultat trouve pour cette recherche.'
|
||||
return results.join('\n')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { POWERSHELL_EXE } from './lib/systemPaths'
|
||||
import type { SkillDefinition } from '../types'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
interface ConnectionInfo {
|
||||
Connected: boolean
|
||||
Ip: string | null
|
||||
}
|
||||
|
||||
const PS_SCRIPT = `
|
||||
$ping = Test-Connection -ComputerName 8.8.8.8 -Count 1 -Quiet -ErrorAction SilentlyContinue
|
||||
$ip = (Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue |
|
||||
Where-Object { $_.InterfaceAlias -notmatch 'Loopback' -and $_.IPAddress -notlike '169.254.*' } |
|
||||
Select-Object -First 1).IPAddress
|
||||
[PSCustomObject]@{ Connected = [bool]$ping; Ip = $ip } | ConvertTo-Json
|
||||
`
|
||||
|
||||
export const checkInternet: SkillDefinition = {
|
||||
name: 'check_internet_connection',
|
||||
description: "Teste si la connexion internet fonctionne et donne l'adresse IP locale.",
|
||||
parameters: { type: 'object', properties: {} },
|
||||
execute: async () => {
|
||||
const { stdout } = await execFileAsync(POWERSHELL_EXE, ['-NoProfile', '-Command', PS_SCRIPT], {
|
||||
timeout: 10000
|
||||
})
|
||||
const data = JSON.parse(stdout) as ConnectionInfo
|
||||
return data.Connected
|
||||
? `Internet fonctionne. Adresse IP locale : ${data.Ip ?? 'inconnue'}.`
|
||||
: 'Pas de connexion internet detectee.'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { clipboard } from 'electron'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const clipboardSkill: SkillDefinition = {
|
||||
name: 'clipboard',
|
||||
description: 'Lit le contenu texte du presse-papier, ou y copie un texte donne.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
action: { type: 'string', enum: ['lire', 'copier'], description: 'Action a effectuer' },
|
||||
text: { type: 'string', description: 'Texte a copier (requis si action = copier)' }
|
||||
},
|
||||
required: ['action']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const action = asString(args.action)
|
||||
|
||||
if (action === 'lire') {
|
||||
const text = await clipboard.readText()
|
||||
return text
|
||||
? `Contenu du presse-papier : ${text}`
|
||||
: 'Le presse-papier est vide ou ne contient pas de texte.'
|
||||
}
|
||||
|
||||
if (action === 'copier') {
|
||||
const text = asString(args.text)
|
||||
if (!text) throw new Error('texte manquant')
|
||||
await clipboard.writeText(text)
|
||||
return 'Texte copie dans le presse-papier.'
|
||||
}
|
||||
|
||||
throw new Error('action invalide')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { APP_REGISTRY } from './lib/appRegistry'
|
||||
import { TASKKILL_EXE } from './lib/systemPaths'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
// Certaines applications se lancent via un executable/raccourci mais tournent sous un autre nom
|
||||
// de process une fois ouvertes (ex: la Calculatrice modernisee de Windows 11, les Parametres).
|
||||
// On essaie chaque candidat jusqu'a ce qu'un taskkill reussisse.
|
||||
const CLOSE_OVERRIDES: Record<string, string[]> = {
|
||||
calculatrice: ['CalculatorApp.exe', 'calc.exe', 'Calculator.exe'],
|
||||
calculator: ['CalculatorApp.exe', 'calc.exe', 'Calculator.exe'],
|
||||
parametres: ['SystemSettings.exe']
|
||||
}
|
||||
|
||||
// explorer.exe n'est pas une "application" mais le shell Windows (bureau + barre des taches) :
|
||||
// le tuer fait disparaitre tout l'affichage. Jamais fermable via cette competence.
|
||||
const PROTECTED_PROCESSES = new Set(['explorer.exe'])
|
||||
|
||||
function lookupAppRegistry(key: string): string | undefined {
|
||||
return Object.hasOwn(APP_REGISTRY, key) ? Reflect.get(APP_REGISTRY, key) : undefined
|
||||
}
|
||||
|
||||
function lookupCloseOverride(key: string): string[] | undefined {
|
||||
return Object.hasOwn(CLOSE_OVERRIDES, key) ? Reflect.get(CLOSE_OVERRIDES, key) : undefined
|
||||
}
|
||||
|
||||
const CLOSABLE_APPS = Array.from(
|
||||
new Set([...Object.keys(APP_REGISTRY), ...Object.keys(CLOSE_OVERRIDES)])
|
||||
).filter((key) => !PROTECTED_PROCESSES.has(lookupAppRegistry(key)?.toLowerCase() ?? ''))
|
||||
|
||||
export const closeApp: SkillDefinition = {
|
||||
name: 'close_app',
|
||||
description: `Ferme une application en cours d'execution par son nom. Applications reconnues : ${CLOSABLE_APPS.join(', ')}.`,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
application: { type: 'string', description: "Nom de l'application a fermer" }
|
||||
},
|
||||
required: ['application']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const application = asString(args.application)
|
||||
const key = application.toLowerCase().trim()
|
||||
const target = lookupAppRegistry(key)
|
||||
const rawCandidates = lookupCloseOverride(key) ?? (target ? [target] : null)
|
||||
|
||||
if (!rawCandidates) {
|
||||
return `Application "${application}" non reconnue.`
|
||||
}
|
||||
|
||||
const candidates = rawCandidates.filter((name) => !PROTECTED_PROCESSES.has(name.toLowerCase()))
|
||||
if (candidates.length === 0) {
|
||||
return "L'explorateur de fichiers est le bureau Windows lui-meme : le fermer couperait tout l'affichage, ce n'est pas autorise."
|
||||
}
|
||||
|
||||
for (const processName of candidates) {
|
||||
try {
|
||||
await execFileAsync(TASKKILL_EXE, ['/IM', processName, '/F'])
|
||||
return `${application} ferme(e).`
|
||||
} catch {
|
||||
// on essaie le candidat suivant
|
||||
}
|
||||
}
|
||||
return `${application} ne semble pas etre ouvert(e).`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { shell } from 'electron'
|
||||
import { writeFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { LOCATION_NAMES, resolveLocation } from './lib/locations'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const createFile: SkillDefinition = {
|
||||
name: 'create_file',
|
||||
description: `Cree un fichier texte (.txt) avec un contenu donne dans un emplacement courant (${LOCATION_NAMES.join(', ')}) et l'ouvre.`,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: {
|
||||
type: 'string',
|
||||
description: "Nom du fichier (l'extension .txt est ajoutee si absente)"
|
||||
},
|
||||
content: { type: 'string', description: 'Contenu texte du fichier' },
|
||||
location: {
|
||||
type: 'string',
|
||||
enum: [...LOCATION_NAMES],
|
||||
description: 'Ou creer le fichier (defaut : bureau)'
|
||||
}
|
||||
},
|
||||
required: ['name']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const name = asString(args.name)
|
||||
.trim()
|
||||
.replace(/[\\/:*?"<>|]/g, '_')
|
||||
if (!name) throw new Error('nom manquant')
|
||||
|
||||
const content = typeof args.content === 'string' ? args.content : ''
|
||||
const base = resolveLocation(args.location)
|
||||
const filePath = join(base, name.toLowerCase().endsWith('.txt') ? name : `${name}.txt`)
|
||||
|
||||
writeFileSync(filePath, content, 'utf-8')
|
||||
await shell.openPath(filePath)
|
||||
return `Fichier cree et ouvert : ${filePath}.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { shell } from 'electron'
|
||||
import { existsSync, mkdirSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import { LOCATION_NAMES, resolveLocation } from './lib/locations'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const createFolder: SkillDefinition = {
|
||||
name: 'create_folder',
|
||||
description: `Cree un nouveau dossier dans un emplacement courant (${LOCATION_NAMES.join(', ')}) et l'ouvre.`,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string', description: 'Nom du dossier a creer' },
|
||||
location: {
|
||||
type: 'string',
|
||||
enum: [...LOCATION_NAMES],
|
||||
description: 'Ou creer le dossier (defaut : bureau)'
|
||||
}
|
||||
},
|
||||
required: ['name']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const name = asString(args.name)
|
||||
.trim()
|
||||
.replace(/[\\/:*?"<>|]/g, '_')
|
||||
if (!name) throw new Error('nom manquant')
|
||||
|
||||
const base = resolveLocation(args.location)
|
||||
const dirPath = join(base, name)
|
||||
if (existsSync(dirPath)) return `Le dossier "${name}" existe deja dans ${base}.`
|
||||
|
||||
mkdirSync(dirPath, { recursive: true })
|
||||
await shell.openPath(dirPath)
|
||||
return `Dossier cree et ouvert : ${dirPath}.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { app, shell } from 'electron'
|
||||
import PptxGenJS from 'pptxgenjs'
|
||||
import { join } from 'path'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
interface SlideInput {
|
||||
title: string
|
||||
content?: string
|
||||
}
|
||||
|
||||
export const createPowerpoint: SkillDefinition = {
|
||||
name: 'create_powerpoint',
|
||||
description:
|
||||
"Cree une presentation a partir d'une liste de diapositives (titre + contenu chacune) et l'enregistre en .pptx dans le dossier Documents.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string', description: 'Titre de la presentation (sert de nom de fichier)' },
|
||||
slides: {
|
||||
type: 'array',
|
||||
description: 'Liste des diapositives a creer',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string', description: 'Titre de la diapositive' },
|
||||
content: { type: 'string', description: 'Texte du corps de la diapositive' }
|
||||
},
|
||||
required: ['title']
|
||||
}
|
||||
}
|
||||
},
|
||||
required: ['title', 'slides']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const title = asString(args.title, 'Presentation')
|
||||
const slides = Array.isArray(args.slides) ? (args.slides as SlideInput[]) : []
|
||||
if (slides.length === 0) throw new Error('diapositives manquantes')
|
||||
|
||||
const pptx = new PptxGenJS()
|
||||
for (const slide of slides) {
|
||||
const s = pptx.addSlide()
|
||||
s.addText(slide.title, { x: 0.5, y: 0.4, w: 9, h: 1, fontSize: 28, bold: true })
|
||||
if (slide.content) {
|
||||
s.addText(slide.content, { x: 0.5, y: 1.6, w: 9, h: 4.5, fontSize: 18 })
|
||||
}
|
||||
}
|
||||
|
||||
const safeName = title.replace(/[\\/:*?"<>|]/g, '_').slice(0, 80) || 'Presentation'
|
||||
const pptxPath = join(app.getPath('documents'), `${safeName}.pptx`)
|
||||
await pptx.writeFile({ fileName: pptxPath })
|
||||
await shell.openPath(pptxPath)
|
||||
|
||||
return `Presentation creee, enregistree et ouverte : ${pptxPath}.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { statSync } from 'fs'
|
||||
import { app } from 'electron'
|
||||
import { findFileByName } from './lib/fileSearch'
|
||||
import { POWERSHELL_EXE } from './lib/systemPaths'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const psQuote = (value: string): string => value.replace(/'/g, "''")
|
||||
|
||||
// Jamais question de supprimer un de ces dossiers eux-memes (seulement leur contenu trouve par
|
||||
// recherche), ni une racine de disque.
|
||||
const PROTECTED_PATHS = new Set(
|
||||
(['desktop', 'documents', 'downloads', 'pictures', 'videos', 'music', 'home'] as const).map(
|
||||
(name) => app.getPath(name).toLowerCase()
|
||||
)
|
||||
)
|
||||
|
||||
function stripTrailingSlashes(value: string): string {
|
||||
let end = value.length
|
||||
while (end > 0 && (value[end - 1] === '\\' || value[end - 1] === '/')) end--
|
||||
return value.slice(0, end)
|
||||
}
|
||||
|
||||
function isProtected(path: string): boolean {
|
||||
const normalized = stripTrailingSlashes(path.toLowerCase())
|
||||
if (PROTECTED_PATHS.has(normalized)) return true
|
||||
// Racine de disque (ex: "C:" ou "C:\\")
|
||||
if (/^[a-z]:\\?$/i.test(path)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
export const deleteFileOrFolder: SkillDefinition = {
|
||||
name: 'delete_file',
|
||||
description:
|
||||
"Recherche un fichier ou dossier par son nom et le supprime en l'envoyant a la corbeille (recuperable, jamais de suppression definitive).",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string', description: 'Nom (ou partie du nom) du fichier/dossier a supprimer' }
|
||||
},
|
||||
required: ['name']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const name = asString(args.name).trim()
|
||||
if (!name) throw new Error('nom manquant')
|
||||
|
||||
const foundPath = await findFileByName(name)
|
||||
if (!foundPath) return `Aucun fichier ou dossier correspondant a "${name}" trouve.`
|
||||
|
||||
if (isProtected(foundPath)) {
|
||||
return `"${foundPath}" est un dossier protege, suppression refusee.`
|
||||
}
|
||||
|
||||
const isDirectory = statSync(foundPath).isDirectory()
|
||||
const method = isDirectory ? 'DeleteDirectory' : 'DeleteFile'
|
||||
const script = `
|
||||
Add-Type -AssemblyName Microsoft.VisualBasic
|
||||
[Microsoft.VisualBasic.FileIO.FileSystem]::${method}('${psQuote(foundPath)}', 'OnlyErrorDialogs', 'SendToRecycleBin')
|
||||
`
|
||||
await execFileAsync(POWERSHELL_EXE, ['-NoProfile', '-Command', script])
|
||||
return `Envoye a la corbeille : ${foundPath}.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { POWERSHELL_EXE } from './lib/systemPaths'
|
||||
import type { SkillDefinition } from '../types'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
export const emptyRecycleBin: SkillDefinition = {
|
||||
name: 'empty_recycle_bin',
|
||||
description: "Vide la corbeille Windows pour liberer de l'espace disque.",
|
||||
parameters: { type: 'object', properties: {} },
|
||||
execute: async () => {
|
||||
try {
|
||||
await execFileAsync(POWERSHELL_EXE, ['-NoProfile', '-Command', 'Clear-RecycleBin -Force'])
|
||||
} catch {
|
||||
// Clear-RecycleBin renvoie parfois un code d'erreur si la corbeille est deja vide.
|
||||
}
|
||||
return 'Corbeille videe.'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { playMusic } from './playMusic'
|
||||
import { openApp } from './openApp'
|
||||
import { closeApp } from './closeApp'
|
||||
import { openNotepad } from './openNotepad'
|
||||
import { writeWordDocument } from './writeWordDocument'
|
||||
import { createPowerpoint } from './createPowerpoint'
|
||||
import { systemMemory } from './systemMemory'
|
||||
import { systemStorage } from './systemStorage'
|
||||
import { systemVolume } from './systemVolume'
|
||||
import { mediaControl } from './mediaControl'
|
||||
import { takeScreenshot } from './takeScreenshot'
|
||||
import { clipboardSkill } from './clipboard'
|
||||
import { systemStatus } from './systemStatus'
|
||||
import { searchFile } from './searchFile'
|
||||
import { reminder } from './reminder'
|
||||
import { lockScreen } from './lockScreen'
|
||||
import { emptyRecycleBin } from './emptyRecycleBin'
|
||||
import { showNotification } from './showNotification'
|
||||
import { checkInternet } from './checkInternet'
|
||||
import { printFile } from './printFile'
|
||||
import { createFolder } from './createFolder'
|
||||
import { createFile } from './createFile'
|
||||
import { deleteFileOrFolder } from './deleteFileOrFolder'
|
||||
|
||||
export const windowsSkills: SkillDefinition[] = [
|
||||
playMusic,
|
||||
openApp,
|
||||
closeApp,
|
||||
openNotepad,
|
||||
writeWordDocument,
|
||||
createPowerpoint,
|
||||
systemMemory,
|
||||
systemStorage,
|
||||
systemVolume,
|
||||
mediaControl,
|
||||
takeScreenshot,
|
||||
clipboardSkill,
|
||||
systemStatus,
|
||||
searchFile,
|
||||
reminder,
|
||||
lockScreen,
|
||||
emptyRecycleBin,
|
||||
showNotification,
|
||||
checkInternet,
|
||||
printFile,
|
||||
createFolder,
|
||||
createFile,
|
||||
deleteFileOrFolder
|
||||
]
|
||||
@@ -0,0 +1,25 @@
|
||||
// Cible fixe et connue a l'avance : la requete utilisateur ne sert qu'a choisir une cle,
|
||||
// jamais a construire une commande, pour eviter toute injection.
|
||||
export const APP_REGISTRY: Record<string, string> = {
|
||||
'bloc-notes': 'notepad.exe',
|
||||
notepad: 'notepad.exe',
|
||||
calculatrice: 'calc.exe',
|
||||
calculator: 'calc.exe',
|
||||
paint: 'mspaint.exe',
|
||||
explorateur: 'explorer.exe',
|
||||
'explorateur de fichiers': 'explorer.exe',
|
||||
word: 'winword.exe',
|
||||
excel: 'excel.exe',
|
||||
powerpoint: 'powerpnt.exe',
|
||||
outlook: 'outlook.exe',
|
||||
'panneau de configuration': 'control.exe',
|
||||
'gestionnaire des taches': 'taskmgr.exe',
|
||||
'invite de commandes': 'cmd.exe',
|
||||
terminal: 'wt.exe',
|
||||
chrome: 'chrome.exe',
|
||||
firefox: 'firefox.exe',
|
||||
edge: 'msedge.exe',
|
||||
spotify: 'spotify.exe',
|
||||
claude: 'claude.exe',
|
||||
discord: 'discord.exe'
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { app } from 'electron'
|
||||
import { POWERSHELL_EXE } from './systemPaths'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const QUICK_FOLDERS = Array.from(
|
||||
new Set(
|
||||
(['desktop', 'documents', 'downloads', 'pictures', 'videos', 'music'] as const).map((name) =>
|
||||
app.getPath(name)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
// Dossiers systeme exclus du scan complet : enormes, lents, et quasiment jamais ce que
|
||||
// l'utilisateur cherche.
|
||||
const EXCLUDED_TOP_LEVEL = [
|
||||
'Windows',
|
||||
'Program Files',
|
||||
'Program Files (x86)',
|
||||
'ProgramData',
|
||||
'$Recycle.Bin',
|
||||
'System Volume Information'
|
||||
]
|
||||
|
||||
const STOPWORDS = new Set(['le', 'la', 'les', 'un', 'une', 'des', 'de', 'du', 'et', 'a', 'au'])
|
||||
|
||||
const psQuote = (value: string): string => value.replace(/'/g, "''")
|
||||
const psArray = (values: string[]): string => values.map((v) => `'${psQuote(v)}'`).join(',')
|
||||
|
||||
/** Decoupe en mots significatifs : "bug d'affichage" -> ["bug", "affichage"] (ignore "d", apostrophes...). */
|
||||
function toSignificantWords(nom: string): string[] {
|
||||
return nom
|
||||
.replace(/[`"$;|&]/g, '')
|
||||
.split(/[^\p{L}\p{N}]+/u)
|
||||
.filter((word) => word.length > 1 && !STOPWORDS.has(word.toLowerCase()))
|
||||
}
|
||||
|
||||
/**
|
||||
* Cherche un fichier/dossier par nom, de maniere approximative (mots dans n'importe quel ordre,
|
||||
* insensible aux apostrophes/casse). Dossiers utilisateur d'abord, puis tout le stockage si besoin.
|
||||
* Renvoie le chemin complet du premier resultat, ou null si rien n'est trouve.
|
||||
*/
|
||||
export async function findFileByName(nom: string): Promise<string | null> {
|
||||
const words = toSignificantWords(nom)
|
||||
const firstWord = words[0]
|
||||
if (!firstWord) return null
|
||||
|
||||
const primaryWord = [...words].sort((a, b) => b.length - a.length)[0] ?? firstWord
|
||||
|
||||
const script = `
|
||||
$ErrorActionPreference = 'SilentlyContinue'
|
||||
$words = @(${psArray(words)})
|
||||
function Test-NameMatch($name) {
|
||||
foreach ($w in $words) { if ($name -notlike "*$w*") { return $false } }
|
||||
return $true
|
||||
}
|
||||
$found = $null
|
||||
|
||||
foreach ($dir in @(${psArray(QUICK_FOLDERS)})) {
|
||||
$match = Get-ChildItem -Path $dir -Recurse -Filter '*${psQuote(primaryWord)}*' -Force -ErrorAction SilentlyContinue |
|
||||
Where-Object { Test-NameMatch $_.Name } | Select-Object -First 1
|
||||
if ($match) { $found = $match.FullName; break }
|
||||
}
|
||||
|
||||
if (-not $found) {
|
||||
$exclude = @(${psArray(EXCLUDED_TOP_LEVEL)})
|
||||
$drives = [System.IO.DriveInfo]::GetDrives() | Where-Object { ($_.DriveType -eq 'Fixed' -or $_.DriveType -eq 'Removable') -and $_.IsReady } | ForEach-Object { $_.RootDirectory.FullName }
|
||||
:scan foreach ($drive in $drives) {
|
||||
$topFile = Get-ChildItem -Path $drive -File -Force -Filter '*${psQuote(primaryWord)}*' -ErrorAction SilentlyContinue |
|
||||
Where-Object { Test-NameMatch $_.Name } | Select-Object -First 1
|
||||
if ($topFile) { $found = $topFile.FullName; break scan }
|
||||
$topDirs = Get-ChildItem -Path $drive -Directory -Force -ErrorAction SilentlyContinue | Where-Object { $exclude -notcontains $_.Name }
|
||||
foreach ($dir in $topDirs) {
|
||||
$match = Get-ChildItem -Path $dir.FullName -Recurse -Filter '*${psQuote(primaryWord)}*' -Force -ErrorAction SilentlyContinue |
|
||||
Where-Object { Test-NameMatch $_.Name } | Select-Object -First 1
|
||||
if ($match) { $found = $match.FullName; break scan }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($found) { Write-Output $found }
|
||||
`
|
||||
const { stdout } = await execFileAsync(POWERSHELL_EXE, ['-NoProfile', '-Command', script], {
|
||||
timeout: 120000,
|
||||
maxBuffer: 10 * 1024 * 1024
|
||||
})
|
||||
const foundPath = stdout.trim()
|
||||
return foundPath || null
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { app } from 'electron'
|
||||
|
||||
export const LOCATION_NAMES = [
|
||||
'bureau',
|
||||
'documents',
|
||||
'telechargements',
|
||||
'images',
|
||||
'videos',
|
||||
'musique'
|
||||
] as const
|
||||
|
||||
export type LocationName = (typeof LOCATION_NAMES)[number]
|
||||
|
||||
const PATH_NAME_BY_LOCATION: Record<LocationName, Parameters<typeof app.getPath>[0]> = {
|
||||
bureau: 'desktop',
|
||||
documents: 'documents',
|
||||
telechargements: 'downloads',
|
||||
images: 'pictures',
|
||||
videos: 'videos',
|
||||
musique: 'music'
|
||||
}
|
||||
|
||||
export function resolveLocation(location: unknown): string {
|
||||
const key =
|
||||
typeof location === 'string' && location in PATH_NAME_BY_LOCATION
|
||||
? (location as LocationName)
|
||||
: 'bureau'
|
||||
return app.getPath(Reflect.get(PATH_NAME_BY_LOCATION, key))
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { POWERSHELL_EXE } from './systemPaths'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const script = (keyCode: number, times: number): string => `
|
||||
Add-Type -TypeDefinition @"
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
public class ForgeAvatarInput {
|
||||
[DllImport("user32.dll")]
|
||||
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
|
||||
}
|
||||
"@
|
||||
for ($i = 0; $i -lt ${times}; $i++) {
|
||||
[ForgeAvatarInput]::keybd_event(${keyCode}, 0, 0, [UIntPtr]::Zero)
|
||||
[ForgeAvatarInput]::keybd_event(${keyCode}, 0, 2, [UIntPtr]::Zero)
|
||||
Start-Sleep -Milliseconds 50
|
||||
}
|
||||
`
|
||||
|
||||
/** Simule l'appui d'une touche virtuelle Windows (volume, media...) via user32.dll. */
|
||||
export async function pressVirtualKey(keyCode: number, times = 1): Promise<void> {
|
||||
await execFileAsync(POWERSHELL_EXE, ['-NoProfile', '-Command', script(keyCode, times)])
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { join } from 'path'
|
||||
|
||||
// Sur certaines configurations, le PATH de l'environnement ou tourne l'app ne contient pas
|
||||
// System32 : un execFile('powershell.exe', ...) ou execFile('taskkill', ...) en nom nu echoue
|
||||
// alors avec ENOENT. On resout donc toujours les chemins absolus des binaires systeme utilises.
|
||||
const systemRoot = process.env.SystemRoot || process.env.windir || 'C:\\Windows'
|
||||
const system32 = join(systemRoot, 'System32')
|
||||
|
||||
export const POWERSHELL_EXE = join(system32, 'WindowsPowerShell', 'v1.0', 'powershell.exe')
|
||||
export const TASKKILL_EXE = join(system32, 'taskkill.exe')
|
||||
export const NOTEPAD_EXE = join(system32, 'notepad.exe')
|
||||
export const RUNDLL32_EXE = join(system32, 'rundll32.exe')
|
||||
@@ -0,0 +1,13 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { RUNDLL32_EXE } from './lib/systemPaths'
|
||||
import type { SkillDefinition } from '../types'
|
||||
|
||||
export const lockScreen: SkillDefinition = {
|
||||
name: 'lock_screen',
|
||||
description: "Verrouille la session Windows (affiche l'ecran de verrouillage).",
|
||||
parameters: { type: 'object', properties: {} },
|
||||
execute: async () => {
|
||||
execFile(RUNDLL32_EXE, ['user32.dll,LockWorkStation'])
|
||||
return 'Ecran verrouille.'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { pressVirtualKey } from './lib/sendVirtualKey'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const VK_MEDIA_NEXT_TRACK = 0xb0
|
||||
const VK_MEDIA_PREV_TRACK = 0xb1
|
||||
const VK_MEDIA_STOP = 0xb2
|
||||
const VK_MEDIA_PLAY_PAUSE = 0xb3
|
||||
|
||||
const KEY_BY_ACTION = new Map<string, number>([
|
||||
['lecture_pause', VK_MEDIA_PLAY_PAUSE],
|
||||
['suivant', VK_MEDIA_NEXT_TRACK],
|
||||
['precedent', VK_MEDIA_PREV_TRACK],
|
||||
['stop', VK_MEDIA_STOP]
|
||||
])
|
||||
|
||||
export const mediaControl: SkillDefinition = {
|
||||
name: 'control_media_playback',
|
||||
description:
|
||||
'Met en pause/relance, passe au morceau suivant/precedent ou arrete la lecture multimedia en cours (musique ou video).',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
action: {
|
||||
type: 'string',
|
||||
enum: ['lecture_pause', 'suivant', 'precedent', 'stop'],
|
||||
description: 'Action a effectuer'
|
||||
}
|
||||
},
|
||||
required: ['action']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const action = asString(args.action)
|
||||
const keyCode = KEY_BY_ACTION.get(action)
|
||||
if (!keyCode) throw new Error('action invalide')
|
||||
await pressVirtualKey(keyCode, 1)
|
||||
return `Commande media envoyee : ${action}.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { exec } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { APP_REGISTRY } from './lib/appRegistry'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
const APPS: Record<string, string> = { ...APP_REGISTRY, parametres: 'ms-settings:' }
|
||||
|
||||
export const openApp: SkillDefinition = {
|
||||
name: 'open_app',
|
||||
description: `Ouvre une application installee sur Windows par son nom. Applications disponibles : ${Object.keys(APPS).join(', ')}.`,
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
application: { type: 'string', description: "Nom de l'application a ouvrir" }
|
||||
},
|
||||
required: ['application']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const application = asString(args.application)
|
||||
const key = application.toLowerCase().trim()
|
||||
const target = Object.hasOwn(APPS, key) ? Reflect.get(APPS, key) : undefined
|
||||
if (!target) {
|
||||
return `Application "${application}" non reconnue. Applications disponibles : ${Object.keys(APPS).join(', ')}.`
|
||||
}
|
||||
await execAsync(`start "" "${target}"`)
|
||||
return `${application} ouvert(e).`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { mkdtempSync, writeFileSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { NOTEPAD_EXE } from './lib/systemPaths'
|
||||
import type { SkillDefinition } from '../types'
|
||||
|
||||
export const openNotepad: SkillDefinition = {
|
||||
name: 'open_notepad',
|
||||
description: 'Ouvre le Bloc-notes Windows, avec un texte pre-rempli si fourni.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
text: { type: 'string', description: 'Texte a pre-remplir dans le Bloc-notes (optionnel)' }
|
||||
}
|
||||
},
|
||||
execute: async (args) => {
|
||||
const text = typeof args.text === 'string' ? args.text : undefined
|
||||
|
||||
const child = text
|
||||
? (() => {
|
||||
const filePath = join(mkdtempSync(join(tmpdir(), 'forge-avatar-')), 'note.txt')
|
||||
writeFileSync(filePath, text, 'utf-8')
|
||||
return execFile(NOTEPAD_EXE, [filePath])
|
||||
})()
|
||||
: execFile(NOTEPAD_EXE)
|
||||
|
||||
child.on('error', (error) => console.error('[skill:open_notepad]', error))
|
||||
return text ? 'Bloc-notes ouvert avec le texte demande.' : 'Bloc-notes ouvert.'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { shell } from 'electron'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const playMusic: SkillDefinition = {
|
||||
name: 'play_music',
|
||||
description:
|
||||
"Ouvre l'application de musique (Spotify si installe, sinon le lecteur web) et lance une recherche pour un titre, artiste ou album.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
query: { type: 'string', description: 'Titre, artiste ou album a jouer' }
|
||||
},
|
||||
required: ['query']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const query = asString(args.query).trim()
|
||||
if (!query) throw new Error('requete manquante')
|
||||
const encoded = encodeURIComponent(query)
|
||||
try {
|
||||
await shell.openExternal(`spotify:search:${encoded}`)
|
||||
return `Spotify ouvert, recherche lancee pour : ${query}.`
|
||||
} catch {
|
||||
await shell.openExternal(`https://open.spotify.com/search/${encoded}`)
|
||||
return `Lecteur Spotify web ouvert, recherche lancee pour : ${query}.`
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { findFileByName } from './lib/fileSearch'
|
||||
import { POWERSHELL_EXE } from './lib/systemPaths'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
const psQuote = (value: string): string => value.replace(/'/g, "''")
|
||||
|
||||
export const printFile: SkillDefinition = {
|
||||
name: 'print_file',
|
||||
description: "Recherche un fichier par son nom et l'envoie a l'imprimante par defaut.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string', description: 'Nom (ou partie du nom) du fichier a imprimer' }
|
||||
},
|
||||
required: ['name']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const name = asString(args.name).trim()
|
||||
if (!name) throw new Error('nom manquant')
|
||||
|
||||
const foundPath = await findFileByName(name)
|
||||
if (!foundPath) return `Aucun fichier correspondant a "${name}" trouve.`
|
||||
|
||||
await execFileAsync(POWERSHELL_EXE, [
|
||||
'-NoProfile',
|
||||
'-Command',
|
||||
`Start-Process -FilePath '${psQuote(foundPath)}' -Verb Print`
|
||||
])
|
||||
return `Impression lancee pour : ${foundPath}.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { synthesizeSpeech } from '../../ai/elevenlabs'
|
||||
import { sendToRenderer } from '../../windowBridge'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const reminder: SkillDefinition = {
|
||||
name: 'set_reminder',
|
||||
description:
|
||||
"Programme un rappel vocal : l'avatar prononcera le message a voix haute une fois le delai ecoule.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
minutes: { type: 'number', description: 'Delai en minutes avant le rappel' },
|
||||
message: { type: 'string', description: 'Message a dire a voix haute lors du rappel' }
|
||||
},
|
||||
required: ['minutes', 'message']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const minutes = Number(args.minutes)
|
||||
const message = asString(args.message).trim()
|
||||
if (!minutes || minutes <= 0) throw new Error('minutes invalide')
|
||||
if (!message) throw new Error('message manquant')
|
||||
|
||||
setTimeout(
|
||||
() => {
|
||||
synthesizeSpeech(message)
|
||||
.then((audio) => {
|
||||
const buffer = audio.buffer.slice(audio.byteOffset, audio.byteOffset + audio.byteLength)
|
||||
sendToRenderer('proactive-speech', buffer)
|
||||
})
|
||||
.catch((error) => console.error('[rappel]', error))
|
||||
},
|
||||
minutes * 60 * 1000
|
||||
)
|
||||
|
||||
return `Rappel programme dans ${minutes} minute(s) : "${message}".`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { shell } from 'electron'
|
||||
import { findFileByName } from './lib/fileSearch'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const searchFile: SkillDefinition = {
|
||||
name: 'search_file',
|
||||
description:
|
||||
"Cherche un fichier ou dossier LOCAL (sur l'ordinateur, pas sur internet/YouTube) par son nom, de maniere approximative (ignore l'ordre des mots, les apostrophes, la casse). Commence par les dossiers utilisateur courants, puis scanne tout le stockage en profondeur si besoin (peut prendre un peu de temps). Ouvre le resultat trouve. Pour une video en ligne, utiliser navigate_browser (avec search_web pour trouver l'URL) a la place.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string', description: 'Nom (ou partie du nom) du fichier/dossier a chercher' }
|
||||
},
|
||||
required: ['name']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const name = asString(args.name).trim()
|
||||
if (!name) throw new Error('nom manquant')
|
||||
|
||||
const foundPath = await findFileByName(name)
|
||||
if (!foundPath) {
|
||||
return `Aucun fichier ou dossier correspondant a "${name}" trouve, meme apres un scan complet du stockage.`
|
||||
}
|
||||
|
||||
await shell.openPath(foundPath)
|
||||
return `Trouve et ouvert : ${foundPath}.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Notification } from 'electron'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
export const showNotification: SkillDefinition = {
|
||||
name: 'show_notification',
|
||||
description: 'Affiche une notification Windows avec un titre et un message.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string', description: 'Titre de la notification (defaut : Max)' },
|
||||
message: { type: 'string', description: 'Contenu du message' }
|
||||
},
|
||||
required: ['message']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const title = asString(args.title, 'Max')
|
||||
const message = asString(args.message).trim()
|
||||
if (!message) throw new Error('message manquant')
|
||||
|
||||
new Notification({ title, body: message }).show()
|
||||
return 'Notification affichee.'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { freemem, totalmem } from 'os'
|
||||
import type { SkillDefinition } from '../types'
|
||||
|
||||
const toGo = (bytes: number): string => (bytes / 1024 ** 3).toFixed(1)
|
||||
|
||||
export const systemMemory: SkillDefinition = {
|
||||
name: 'check_system_memory',
|
||||
description: "Renvoie l'etat de la memoire RAM de l'ordinateur (totale, utilisee, libre).",
|
||||
parameters: { type: 'object', properties: {} },
|
||||
execute: async () => {
|
||||
const total = totalmem()
|
||||
const free = freemem()
|
||||
const used = total - free
|
||||
return `Memoire RAM : ${toGo(used)} Go utilises sur ${toGo(total)} Go (${toGo(free)} Go libres).`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { POWERSHELL_EXE } from './lib/systemPaths'
|
||||
import type { SkillDefinition } from '../types'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
interface StatusInfo {
|
||||
BatteryPercent: number | null
|
||||
Charging: boolean | null
|
||||
CpuPercent: number
|
||||
}
|
||||
|
||||
const PS_SCRIPT = `
|
||||
$battery = Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
$cpu = (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average
|
||||
[PSCustomObject]@{
|
||||
BatteryPercent = if ($battery) { $battery.EstimatedChargeRemaining } else { $null }
|
||||
Charging = if ($battery) { $battery.BatteryStatus -eq 2 } else { $null }
|
||||
CpuPercent = [math]::Round($cpu, 0)
|
||||
} | ConvertTo-Json
|
||||
`
|
||||
|
||||
export const systemStatus: SkillDefinition = {
|
||||
name: 'check_battery_and_cpu',
|
||||
description:
|
||||
'Renvoie le niveau de batterie (si ordinateur portable) et la charge processeur actuelle.',
|
||||
parameters: { type: 'object', properties: {} },
|
||||
execute: async () => {
|
||||
const { stdout } = await execFileAsync(POWERSHELL_EXE, ['-NoProfile', '-Command', PS_SCRIPT])
|
||||
const data = JSON.parse(stdout) as StatusInfo
|
||||
|
||||
const batteryText =
|
||||
data.BatteryPercent !== null
|
||||
? `Batterie a ${data.BatteryPercent}%${data.Charging ? ' (en charge)' : ''}.`
|
||||
: 'Pas de batterie detectee (ordinateur fixe).'
|
||||
|
||||
return `${batteryText} Processeur utilise a ${data.CpuPercent}%.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { promisify } from 'util'
|
||||
import { POWERSHELL_EXE } from './lib/systemPaths'
|
||||
import type { SkillDefinition } from '../types'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
interface VolumeInfo {
|
||||
DriveLetter: string
|
||||
SizeGB: number
|
||||
FreeGB: number
|
||||
}
|
||||
|
||||
const PS_SCRIPT = `Get-Volume | Where-Object { $_.DriveLetter } | Select-Object DriveLetter,@{N='SizeGB';E={[math]::Round($_.Size/1GB,1)}},@{N='FreeGB';E={[math]::Round($_.SizeRemaining/1GB,1)}} | ConvertTo-Json`
|
||||
|
||||
export const systemStorage: SkillDefinition = {
|
||||
name: 'check_storage',
|
||||
description:
|
||||
"Renvoie l'espace de stockage utilise et disponible sur les disques de l'ordinateur.",
|
||||
parameters: { type: 'object', properties: {} },
|
||||
execute: async () => {
|
||||
const { stdout } = await execFileAsync(POWERSHELL_EXE, ['-NoProfile', '-Command', PS_SCRIPT])
|
||||
const parsed = JSON.parse(stdout) as VolumeInfo | VolumeInfo[]
|
||||
const volumes = Array.isArray(parsed) ? parsed : [parsed]
|
||||
return volumes
|
||||
.map(
|
||||
(v) =>
|
||||
`Disque ${v.DriveLetter} : ${(v.SizeGB - v.FreeGB).toFixed(1)} Go utilises sur ${v.SizeGB} Go (${v.FreeGB} Go libres)`
|
||||
)
|
||||
.join('. ')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { pressVirtualKey } from './lib/sendVirtualKey'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
const VK_VOLUME_MUTE = 0xad
|
||||
const VK_VOLUME_DOWN = 0xae
|
||||
const VK_VOLUME_UP = 0xaf
|
||||
|
||||
export const systemVolume: SkillDefinition = {
|
||||
name: 'control_volume',
|
||||
description: "Augmente, baisse ou coupe le son de l'ordinateur.",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
action: {
|
||||
type: 'string',
|
||||
enum: ['augmenter', 'baisser', 'couper'],
|
||||
description: 'Action a effectuer'
|
||||
},
|
||||
steps: {
|
||||
type: 'number',
|
||||
description: 'Nombre de crans de volume (environ 2% chacun), defaut 5'
|
||||
}
|
||||
},
|
||||
required: ['action']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const action = asString(args.action)
|
||||
const steps = typeof args.steps === 'number' && args.steps > 0 ? Math.min(args.steps, 25) : 5
|
||||
|
||||
if (action === 'couper') {
|
||||
await pressVirtualKey(VK_VOLUME_MUTE, 1)
|
||||
return 'Son coupe (ou reactive si deja coupe).'
|
||||
}
|
||||
if (action === 'augmenter') {
|
||||
await pressVirtualKey(VK_VOLUME_UP, steps)
|
||||
return 'Volume augmente.'
|
||||
}
|
||||
if (action === 'baisser') {
|
||||
await pressVirtualKey(VK_VOLUME_DOWN, steps)
|
||||
return 'Volume baisse.'
|
||||
}
|
||||
throw new Error('action invalide')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { app, desktopCapturer, screen } from 'electron'
|
||||
import { writeFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import type { SkillDefinition } from '../types'
|
||||
|
||||
export const takeScreenshot: SkillDefinition = {
|
||||
name: 'take_screenshot',
|
||||
description: "Prend une capture de l'ecran et l'enregistre dans le dossier Images.",
|
||||
parameters: { type: 'object', properties: {} },
|
||||
execute: async () => {
|
||||
const display = screen.getPrimaryDisplay()
|
||||
const sources = await desktopCapturer.getSources({
|
||||
types: ['screen'],
|
||||
thumbnailSize: display.size
|
||||
})
|
||||
const source = sources[0]
|
||||
if (!source) throw new Error('Aucun ecran detecte')
|
||||
|
||||
const fileName = `capture-${new Date().toISOString().replace(/[:.]/g, '-')}.png`
|
||||
const filePath = join(app.getPath('pictures'), fileName)
|
||||
writeFileSync(filePath, source.thumbnail.toPNG())
|
||||
return `Capture d'ecran enregistree : ${filePath}.`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { app, shell } from 'electron'
|
||||
import { Document, Packer, Paragraph, TextRun } from 'docx'
|
||||
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'
|
||||
import { writeFileSync } from 'fs'
|
||||
import { join } from 'path'
|
||||
import type { SkillDefinition } from '../types'
|
||||
import { asString } from '../argUtils'
|
||||
|
||||
function safeFileName(titre: string): string {
|
||||
return titre.replace(/[\\/:*?"<>|]/g, '_').slice(0, 80) || 'Document'
|
||||
}
|
||||
|
||||
async function writeDocx(path: string, titre: string, contenu: string): Promise<void> {
|
||||
const doc = new Document({
|
||||
sections: [
|
||||
{
|
||||
children: [
|
||||
new Paragraph({ children: [new TextRun({ text: titre, bold: true, size: 32 })] }),
|
||||
...contenu
|
||||
.split('\n')
|
||||
.map((line) => new Paragraph({ children: [new TextRun({ text: line, size: 22 })] }))
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
writeFileSync(path, await Packer.toBuffer(doc))
|
||||
}
|
||||
|
||||
async function writePdf(path: string, titre: string, contenu: string): Promise<void> {
|
||||
const pdf = await PDFDocument.create()
|
||||
const font = await pdf.embedFont(StandardFonts.Helvetica)
|
||||
const bold = await pdf.embedFont(StandardFonts.HelveticaBold)
|
||||
const pageWidth = 595
|
||||
const pageHeight = 842
|
||||
const margin = 50
|
||||
const maxWidth = pageWidth - margin * 2
|
||||
const fontSize = 12
|
||||
const lineHeight = 16
|
||||
|
||||
const wrapLine = (line: string): string[] => {
|
||||
if (!line) return ['']
|
||||
const words = line.split(' ')
|
||||
const wrapped: string[] = []
|
||||
let current = ''
|
||||
for (const word of words) {
|
||||
const candidate = current ? `${current} ${word}` : word
|
||||
if (font.widthOfTextAtSize(candidate, fontSize) > maxWidth && current) {
|
||||
wrapped.push(current)
|
||||
current = word
|
||||
} else {
|
||||
current = candidate
|
||||
}
|
||||
}
|
||||
wrapped.push(current)
|
||||
return wrapped
|
||||
}
|
||||
|
||||
const lines = contenu.split('\n').flatMap(wrapLine)
|
||||
|
||||
let page = pdf.addPage([pageWidth, pageHeight])
|
||||
let y = pageHeight - margin
|
||||
page.drawText(titre, { x: margin, y, size: 20, font: bold, color: rgb(0, 0, 0) })
|
||||
y -= 32
|
||||
|
||||
for (const line of lines) {
|
||||
if (y < margin) {
|
||||
page = pdf.addPage([pageWidth, pageHeight])
|
||||
y = pageHeight - margin
|
||||
}
|
||||
page.drawText(line, { x: margin, y, size: fontSize, font })
|
||||
y -= lineHeight
|
||||
}
|
||||
|
||||
writeFileSync(path, await pdf.save())
|
||||
}
|
||||
|
||||
export const writeWordDocument: SkillDefinition = {
|
||||
name: 'create_document',
|
||||
description:
|
||||
"Cree un document texte avec un titre et un contenu, et l'enregistre dans le dossier Documents (.docx et/ou .pdf).",
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string', description: 'Titre du document (sert aussi de nom de fichier)' },
|
||||
content: { type: 'string', description: 'Texte a ecrire dans le document' },
|
||||
format: {
|
||||
type: 'string',
|
||||
enum: ['docx', 'pdf', 'both'],
|
||||
description: "Format d'enregistrement (defaut : both)"
|
||||
}
|
||||
},
|
||||
required: ['title', 'content']
|
||||
},
|
||||
execute: async (args) => {
|
||||
const title = asString(args.title, 'Document')
|
||||
const content = asString(args.content)
|
||||
const format = typeof args.format === 'string' ? args.format : 'both'
|
||||
if (!content) throw new Error('contenu manquant')
|
||||
|
||||
const safeName = safeFileName(title)
|
||||
const documentsDir = app.getPath('documents')
|
||||
const docxPath = join(documentsDir, `${safeName}.docx`)
|
||||
const pdfPath = join(documentsDir, `${safeName}.pdf`)
|
||||
|
||||
if (format !== 'pdf') await writeDocx(docxPath, title, content)
|
||||
if (format !== 'docx') await writePdf(pdfPath, title, content)
|
||||
|
||||
const openedPath = format === 'docx' ? docxPath : pdfPath
|
||||
await shell.openPath(openedPath)
|
||||
|
||||
const saved =
|
||||
format === 'both' ? `${docxPath} et ${pdfPath}` : format === 'pdf' ? pdfPath : docxPath
|
||||
return `Document cree, enregistre et ouvert : ${saved}.`
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user