- Commande am ai (alias CLI: am shell) : conversationnel par defaut (aichat -f <ctx> "<prompt>"), mode --exec avec generation aichat --dry-run - Securite (issue #97) : classification safe/risky + certainite affichee, politique dry-run par defaut (settings.shell_ai.default_safety: dry-run | confirm | auto), confirmation y/N pour les commandes risky, --yes pour executer, --dry-run force la simulation - Flags : --exec/-e, --files/-f (defaut: dossier courant), --provider, --model (registre providers -> env aichat + modele, token via keyring) - Execution via le shell utilisateur (default_shell > SHELL > COMSPEC) - Journalisation : EventKind::ShellAi (mode, risk, certainty, executed) - Module src/shell_ai.rs (classification, politique, generation, execution) - Câblage complet : cli, dispatch, help, REPL (parseur+completer+banner), tip, man pages (am-ai.1), i18n EN, config.yaml (bloc shell_ai) - Tests : 7 unitaires (classification, certainty, extraction, decision) + 4 integration (shim aichat.cmd : dry-run par defaut, --yes, mode conversationnel, mode confirm) — 339 tests verts - v1.0.5 ; ROADMAP axe 13.3 coche (6 lignes), epic #93 clôturee closes #93 closes #96 closes #97
This commit is contained in:
@@ -0,0 +1,184 @@
|
||||
//! 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::{Context, Result};
|
||||
use std::process::Command;
|
||||
|
||||
pub fn run(app: &App, args: &AiArgs) -> Result<i32> {
|
||||
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)
|
||||
}
|
||||
|
||||
/// 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();
|
||||
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 cmd = crate::shell_ai::generate(
|
||||
app,
|
||||
prompt,
|
||||
files,
|
||||
args.provider.as_deref(),
|
||||
args.model.as_deref(),
|
||||
)?;
|
||||
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 mut executed = false;
|
||||
match decision {
|
||||
Decision::Abort => {
|
||||
let msg = if dry_run {
|
||||
"dry-run : commande non exécutée"
|
||||
} else {
|
||||
"politique de sécurité (dry-run par défaut) : commande non exécutée — utilisez --yes"
|
||||
};
|
||||
app.log.info(crate::i18n::tr(msg));
|
||||
}
|
||||
Decision::Ask => {
|
||||
let ok = app.confirm(crate::i18n::tr("Exécuter ?"))?;
|
||||
if ok {
|
||||
executed = true;
|
||||
} else {
|
||||
app.log.info(crate::i18n::tr("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);
|
||||
}
|
||||
}
|
||||
@@ -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,7 @@ 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::Start(a) => run_cmd::start(app, a),
|
||||
Command::Stop {
|
||||
agent,
|
||||
|
||||
@@ -109,6 +109,18 @@ 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>]",
|
||||
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)"),
|
||||
("--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: "models",
|
||||
about: "inventaire des modèles locaux (ollama, llama.cpp, LM Studio)",
|
||||
|
||||
Reference in New Issue
Block a user