chore(cleanup): remove basic-only utility skills
Removes the system-action skills that were only ever available in the now -retired Basic/Assistant modes (play_music, open/close_app, open_notepad, create_document, create_powerpoint, control_volume, control_media_playback, take_screenshot, clipboard, search_file, set_reminder, lock_screen, empty_recycle_bin, show_notification, print_file, create_folder, create_file, delete_file, fill_browser_field) along with their windows/lib helpers (appRegistry, fileSearch, locations, sendVirtualKey) and the fillField browser-window helper. Keeps the read-only, side-effect -free transversal skills (search_web, navigate_browser and friends, check_system_memory/storage/battery/internet). Drops the now-unused docx/pptxgenjs dependencies and the stale coachStore/meetingStore entries from the coverage exclude list. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -147,47 +147,6 @@ export function clickByTextInPage(target: string): boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
export async function fillField(field: string, value: string, submit: boolean): Promise<boolean> {
|
||||
const window = requireWindow()
|
||||
return (await window.webContents.executeJavaScript(
|
||||
`(${fillFieldInPage.toString()})(${JSON.stringify(field)}, ${JSON.stringify(value)}, ${JSON.stringify(submit)})`
|
||||
)) as boolean
|
||||
}
|
||||
|
||||
export function fillFieldInPage(field: string, value: string, submit: boolean): boolean {
|
||||
const needle = field.trim().toLowerCase()
|
||||
const inputs = Array.from(
|
||||
document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>('input, textarea')
|
||||
)
|
||||
|
||||
const score = (el: HTMLInputElement | HTMLTextAreaElement): string => {
|
||||
const label = el.labels?.[0]?.innerText ?? ''
|
||||
return [el.name, el.id, el.placeholder, label, el.getAttribute('aria-label') ?? '']
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
const match = inputs.find((el) => score(el).includes(needle))
|
||||
if (!match) return false
|
||||
|
||||
const descriptor = Object.getOwnPropertyDescriptor(
|
||||
match instanceof HTMLTextAreaElement
|
||||
? HTMLTextAreaElement.prototype
|
||||
: HTMLInputElement.prototype,
|
||||
'value'
|
||||
)
|
||||
descriptor?.set?.call(match, value)
|
||||
match.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
match.dispatchEvent(new Event('change', { bubbles: true }))
|
||||
|
||||
if (submit) {
|
||||
const form = match.closest('form')
|
||||
if (form) form.requestSubmit ? form.requestSubmit() : form.submit()
|
||||
else match.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
interface TaggedElement {
|
||||
id: string
|
||||
text: string
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
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.`
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@ 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'
|
||||
|
||||
@@ -13,7 +12,6 @@ export const browserSkills: SkillDefinition[] = [
|
||||
readBrowserPage,
|
||||
clickBrowserElement,
|
||||
goBackBrowser,
|
||||
fillBrowserField,
|
||||
translateBrowserPage,
|
||||
highlightBrowserText
|
||||
]
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
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')
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
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).`
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
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}.`
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
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}.`
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
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}.`
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
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}.`
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
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.'
|
||||
}
|
||||
}
|
||||
@@ -1,50 +1,12 @@
|
||||
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
|
||||
checkInternet
|
||||
]
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
// 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'
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
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))
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
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)])
|
||||
}
|
||||
@@ -7,6 +7,3 @@ 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')
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
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.'
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
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}.`
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
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).`
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
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.'
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
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}.`
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
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}.`
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
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}".`
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
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}.`
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
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.'
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
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')
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
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}.`
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
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