Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fb65c257d | ||
|
|
068940495a | ||
|
|
d71c3dd34d | ||
|
|
50f515e406 | ||
|
|
313645eea2 | ||
|
|
02517735be |
Generated
+23
-1
@@ -21,7 +21,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "agent-manager"
|
||||
version = "1.0.4"
|
||||
version = "1.1.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
@@ -36,6 +36,7 @@ dependencies = [
|
||||
"nu-ansi-term",
|
||||
"ratatui",
|
||||
"reedline",
|
||||
"rpassword",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -1779,6 +1780,27 @@ version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189"
|
||||
|
||||
[[package]]
|
||||
name = "rpassword"
|
||||
version = "7.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rtoolbox",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rtoolbox"
|
||||
version = "0.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "50a0e551c1e27e1731aba276dbeaeac73f53c7cd34d1bda485d02bd1e0f36844"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "agent-manager"
|
||||
version = "1.0.4"
|
||||
version = "1.1.2"
|
||||
edition = "2021"
|
||||
description = "Manage local AI coding agents: list, install, start, stop, update — with automatic dependency handling and a YAML-driven catalog."
|
||||
license = "MIT"
|
||||
@@ -38,6 +38,7 @@ toml = "0.8"
|
||||
ureq = { version = "2", default-features = false, features = ["tls"] }
|
||||
wait-timeout = "0.2"
|
||||
keyring = { version = "3", features = ["windows-native", "linux-native"] }
|
||||
rpassword = "7"
|
||||
which = "7"
|
||||
zip = "0.6"
|
||||
crossterm = "0.29"
|
||||
|
||||
@@ -48,6 +48,32 @@ plateforme, il compile automatiquement depuis les sources.
|
||||
|
||||
> 🔄 **Mise à jour** : relancez simplement la même commande.
|
||||
|
||||
### 🚀 Premier lancement (onboarding v1.1.0)
|
||||
|
||||
Au premier lancement (ou dès que vous tapez `am ai` / `am ask` sans
|
||||
provider configuré), `am` vous propose le wizard d'onboarding :
|
||||
|
||||
am setup
|
||||
|
||||
Il vous guide en 3 étapes :
|
||||
1. **Provider** : anthropic, openai, deepseek, google, ollama (local) ou
|
||||
custom (base URL).
|
||||
2. **Token API** : saisie masquée, stockée dans le trousseau OS (keyring)
|
||||
— jamais écrite en clair dans la config.
|
||||
3. **Modèle par défaut** : choisi parmi les modèles déclarés du provider.
|
||||
|
||||
Le wizard installe ensuite **aichat** (le moteur de `am ai`) si vous
|
||||
acceptez, et génère **6 rôles copilot** pour aichat (`am setup --roles`
|
||||
pour les régénérer) :
|
||||
|
||||
| Rôle | Rôle |
|
||||
|---|---|
|
||||
| `am-copilot` — guide & catalogue am | `am-dev` — code, git, tests |
|
||||
| `am-operator` — shell sécurisé | `am-analyst` — coûts, logs, stats |
|
||||
| `am-do` — exécution pure pour `--exec` | `am-orchestrator` — groupes, lab |
|
||||
|
||||
Utilisation : `am ai --role am-operator "compresse les fichiers JSON"`.
|
||||
|
||||
---
|
||||
|
||||
## 🎬 Vos 3 premières commandes
|
||||
@@ -79,6 +105,8 @@ plateforme, il compile automatiquement depuis les sources.
|
||||
| am search <mot-clé> | recherche fuzzy : tolère les fautes de frappe, classe par pertinence, propose « vouliez-vous dire » |
|
||||
| am suggest <requête> | recommande un agent pour une demande en langage naturel (tags + usage réel) |
|
||||
| am ask "<demande>" | langage naturel → commande(s) am : règles locales hors-ligne, raffinement LLM optionnel (settings.ask), confirmation avant exécution — ex: am ask "installe claude et lance-le" |
|
||||
| am ai "<demande>" [--exec] [--files <path>] [--role <rôle>] | langage naturel → action shell via AIChat (alias: am shell) : conversationnel par défaut ; --exec génère la commande, la classe safe/risky et applique la politique de sécurité (settings.shell_ai, dry-run par défaut — --yes pour exécuter) ; --role = rôle copilot am-* (am setup) |
|
||||
| am setup [--roles] | wizard d'onboarding : provider, token (trousseau OS), modèle par défaut, installation d'aichat + rôles copilot (v1.1.0) |
|
||||
| am info <agent> | fiche détaillée (installation, dépendances, site…) |
|
||||
| am status [agent] | état, version, PID, logs |
|
||||
| am models | inventaire des modèles locaux (ollama, llama.cpp, LM Studio) |
|
||||
|
||||
+70
-9
@@ -1,7 +1,7 @@
|
||||
# 🗺️ ROADMAP agent-manager — vers le « super outil »
|
||||
|
||||
> **Version du document : 2.4** · Statut : phases 0 à 3 livrées
|
||||
> (v0.3.0 → v1.0.1), maintenance v1.0.2 → v1.0.4
|
||||
> **Version du document : 3.0** · Statut : phases 0 à 3 livrées
|
||||
> (v0.3.0 → v1.0.1), maintenance v1.0.2 → v1.1.0
|
||||
> Base : analyse du code **v0.2.7** (Rust, 45+ tests, zéro dépendance runtime)
|
||||
>
|
||||
> ✅ **Phase 0 livrée en v0.3.0 (2026-08-17)** : issues #2 à #16 clôturées,
|
||||
@@ -38,6 +38,50 @@
|
||||
> **shell-ai** ajoutés (issues #94 #95) : AIChat (alias `ai`, binaire GitHub
|
||||
> Release), ShellGPT (pip), Fabric (go), Shell AI (npm/Ollama), AI CLI
|
||||
> (binaire, politique de sécurité risk/certainty). Catalogue : 77 agents.
|
||||
>
|
||||
> 🔧 **Maintenance v1.0.5 (2026-08-20)** : **commande `am ai` livrée**
|
||||
> (issues #96 #97) — langage naturel → action shell via AIChat : mode
|
||||
> conversationnel (aichat -f <ctx>), mode --exec avec pipeline de sécurité
|
||||
> (génération aichat --dry-run, classification safe/risky + certainité,
|
||||
> politique dry-run par défaut configurable settings.shell_ai, confirmation
|
||||
> y/N pour les commandes risky, exécution via le shell de l'utilisateur),
|
||||
> flags --files/--provider/--model/--yes, alias CLI `am shell`, événements
|
||||
> `shell_ai` journalisés. Épique Axe 13 (#93) clôturée.
|
||||
>
|
||||
> 🔧 **Maintenance v1.0.6 (2026-08-20)** : installateur Windows corrigé —
|
||||
> `install.ps1` n'acceptait que l'entrée `am.exe` dans l'archive de release
|
||||
> (la CI et les archives manuelles utilisent `am-windows-x86_64.exe`) →
|
||||
> repli systématique sur `cargo install` au lieu du binaire précompilé.
|
||||
> Le script accepte désormais les deux noms ; archives v1.0.6 publiées avec
|
||||
> les deux entrées pour la compatibilité maximale. Chemin du message
|
||||
> cargo install corrigé (`.cargo\bin\am.exe`).
|
||||
>
|
||||
> 🚀 **Épique v1.1.0 (2026-08-20)** : **Onboarding, Copilot & Rôles aichat**
|
||||
> (Axe 14) — `am setup` (wizard provider + token keyring + modèle + ping),
|
||||
> installation automatique d'aichat (wizard + `am ai` + installateurs),
|
||||
> 6 rôles copilot générés pour aichat (am-copilot, am-operator, am-dev,
|
||||
> am-do, am-analyst, am-orchestrator), `am ai --role <nom>`, tip
|
||||
> d'onboarding dans le banner REPL et les commandes IA (non-bloquant).
|
||||
>
|
||||
> 🔧 **Maintenance v1.1.1 (2026-08-20)** : fix `am setup` — le wizard écrivait
|
||||
> `providers.<nom>` au TOP-LEVEL de la config user (clé rejetée par le
|
||||
> validateur : « unknown field `providers` »). Le registre vivant sous
|
||||
> `settings.providers`, le wizard écrit désormais
|
||||
> `settings.providers.<nom>.base_url` + `.default_model` (le schéma exige
|
||||
> base_url quand un bloc provider est écrit). Test de régression
|
||||
> `setup_persists_under_settings_providers`.
|
||||
>
|
||||
> 🔧 **Maintenance v1.1.2 (2026-08-20)** :
|
||||
> - `am setup` : **openrouter** ajouté au choix des providers (base URL,
|
||||
> token via OPENROUTER_API_KEY, 6 modèles déclarés proposés) ;
|
||||
> le choix du modèle liste les modèles disponibles du provider.
|
||||
> - `am ai` sans `--role` utilise **am-copilot par défaut** (régénération
|
||||
> automatique des rôles si le fichier manque, dégradation douce).
|
||||
> - Bug `am migrate --import` : la config importée était écrite dans le
|
||||
> répertoire config GLOBAL (user_config_dir) au lieu du config actif de
|
||||
> l'app — l'import écrasait la config réelle de la machine (et la suite
|
||||
> de tests détruisait la config utilisateur à chaque `cargo test`).
|
||||
> L'import respecte désormais `app.paths.config_dir` (--config/isolated).
|
||||
|
||||
---
|
||||
|
||||
@@ -403,12 +447,12 @@ aichat -f . "résume les données de ces fichiers JSON"
|
||||
| Fonctionnalité | Description | Effort | Phase |
|
||||
|---|---|---|---|
|
||||
| ✅ **Catalogue : ajouter AIChat** | Définition `AgentDef` + alias `ai` → `aichat` — livré en v1.0.4 (issues #94 #95) | S | P1 |
|
||||
| **Commande `am ai <prompt>`** | Lancer AIChat avec le dossier courant comme contexte | S | P3 |
|
||||
| **Flag `--exec` / `-e`** | Active le mode exécution directe (`aichat -e`) | S | P3 |
|
||||
| **Flag `--files <path>`** | Passer fichiers/dossiers spécifiques en contexte | S | P3 |
|
||||
| **Sécurité : `--dry-run` par défaut** | Simuler avant exécution ; confirmation si modification | M | P3 |
|
||||
| **Provider configurable** | Réutiliser le registre `providers.rs` (cheap model par défaut) | M | P3 |
|
||||
| **Alias intégrés** | `am shell`, `am do` comme synonymes | S | P3 |
|
||||
| ✅ **Commande `am ai <prompt>`** | Lancer AIChat avec le dossier courant comme contexte — livré en v1.0.5 (issue #96) | S | P3 |
|
||||
| ✅ **Flag `--exec` / `-e`** | Active le mode exécution directe (`aichat -e` via aichat --dry-run + exécution sécurisée par am) — livré en v1.0.5 (issue #96) | S | P3 |
|
||||
| ✅ **Flag `--files <path>`** | Passer fichiers/dossiers spécifiques en contexte — livré en v1.0.5 (issue #96) | S | P3 |
|
||||
| ✅ **Sécurité : `--dry-run` par défaut** | Simuler avant exécution ; classification safe/risky + confirmation — livré en v1.0.5 (issue #97, settings.shell_ai) | M | P3 |
|
||||
| ✅ **Provider configurable** | Réutiliser le registre `providers.rs` (--provider/--model → env aichat + modèle) — livré en v1.0.5 (issue #96) | M | P3 |
|
||||
| ✅ **Alias intégrés** | `am shell` comme synonyme CLI de `am ai` — livré en v1.0.5 (issue #96) | S | P3 |
|
||||
| **Extensions sœurs** | `am summarize`, `am explain`, `am fix` (voir ci-dessous) | M | P3 |
|
||||
|
||||
---
|
||||
@@ -439,6 +483,21 @@ aichat -f . "résume les données de ces fichiers JSON"
|
||||
| `am note` | Extrait des action items d'un texte/réunion | Axe 10 |
|
||||
| `am search-web "..."` | Recherche web rapide et réponse synthétisée | Axe 7 |
|
||||
|
||||
---
|
||||
|
||||
## 14. 🚀 Onboarding & Copilot aichat (épique v1.1.0)
|
||||
|
||||
> Objectif : réduire le **Time-To-First-Value à 0** — rendre `am` opérationnel
|
||||
> pour l'IA locale dès la première seconde, et faire d'aichat le copilot de
|
||||
> agent-manager. Livré en **v1.1.0 (2026-08-20)**.
|
||||
|
||||
| Fonctionnalité | Description | Statut |
|
||||
|---|---|---|
|
||||
| ✅ **Wizard d'onboarding (`am setup`)** | Provider (anthropic, openai, deepseek, google, ollama, custom), token masqué → trousseau OS (keyring, jamais en clair), modèle par défaut, ping API non-bloquant. Déclenché par `am ai`/`am ask`/banner REPL quand aucun provider n'est configuré (message discret, jamais bloquant), ré-exécutable à la main (mode revoir) | ✅ v1.1.0 |
|
||||
| ✅ **Installation automatique d'aichat** | Étape du wizard « Installer le moteur IA (aichat) ? [Y/n] » → `am install aichat` (catalogue) ; `am ai` sans aichat propose l'installation ; install.ps1/install.sh enchaînent sur `am setup` si stdin interactif | ✅ v1.1.0 |
|
||||
| ✅ **Rôles copilot aichat (am-*)** | 6 agents générés dans `~/.config/aichat/agents/` (ou %APPDATA%\\aichat\\agents) : am-copilot (guide & catalogue), am-operator (shell sécurisé), am-dev (code & git), am-do (exécution pure pour --exec), am-analyst (coûts/logs/stats), am-orchestrator (groupes/lab). Prompts bilingues (FR par défaut), privilégient les contrats `--json` | ✅ v1.1.0 |
|
||||
| ✅ **`am ai --role <nom>`** | Rôle copilot passé à aichat (`--agent`) ; validation du fichier généré ; complétion REPL des rôles am-* ; config aichat créée (provider + modèle) seulement si absente | ✅ v1.1.0 |
|
||||
| ✅ **Settings dédiés** | `settings.shell_ai` (default_safety dry-run/confirm/auto, risky_patterns) documenté dans config.yaml ; module `src/setup.rs` + `src/roles.rs` | ✅ v1.1.0 |
|
||||
|
||||
---
|
||||
|
||||
@@ -618,4 +677,6 @@ configuration manuelle (tokens au keyring, provider/modèle par défaut).
|
||||
*Document généré à partir de l'analyse du code (v0.2.7, commit d886de3).
|
||||
Phases livrées : 0 (v0.3.0), 1 (v0.4.1), 2 (v0.6.0), v0.7.0 (providers,
|
||||
2026-08-19), 3 (v1.0.0, #76–#80, 2026-08-20) ; maintenance v1.0.1/v1.0.2
|
||||
(self-update décompression, REPL).*
|
||||
(self-update décompression, REPL), v1.0.3 (détection externe), v1.0.4
|
||||
(catalogue shell AI, #94 #95), v1.0.5 (commande am ai, #93 #96 #97),
|
||||
v1.0.6 (installateur Windows accepte l'entrée am-windows-x86_64.exe).*
|
||||
|
||||
+21
@@ -64,6 +64,17 @@ settings:
|
||||
# sources:
|
||||
# - https://git.dracodev.net/bruno/am-catalog/raw/branch/main/am-catalog.yaml
|
||||
# author: bruno
|
||||
# am ai (#96 #97) : politique de sécurité Shell AI. dry-run par défaut —
|
||||
# aucune commande modifiante n'est exécutée sans confirmation explicite
|
||||
# (--yes). `confirm` demande validation pour les commandes risky ;
|
||||
# `auto` exécute tout (déconseillé). Les motifs supplémentaires s'ajoutent
|
||||
# aux patterns intégrés (rm -rf, dd if, mkfs, chmod -R 777, ...).
|
||||
# shell_ai:
|
||||
# default_safety: dry-run # dry-run | confirm | auto
|
||||
# risky_patterns:
|
||||
# - "rm -rf"
|
||||
# - "> /dev"
|
||||
# - "dd if"
|
||||
# Profil sandbox par agent (#79) : commandes autorisées (binaires), répertoires
|
||||
# de travail et politique réseau. Désactivé par défaut (mode non sandboxé).
|
||||
# Les tentatives refusées sont journalisées (events sandbox) pour l'audit.
|
||||
@@ -97,6 +108,16 @@ settings:
|
||||
base_url: https://generativelanguage.googleapis.com/v1beta
|
||||
default_model: gemini-2.5-pro
|
||||
models: [gemini-2.5-pro, gemini-2.5-flash]
|
||||
openrouter:
|
||||
base_url: https://openrouter.ai/api/v1
|
||||
default_model: deepseek/deepseek-chat-v3-0324
|
||||
models:
|
||||
- deepseek/deepseek-chat-v3-0324
|
||||
- anthropic/claude-sonnet-4.5
|
||||
- openai/gpt-4o
|
||||
- google/gemini-2.5-pro
|
||||
- meta-llama/llama-3.3-70b-instruct
|
||||
- mistralai/mistral-large-2411
|
||||
|
||||
# --- Command aliases ----------------------------------------------------------
|
||||
aliases:
|
||||
|
||||
+11
-1
@@ -24,7 +24,7 @@ function Install-FromSource {
|
||||
Write-Host "Installation depuis les sources (cargo install --git $BaseUrl.git) ..."
|
||||
cargo install --git "$BaseUrl.git" --locked
|
||||
if ($LASTEXITCODE -ne 0) { Fail "cargo install a echoue" }
|
||||
$bin = Join-Path $env:USERPROFILE ".cargo\binam.exe"
|
||||
$bin = Join-Path $env:USERPROFILE ".cargo\bin\am.exe"
|
||||
Write-Host ""
|
||||
Write-Host "OK - am est installe dans $bin"
|
||||
Write-Host "Essayez : am list | am doctor (mise a jour : relancez ce script)"
|
||||
@@ -47,7 +47,10 @@ if ($arch -eq "x86_64") {
|
||||
$tmpDir = Join-Path $env:TEMP "am-$tag"
|
||||
Remove-Item $tmpDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Expand-Archive -Path $tmp -DestinationPath $tmpDir -Force
|
||||
# L'entrée de l'archive varie selon le pipeline : « am.exe » ou
|
||||
# « am-windows-x86_64.exe » (nom de l'asset). Accepter les deux.
|
||||
$exe = Join-Path $tmpDir "am.exe"
|
||||
if (-not (Test-Path $exe)) { $exe = Join-Path $tmpDir "am-windows-x86_64.exe" }
|
||||
if (Test-Path $exe) {
|
||||
New-Item -ItemType Directory -Force -Path $binDir | Out-Null
|
||||
Copy-Item $exe (Join-Path $binDir "am.exe") -Force
|
||||
@@ -75,6 +78,13 @@ if (-not $InstallDir) {
|
||||
$env:Path = "$binDir;$env:Path"
|
||||
& (Join-Path $binDir "am.exe") --version
|
||||
Write-Host ""
|
||||
# Épique v1.1.0 : wizard d'onboarding (provider + token + aichat + rôles)
|
||||
# uniquement quand stdin est un terminal interactif (pas en CI).
|
||||
if ([Console]::IsInputRedirected -eq $false) {
|
||||
Write-Host "Configuration initiale (provider, token, aichat) :"
|
||||
& (Join-Path $binDir "am.exe") setup
|
||||
}
|
||||
Write-Host ""
|
||||
Write-Host "OK - 'am' est installe. Essayez :"
|
||||
Write-Host " am list"
|
||||
Write-Host " am doctor"
|
||||
|
||||
@@ -93,6 +93,13 @@ esac
|
||||
|
||||
"$INSTALL_DIR/am" --version || true
|
||||
echo ""
|
||||
# Épique v1.1.0 : wizard d'onboarding (provider + token + aichat + rôles)
|
||||
# uniquement quand stdin est un terminal interactif (pas en CI).
|
||||
if [ -t 0 ]; then
|
||||
echo "Configuration initiale (provider, token, aichat) :"
|
||||
"$INSTALL_DIR/am" setup
|
||||
fi
|
||||
echo ""
|
||||
echo "OK — 'am' est installé. Essayez :"
|
||||
echo " am list"
|
||||
echo " am doctor"
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
.ie \n(.g .ds Aq \(aq
|
||||
.el .ds Aq '
|
||||
.TH am-ai 1 "ai "
|
||||
.SH NAME
|
||||
ai \- Langage naturel → action shell via AIChat (issues #96 #97); alias: shell
|
||||
.SH SYNOPSIS
|
||||
\fBai\fR [\fB\-e\fR|\fB\-\-exec\fR] [\fB\-f\fR|\fB\-\-files\fR] [\fB\-\-provider\fR] [\fB\-\-model\fR] [\fB\-\-role\fR] [\fB\-h\fR|\fB\-\-help\fR] <\fIPROMPT\fR>
|
||||
.SH DESCRIPTION
|
||||
Langage naturel → action shell via AIChat (issues #96 #97); alias: shell
|
||||
.SH OPTIONS
|
||||
.TP
|
||||
\fB\-e\fR, \fB\-\-exec\fR
|
||||
Execute the generated shell command (after the safety policy)
|
||||
.TP
|
||||
\fB\-f\fR, \fB\-\-files\fR \fI<PATH>\fR
|
||||
Files or directories passed as context (repeatable; default: the current directory)
|
||||
.TP
|
||||
\fB\-\-provider\fR \fI<ID>\fR
|
||||
Provider of the registry used by aichat (env vars + model)
|
||||
.TP
|
||||
\fB\-\-model\fR \fI<MODEL>\fR
|
||||
Force a model (aichat \-\-model)
|
||||
.TP
|
||||
\fB\-\-role\fR \fI<ROLE>\fR
|
||||
Use one of the generated copilot roles (am\-copilot, am\-operator, am\-dev, am\-do, am\-analyst, am\-orchestrator — issue v1.1.0 F3)
|
||||
.TP
|
||||
\fB\-h\fR, \fB\-\-help\fR
|
||||
Print help
|
||||
.TP
|
||||
<\fIPROMPT\fR>
|
||||
The request in natural language
|
||||
@@ -0,0 +1,16 @@
|
||||
.ie \n(.g .ds Aq \(aq
|
||||
.el .ds Aq '
|
||||
.TH am-setup 1 "setup "
|
||||
.SH NAME
|
||||
setup \- Onboarding wizard: provider, token, modèle par défaut, aichat, rôles copilot (épique v1.1.0)
|
||||
.SH SYNOPSIS
|
||||
\fBsetup\fR [\fB\-\-roles\fR] [\fB\-h\fR|\fB\-\-help\fR]
|
||||
.SH DESCRIPTION
|
||||
Onboarding wizard: provider, token, modèle par défaut, aichat, rôles copilot (épique v1.1.0)
|
||||
.SH OPTIONS
|
||||
.TP
|
||||
\fB\-\-roles\fR
|
||||
Only (re)generate the am\-* copilot roles for aichat
|
||||
.TP
|
||||
\fB\-h\fR, \fB\-\-help\fR
|
||||
Print help
|
||||
@@ -1,6 +1,6 @@
|
||||
.ie \n(.g .ds Aq \(aq
|
||||
.el .ds Aq '
|
||||
.TH am 1 "am 1.0.3"
|
||||
.TH am 1 "am 1.1.0"
|
||||
.SH NAME
|
||||
am \- agent\-manager (am) — manage local AI coding agents
|
||||
.SH SYNOPSIS
|
||||
@@ -133,6 +133,12 @@ Suggest agents matching a query, boosted by real usage (issue #61)
|
||||
am\-ask(1)
|
||||
Ask a natural\-language request and get the matching am command(s) (issue #78): local rules first, optional LLM refinement, confirmation before execution
|
||||
.TP
|
||||
am\-ai(1)
|
||||
Langage naturel → action shell via AIChat (issues #96 #97); alias: shell
|
||||
.TP
|
||||
am\-setup(1)
|
||||
Onboarding wizard: provider, token, modèle par défaut, aichat, rôles copilot (épique v1.1.0)
|
||||
.TP
|
||||
am\-start(1)
|
||||
Start an agent (foreground by default, or detached with \-\-background)
|
||||
.TP
|
||||
@@ -244,4 +250,4 @@ Export the configuration and installation state (backup)
|
||||
am\-import(1)
|
||||
Import a previously exported configuration and state
|
||||
.SH VERSION
|
||||
v1.0.3
|
||||
v1.1.0
|
||||
|
||||
+42
@@ -214,6 +214,15 @@ pub enum Command {
|
||||
#[arg(long)]
|
||||
yes: bool,
|
||||
},
|
||||
/// Langage naturel → action shell via AIChat (issues #96 #97); alias: shell
|
||||
#[command(alias = "shell")]
|
||||
Ai(AiArgs),
|
||||
/// Onboarding wizard: provider, token, modèle par défaut, aichat, rôles copilot (épique v1.1.0)
|
||||
Setup {
|
||||
/// Only (re)generate the am-* copilot roles for aichat
|
||||
#[arg(long)]
|
||||
roles: bool,
|
||||
},
|
||||
/// Start an agent (foreground by default, or detached with --background)
|
||||
Start(StartArgs),
|
||||
/// Stop a background agent (SIGTERM, then SIGKILL after the timeout)
|
||||
@@ -700,6 +709,39 @@ pub struct WebArgs {
|
||||
pub no_open: bool,
|
||||
}
|
||||
|
||||
/// Arguments of am ai (issues #96 #97): natural language → shell action
|
||||
/// via AIChat. The global flags --dry-run and --yes/-y apply as well.
|
||||
#[derive(Args, Debug, Clone, Default)]
|
||||
pub struct AiArgs {
|
||||
/// The request in natural language
|
||||
#[arg(value_name = "PROMPT", num_args = 1.., required = true)]
|
||||
pub prompt: Vec<String>,
|
||||
/// Execute the generated shell command (after the safety policy)
|
||||
#[arg(short = 'e', long, action = ArgAction::SetTrue)]
|
||||
pub exec: bool,
|
||||
/// Files or directories passed as context (repeatable; default: the
|
||||
/// current directory)
|
||||
#[arg(short = 'f', long = "files", value_name = "PATH", action = ArgAction::Append)]
|
||||
pub files: Vec<std::path::PathBuf>,
|
||||
/// Provider of the registry used by aichat (env vars + model)
|
||||
#[arg(long, value_name = "ID")]
|
||||
pub provider: Option<String>,
|
||||
/// Force a model (aichat --model)
|
||||
#[arg(long, value_name = "MODEL")]
|
||||
pub model: Option<String>,
|
||||
/// Use one of the generated copilot roles (am-copilot, am-operator,
|
||||
/// am-dev, am-do, am-analyst, am-orchestrator — issue v1.1.0 F3)
|
||||
#[arg(long, value_name = "ROLE")]
|
||||
pub role: Option<String>,
|
||||
/// REPL-only: --yes given on the REPL line (the CLI global -y/--yes is
|
||||
/// handled by clap directly).
|
||||
#[arg(skip)]
|
||||
pub yes: bool,
|
||||
/// REPL-only: --dry-run given on the REPL line.
|
||||
#[arg(skip)]
|
||||
pub dry_run: bool,
|
||||
}
|
||||
|
||||
/// Arguments of am serve (issue #80).
|
||||
#[derive(Args, Debug, Clone, Default)]
|
||||
pub struct ServeArgs {
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
//! am ai — langage naturel → action shell (issues #96 #97).
|
||||
//!
|
||||
//! Conversational mode (no `--exec`) spawns AIChat with the prompt and the
|
||||
//! context files (default: the current directory). Exec mode generates the
|
||||
//! shell command through aichat in dry-run, classifies it, applies the
|
||||
//! safety policy (settings.shell_ai, dry-run by default) and only executes
|
||||
//! after confirmation when required.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::cli::AiArgs;
|
||||
use crate::commands::{require_agent, resolve_exec};
|
||||
use crate::events::{Event, EventKind};
|
||||
use crate::shell_ai::{Decision, SafetyMode};
|
||||
use anyhow::{bail, Context, Result};
|
||||
use std::process::Command;
|
||||
|
||||
pub fn run(app: &App, args: &AiArgs) -> Result<i32> {
|
||||
// Onboarding hint (v1.1.0 F1) — non-blocking: the AI commands propose
|
||||
// `am setup` when no provider is configured, then continue anyway.
|
||||
if crate::setup::needs_setup(app) {
|
||||
app.log.info(crate::i18n::tr_in(
|
||||
app.lang(),
|
||||
"am n'est pas configuré — lancez am setup (provider + token)",
|
||||
));
|
||||
}
|
||||
|
||||
// F2 (v1.1.0): aichat must be INSTALLED (not only in the catalog) to
|
||||
// power am ai. Offer the installation when missing.
|
||||
if !aichat_installed(app) {
|
||||
let ask_install = !app.cli.yes
|
||||
&& app.confirm(crate::i18n::tr_in(
|
||||
app.lang(),
|
||||
"aichat est manquant. Installer ?",
|
||||
))?;
|
||||
if app.cli.yes || ask_install {
|
||||
app.log.info(crate::i18n::tr_in(app.lang(), "Installation d'aichat…"));
|
||||
crate::commands::install_cmd::run(app, "aichat", None, false, None, None, false)?;
|
||||
} else {
|
||||
bail!(crate::i18n::tr_in(
|
||||
app.lang(),
|
||||
"installez aichat: am install aichat — puis réessayez"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let prompt = args.prompt.join(" ");
|
||||
// Context files: explicit --files wins, else the current directory
|
||||
// (issue #96: `aichat -f . "<prompt>"`).
|
||||
let files: Vec<String> = if args.files.is_empty() {
|
||||
vec![".".to_string()]
|
||||
} else {
|
||||
args.files
|
||||
.iter()
|
||||
.map(|p| p.display().to_string())
|
||||
.collect()
|
||||
};
|
||||
|
||||
// REPL per-line flags combine with the CLI globals.
|
||||
let yes = app.cli.yes || args.yes;
|
||||
let dry_run = app.cli.dry_run || args.dry_run;
|
||||
|
||||
let agent = require_agent(app, "aichat")?;
|
||||
|
||||
if !args.exec {
|
||||
return chat_mode(app, agent, &prompt, &files, args, dry_run);
|
||||
}
|
||||
exec_mode(app, &prompt, &files, args, yes, dry_run)
|
||||
}
|
||||
|
||||
/// True when the aichat binary is available (installed or on PATH).
|
||||
/// Uses a direct PATH lookup — the probe cache would mask a shim added
|
||||
/// mid-test and is meant for agent inventories, not runtime checks.
|
||||
fn aichat_installed(app: &App) -> bool {
|
||||
app.state.get("aichat").ok().flatten().is_some()
|
||||
|| which::which("aichat").is_ok()
|
||||
}
|
||||
|
||||
/// Build the aichat `--agent` arguments for the requested role. Without a
|
||||
/// `--role` flag the am-copilot role is used by default (v1.1.2): when its
|
||||
/// file is missing the roles are regenerated on the fly, and a generation
|
||||
/// failure degrades gracefully (no role). An explicit unknown role is an
|
||||
/// error.
|
||||
fn role_args(app: &App, role: Option<&str>) -> Result<Vec<String>> {
|
||||
let role = role.unwrap_or("am-copilot");
|
||||
let dir = crate::roles::aichat_agents_dir();
|
||||
let path = dir.join(format!("{role}.md"));
|
||||
if path.exists() {
|
||||
return Ok(vec!["--agent".to_string(), role.to_string()]);
|
||||
}
|
||||
if role == "am-copilot" {
|
||||
if let Err(e) = crate::roles::generate_all(app) {
|
||||
app.log.verbose(&format!("roles generation skipped: {e:#}"));
|
||||
}
|
||||
if path.exists() {
|
||||
return Ok(vec!["--agent".to_string(), role.to_string()]);
|
||||
}
|
||||
app.log.warn(crate::i18n::tr_in(
|
||||
app.lang(),
|
||||
"rôle 'am-copilot' introuvable — lancez am setup --roles",
|
||||
));
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
bail!(crate::i18n::tr_in(
|
||||
app.lang(),
|
||||
"rôle '{}' inconnu — générez les rôles avec: am setup --roles (am-copilot, am-operator, am-dev, am-do, am-analyst, am-orchestrator)"
|
||||
)
|
||||
.replace("{}", role));
|
||||
}
|
||||
|
||||
/// Conversational mode: aichat -f <ctx> "<prompt>" in the foreground, with
|
||||
/// the provider/model environment applied when requested.
|
||||
fn chat_mode(
|
||||
app: &App,
|
||||
agent: &crate::config::AgentDef,
|
||||
prompt: &str,
|
||||
files: &[String],
|
||||
args: &AiArgs,
|
||||
dry_run: bool,
|
||||
) -> Result<i32> {
|
||||
let mut extra: Vec<String> = Vec::new();
|
||||
extra.extend(role_args(app, args.role.as_deref())?);
|
||||
for f in files {
|
||||
extra.push("-f".to_string());
|
||||
extra.push(f.clone());
|
||||
}
|
||||
extra.push(prompt.to_string());
|
||||
let (p_args, p_env) =
|
||||
crate::shell_ai::provider_env(app, args.provider.as_deref(), args.model.as_deref())?;
|
||||
extra.extend(p_args);
|
||||
if dry_run {
|
||||
app.log.dry(&format!(
|
||||
"would run aichat {} (conversationnel)",
|
||||
extra.join(" ")
|
||||
));
|
||||
return Ok(0);
|
||||
}
|
||||
let exec = resolve_exec(app, agent, &extra, &p_env)?;
|
||||
app.log.verbose(&format!(
|
||||
"shell-ai: {} {}",
|
||||
exec.program,
|
||||
exec.args.join(" ")
|
||||
));
|
||||
let (prog, prefix) = crate::runner::resolve_program(&exec.program);
|
||||
let mut full_args = prefix;
|
||||
full_args.extend(exec.args.iter().cloned());
|
||||
let status = Command::new(&prog)
|
||||
.args(&full_args)
|
||||
.envs(&exec.env)
|
||||
.status()
|
||||
.with_context(|| format!("failed to run {}", exec.program))?;
|
||||
app.emit(
|
||||
&Event::now(EventKind::ShellAi)
|
||||
.with_agent("aichat".to_string())
|
||||
.with_args(vec!["mode=chat".to_string(), "executed=true".to_string()]),
|
||||
);
|
||||
Ok(status.code().unwrap_or(1))
|
||||
}
|
||||
|
||||
/// Exec mode: generate the command (aichat --dry-run), classify it, apply
|
||||
/// the safety policy, then execute through the shell when allowed.
|
||||
fn exec_mode(
|
||||
app: &App,
|
||||
prompt: &str,
|
||||
files: &[String],
|
||||
args: &AiArgs,
|
||||
yes: bool,
|
||||
dry_run: bool,
|
||||
) -> Result<i32> {
|
||||
if dry_run {
|
||||
app.log.dry(&format!(
|
||||
"would generate & classify via aichat (exec) — commande non exécutée"
|
||||
));
|
||||
}
|
||||
let role = role_args(app, args.role.as_deref())?;
|
||||
let cmd = crate::shell_ai::generate(
|
||||
app,
|
||||
prompt,
|
||||
files,
|
||||
args.provider.as_deref(),
|
||||
args.model.as_deref(),
|
||||
&role,
|
||||
)?;
|
||||
let settings = app
|
||||
.config
|
||||
.settings
|
||||
.shell_ai
|
||||
.clone()
|
||||
.unwrap_or_default();
|
||||
let risk = crate::shell_ai::classify(&cmd, &settings.risky_patterns);
|
||||
let certainty = crate::shell_ai::estimate_certainty(&cmd, risk);
|
||||
let mode = settings.safety_mode();
|
||||
|
||||
// Show the generated command and its classification (issue #97 UX).
|
||||
println!("🔒 Commande générée : {}", cmd);
|
||||
println!(" Risk : {}", risk.as_str());
|
||||
println!(" Certainty: {}%", certainty);
|
||||
println!(
|
||||
" Safety : {} (settings.shell_ai.default_safety; --yes pour exécuter)",
|
||||
mode.as_str()
|
||||
);
|
||||
|
||||
let decision = crate::shell_ai::decide(mode, risk, dry_run, yes);
|
||||
let lang = app.lang();
|
||||
let mut executed = false;
|
||||
match decision {
|
||||
Decision::Abort => {
|
||||
let msg = if dry_run {
|
||||
crate::i18n::tr_in(lang, "dry-run : commande non exécutée")
|
||||
} else {
|
||||
crate::i18n::tr_in(
|
||||
lang,
|
||||
"politique de sécurité (dry-run par défaut) : commande non exécutée — utilisez --yes",
|
||||
)
|
||||
};
|
||||
app.log.info(msg);
|
||||
}
|
||||
Decision::Ask => {
|
||||
let ok = app.confirm(crate::i18n::tr_in(lang, "Exécuter ?"))?;
|
||||
if ok {
|
||||
executed = true;
|
||||
} else {
|
||||
app.log.info(crate::i18n::tr_in(lang, "annulé"));
|
||||
}
|
||||
}
|
||||
Decision::Execute => {
|
||||
executed = true;
|
||||
}
|
||||
}
|
||||
let code = if executed {
|
||||
app.log.info(&format!("exécution: {}", cmd));
|
||||
let code = crate::shell_ai::execute(app, &cmd)?;
|
||||
code
|
||||
} else {
|
||||
0
|
||||
};
|
||||
app.emit(
|
||||
&Event::now(EventKind::ShellAi)
|
||||
.with_agent("aichat".to_string())
|
||||
.with_args(vec![
|
||||
"mode=exec".to_string(),
|
||||
format!("risk={}", risk.as_str()),
|
||||
format!("certainty={certainty}"),
|
||||
format!("executed={executed}"),
|
||||
]),
|
||||
);
|
||||
Ok(code)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn decision_dry_run_is_the_default_policy() {
|
||||
// The embedded config does not set shell_ai -> dry-run default.
|
||||
let s = crate::config::ShellAiSettings::default();
|
||||
assert_eq!(s.safety_mode(), SafetyMode::DryRun);
|
||||
}
|
||||
}
|
||||
@@ -266,9 +266,14 @@ pub fn import_bundle(app: &App, bundle: &Path, confirm: bool) -> Result<Vec<Stri
|
||||
for (bf, data) in manifest.files.iter().zip(blobs.iter()) {
|
||||
let rel = Path::new(&bf.path);
|
||||
let target = if bf.path == "config.yaml" {
|
||||
// Config goes to the user config directory of machine B.
|
||||
let dir = crate::config::user_config_dir()
|
||||
.unwrap_or_else(|| crate::config::home_dir().unwrap_or_else(|| PathBuf::from(".")));
|
||||
// Config goes to the ACTIVE user config directory of this app
|
||||
// (respects --config / isolated tests) — NOT the machine-global
|
||||
// user config dir: importing must not clobber the real config.
|
||||
let dir = app
|
||||
.paths
|
||||
.config_dir
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow!("cannot determine the user config directory (no HOME set)"))?;
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
dir.join(crate::config::CONFIG_FILE_NAME)
|
||||
} else {
|
||||
@@ -292,8 +297,11 @@ pub fn import_bundle(app: &App, bundle: &Path, confirm: bool) -> Result<Vec<Stri
|
||||
// confirmed; otherwise it is written next to it as config.migrated.yaml.
|
||||
let cfg_rel = "config.yaml";
|
||||
if restored.iter().any(|r| r == cfg_rel) && !confirm {
|
||||
let dir = crate::config::user_config_dir()
|
||||
.unwrap_or_else(|| crate::config::home_dir().unwrap_or_else(|| PathBuf::from(".")));
|
||||
let dir = app
|
||||
.paths
|
||||
.config_dir
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow!("cannot determine the user config directory (no HOME set)"))?;
|
||||
let imported = dir.join(crate::config::CONFIG_FILE_NAME);
|
||||
if imported.exists() {
|
||||
let target = dir.join("config.migrated.yaml");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Command implementations and dispatch.
|
||||
|
||||
pub mod agents_cmd;
|
||||
pub mod ai_cmd;
|
||||
pub mod alias_cmd;
|
||||
pub mod annotations_cmd;
|
||||
pub mod audit_cmd;
|
||||
@@ -106,6 +107,14 @@ pub fn execute_command(app: &App, cmd: &Command) -> Result<i32> {
|
||||
Command::Providers(args) => providers_cmd::run(app, args.sub.as_ref()),
|
||||
Command::Suggest { words } => suggest_cmd::run(app, &words.join(" ")),
|
||||
Command::Ask { query, yes } => crate::ask::run(app, &query.join(" "), *yes),
|
||||
Command::Ai(args) => ai_cmd::run(app, args),
|
||||
Command::Setup { roles } => {
|
||||
if *roles {
|
||||
crate::setup::run_roles(app)
|
||||
} else {
|
||||
crate::setup::run(app)
|
||||
}
|
||||
}
|
||||
Command::Start(a) => run_cmd::start(app, a),
|
||||
Command::Stop {
|
||||
agent,
|
||||
|
||||
@@ -109,6 +109,28 @@ pub static SECTIONS: &[TipSection] = &[
|
||||
options: &[("--yes", "exécute la commande sans confirmation")],
|
||||
example: "ask installe claude et lance-le",
|
||||
},
|
||||
TipEntry {
|
||||
usage: "ai <demande> [--exec] [--files <path>] [--role <rôle>]",
|
||||
about: "langage naturel → action shell via AIChat (issues #96 #97) : génère avec aichat, classe safe/risky, dry-run par défaut",
|
||||
options: &[
|
||||
("--exec", "génère PUIS exécute la commande (après la politique de sécurité)"),
|
||||
("-f, --files", "fichiers/dossiers en contexte (défaut: dossier courant)"),
|
||||
("--role", "rôle copilot aichat (am-copilot, am-operator, am-dev, am-do, am-analyst, am-orchestrator)"),
|
||||
("--provider", "provider du registre (clé du keyring + modèle)"),
|
||||
("--model", "forcer un modèle"),
|
||||
("--yes", "exécute sans confirmation"),
|
||||
],
|
||||
example: "ai --exec \"compresse les fichiers JSON en un zip\"",
|
||||
},
|
||||
TipEntry {
|
||||
usage: "setup [--roles]",
|
||||
about: "wizard d'onboarding : provider, token (trousseau OS), modèle par défaut, installation d'aichat, rôles copilot am-* (v1.1.0)",
|
||||
options: &[
|
||||
("--roles", "régénérer uniquement les rôles copilot aichat"),
|
||||
("--yes", "non-interactif (valeurs actuelles)"),
|
||||
],
|
||||
example: "setup",
|
||||
},
|
||||
TipEntry {
|
||||
usage: "models",
|
||||
about: "inventaire des modèles locaux (ollama, llama.cpp, LM Studio)",
|
||||
|
||||
@@ -162,6 +162,10 @@ pub struct Settings {
|
||||
/// (issue #89).
|
||||
#[serde(default)]
|
||||
pub providers: Option<BTreeMap<String, Option<ProviderDef>>>,
|
||||
/// am ai security settings (issue #97): default safety policy and
|
||||
/// extra risky command patterns for the Shell AI command.
|
||||
#[serde(default)]
|
||||
pub shell_ai: Option<ShellAiSettings>,
|
||||
}
|
||||
|
||||
/// Anonymous opt-in telemetry (issue #76): aggregated counters only — never
|
||||
@@ -200,6 +204,34 @@ impl Default for AskSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// am ai security settings (issue #97): safety policy and risky patterns
|
||||
/// for the Shell AI command. The default policy is `dry-run` — nothing is
|
||||
/// executed without an explicit confirmation.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct ShellAiSettings {
|
||||
/// Default safety policy of `am ai --exec`:
|
||||
/// `dry-run` (show only), `confirm` (ask for risky commands) or
|
||||
/// `auto` (execute everything). Default: dry-run.
|
||||
pub default_safety: Option<String>,
|
||||
/// Extra command substrings classified as risky (in addition to the
|
||||
/// built-in patterns: rm -rf, dd if, mkfs, chmod -R 777, ...).
|
||||
#[serde(default)]
|
||||
pub risky_patterns: Vec<String>,
|
||||
}
|
||||
|
||||
impl ShellAiSettings {
|
||||
/// The effective default safety mode (unknown values fall back to
|
||||
/// dry-run — the safe choice).
|
||||
pub fn safety_mode(&self) -> crate::shell_ai::SafetyMode {
|
||||
match self.default_safety.as_deref() {
|
||||
Some("auto") => crate::shell_ai::SafetyMode::Auto,
|
||||
Some("confirm") => crate::shell_ai::SafetyMode::Confirm,
|
||||
_ => crate::shell_ai::SafetyMode::DryRun,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Community registry settings (issue #77).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
@@ -969,6 +1001,9 @@ pub fn merge(base: &mut Config, overlay: Config) {
|
||||
if o.default_provider.is_some() {
|
||||
s.default_provider = o.default_provider;
|
||||
}
|
||||
if o.shell_ai.is_some() {
|
||||
s.shell_ai = o.shell_ai;
|
||||
}
|
||||
// Providers merge key by key (issue #88): an overlay adds or replaces
|
||||
// one provider without wiping the others. An explicit `null` in the
|
||||
// overlay DELETES the provider (the standard YAML overlay pattern) so a
|
||||
|
||||
@@ -52,6 +52,9 @@ pub enum EventKind {
|
||||
Provider,
|
||||
/// Sandbox refusal journalized for audit (issue #79).
|
||||
Sandbox,
|
||||
/// am ai — Shell AI action: generated, classified and/or executed
|
||||
/// (issues #96 #97).
|
||||
ShellAi,
|
||||
}
|
||||
|
||||
impl EventKind {
|
||||
@@ -79,6 +82,7 @@ impl EventKind {
|
||||
EventKind::Lab => "lab",
|
||||
EventKind::Provider => "provider",
|
||||
EventKind::Sandbox => "sandbox",
|
||||
EventKind::ShellAi => "shell_ai",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+46
@@ -857,6 +857,25 @@ pub static HELP_SPECS: &[HelpSpec] = &[
|
||||
HelpExample { desc: "Remove everything, including logs and the config entry.", code: "uninstall claude-code --purge" },
|
||||
],
|
||||
},
|
||||
HelpSpec {
|
||||
name: "setup",
|
||||
category: "Commands",
|
||||
usage: "setup {flags}",
|
||||
about: "Wizard d'onboarding : provider, token (trousseau OS), modèle par défaut, installation d'aichat et génération des rôles copilot am-* (épique v1.1.0). Ré-exécutable à tout moment (mode revoir).",
|
||||
search_terms: &["wizard", "onboarding", "provider", "token", "setup", "configurer", "premier"],
|
||||
flags: &[
|
||||
HelpFlag { short: "-y", long: "--yes", value: "", desc: "Mode non-interactif : garde les valeurs actuelles (provider/modèle), installe aichat, régénère les rôles" },
|
||||
HelpFlag { short: "", long: "--roles", value: "", desc: "Régénérer uniquement les rôles copilot aichat (am-copilot, am-operator, am-dev, am-do, am-analyst, am-orchestrator)" },
|
||||
],
|
||||
subcommands: &[],
|
||||
parameters: &[],
|
||||
io: None,
|
||||
examples: &[
|
||||
HelpExample { desc: "Premier lancement (proposé aussi par am ai / le banner REPL)", code: "am setup" },
|
||||
HelpExample { desc: "Régénérer les rôles après une mise à jour", code: "am setup --roles" },
|
||||
HelpExample { desc: "Non-interactif (scripts)", code: "am setup --yes" },
|
||||
],
|
||||
},
|
||||
HelpSpec {
|
||||
name: "ask",
|
||||
category: "Commands",
|
||||
@@ -876,6 +895,33 @@ pub static HELP_SPECS: &[HelpSpec] = &[
|
||||
HelpExample { desc: "Une commande simple sans confirmation.", code: "ask liste les agents --yes" },
|
||||
],
|
||||
},
|
||||
HelpSpec {
|
||||
name: "ai",
|
||||
category: "Commands",
|
||||
usage: "ai {flags} <prompt...>",
|
||||
about: "Langage naturel → action shell via AIChat (issues #96 #97). Sans --exec : conversationnel (aichat -f <ctx>). Avec --exec : génère la commande (aichat --dry-run), la classe safe/risky, applique la politique de sécurité (dry-run par défaut — settings.shell_ai) puis exécute après confirmation. Alias CLI : am shell.",
|
||||
search_terms: &["shell", "nlp", "natural", "language", "commande", "exec", "langage"],
|
||||
flags: &[
|
||||
HelpFlag { short: "-e", long: "--exec", value: "", desc: "Génère puis exécute la commande shell (après la politique de sécurité)" },
|
||||
HelpFlag { short: "-f", long: "--files", value: "PATH", desc: "Fichier ou dossier passé en contexte (répétable ; défaut : dossier courant)" },
|
||||
HelpFlag { short: "", long: "--provider", value: "ID", desc: "Provider du registre utilisé par aichat (variables d'env + modèle)" },
|
||||
HelpFlag { short: "", long: "--model", value: "MODEL", desc: "Forcer un modèle (aichat --model)" },
|
||||
HelpFlag { short: "", long: "--role", value: "ROLE", desc: "Rôle copilot aichat (am-copilot, am-operator, am-dev, am-do, am-analyst, am-orchestrator — générés par am setup)" },
|
||||
HelpFlag { short: "-y", long: "--yes", value: "", desc: "Exécuter sans confirmation (global)" },
|
||||
HelpFlag { short: "", long: "--dry-run", value: "", desc: "Simuler : génère et classe la commande sans rien exécuter (global)" },
|
||||
],
|
||||
subcommands: &[],
|
||||
parameters: &[
|
||||
HelpParam { name: "prompt", typ: "string", desc: "La demande en langage naturel, ex: «liste les fichiers JSON du dossier courant»" },
|
||||
],
|
||||
io: None,
|
||||
examples: &[
|
||||
HelpExample { desc: "Mode conversationnel (défaut).", code: "ai liste tous les fichiers JSON et extrait les clés uniques" },
|
||||
HelpExample { desc: "Générer la commande sans l'exécuter (dry-run par défaut).", code: "ai --exec \"compresse les fichiers JSON en un zip\"" },
|
||||
HelpExample { desc: "Exécuter après confirmation explicite.", code: "ai --exec \"supprime les fichiers .tmp\" --yes" },
|
||||
HelpExample { desc: "Passer un dossier en contexte.", code: "ai --files ./data \"résume les données de ces fichiers\"" },
|
||||
],
|
||||
},
|
||||
HelpSpec {
|
||||
name: "registry",
|
||||
category: "Commands",
|
||||
|
||||
+27
@@ -163,6 +163,24 @@ pub const CATALOG: &[(&str, &str)] = &[
|
||||
("je n'ai pas compris — exemples: «installe claude et lance-le», «liste les agents», «arrête codex»", "I did not understand — examples: «installe claude et lance-le», «liste les agents», «arrête codex»"),
|
||||
("exécuter ces commandes ?", "run these commands?"),
|
||||
("annulé", "cancelled"),
|
||||
("Exécuter ?", "Execute?"),
|
||||
("dry-run : commande non exécutée", "dry-run: command not executed"),
|
||||
("politique de sécurité (dry-run par défaut) : commande non exécutée — utilisez --yes", "safety policy (dry-run by default): command not executed — use --yes"),
|
||||
("aichat n'a retourné aucune commande (dry-run)", "aichat returned no command (dry-run)"),
|
||||
("aichat n'a pas généré de commande (exit {}){}", "aichat generated no command (exit {}){}"),
|
||||
("usage: ai <demande> — ex: ai --exec \"compresse les fichiers JSON\"", "usage: ai <request> — e.g. ai --exec \"compress the JSON files\""),
|
||||
("am n'est pas configuré — lancez am setup (provider + token)", "am is not configured — run am setup (provider + token)"),
|
||||
("Configuration d'agent-manager (am setup)", "agent-manager configuration (am setup)"),
|
||||
("Le token est stocké dans le trousseau OS — jamais en clair.", "The token is stored in the OS keyring — never in clear."),
|
||||
("Installer le moteur IA (aichat) ?", "Install the AI engine (aichat)?"),
|
||||
("Installation d'aichat…", "Installing aichat…"),
|
||||
("aichat est manquant. Installer ?", "aichat is missing. Install it?"),
|
||||
("installez aichat: am install aichat — puis réessayez", "install aichat: am install aichat — then retry"),
|
||||
("Rôles copilot am-* générés", "am-* copilot roles generated"),
|
||||
("Config aichat créée (provider + modèle)", "aichat config created (provider + model)"),
|
||||
("am est configuré — essayez: am ai \"...\" ou am ai --exec \"...\"", "am is configured — try: am ai \"...\" or am ai --exec \"...\""),
|
||||
("rôle '{}' inconnu — générez les rôles avec: am setup --roles (am-copilot, am-operator, am-dev, am-do, am-analyst, am-orchestrator)", "unknown role '{}' — generate the roles with: am setup --roles (am-copilot, am-operator, am-dev, am-do, am-analyst, am-orchestrator)"),
|
||||
("rôle 'am-copilot' introuvable — lancez am setup --roles", "role 'am-copilot' not found — run am setup --roles"),
|
||||
("usage: ask <demande> — ex: ask installe claude et lance-le", "usage: ask <request> — e.g. ask installe claude et lance-le"),
|
||||
("aucune source enregistrée — settings.registry.sources ou: am registry install <url>", "no sources registered — settings.registry.sources or: am registry install <url>"),
|
||||
("installation refusée — source non fiable", "installation refused — untrusted source"),
|
||||
@@ -430,6 +448,15 @@ pub fn tr_fmt<'a>(key: &'a str, args: &[&dyn std::fmt::Display]) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Format a message for a GIVEN locale (deterministic — follows the app's
|
||||
/// resolved language instead of the process-global locale).
|
||||
pub fn tr_fmt_in<'a>(lang: Lang, key: &'a str, args: &[&dyn std::fmt::Display]) -> String {
|
||||
match lang {
|
||||
Lang::Fr => fmt_args(key, args),
|
||||
Lang::En => fmt_args(lookup_en(key).unwrap_or(key), args),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace `{}` placeholders (positional) with the Display of each argument.
|
||||
fn fmt_args(template: &str, args: &[&dyn std::fmt::Display]) -> String {
|
||||
let mut out = String::with_capacity(template.len() + 16);
|
||||
|
||||
@@ -14,6 +14,9 @@
|
||||
pub mod app;
|
||||
pub mod agent_config;
|
||||
pub mod ask;
|
||||
pub mod roles;
|
||||
pub mod setup;
|
||||
pub mod shell_ai;
|
||||
pub mod automation;
|
||||
pub mod backup;
|
||||
pub mod catalog;
|
||||
|
||||
+77
-2
@@ -114,6 +114,8 @@ const COMMAND_DESCRIPTIONS: &[(&str, &str)] = &[
|
||||
("providers", "manage the LLM provider registry (base URLs, models, default)"),
|
||||
("suggest", "recommend an agent for a request"),
|
||||
("ask", "natural language → am commands (local rules first, optional LLM refinement)"),
|
||||
("ai", "natural language → shell action via AIChat (--exec to run, dry-run by default)"),
|
||||
("setup", "onboarding wizard: provider, token, default model, aichat, copilot roles"),
|
||||
("audit", "who changed what, when (config checksums)"),
|
||||
("service", "register an agent as a system service (autostart)"),
|
||||
("schedule", "plan am commands (daily) and check the fleet health"),
|
||||
@@ -239,7 +241,7 @@ impl AmCompleter {
|
||||
"start", "stop", "restart", "run", "doctor", "config", "completion",
|
||||
"self-update", "self-uninstall", "export", "import", "shell", "theme", "lang",
|
||||
"tip", "dashboard", "favorite", "unfavorite", "note", "tag", "untag", "tags",
|
||||
"profile", "man", "models", "catalog", "providers", "suggest", "ask", "registry", "audit",
|
||||
"profile", "man", "models", "catalog", "providers", "suggest", "ask", "ai", "setup", "registry", "audit",
|
||||
"service", "schedule", "monitor", "web", "serve", "sync", "migrate", "playbook", "lab", "plugins",
|
||||
"ls", "dir", "cd", "ps", "where", "get", "help", "version", "exit",
|
||||
],
|
||||
@@ -799,7 +801,7 @@ pub fn banner_box(
|
||||
.to_string(),
|
||||
));
|
||||
rows.push(inner(
|
||||
" models models · models --prune · catalog · suggest · ask · audit".to_string(),
|
||||
" models models · models --prune · catalog · suggest · ask · ai · setup · audit".to_string(),
|
||||
));
|
||||
rows.push(inner(
|
||||
" automate service install · schedule add · doctor --watch · monitor · sync · migrate · playbook".to_string(),
|
||||
@@ -1109,6 +1111,14 @@ pub fn run(app: &App) -> Result<i32> {
|
||||
app.log.verbose(&format!("history migration skipped: {e:#}"));
|
||||
}
|
||||
print!("{}", banner(app, &session, &sid));
|
||||
// Onboarding tip (v1.1.0 F1): one discreet line when no provider is
|
||||
// configured yet.
|
||||
if crate::setup::needs_setup(app) {
|
||||
app.log.info(crate::i18n::tr_in(
|
||||
app.lang(),
|
||||
"am n'est pas configuré — lancez am setup (provider + token)",
|
||||
));
|
||||
}
|
||||
let result = match run_with_editor(app, &mut session, &sid) {
|
||||
Ok(code) => Ok(code),
|
||||
Err(e) => {
|
||||
@@ -1603,6 +1613,69 @@ fn handle_line(
|
||||
yes: flag("--yes"),
|
||||
}
|
||||
},
|
||||
"ai" => {
|
||||
let mut exec = false;
|
||||
let mut yes = false;
|
||||
let mut dry_run = false;
|
||||
let mut files: Vec<std::path::PathBuf> = Vec::new();
|
||||
let mut provider: Option<String> = None;
|
||||
let mut model: Option<String> = None;
|
||||
let mut role: Option<String> = None;
|
||||
let mut prompt: Vec<String> = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < rest.len() {
|
||||
match rest[i].as_str() {
|
||||
"--exec" | "-e" => exec = true,
|
||||
"--yes" | "-y" => yes = true,
|
||||
"--dry-run" => dry_run = true,
|
||||
"--files" | "-f" => {
|
||||
i += 1;
|
||||
if i < rest.len() {
|
||||
files.push(std::path::PathBuf::from(&rest[i]));
|
||||
}
|
||||
}
|
||||
"--provider" => {
|
||||
i += 1;
|
||||
if i < rest.len() {
|
||||
provider = Some(rest[i].clone());
|
||||
}
|
||||
}
|
||||
"--model" => {
|
||||
i += 1;
|
||||
if i < rest.len() {
|
||||
model = Some(rest[i].clone());
|
||||
}
|
||||
}
|
||||
"--role" => {
|
||||
i += 1;
|
||||
if i < rest.len() {
|
||||
role = Some(rest[i].clone());
|
||||
}
|
||||
}
|
||||
other => prompt.push(other.to_string()),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if prompt.is_empty() {
|
||||
app.log.error(crate::i18n::tr(
|
||||
"usage: ai <demande> — ex: ai --exec \"compresse les fichiers JSON\"",
|
||||
));
|
||||
return Ok(false);
|
||||
}
|
||||
Command::Ai(crate::cli::AiArgs {
|
||||
prompt,
|
||||
exec,
|
||||
files,
|
||||
provider,
|
||||
model,
|
||||
role,
|
||||
yes,
|
||||
dry_run,
|
||||
})
|
||||
},
|
||||
"setup" => Command::Setup {
|
||||
roles: flag("--roles"),
|
||||
},
|
||||
"alias" => match rest.first().map(|s| s.as_str()) {
|
||||
Some("add") if rest.len() >= 3 => Command::Alias(crate::cli::AliasCmd::Add {
|
||||
name: rest[1].clone(),
|
||||
@@ -2019,6 +2092,8 @@ pub fn is_am_command(word: &str) -> bool {
|
||||
| "providers"
|
||||
| "suggest"
|
||||
| "ask"
|
||||
| "ai"
|
||||
| "setup"
|
||||
| "audit"
|
||||
| "service"
|
||||
| "schedule"
|
||||
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
//! am roles — the aichat copilot layer (épique v1.1.0, F3).
|
||||
//!
|
||||
//! Generates aichat agent files (`~/.config/aichat/agents/am-*.md` — or
|
||||
//! `%APPDATA%\aichat\agents\` on Windows) that turn `am ai` into a
|
||||
//! contextual copilot: guide & catalog, secured OS operator, dev helper,
|
||||
//! raw execution, analyst, orchestrator. Each prompt is bilingual (French
|
||||
//! by default, English supported) and instructs the model to use the
|
||||
//! stable `--json` contracts of `am` to inspect the environment.
|
||||
//!
|
||||
//! The aichat config file is only created when it does not exist yet —
|
||||
//! an existing configuration is never touched (respect of the user setup).
|
||||
|
||||
use crate::app::App;
|
||||
use anyhow::Result;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The six copilot roles shipped by `am setup` / `am setup --roles`.
|
||||
pub const ROLE_NAMES: &[&str] = &[
|
||||
"am-copilot",
|
||||
"am-operator",
|
||||
"am-dev",
|
||||
"am-do",
|
||||
"am-analyst",
|
||||
"am-orchestrator",
|
||||
];
|
||||
|
||||
/// Directory where aichat stores its agent definitions. Candidates are
|
||||
/// probed in order: an existing aichat config wins, otherwise the platform
|
||||
/// default (XDG on unix, %APPDATA% on Windows).
|
||||
pub fn aichat_agents_dir() -> PathBuf {
|
||||
let mut candidates: Vec<PathBuf> = Vec::new();
|
||||
if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
|
||||
candidates.push(PathBuf::from(xdg).join("aichat").join("agents"));
|
||||
}
|
||||
if let Some(home) = crate::config::home_dir() {
|
||||
candidates.push(home.join(".config").join("aichat").join("agents"));
|
||||
}
|
||||
if cfg!(windows) {
|
||||
if let Ok(appdata) = std::env::var("APPDATA") {
|
||||
candidates.push(PathBuf::from(appdata).join("aichat").join("agents"));
|
||||
}
|
||||
}
|
||||
for c in &candidates {
|
||||
if c.exists() {
|
||||
return c.clone();
|
||||
}
|
||||
}
|
||||
// No existing aichat config: platform default.
|
||||
if cfg!(windows) {
|
||||
if let Ok(appdata) = std::env::var("APPDATA") {
|
||||
return PathBuf::from(appdata).join("aichat").join("agents");
|
||||
}
|
||||
}
|
||||
crate::config::home_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
.join(".config")
|
||||
.join("aichat")
|
||||
.join("agents")
|
||||
}
|
||||
|
||||
/// Path of the aichat configuration file (created only if absent).
|
||||
pub fn aichat_config_path() -> PathBuf {
|
||||
aichat_agents_dir().parent().unwrap().join("config.yaml")
|
||||
}
|
||||
|
||||
/// The list of `am` commands, embedded in the copilot prompt so the model
|
||||
/// always knows what the CLI can do (kept in sync with `am help commands`).
|
||||
pub fn command_list() -> String {
|
||||
let mut out = String::from(
|
||||
"list, status, sessions, stats, top, report, projects, timeline, log, logs, history, ",
|
||||
);
|
||||
out.push_str(
|
||||
"init, alias, secret, open, watch, search, info, install, uninstall, update, start, stop, ",
|
||||
);
|
||||
out.push_str(
|
||||
"restart, run, doctor, config, completion, self-update, self-uninstall, export, import, ",
|
||||
);
|
||||
out.push_str(
|
||||
"shell, theme, lang, tip, dashboard, favorite, unfavorite, note, tag, untag, tags, ",
|
||||
);
|
||||
out.push_str(
|
||||
"profile, man, models, catalog, providers, suggest, ask, ai, registry, audit, service, ",
|
||||
);
|
||||
out.push_str("schedule, monitor, web, serve, sync, migrate, playbook, lab, plugins, setup");
|
||||
out
|
||||
}
|
||||
|
||||
fn frontmatter(name: &str, description: &str, tools: &[&str]) -> String {
|
||||
let mut out = String::from("---\n");
|
||||
out.push_str(&format!("name: {name}\n"));
|
||||
out.push_str(&format!("description: {description}\n"));
|
||||
if !tools.is_empty() {
|
||||
out.push_str(&format!("tools: [{}]\n", tools.join(", ")));
|
||||
}
|
||||
out.push_str("---\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// The bilingual instruction footer shared by every role.
|
||||
const LANG_FOOTER: &str = "\n\n## Langue / Language\nRéponds en français par défaut, dans la langue de la demande si une autre est utilisée.\nAnswer in French by default, or in the language of the request when it differs.\n";
|
||||
|
||||
/// Build the markdown content of one role.
|
||||
pub fn role_content(name: &str) -> Option<String> {
|
||||
let (desc, tools, body) = match name {
|
||||
"am-copilot" => (
|
||||
"Copilot de agent-manager : guide, catalogue, dépannage",
|
||||
&[][..],
|
||||
format!(
|
||||
"Tu es le copilot de **agent-manager (am)**, le gestionnaire d'agents IA locaux.\n\
|
||||
Tu aides l'utilisateur à exploiter am : catalogue, agents, installation, REPL.\n\
|
||||
\n\
|
||||
Commandes am disponibles : {}\n\
|
||||
\n\
|
||||
Règles :\n\
|
||||
- Privilégie les sorties --json pour inspecter l'environnement : am list --json, am status --json, am info <agent>, am search <mot>.\n\
|
||||
- Pour comprendre l'état : am doctor, am stats --json, am log --kind error.\n\
|
||||
- Propose TOUJOURS la commande exacte à taper, dans un bloc de code.\n\
|
||||
- Si une commande est incertaine, dis-le et propose am help <cmd>.",
|
||||
command_list()
|
||||
),
|
||||
),
|
||||
"am-operator" => (
|
||||
"Opérateur système sécurisé : commandes shell, fichiers, processus",
|
||||
&["shell"][..],
|
||||
"Tu es un opérateur système SÉCURISÉ. Tu transformes les demandes en commandes shell précises.\n\
|
||||
\n\
|
||||
Règles de sécurité (non négociables) :\n\
|
||||
- N'exécute jamais directement : propose la commande, laisse l'utilisateur ou am ai --exec l'exécuter après confirmation.\n\
|
||||
- Signale clairement les commandes RISKY (rm -rf, dd, mkfs, chmod -R 777, git push --force...) et propose une alternative plus sûre quand elle existe.\n\
|
||||
- Adapte-toi à l'OS détecté (Windows/cmd/powershell vs Linux/macOS/bash).\n\
|
||||
- Pour lister/trier/compresser des fichiers, propose la commande la plus simple possible.".to_string(),
|
||||
),
|
||||
"am-dev" => (
|
||||
"Assistant développeur : code, git, tests, revue",
|
||||
&[][..],
|
||||
"Tu es un assistant développeur qui travaille AVEC am (agent-manager).\n\
|
||||
\n\
|
||||
Tu aides sur :\n\
|
||||
- Refactoring, debugging, écriture de tests, revue de code (diff).\n\
|
||||
- Git : am ne gère pas git directement — propose les commandes git exactes.\n\
|
||||
- Suivi de projets : am projects --json, am timeline --json pour le contexte d'activité.\n\
|
||||
- Choix d'agent : am search <tâche> pour recommander un coding agent du catalogue, puis am install / am run.\n\
|
||||
\n\
|
||||
Réponds avec du code concret et des commandes exactes.".to_string(),
|
||||
),
|
||||
"am-do" => (
|
||||
"Exécution pure : génère la commande brute pour am ai --exec",
|
||||
&["shell"][..],
|
||||
"Tu es le moteur d'exécution de am ai --exec.\n\
|
||||
\n\
|
||||
Réponds UNIQUEMENT par la commande shell exacte à exécuter, sur une seule ligne si possible.\n\
|
||||
- Aucune explication avant/après : seulement la commande.\n\
|
||||
- Si la demande est dangereuse, réponds par la commande la plus conservatrice qui satisfait la demande.\n\
|
||||
- Adapte-toi à l'OS détecté.".to_string(),
|
||||
),
|
||||
"am-analyst" => (
|
||||
"Analyste : coûts, logs, statistiques, santé du parc d'agents",
|
||||
&[][..],
|
||||
"Tu es l'analyste de la flotte d'agents gérée par am.\n\
|
||||
\n\
|
||||
Sources de données (toujours en --json) :\n\
|
||||
- Coûts : am stats --costs --json, am top --json\n\
|
||||
- Logs & erreurs : am log --kind error --limit 50 --json, am logs <agent> --lines 50\n\
|
||||
- Activité : am timeline --json, am sessions --json, am report --period week\n\
|
||||
- Santé : am doctor --json, am status --json\n\
|
||||
\n\
|
||||
Produis des synthèses courtes avec les chiffres clés, et propose des actions concrètes.".to_string(),
|
||||
),
|
||||
"am-orchestrator" => (
|
||||
"Orchestrateur : groupes, lab, benchmarks, automatisation",
|
||||
&[][..],
|
||||
"Tu es l'orchestrateur des agents am.\n\
|
||||
\n\
|
||||
Tu aides à :\n\
|
||||
- Lancer des groupes : am start group:dev, am start group:dev --parallel\n\
|
||||
- Benchmarker : am lab --agents a,b --task <fichier> --json\n\
|
||||
- Automatiser : am schedule add <cmd...>, am service install <agent>, am playbook <fichier>\n\
|
||||
- Planifier des runs et interpréter les résultats (am lab --json).\n\
|
||||
\n\
|
||||
Propose toujours des commandes exactes et des benchmarks comparables.".to_string(),
|
||||
),
|
||||
_ => return None,
|
||||
};
|
||||
let content = format!(
|
||||
"{}{}{}",
|
||||
frontmatter(name, desc, tools),
|
||||
body,
|
||||
LANG_FOOTER
|
||||
);
|
||||
Some(content)
|
||||
}
|
||||
|
||||
/// Write every am-* role into the aichat agents directory (creates the
|
||||
/// directory when missing). Existing files with the same name are
|
||||
/// overwritten — they are generated artifacts of am.
|
||||
pub fn generate_all(_app: &App) -> Result<Vec<PathBuf>> {
|
||||
let dir = aichat_agents_dir();
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let mut written = Vec::new();
|
||||
for name in ROLE_NAMES {
|
||||
let content = role_content(name).expect("known role");
|
||||
let path = dir.join(format!("{name}.md"));
|
||||
std::fs::write(&path, content)?;
|
||||
written.push(path);
|
||||
}
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// Create the aichat config file (provider + default model) ONLY when it
|
||||
/// does not exist. An existing configuration is left untouched.
|
||||
pub fn ensure_config_file(app: &App) -> Result<bool> {
|
||||
let path = aichat_config_path();
|
||||
if path.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
let provider = crate::providers::default_name(&app.config);
|
||||
let model = provider.and_then(|p| crate::providers::get(&app.config, p))
|
||||
.and_then(|def| def.default_model.clone());
|
||||
let mut body = String::from("# generated by `am setup` — first run only\n");
|
||||
if let Some(p) = provider {
|
||||
body.push_str(&format!("model_provider: {p}\n"));
|
||||
}
|
||||
if let Some(m) = model {
|
||||
body.push_str(&format!("model: {m}\n"));
|
||||
}
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
std::fs::write(&path, body)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn generates_all_six_roles_with_frontmatter() {
|
||||
for name in ROLE_NAMES {
|
||||
let content = role_content(name).expect("role");
|
||||
assert!(content.starts_with("---\n"), "{name}");
|
||||
assert!(content.contains(&format!("name: {name}")), "{name}");
|
||||
assert!(content.contains("description:"), "{name}");
|
||||
// Bilingual footer present.
|
||||
assert!(content.contains("Réponds en français"), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_tools_only_on_execution_roles() {
|
||||
let operator = role_content("am-operator").unwrap();
|
||||
assert!(operator.contains("tools: [shell]"));
|
||||
let copilot = role_content("am-copilot").unwrap();
|
||||
assert!(!copilot.contains("tools:"), "copilot must not have tools");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_role_returns_none() {
|
||||
assert!(role_content("am-inconnu").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copilot_prompt_embeds_the_command_list() {
|
||||
let copilot = role_content("am-copilot").unwrap();
|
||||
assert!(copilot.contains("am list --json"));
|
||||
assert!(copilot.contains("setup"), "command list must include setup");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agents_dir_prefers_existing_aichat_config() {
|
||||
// With a home dir, the unix candidate is ~/.config/aichat/agents.
|
||||
let dir = aichat_agents_dir();
|
||||
assert!(dir.ends_with("agents"), "{dir:?}");
|
||||
}
|
||||
}
|
||||
+389
@@ -0,0 +1,389 @@
|
||||
//! am setup — the onboarding wizard (épique v1.1.0, F1).
|
||||
//!
|
||||
//! Guides the user through: provider choice, masked API-token entry (OS
|
||||
//! keyring, never in clear), default model selection, a non-blocking API
|
||||
//! ping, the optional aichat installation (F2) and the generation of the
|
||||
//! am-* copilot roles for aichat (F3). Re-runnable at any time (`am setup`
|
||||
//! = "review" mode); triggered on first run by the AI commands and the
|
||||
//! REPL banner when no provider is configured.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::cli::ProvidersCmd;
|
||||
use crate::commands::{config_cmd, install_cmd, providers_cmd};
|
||||
use crate::secrets::SecretStore;
|
||||
use anyhow::{bail, Result};
|
||||
use std::io::Write;
|
||||
|
||||
/// Known providers offered by the wizard (from the embedded registry plus
|
||||
/// the local Ollama runtime and a custom endpoint).
|
||||
const CHOICES: &[&str] = &["anthropic", "openai", "deepseek", "google", "openrouter", "ollama", "custom"];
|
||||
|
||||
/// True when the user has not configured a usable default provider yet:
|
||||
/// no `settings.default_provider`, or the default provider has no API
|
||||
/// token in the keyring (except local Ollama, which needs none).
|
||||
pub fn needs_setup(app: &App) -> bool {
|
||||
let Some(def) = crate::providers::default_name(&app.config) else {
|
||||
return true;
|
||||
};
|
||||
if def == "ollama" {
|
||||
return false;
|
||||
}
|
||||
let store = crate::secrets::store();
|
||||
store
|
||||
.get(&crate::secrets::key_for_provider_token(def))
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_none()
|
||||
}
|
||||
|
||||
fn read_line() -> Result<String> {
|
||||
let mut line = String::new();
|
||||
std::io::stdin().read_line(&mut line)?;
|
||||
Ok(line.trim().to_string())
|
||||
}
|
||||
|
||||
/// Ask a y/N question on stderr, defaulting to yes when `yes` is set.
|
||||
fn ask(app: &App, question: &str, default_yes: bool) -> Result<bool> {
|
||||
if app.cli.yes {
|
||||
return Ok(true);
|
||||
}
|
||||
let suffix = if default_yes { "[Y/n]" } else { "[y/N]" };
|
||||
eprint!("{question} {suffix} ");
|
||||
std::io::stderr().flush()?;
|
||||
let answer = read_line()?.to_lowercase();
|
||||
Ok(match answer.as_str() {
|
||||
"" => default_yes,
|
||||
"y" | "yes" | "o" | "oui" | "true" => true,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Pick a provider from the list (or the current default when --yes).
|
||||
fn pick_provider(app: &App) -> Result<(String, Option<String>)> {
|
||||
let current = crate::providers::default_name(&app.config);
|
||||
println!("Provider disponible :");
|
||||
for (i, p) in CHOICES.iter().enumerate() {
|
||||
let star = if Some(*p) == current { " (actuel)" } else { "" };
|
||||
println!(" {}) {}{star}", i + 1, p);
|
||||
}
|
||||
if app.cli.yes {
|
||||
let name = current.unwrap_or("anthropic").to_string();
|
||||
return Ok((name, None));
|
||||
}
|
||||
loop {
|
||||
print!("Choisissez (1-{}) : ", CHOICES.len());
|
||||
std::io::stdout().flush()?;
|
||||
let raw = read_line()?;
|
||||
if let Ok(n) = raw.parse::<usize>() {
|
||||
if (1..=CHOICES.len()).contains(&n) {
|
||||
let name = CHOICES[n - 1];
|
||||
if name == "custom" {
|
||||
print!("Base URL de l'API (ex: https://api.openai.com/v1) : ");
|
||||
std::io::stdout().flush()?;
|
||||
let url = read_line()?;
|
||||
if url.is_empty() {
|
||||
continue;
|
||||
}
|
||||
return Ok(("custom".to_string(), Some(url)));
|
||||
}
|
||||
return Ok((name.to_string(), None));
|
||||
}
|
||||
}
|
||||
if !raw.is_empty() {
|
||||
return Ok((raw, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The declared models of a provider (embedded registry), or an empty list
|
||||
/// for local/custom providers.
|
||||
fn declared_models(app: &App, name: &str) -> Vec<String> {
|
||||
crate::providers::get(&app.config, name)
|
||||
.map(|d| d.models.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Ask for the default model: numbered list of the declared models plus a
|
||||
/// free entry. `--yes` keeps the provider's current default.
|
||||
fn pick_model(app: &App, name: &str) -> Result<String> {
|
||||
let models = declared_models(app, name);
|
||||
let current = crate::providers::get(&app.config, name)
|
||||
.and_then(|d| d.default_model.clone())
|
||||
.or_else(|| models.first().cloned());
|
||||
if !models.is_empty() {
|
||||
println!("Modèles disponibles pour {name} :");
|
||||
for (i, m) in models.iter().enumerate() {
|
||||
let star = if Some(m) == current.as_ref() { " (défaut)" } else { "" };
|
||||
println!(" {}) {m}{star}", i + 1);
|
||||
}
|
||||
println!(" {}) autre modèle…", models.len() + 1);
|
||||
} else {
|
||||
println!("Aucun modèle déclaré pour {name} — saisissez le modèle par défaut.");
|
||||
}
|
||||
if app.cli.yes {
|
||||
return Ok(current.unwrap_or_else(|| "gpt-4o".to_string()));
|
||||
}
|
||||
loop {
|
||||
print!("Modèle par défaut : ");
|
||||
std::io::stdout().flush()?;
|
||||
let raw = read_line()?;
|
||||
if let Ok(n) = raw.parse::<usize>() {
|
||||
if n >= 1 && n <= models.len() {
|
||||
return Ok(models[n - 1].clone());
|
||||
}
|
||||
if n == models.len() + 1 {
|
||||
print!("Nom du modèle : ");
|
||||
std::io::stdout().flush()?;
|
||||
let custom = read_line()?;
|
||||
if !custom.is_empty() {
|
||||
return Ok(custom);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if !raw.is_empty() {
|
||||
return Ok(raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-blocking API ping: any HTTP answer (200, 401…) proves the endpoint
|
||||
/// is reachable and the token is transmitted. Network failures are logged
|
||||
/// as warnings only — the wizard never blocks on this.
|
||||
fn ping_provider(name: &str, base_url: &str, token: Option<&str>) {
|
||||
let url = format!("{}/models", base_url.trim_end_matches('/'));
|
||||
let result = match token {
|
||||
Some(t) => ureq::get(&url).set("Authorization", &format!("Bearer {t}")).call(),
|
||||
None => ureq::get(&url).call(),
|
||||
};
|
||||
match result {
|
||||
Ok(_) | Err(ureq::Error::Status(_, _)) => {
|
||||
// Reachable (200 or an auth-status): the endpoint answered.
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("⚠ ping du provider échoué (non bloquant) : {e}");
|
||||
}
|
||||
}
|
||||
let _ = name;
|
||||
}
|
||||
|
||||
/// Main wizard. `--yes` runs it non-interactively with the current
|
||||
/// defaults (install aichat + roles included).
|
||||
pub fn run(app: &App) -> Result<i32> {
|
||||
let lang = app.lang();
|
||||
if !app.cli.yes {
|
||||
println!("⚙ {}", crate::i18n::tr_in(lang, "Configuration d'agent-manager (am setup)"));
|
||||
println!("{}", crate::i18n::tr_in(lang, "Le token est stocké dans le trousseau OS — jamais en clair."));
|
||||
}
|
||||
|
||||
// 1) Provider.
|
||||
let (provider, custom_url) = pick_provider(app)?;
|
||||
let base_url = if provider == "custom" {
|
||||
custom_url.clone().unwrap_or_default()
|
||||
} else {
|
||||
crate::providers::get(&app.config, &provider)
|
||||
.map(|d| d.base_url.clone())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
if provider == "custom" {
|
||||
let cmd = ProvidersCmd::Add {
|
||||
name: "custom".to_string(),
|
||||
base_url: custom_url.clone().unwrap_or_default(),
|
||||
model: None,
|
||||
models: None,
|
||||
};
|
||||
providers_cmd::run(app, Some(&cmd))?;
|
||||
} else if provider == "ollama" {
|
||||
// Local runtime: register it (it is not part of the embedded
|
||||
// registry) so the config stays valid, then keep going tokenless.
|
||||
let cmd = ProvidersCmd::Add {
|
||||
name: "ollama".to_string(),
|
||||
base_url: "http://localhost:11434/v1".to_string(),
|
||||
model: None,
|
||||
models: None,
|
||||
};
|
||||
providers_cmd::run(app, Some(&cmd))?;
|
||||
}
|
||||
|
||||
// 2) Token (masked) — skipped for local Ollama.
|
||||
let mut token: Option<String> = None;
|
||||
if provider != "ollama" {
|
||||
if app.cli.yes {
|
||||
let store = crate::secrets::store();
|
||||
token = store
|
||||
.get(&crate::secrets::key_for_provider_token(&provider))
|
||||
.ok()
|
||||
.flatten();
|
||||
} else {
|
||||
let value = rpassword::prompt_password(&format!(
|
||||
"Token API pour {provider} (invisible) : "
|
||||
))?;
|
||||
if !value.is_empty() {
|
||||
token = Some(value.clone());
|
||||
let cmd = ProvidersCmd::SetToken {
|
||||
name: provider.clone(),
|
||||
value,
|
||||
};
|
||||
providers_cmd::run(app, Some(&cmd))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3) Default model. The registry lives under settings.providers — a
|
||||
// top-level `providers:` key is rejected by the schema validator, and a
|
||||
// provider block written to the user config requires base_url too.
|
||||
let model = pick_model(app, &provider)?;
|
||||
if provider == "ollama" {
|
||||
// base_url was already written by the Add above.
|
||||
config_cmd::persist_setting(app, "settings.providers.ollama.default_model", &model)?;
|
||||
} else if provider != "custom" {
|
||||
if let Some(def) = crate::providers::get(&app.config, &provider) {
|
||||
config_cmd::persist_setting(
|
||||
app,
|
||||
&format!("settings.providers.{provider}.base_url"),
|
||||
&def.base_url,
|
||||
)?;
|
||||
config_cmd::persist_setting(
|
||||
app,
|
||||
&format!("settings.providers.{provider}.default_model"),
|
||||
&model,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
// 4) Default provider.
|
||||
config_cmd::persist_setting(app, "settings.default_provider", &provider)?;
|
||||
|
||||
// 5) Non-blocking ping.
|
||||
if provider != "ollama" && !base_url.is_empty() {
|
||||
ping_provider(&provider, &base_url, token.as_deref());
|
||||
}
|
||||
|
||||
// 6) Install aichat (F2) — skipped when already present.
|
||||
let aichat_present = app
|
||||
.state
|
||||
.get("aichat")
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some()
|
||||
|| which::which("aichat").is_ok();
|
||||
if !aichat_present {
|
||||
if ask(app, crate::i18n::tr_in(lang, "Installer le moteur IA (aichat) ?"), true)? {
|
||||
println!("{}", crate::i18n::tr_in(lang, "Installation d'aichat…"));
|
||||
install_cmd::run(app, "aichat", None, false, None, None, false)?;
|
||||
}
|
||||
} else {
|
||||
println!("✓ aichat déjà installé");
|
||||
}
|
||||
|
||||
// 7) Copilot roles (F3) + aichat config (only when absent).
|
||||
let roles = crate::roles::generate_all(app)?;
|
||||
let config_created = crate::roles::ensure_config_file(app)?;
|
||||
println!(
|
||||
"✓ {} ({} fichiers)",
|
||||
crate::i18n::tr_in(lang, "Rôles copilot am-* générés"),
|
||||
roles.len()
|
||||
);
|
||||
if config_created {
|
||||
println!("✓ {}", crate::i18n::tr_in(lang, "Config aichat créée (provider + modèle)"));
|
||||
}
|
||||
|
||||
app.log.success(&crate::i18n::tr_in(
|
||||
lang,
|
||||
"am est configuré — essayez: am ai \"...\" ou am ai --exec \"...\"",
|
||||
));
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// `am setup --roles`: (re)generate only the copilot roles.
|
||||
pub fn run_roles(app: &App) -> Result<i32> {
|
||||
let roles = crate::roles::generate_all(app)?;
|
||||
println!("✓ {} fichiers de rôle :", roles.len());
|
||||
for p in &roles {
|
||||
println!(" {}", p.display());
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app::App;
|
||||
use crate::cli::Cli;
|
||||
use clap::Parser;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
fn app_with(settings_yaml: &str) -> App {
|
||||
app_with_path(settings_yaml).0
|
||||
}
|
||||
|
||||
fn app_with_path(settings_yaml: &str) -> (App, PathBuf) {
|
||||
let id = COUNTER.fetch_add(1, Ordering::SeqCst);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"am-setup-test-{}-{id}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let cfg = dir.join("config.yaml");
|
||||
std::fs::write(
|
||||
&cfg,
|
||||
format!(
|
||||
"version: \"1.0\"\nsettings:\n auto_install_deps: false\n confirm_before_run: false\n{settings_yaml}agents: []\n"
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let cli = Cli::parse_from(["am", "--config", cfg.to_str().unwrap()]);
|
||||
(App::from_cli(cli).unwrap(), cfg)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_setup_true_without_a_configured_provider() {
|
||||
// The embedded default ships default_provider: anthropic, but no
|
||||
// keyring token exists in a test process -> setup needed.
|
||||
let app = app_with("");
|
||||
assert!(needs_setup(&app));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_setup_false_for_local_ollama() {
|
||||
let app = app_with(
|
||||
" default_provider: ollama\n providers:\n ollama:\n base_url: http://localhost:11434/v1\n",
|
||||
);
|
||||
assert!(!needs_setup(&app));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setup_persists_under_settings_providers() {
|
||||
// Regression: a top-level `providers:` key is rejected by the
|
||||
// schema validator ("unknown field `providers`"). The wizard must
|
||||
// write settings.providers.<name>.default_model.
|
||||
let (app, cfg) = app_with_path("");
|
||||
config_cmd::persist_setting(
|
||||
&app,
|
||||
"settings.providers.deepseek.base_url",
|
||||
"https://api.deepseek.com",
|
||||
)
|
||||
.unwrap();
|
||||
config_cmd::persist_setting(
|
||||
&app,
|
||||
"settings.providers.deepseek.default_model",
|
||||
"deepseek-reasoner",
|
||||
)
|
||||
.unwrap();
|
||||
config_cmd::persist_setting(&app, "settings.default_provider", "deepseek").unwrap();
|
||||
|
||||
// Reloading the config must succeed (validation passes) and the
|
||||
// merged registry must reflect the new default model.
|
||||
let cli = Cli::parse_from(["am", "--config", cfg.to_str().unwrap()]);
|
||||
let app2 = App::from_cli(cli).expect("config must stay valid after setup writes");
|
||||
let def = crate::providers::get(&app2.config, "deepseek").unwrap();
|
||||
assert_eq!(def.default_model.as_deref(), Some("deepseek-reasoner"));
|
||||
assert_eq!(
|
||||
crate::providers::default_name(&app2.config).as_deref(),
|
||||
Some("deepseek")
|
||||
);
|
||||
}
|
||||
}
|
||||
+465
@@ -0,0 +1,465 @@
|
||||
//! am ai — langage naturel → action shell (issues #96 #97).
|
||||
//!
|
||||
//! The Shell AI command turns a natural-language request into a shell
|
||||
//! action using AIChat (the `aichat` catalog agent) as the generation
|
||||
//! engine:
|
||||
//!
|
||||
//! - conversational mode (no `--exec`): `aichat -f <ctx> "<prompt>"` is
|
||||
//! spawned in the foreground, exactly as the user would run it;
|
||||
//! - exec mode (`--exec`): aichat is asked to generate the command with
|
||||
//! `--dry-run` (it prints the command and never runs it), then the
|
||||
//! generated command is classified (safe / risky), a confidence score
|
||||
//! is estimated, the configured safety policy is applied (dry-run by
|
||||
//! default), and only then — after confirmation when required — is the
|
||||
//! command executed through the user's shell.
|
||||
//!
|
||||
//! Nothing is ever executed without an explicit confirmation: the default
|
||||
//! policy is `dry-run`, overridden by `--yes` (execute without asking),
|
||||
//! the `settings.shell_ai.default_safety` setting (dry-run | confirm |
|
||||
//! auto) or the explicit `--dry-run` flag (never execute, show only).
|
||||
|
||||
use crate::app::App;
|
||||
use crate::commands::{require_agent, resolve_exec};
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use std::collections::BTreeMap;
|
||||
use std::process::Command;
|
||||
|
||||
/// Safety policies of `am ai --exec` (issue #97).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SafetyMode {
|
||||
/// Show the generated command only — nothing is executed unless the
|
||||
/// user passes `--yes`.
|
||||
DryRun,
|
||||
/// Execute safe commands directly; ask before risky ones.
|
||||
Confirm,
|
||||
/// Execute everything without asking (explicitly enabled by the user).
|
||||
Auto,
|
||||
}
|
||||
|
||||
impl SafetyMode {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
SafetyMode::DryRun => "dry-run",
|
||||
SafetyMode::Confirm => "confirm",
|
||||
SafetyMode::Auto => "auto",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Risk class of a generated shell command.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Risk {
|
||||
Safe,
|
||||
Risky,
|
||||
}
|
||||
|
||||
impl Risk {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Risk::Safe => "safe",
|
||||
Risk::Risky => "risky",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Built-in substrings that mark a command as risky (issue #97). The user
|
||||
/// can extend this list with `settings.shell_ai.risky_patterns`.
|
||||
pub const BUILTIN_RISKY_PATTERNS: &[&str] = &[
|
||||
"rm -rf",
|
||||
"rm -fr",
|
||||
"rm -r -f",
|
||||
"dd if=",
|
||||
"mkfs.",
|
||||
"fdisk",
|
||||
"parted",
|
||||
"gdisk",
|
||||
":(){",
|
||||
"chmod -R 777",
|
||||
"chmod 777 /",
|
||||
"chown -R",
|
||||
"> /dev/sd",
|
||||
">/dev/sd",
|
||||
"sudo rm",
|
||||
"git push --force",
|
||||
"git push -f",
|
||||
"drop database",
|
||||
"drop table",
|
||||
"truncate table",
|
||||
"shutdown",
|
||||
"reboot",
|
||||
"poweroff",
|
||||
"kill -9",
|
||||
"pkill -9",
|
||||
"killall",
|
||||
"init 0",
|
||||
"init 6",
|
||||
"mv / ",
|
||||
"rm /",
|
||||
"format c:",
|
||||
"del /f /s",
|
||||
"rd /s",
|
||||
"cipher /w",
|
||||
"curl ... | sh",
|
||||
"curl ... | bash",
|
||||
"wget ... | sh",
|
||||
];
|
||||
|
||||
/// Classify a generated command against the built-in patterns plus the
|
||||
/// user-configured ones (`settings.shell_ai.risky_patterns`).
|
||||
pub fn classify(cmd: &str, extra_patterns: &[String]) -> Risk {
|
||||
let lower = cmd.to_lowercase();
|
||||
let hits = BUILTIN_RISKY_PATTERNS
|
||||
.iter()
|
||||
.any(|p| lower.contains(&p.to_lowercase()))
|
||||
|| extra_patterns.iter().any(|p| lower.contains(&p.to_lowercase()));
|
||||
if hits {
|
||||
Risk::Risky
|
||||
} else {
|
||||
Risk::Safe
|
||||
}
|
||||
}
|
||||
|
||||
/// A coarse confidence heuristic (0-100) shown to the user. Risky or
|
||||
/// compound commands are scored lower; simple, read-only commands score
|
||||
/// higher. It is an estimate, never a guarantee.
|
||||
pub fn estimate_certainty(cmd: &str, risk: Risk) -> u8 {
|
||||
let mut score: i32 = 92;
|
||||
if risk == Risk::Risky {
|
||||
score -= 25;
|
||||
}
|
||||
// Compound commands chain several effects — harder to predict.
|
||||
for sep in ["&&", "||", ";\n", "\n", " | ", " 2>"] {
|
||||
if cmd.contains(sep) {
|
||||
score -= 6;
|
||||
}
|
||||
}
|
||||
// Redirections and pipes move data around.
|
||||
if cmd.contains('>') || cmd.contains('<') {
|
||||
score -= 5;
|
||||
}
|
||||
if cmd.contains("sudo") {
|
||||
score -= 8;
|
||||
}
|
||||
score.clamp(40, 99) as u8
|
||||
}
|
||||
|
||||
/// Decide what to do with a generated command under the effective policy.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Decision {
|
||||
/// Print and abort (dry-run or declined confirmation).
|
||||
Abort,
|
||||
/// Ask the user (y/N) before executing.
|
||||
Ask,
|
||||
/// Execute directly.
|
||||
Execute,
|
||||
}
|
||||
|
||||
/// Apply the safety policy: explicit `--dry-run` flag > `--yes` flag >
|
||||
/// configured default mode (fallback: dry-run).
|
||||
pub fn decide(
|
||||
mode: SafetyMode,
|
||||
risk: Risk,
|
||||
dry_run_flag: bool,
|
||||
yes_flag: bool,
|
||||
) -> Decision {
|
||||
if dry_run_flag {
|
||||
return Decision::Abort;
|
||||
}
|
||||
if yes_flag {
|
||||
return Decision::Execute;
|
||||
}
|
||||
match mode {
|
||||
SafetyMode::Auto => Decision::Execute,
|
||||
SafetyMode::Confirm => {
|
||||
if risk == Risk::Risky {
|
||||
Decision::Ask
|
||||
} else {
|
||||
Decision::Execute
|
||||
}
|
||||
}
|
||||
SafetyMode::DryRun => Decision::Abort,
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the shell command from aichat's `--dry-run` output: strips a
|
||||
/// fenced code block if present, otherwise uses the trimmed output as-is.
|
||||
pub fn extract_command(stdout: &str) -> Option<String> {
|
||||
let trimmed = stdout.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Fenced block: ```bash ... ``` (or ```sh, ```powershell, ```cmd ...)
|
||||
let mut lines = trimmed.lines();
|
||||
if lines.next().is_some_and(|l| l.trim_start().starts_with("```")) {
|
||||
let body: Vec<&str> = lines
|
||||
.take_while(|l| !l.trim().starts_with("```"))
|
||||
.collect();
|
||||
let cmd = body.join("\n").trim().to_string();
|
||||
if !cmd.is_empty() {
|
||||
return Some(cmd);
|
||||
}
|
||||
}
|
||||
Some(trimmed.to_string())
|
||||
}
|
||||
|
||||
/// Map a provider of the registry to the environment variables AIChat
|
||||
/// understands, and resolve the model to pass with `--model`. The token is
|
||||
/// resolved from the OS keyring via the standard `@secret` mechanism and
|
||||
/// never appears on the command line (issue #89).
|
||||
pub fn provider_env(
|
||||
app: &App,
|
||||
provider: Option<&str>,
|
||||
model: Option<&str>,
|
||||
) -> Result<(Vec<String>, BTreeMap<String, String>)> {
|
||||
// Without any flag, aichat keeps its own configuration (its config file
|
||||
// and API keys) — the registry is only applied on explicit request.
|
||||
if provider.is_none() && model.is_none() {
|
||||
return Ok((Vec::new(), BTreeMap::new()));
|
||||
}
|
||||
let Some((pname, def, resolved_model)) =
|
||||
crate::providers::resolve_for(&app.config, None, None, provider, model)
|
||||
else {
|
||||
if provider.is_some() {
|
||||
let known = crate::providers::names(&app.config);
|
||||
let hint = if known.is_empty() {
|
||||
"aucun (am providers add <nom> --base-url <url>)".to_string()
|
||||
} else {
|
||||
known.join(", ")
|
||||
};
|
||||
bail!(crate::i18n::tr_fmt_in(
|
||||
app.lang(),
|
||||
"provider '{}' inconnu — providers enregistrés: {}",
|
||||
&[&provider.unwrap_or(""), &hint]
|
||||
));
|
||||
}
|
||||
return Ok((Vec::new(), BTreeMap::new()));
|
||||
};
|
||||
let mut args: Vec<String> = Vec::new();
|
||||
let mut env: BTreeMap<String, String> = BTreeMap::new();
|
||||
// Known providers map to AIChat's standard API-key variables; custom
|
||||
// provider names fall back to the openai-compatible channel.
|
||||
let key_var = match pname {
|
||||
"anthropic" => Some("ANTHROPIC_API_KEY"),
|
||||
"openai" => Some("OPENAI_API_KEY"),
|
||||
"deepseek" => Some("DEEPSEEK_API_KEY"),
|
||||
"google" => Some("GOOGLE_API_KEY"),
|
||||
"groq" => Some("GROQ_API_KEY"),
|
||||
"openrouter" => Some("OPENROUTER_API_KEY"),
|
||||
"xai" | "grok" => Some("XAI_API_KEY"),
|
||||
"ollama" => None, // local — no key; aichat knows its default endpoint
|
||||
_ => Some("OPENAI_API_KEY"),
|
||||
};
|
||||
if let Some(var) = key_var {
|
||||
env.insert(var.to_string(), "@secret".to_string());
|
||||
if !matches!(pname, "openai" | "ollama" | "anthropic" | "deepseek" | "google" | "groq" | "openrouter" | "xai" | "grok") {
|
||||
// Custom endpoints ride the openai-compatible channel.
|
||||
env.insert("OPENAI_API_BASE".to_string(), def.base_url.clone());
|
||||
}
|
||||
}
|
||||
if let Some(m) = resolved_model {
|
||||
args.push("--model".to_string());
|
||||
args.push(m.to_string());
|
||||
}
|
||||
let warnings = crate::secrets::resolve_env_secrets(
|
||||
&crate::secrets::store(),
|
||||
"aichat",
|
||||
Some(pname),
|
||||
&mut env,
|
||||
);
|
||||
for w in warnings {
|
||||
app.log.warn(&w);
|
||||
}
|
||||
Ok((args, env))
|
||||
}
|
||||
|
||||
/// Generate a shell command for `prompt` using aichat in dry-run mode.
|
||||
/// Returns the generated command (never executed by aichat).
|
||||
pub fn generate(
|
||||
app: &App,
|
||||
prompt: &str,
|
||||
files: &[String],
|
||||
provider: Option<&str>,
|
||||
model: Option<&str>,
|
||||
role_args: &[String],
|
||||
) -> Result<String> {
|
||||
let agent = require_agent(app, "aichat")?;
|
||||
let mut extra_args: Vec<String> = vec!["--exec".to_string(), "--dry-run".to_string()];
|
||||
extra_args.extend(role_args.iter().cloned());
|
||||
for f in files {
|
||||
extra_args.push("-f".to_string());
|
||||
extra_args.push(f.clone());
|
||||
}
|
||||
extra_args.push(prompt.to_string());
|
||||
let (p_args, p_env) = provider_env(app, provider, model)?;
|
||||
extra_args.extend(p_args);
|
||||
let exec = resolve_exec(app, agent, &extra_args, &p_env)?;
|
||||
app.log.verbose(&format!(
|
||||
"shell-ai: {} {} (dry-run generation)",
|
||||
exec.program,
|
||||
exec.args.join(" ")
|
||||
));
|
||||
let (prog, prefix) = crate::runner::resolve_program(&exec.program);
|
||||
let mut full_args = prefix;
|
||||
full_args.extend(exec.args.iter().cloned());
|
||||
let out = Command::new(&prog)
|
||||
.args(&full_args)
|
||||
.envs(&exec.env)
|
||||
.output()
|
||||
.with_context(|| format!("failed to run {}", exec.program))?;
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
let err = err.trim();
|
||||
bail!(crate::i18n::tr_fmt_in(
|
||||
app.lang(),
|
||||
"aichat n'a pas généré de commande (exit {}){}",
|
||||
&[
|
||||
&out.status.code().unwrap_or(-1).to_string(),
|
||||
&if err.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(": {err}")
|
||||
},
|
||||
]
|
||||
));
|
||||
}
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
extract_command(&stdout).ok_or_else(|| {
|
||||
anyhow!(crate::i18n::tr_in(
|
||||
app.lang(),
|
||||
"aichat n'a retourné aucune commande (dry-run)"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute a generated command through the user's shell (default_shell >
|
||||
/// $SHELL > $COMSPEC > cmd). The command is passed as a single argument.
|
||||
pub fn execute(app: &App, command: &str) -> Result<i32> {
|
||||
let spec = crate::shell::resolve_default(
|
||||
app.config.settings.default_shell.as_deref(),
|
||||
std::env::var_os("SHELL"),
|
||||
std::env::var_os("COMSPEC"),
|
||||
);
|
||||
app.log.verbose(&format!(
|
||||
"shell-ai: executing via {} {}",
|
||||
spec.program,
|
||||
spec.args.join(" ")
|
||||
));
|
||||
let (prog, prefix) = crate::runner::resolve_program(spec.program);
|
||||
let mut args = prefix;
|
||||
args.extend(spec.args.iter().map(|s| s.to_string()));
|
||||
args.push(command.to_string());
|
||||
let status = Command::new(&prog)
|
||||
.args(&args)
|
||||
.status()
|
||||
.with_context(|| format!("failed to run {}", spec.program))?;
|
||||
Ok(status.code().unwrap_or(1))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn classifies_safe_and_risky() {
|
||||
assert_eq!(classify("ls -la", &[]), Risk::Safe);
|
||||
assert_eq!(classify("echo hello", &[]), Risk::Safe);
|
||||
assert_eq!(classify("find . -name '*.json'", &[]), Risk::Safe);
|
||||
assert_eq!(classify("rm -rf /tmp/x", &[]), Risk::Risky);
|
||||
assert_eq!(classify("sudo rm -rf /var/log", &[]), Risk::Risky);
|
||||
assert_eq!(classify("dd if=/dev/zero of=/dev/sda", &[]), Risk::Risky);
|
||||
assert_eq!(classify("git push --force origin main", &[]), Risk::Risky);
|
||||
assert_eq!(classify("drop database prod;", &[]), Risk::Risky);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_extra_user_patterns() {
|
||||
let extra = vec!["killall node".to_string()];
|
||||
assert_eq!(classify("killall node", &extra), Risk::Risky);
|
||||
assert_eq!(classify("killall nodejs", &extra), Risk::Risky);
|
||||
assert_eq!(classify("node --version", &extra), Risk::Safe);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certainty_stays_in_bounds_and_penalizes_risk() {
|
||||
let safe = estimate_certainty("ls -la", Risk::Safe);
|
||||
let risky = estimate_certainty("rm -rf /", Risk::Risky);
|
||||
assert!(safe > risky, "{safe} should be > {risky}");
|
||||
assert!((40..=99).contains(&safe));
|
||||
assert!((40..=99).contains(&risky));
|
||||
let compound = estimate_certainty("rm -rf /tmp/a && echo ok", Risk::Risky);
|
||||
assert!(compound < risky || compound == risky);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_command_handles_fences_and_plain() {
|
||||
assert_eq!(
|
||||
extract_command("```bash\nrm *.tmp\n```"),
|
||||
Some("rm *.tmp".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
extract_command("```sh\necho hello\n```\n"),
|
||||
Some("echo hello".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
extract_command("rm *.tmp\n"),
|
||||
Some("rm *.tmp".to_string())
|
||||
);
|
||||
assert_eq!(extract_command(" \n "), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decision_matrix() {
|
||||
// dry-run (default): abort, even with --yes overriding to execute.
|
||||
assert_eq!(
|
||||
decide(SafetyMode::DryRun, Risk::Risky, false, false),
|
||||
Decision::Abort
|
||||
);
|
||||
assert_eq!(
|
||||
decide(SafetyMode::DryRun, Risk::Safe, false, false),
|
||||
Decision::Abort
|
||||
);
|
||||
assert_eq!(
|
||||
decide(SafetyMode::DryRun, Risk::Risky, false, true),
|
||||
Decision::Execute
|
||||
);
|
||||
// explicit --dry-run wins over --yes.
|
||||
assert_eq!(
|
||||
decide(SafetyMode::Auto, Risk::Risky, true, true),
|
||||
Decision::Abort
|
||||
);
|
||||
// confirm: ask only for risky.
|
||||
assert_eq!(
|
||||
decide(SafetyMode::Confirm, Risk::Safe, false, false),
|
||||
Decision::Execute
|
||||
);
|
||||
assert_eq!(
|
||||
decide(SafetyMode::Confirm, Risk::Risky, false, false),
|
||||
Decision::Ask
|
||||
);
|
||||
// auto: execute everything.
|
||||
assert_eq!(
|
||||
decide(SafetyMode::Auto, Risk::Risky, false, false),
|
||||
Decision::Execute
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safety_mode_parsing_falls_back_to_dry_run() {
|
||||
use crate::config::ShellAiSettings;
|
||||
let s = ShellAiSettings {
|
||||
default_safety: Some("confirm".to_string()),
|
||||
risky_patterns: vec![],
|
||||
};
|
||||
assert_eq!(s.safety_mode(), SafetyMode::Confirm);
|
||||
let s = ShellAiSettings {
|
||||
default_safety: Some("n'importe quoi".to_string()),
|
||||
risky_patterns: vec![],
|
||||
};
|
||||
assert_eq!(s.safety_mode(), SafetyMode::DryRun);
|
||||
let s = ShellAiSettings {
|
||||
default_safety: None,
|
||||
risky_patterns: vec![],
|
||||
};
|
||||
assert_eq!(s.safety_mode(), SafetyMode::DryRun);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Integration tests for `am ai` (issues #96 #97): the command resolves
|
||||
//! the `aichat` catalog agent, so a fake `aichat.cmd` shim is placed on
|
||||
//! PATH and emits a canned command. The safety pipeline (dry-run default,
|
||||
//! classification, confirmation, --yes) is exercised end to end through
|
||||
//! the real command dispatch.
|
||||
|
||||
mod common;
|
||||
|
||||
use agent_manager::cli::Cli;
|
||||
use clap::Parser;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Serialize PATH mutation and process spawning between parallel tests.
|
||||
static ENV_LOCK: Mutex<()> = Mutex::new(());
|
||||
static COUNTER: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
const AICHAT_DEF: &str = r#"
|
||||
agents:
|
||||
- name: aichat
|
||||
display_name: AIChat
|
||||
description: fake shim for tests
|
||||
category: shell-ai
|
||||
install:
|
||||
type: binary
|
||||
repo: sigoden/aichat
|
||||
binary: aichat
|
||||
run: aichat
|
||||
installable: false
|
||||
"#;
|
||||
|
||||
fn fresh_dir(tag: &str) -> PathBuf {
|
||||
let id = COUNTER.fetch_add(1, Ordering::SeqCst);
|
||||
let dir = std::env::temp_dir().join(format!("am-ai-{tag}-{}-{id}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// Write a fake `aichat.cmd` into `dir` and prepend `dir` to PATH.
|
||||
fn fake_aichat(dir: &PathBuf, body: &str) {
|
||||
std::fs::write(dir.join("aichat.cmd"), body).unwrap();
|
||||
let mut paths = vec![dir.clone()];
|
||||
if let Some(existing) = std::env::var_os("PATH") {
|
||||
paths.extend(std::env::split_paths(&existing));
|
||||
}
|
||||
std::env::set_var("PATH", std::env::join_paths(paths).unwrap());
|
||||
}
|
||||
|
||||
/// Build the App for an `am ai` invocation with the aichat shim on PATH.
|
||||
fn app_for(shim_body: &str, settings: &str, args: &[&str]) -> (agent_manager::app::App, PathBuf) {
|
||||
let dir = fresh_dir("app");
|
||||
fake_aichat(&dir, shim_body);
|
||||
let cfg = common::write_config(&dir, &format!("{settings}{AICHAT_DEF}"));
|
||||
let mut full = vec!["am".to_string(), "--config".to_string(), cfg.display().to_string()];
|
||||
full.extend(args.iter().map(|s| s.to_string()));
|
||||
let cli = Cli::parse_from(full);
|
||||
let mut app = agent_manager::app::App::from_cli(cli).expect("app should build");
|
||||
common::isolate(&mut app, &dir);
|
||||
(app, dir)
|
||||
}
|
||||
|
||||
fn run(args: &[&str], shim_body: &str, settings: &str) -> (String, String, i32) {
|
||||
let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let (app, dir) = app_for(shim_body, settings, args);
|
||||
let cmd = app.cli.command.as_ref().expect("a command was parsed");
|
||||
let code = agent_manager::commands::execute_command(&app, cmd).unwrap_or_else(|e| {
|
||||
eprintln!("ERR: {e:#}");
|
||||
1
|
||||
});
|
||||
let log = std::fs::read_to_string(app.paths.log_dir.join("agent-manager.log"))
|
||||
.unwrap_or_default();
|
||||
// Events journal lives next to state.json (isolated dir).
|
||||
let mut events = String::new();
|
||||
if let Ok(rd) = std::fs::read_dir(&dir) {
|
||||
for e in rd.flatten() {
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with("events-") && name.ends_with(".jsonl") {
|
||||
events.push_str(&std::fs::read_to_string(e.path()).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
}
|
||||
(log, events, code)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_exec_dry_run_is_the_default_and_never_executes() {
|
||||
let (log, events, code) = run(
|
||||
&["ai", "--exec", "supprime tout"],
|
||||
"@echo off\r\necho rm -rf /tmp/nonexistent-xyz\r\n",
|
||||
"",
|
||||
);
|
||||
assert_eq!(code, 0);
|
||||
assert!(
|
||||
log.contains("non exécutée") || log.contains("not executed"),
|
||||
"dry-run policy must abort, log: {log}"
|
||||
);
|
||||
assert!(!log.contains("exécution:"), "nothing must run, log: {log}");
|
||||
assert!(
|
||||
events.contains("shell_ai") && events.contains("executed=false"),
|
||||
"journal must record the aborted exec, events: {events}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_exec_with_yes_executes_through_the_shell() {
|
||||
// Shim emits a harmless command; --yes skips the policy gate.
|
||||
let (log, events, code) = run(
|
||||
&["ai", "--exec", "dis bonjour", "--yes"],
|
||||
"@echo off\r\necho echo hello-from-shim\r\n",
|
||||
"",
|
||||
);
|
||||
assert_eq!(code, 0);
|
||||
assert!(
|
||||
log.contains("exécution: echo hello-from-shim"),
|
||||
"the generated command must run, log: {log}"
|
||||
);
|
||||
assert!(
|
||||
events.contains("executed=true"),
|
||||
"journal must record the execution, events: {events}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_conversational_passes_prompt_and_context_to_aichat() {
|
||||
// Shim echoes its arguments; conversational mode passes -f . + prompt.
|
||||
let (log, events, code) = run(
|
||||
&["ai", "liste les fichiers"],
|
||||
"@echo off\r\necho %*\r\n",
|
||||
"",
|
||||
);
|
||||
assert_eq!(code, 0);
|
||||
assert!(
|
||||
log.contains("shell-ai:") || events.contains("mode=chat"),
|
||||
"conversational mode must be journalized, log: {log} events: {events}"
|
||||
);
|
||||
assert!(events.contains("mode=chat"), "events: {events}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_exec_respects_configured_confirm_mode() {
|
||||
// default_safety: confirm + risky command => the confirmation prompt is
|
||||
// reached; without stdin input the prompt is declined (empty answer).
|
||||
let (log, events, code) = run(
|
||||
&["ai", "--exec", "supprime"],
|
||||
"@echo off\r\necho rm -rf /tmp/nonexistent-xyz\r\n",
|
||||
" shell_ai:\n default_safety: confirm\n",
|
||||
);
|
||||
assert_eq!(code, 0);
|
||||
assert!(
|
||||
log.contains("annulé") || log.contains("cancelled") || log.contains("non exécutée")
|
||||
|| log.contains("not executed"),
|
||||
"declined confirmation must abort, log: {log}"
|
||||
);
|
||||
assert!(!log.contains("exécution:"), "log: {log}");
|
||||
assert!(events.contains("executed=false"), "events: {events}");
|
||||
}
|
||||
Reference in New Issue
Block a user