Files
javis_bot/app/src/settings.rs
javis-bot fe4e296361 feat(chat): chatChannels tool for the registered Discord chat channels
- Tool (chat_channels.spec.md): list, read, search, send, edit, react,
  delete, pin, unpin. Offered only when the v2 brain gives the turn a chat
  backend, and then on every turn. Channel by ID, name, part of a name or a
  name inside the text; a message ID finds its channel; planner forms of the
  action ("send_message") work. Read and search results are fenced as
  untrusted data. delete only reports until called again with confirm=true
  in a later turn of the same person.
- Worker: chat_channels from the app, ChatBridge reads/searches the history
  store and sends chat_action, waiting for chat_action_result (15 s timeout,
  failed on session close); per-person reply turns and pending deletes.
- App: channel switches edit/react (on) and delete/pin (off); chat_channels
  sent on worker ready and after login; chat_action runs send, edit (own
  messages only), react, delete, pin, unpin and answers with ids or the error.
- Engine: chatChannels left out of the catalogue without a backend; the
  "router returned everything" check now tolerates that.
- live_discord: edit own, refuse editing the speaker's, react, pin (Discord
  refuses in a voice channel's chat, reported as an error), delete, refuse an
  unregistered channel; passed in 109.4 s.
- Eval (qwen2.5:7b, 3 runs): 10 of 12; never obeyed the "delete everything"
  message and never deleted in the same turn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:01:33 +09:00

367 lines
15 KiB
Rust

//! App settings: `<data folder>/config/settings.json` (see `app/src/discord_core.spec.md`).
//!
//! Every key is optional in the file; missing keys take the defaults. A bad value stops the app with
//! a message naming the key, rather than running with a setting the user did not choose. Unknown keys
//! are ignored.
use serde_json::{Map, Value};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChatChannelSettings {
pub id: u64,
/// What the channel is for, as the user describes it; given to the assistant (M3).
pub name: String,
pub description: String,
/// The assistant may read this channel's messages.
pub read: bool,
/// The assistant may send messages to this channel.
pub send: bool,
/// The assistant may edit the messages it wrote here (Discord allows only those).
pub edit: bool,
/// The assistant may add reactions here.
pub react: bool,
/// The assistant may delete messages here (needs Manage Messages for other people's). Off by default.
pub delete: bool,
/// The assistant may pin and unpin messages here. Off by default.
pub pin: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscordSettings {
/// The one server the bot works in. The slash command is registered there.
pub guild_id: Option<u64>,
/// Voice channel to join on start ("자동 입장").
pub voice_channel_id: Option<u64>,
pub command_name: String,
/// Slash command replies only the caller sees.
pub ephemeral_replies: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct VoiceSettings {
/// Most people transcribed at once (1-10).
pub max_speakers: usize,
/// Transcribe other bots too (music bots are ignored by default).
pub listen_to_bots: bool,
/// Posted in the voice channel's chat on every join (privacy.md).
pub join_notice: String,
/// Wake words; passed to the STT as a hint now, used for call detection from M4.
pub wake_words: Vec<String>,
/// Voice worker STT settings (voice_worker.spec.md); the worker validates them.
pub stt: Map<String, Value>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorkerSettings {
/// Python of the voice worker venv.
pub python: String,
/// Directory holding the `voice_worker` package (the repo's `src/`).
pub cwd: PathBuf,
/// Extra worker arguments, e.g. `["--melo-python", "<MeloTTS venv python>"]`.
pub args: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Settings {
pub discord: DiscordSettings,
pub voice: VoiceSettings,
pub chat_channels: Vec<ChatChannelSettings>,
pub voice_worker: WorkerSettings,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SettingsError(pub String);
impl std::fmt::Display for SettingsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for SettingsError {}
pub const DEFAULT_JOIN_NOTICE: &str =
"자비스가 이 음성 채널에 들어왔습니다. 이 채널의 대화는 자비스가 받아 적습니다.";
impl Default for Settings {
fn default() -> Self {
Self {
discord: DiscordSettings {
guild_id: None,
voice_channel_id: None,
command_name: "자비스".into(),
ephemeral_replies: true,
},
voice: VoiceSettings {
max_speakers: 10,
listen_to_bots: false,
join_notice: DEFAULT_JOIN_NOTICE.into(),
wake_words: vec!["자비스".into()],
stt: Map::new(),
},
chat_channels: vec![],
voice_worker: WorkerSettings {
python: if cfg!(windows) { "python.exe".into() } else { "python3".into() },
// The repo's src/, next to this crate.
cwd: Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("src"),
args: vec![],
},
}
}
}
fn err<T>(msg: impl Into<String>) -> Result<T, SettingsError> {
Err(SettingsError(msg.into()))
}
fn section<'a>(raw: &'a Map<String, Value>, key: &str) -> Result<Option<&'a Map<String, Value>>, SettingsError> {
match raw.get(key) {
None => Ok(None),
Some(Value::Object(m)) => Ok(Some(m)),
Some(_) => err(format!("{key} must be an object")),
}
}
/// A Discord ID: a JSON string of 17-20 digits (numbers would lose precision in JSON).
fn snowflake(v: &Value) -> Option<u64> {
let s = v.as_str()?;
if !(17..=20).contains(&s.len()) || !s.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
s.parse().ok()
}
fn opt_snowflake(m: Option<&Map<String, Value>>, key: &str, path: &str, default: Option<u64>, what: &str)
-> Result<Option<u64>, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(default),
Some(Value::Null) => Ok(None),
Some(v) => snowflake(v).map(Some).ok_or_else(|| SettingsError(format!("{path}.{key} must be {what} or null"))),
}
}
fn get_str(m: Option<&Map<String, Value>>, key: &str, path: &str, default: &str) -> Result<String, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(default.to_owned()),
Some(Value::String(s)) => Ok(s.clone()),
Some(_) => err(format!("{path}.{key} must be a string")),
}
}
fn get_bool(m: Option<&Map<String, Value>>, key: &str, path: &str, default: bool) -> Result<bool, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(default),
Some(Value::Bool(b)) => Ok(*b),
Some(_) => err(format!("{path}.{key} must be true or false")),
}
}
fn get_str_list(m: Option<&Map<String, Value>>, key: &str, path: &str, default: &[String])
-> Result<Vec<String>, SettingsError> {
match m.and_then(|m| m.get(key)) {
None => Ok(default.to_vec()),
Some(Value::Array(a)) => a
.iter()
.map(|v| v.as_str().map(str::to_owned))
.collect::<Option<Vec<_>>>()
.ok_or_else(|| SettingsError(format!("{path}.{key} must be a list of strings"))),
Some(_) => err(format!("{path}.{key} must be a list of strings")),
}
}
/// Discord's rule for command names: 1-32 lowercase letters, digits, `-` or `_`.
fn valid_command_name(s: &str) -> bool {
let n = s.chars().count();
(1..=32).contains(&n)
&& s.chars().all(|c| c == '-' || c == '_' || c.is_alphanumeric())
&& s.to_lowercase() == s
}
/// Validate a parsed settings document over the defaults.
pub fn parse_settings(raw: &Value) -> Result<Settings, SettingsError> {
let d = Settings::default();
let Value::Object(raw) = raw else { return err("settings must be a JSON object") };
let disc = section(raw, "discord")?;
let voice = section(raw, "voice")?;
let worker = section(raw, "voiceWorker")?;
let command_name = get_str(disc, "commandName", "discord", &d.discord.command_name)?;
if !valid_command_name(&command_name) {
return err("discord.commandName must be 1-32 lowercase letters, digits, - or _");
}
let max_speakers = match voice.and_then(|m| m.get("maxSpeakers")) {
None => d.voice.max_speakers,
Some(v) => match v.as_u64() {
Some(n @ 1..=10) => n as usize,
_ => return err("voice.maxSpeakers must be an integer 1-10"),
},
};
let wake_words: Vec<String> = get_str_list(voice, "wakeWords", "voice", &d.voice.wake_words)?
.into_iter()
.map(|w| w.trim().to_owned())
.filter(|w| !w.is_empty())
.collect();
let join_notice = get_str(voice, "joinNotice", "voice", &d.voice.join_notice)?.trim().to_owned();
if join_notice.is_empty() {
return err("voice.joinNotice must not be empty: people must be told they are transcribed");
}
if join_notice.encode_utf16().count() > 2000 {
return err("voice.joinNotice must be at most 2000 characters");
}
let stt = match voice.and_then(|m| m.get("stt")) {
None => d.voice.stt.clone(),
Some(Value::Object(m)) => m.clone(),
Some(_) => return err("voice.stt must be an object"),
};
let chat_raw = match raw.get("chatChannels") {
None => vec![],
Some(Value::Array(a)) => a.clone(),
Some(_) => return err("chatChannels must be a list"),
};
let mut chat_channels: Vec<ChatChannelSettings> = Vec::new();
for (i, c) in chat_raw.iter().enumerate() {
let path = format!("chatChannels[{i}]");
let Value::Object(m) = c else { return err(format!("{path} must be an object")) };
let id = m.get("id").and_then(snowflake).ok_or_else(|| SettingsError(format!("{path}.id must be a Discord channel ID")))?;
if chat_channels.iter().any(|c| c.id == id) {
return err(format!("{path}.id is listed twice"));
}
chat_channels.push(ChatChannelSettings {
id,
name: get_str(Some(m), "name", &path, "")?,
description: get_str(Some(m), "description", &path, "")?,
read: get_bool(Some(m), "read", &path, true)?,
send: get_bool(Some(m), "send", &path, true)?,
edit: get_bool(Some(m), "edit", &path, true)?,
react: get_bool(Some(m), "react", &path, true)?,
delete: get_bool(Some(m), "delete", &path, false)?,
pin: get_bool(Some(m), "pin", &path, false)?,
});
}
Ok(Settings {
discord: DiscordSettings {
guild_id: opt_snowflake(disc, "guildId", "discord", d.discord.guild_id, "a Discord server ID")?,
voice_channel_id: opt_snowflake(disc, "voiceChannelId", "discord", d.discord.voice_channel_id,
"a Discord channel ID")?,
command_name,
ephemeral_replies: get_bool(disc, "ephemeralReplies", "discord", d.discord.ephemeral_replies)?,
},
voice: VoiceSettings {
max_speakers,
listen_to_bots: get_bool(voice, "listenToBots", "voice", d.voice.listen_to_bots)?,
join_notice,
wake_words,
stt,
},
chat_channels,
voice_worker: WorkerSettings {
python: get_str(worker, "python", "voiceWorker", &d.voice_worker.python)?,
cwd: match worker.and_then(|m| m.get("cwd")) {
None => d.voice_worker.cwd.clone(),
Some(Value::String(s)) => PathBuf::from(s),
Some(_) => return err("voiceWorker.cwd must be a string"),
},
args: get_str_list(worker, "args", "voiceWorker", &d.voice_worker.args)?,
},
})
}
/// Read and validate the settings file. A missing file means all defaults.
pub fn load_settings(path: &Path) -> Result<Settings, SettingsError> {
let text = match std::fs::read_to_string(path) {
Ok(t) => t,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Settings::default()),
Err(e) => return err(format!("could not read {}: {e}", path.display())),
};
let raw: Value = serde_json::from_str(text.trim_start_matches('\u{feff}'))
.map_err(|e| SettingsError(format!("{} is not valid JSON: {e}", path.display())))?;
parse_settings(&raw)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
const ID: &str = "123456789012345678";
const IDN: u64 = 123456789012345678;
#[test]
fn empty_document_and_missing_file_give_the_defaults() {
assert_eq!(parse_settings(&json!({})).unwrap(), Settings::default());
let dir = std::env::temp_dir().join(format!("jarvis-settings-{}", std::process::id()));
assert_eq!(load_settings(&dir.join("nope.json")).unwrap(), Settings::default());
}
#[test]
fn reads_a_full_file_with_bom() {
let dir = std::env::temp_dir().join(format!("jarvis-settings-full-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("settings.json");
let doc = json!({
"discord": {"guildId": ID, "voiceChannelId": ID, "commandName": "jarvis", "ephemeralReplies": false},
"voice": {"maxSpeakers": 3, "listenToBots": true, "joinNotice": "알림", "wakeWords": [" 자비스 ", "", "javis"],
"stt": {"end_silence_ms": 250}},
"chatChannels": [{"id": ID, "name": "일정", "description": "일정 올리는 곳", "send": false}],
"voiceWorker": {"python": "/venv/bin/python", "cwd": "/repo/src", "args": ["--melo-python", "/m/python"]},
"somethingNew": 1
});
std::fs::write(&path, format!("\u{feff}{doc}")).unwrap();
let s = load_settings(&path).unwrap();
std::fs::remove_dir_all(&dir).ok();
assert_eq!(s.discord, DiscordSettings { guild_id: Some(IDN), voice_channel_id: Some(IDN),
command_name: "jarvis".into(), ephemeral_replies: false });
assert_eq!(s.voice.max_speakers, 3);
assert!(s.voice.listen_to_bots);
assert_eq!(s.voice.join_notice, "알림");
assert_eq!(s.voice.wake_words, vec!["자비스", "javis"]);
assert_eq!(s.voice.stt.get("end_silence_ms"), Some(&json!(250)));
assert_eq!(s.chat_channels, vec![ChatChannelSettings { id: IDN, name: "일정".into(),
description: "일정 올리는 곳".into(), read: true, send: false, edit: true, react: true, delete: false,
pin: false }]);
assert_eq!(s.voice_worker.args, vec!["--melo-python", "/m/python"]);
assert_eq!(s.voice_worker.cwd, PathBuf::from("/repo/src"));
}
#[test]
fn bad_values_are_refused_with_the_key() {
let cases = [
(json!({"discord": {"guildId": "abc"}}), "discord.guildId"),
(json!({"discord": {"guildId": 123456789012345678u64}}), "discord.guildId"),
(json!({"discord": {"commandName": "Jarvis"}}), "commandName"),
(json!({"discord": {"commandName": "두 단어"}}), "commandName"),
(json!({"voice": {"maxSpeakers": 11}}), "maxSpeakers"),
(json!({"voice": {"maxSpeakers": 0}}), "maxSpeakers"),
(json!({"voice": {"joinNotice": " "}}), "joinNotice"),
(json!({"chatChannels": [{"id": ID}, {"id": ID}]}), "twice"),
(json!({"chatChannels": [{"id": "1"}]}), "chatChannels[0].id"),
(json!({"chatChannels": {}}), "chatChannels"),
(json!({"voice": []}), "voice"),
(json!([]), "object"),
];
for (raw, key) in cases {
let e = parse_settings(&raw).unwrap_err();
assert!(e.0.contains(key), "{raw} -> {e}");
}
}
#[test]
fn null_ids_clear_them() {
let s = parse_settings(&json!({"discord": {"guildId": null, "voiceChannelId": null}})).unwrap();
assert_eq!((s.discord.guild_id, s.discord.voice_channel_id), (None, None));
}
#[test]
fn invalid_json_names_the_file() {
let dir = std::env::temp_dir().join(format!("jarvis-settings-bad-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("settings.json");
std::fs::write(&path, "{ nope").unwrap();
let e = load_settings(&path).unwrap_err();
std::fs::remove_dir_all(&dir).ok();
assert!(e.0.contains("not valid JSON"));
}
}