Skip to main content

kcode_kennedy_app/
lib.rs

1#![forbid(unsafe_code)]
2
3use std::{
4    path::{Path, PathBuf},
5    str::FromStr,
6    sync::Arc,
7};
8
9use anyhow::Context;
10use clap::{Parser, Subcommand};
11use kcode_credential_vault::{CredentialVault, ExposeSecret, SecretString};
12use kcode_kweb_db::{Config as KwebConfig, NoopGossip, WriterId};
13use kcode_speech_classification::SpeechClassifier;
14use zeroize::{Zeroize, Zeroizing};
15
16const OPENAI_API_KEY_SECRET: &str = "openai-api-key";
17const GEMINI_API_KEY_SECRET: &str = "gemini-api-key";
18const TELEGRAM_BOT_TOKEN_SECRET: &str = "telegram-bot-token";
19const CRATES_IO_KEY_SECRET: &str = "cratesio-key";
20const KWEB_WRITER_SIGNING_KEY_SECRET: &str = "kweb-writer-signing-key";
21const KWEB_WRITERS_SECRET: &str = "kweb-writers-by-priority";
22const SPEECH_CLASSIFICATION_DATABASE_PATH: &str = "./data/kennedy-speech-classification.sqlite3";
23
24#[derive(Parser, Debug)]
25struct Args {
26    #[arg(long, global = true, default_value = "./data/kennedy-secrets.age")]
27    vault_path: PathBuf,
28    #[command(subcommand)]
29    command: Option<Command>,
30    #[arg(long, global = true, default_value = "127.0.0.1:4321")]
31    kweb_bind: String,
32    #[arg(long, global = true, default_value = "./data/kweb")]
33    kweb_root: PathBuf,
34    #[arg(
35        long,
36        global = true,
37        default_value = "./data/kennedy-conversations.sqlite3"
38    )]
39    conversation_history_database: PathBuf,
40    #[arg(long, global = true, default_value = "./data/sessions/in-progress")]
41    session_directory: PathBuf,
42    #[arg(long, global = true, default_value = "./data/session-history.txt")]
43    session_history_file: PathBuf,
44    #[arg(long, global = true, default_value = "./data/kennedy-telegram.sqlite3")]
45    telegram_database: PathBuf,
46    #[arg(long, global = true, default_value = "./data/kennedy-users.sqlite3")]
47    user_database: PathBuf,
48    #[arg(
49        long,
50        alias = "audio-ingress-database",
51        global = true,
52        default_value = "./data/kennedy-audio.sqlite3",
53        help = "Optional pre-library AudioIngress database used only for one-time migration"
54    )]
55    legacy_audio_ingress_database: PathBuf,
56    #[arg(
57        long,
58        alias = "audio-ingress-media",
59        global = true,
60        default_value = "./data/audio-ingress-media",
61        help = "AudioIngress-owned persistence root (database and original audio)"
62    )]
63    audio_ingress_directory: PathBuf,
64    #[arg(
65        long,
66        global = true,
67        default_value = "./data/intelligence-usage",
68        help = "One-file-per-call intelligence usage receipt directory"
69    )]
70    intelligence_usage_directory: PathBuf,
71    #[arg(long, default_value = "./data/kcode/kcode-rust-libs")]
72    rust_libs_root: PathBuf,
73    #[arg(long, default_value = "./data/kcode/kcode-web-libs")]
74    web_libs_root: PathBuf,
75    #[arg(long, default_value = "./data/kcode/kcode-web-libs-published")]
76    web_libs_published_root: PathBuf,
77    #[arg(long, default_value = "./data/kcode/kcode-rust-bins")]
78    rust_bins_root: PathBuf,
79    #[arg(long, default_value = "./data/kcode/kcode-rust-bin-artifacts")]
80    rust_bin_artifacts_root: PathBuf,
81    #[arg(long, default_value = "./KennedyServer/runtime/system-prompts")]
82    system_prompts_dir: PathBuf,
83    #[arg(long, default_value = "@taek42")]
84    telegram_bootstrap_username: String,
85    #[arg(long, default_value_t = 20 * 1024 * 1024)]
86    telegram_max_voice_bytes: usize,
87    #[arg(long, default_value_t = 8 * 1024 * 1024 * 1024)]
88    audio_ingress_max_upload_bytes: usize,
89}
90
91#[derive(Subcommand, Debug)]
92enum Command {
93    /// Create and manage generic named secrets in Kennedy's encrypted vault.
94    Secrets {
95        #[command(subcommand)]
96        command: SecretsCommand,
97    },
98    /// Estimate the token footprint of all current Kmap node text.
99    KmapSize,
100}
101
102#[derive(Subcommand, Debug)]
103enum SecretsCommand {
104    /// Prompt for and store a named secret, replacing any previous value.
105    Set { name: String },
106    /// Remove a named secret without displaying its value.
107    Remove { name: String },
108    /// List configured secret names without displaying their values.
109    List,
110    /// Re-encrypt the vault with a new passphrase.
111    ChangePassphrase,
112}
113
114#[tokio::main]
115pub async fn main() -> anyhow::Result<()> {
116    tracing_subscriber::fmt()
117        .with_env_filter(
118            tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
119                "kennedy_server=info,kcode_kennedy_app=info,kcode_kennedy_orchestration=info,kcode_kennedy_telegram_runtime=info,kcode_kennedy_roots=info,kcode_kweb_db=info,kcode_codex_runtime=info,kcode_session_history=info,kcode_tg_kennedy_bot=info,tower_http=info".into()
120            }),
121        )
122        .init();
123    rustls::crypto::ring::default_provider()
124        .install_default()
125        .map_err(|_| anyhow::anyhow!("installing TLS crypto provider"))?;
126    let mut args = Args::parse();
127    let vault_path = args.vault_path.clone();
128    match args.command.take() {
129        Some(Command::Secrets { command }) => {
130            let _maintenance_guard = tokio::net::TcpListener::bind(&args.kweb_bind)
131                .await
132                .with_context(|| {
133                    format!(
134                        "binding maintenance lock {}; stop the running Kennedy server before changing its credential vault",
135                        args.kweb_bind
136                    )
137                })?;
138            manage_secrets(command, &vault_path)
139        }
140        Some(Command::KmapSize) => {
141            let _maintenance_guard =
142                maintenance_guard(&args.kweb_bind, "measuring the Kweb").await?;
143            let passphrase = prompt_passphrase("Unlock Kennedy credential vault: ")?;
144            let vault = CredentialVault::unlock(&vault_path, passphrase)?;
145            let size = kcode_kmap_size::measure(&args.kweb_root, kweb_config(&vault)?)?;
146            println!("{}", kcode_kmap_size::render(&size));
147            Ok(())
148        }
149        None => run_server(args, vault_path).await,
150    }
151}
152
153async fn run_server(args: Args, vault_path: PathBuf) -> anyhow::Result<()> {
154    // Bind the public Kennedy address before opening any persistent state.
155    // Offline maintenance checks this address before copying the data tree.
156    let kweb_listener = tokio::net::TcpListener::bind(&args.kweb_bind)
157        .await
158        .with_context(|| format!("binding Kweb listener {}", args.kweb_bind))?;
159    ensure_runtime_parent_directories(&args, &vault_path)?;
160    let vault = if vault_path.exists() {
161        let passphrase = prompt_passphrase("Unlock Kennedy credential vault: ")?;
162        CredentialVault::unlock(&vault_path, passphrase)?
163    } else {
164        tracing::warn!(path=%vault_path.display(), "Kennedy credential vault does not exist; secret-backed features are unavailable");
165        CredentialVault::empty()
166    };
167    let openai_api_key = resolve_optional_secret(
168        &vault,
169        OPENAI_API_KEY_SECRET,
170        "OpenAI transcription, media annotation, agents, and image generation/editing",
171    )?;
172    let gemini_api_key = resolve_optional_secret(
173        &vault,
174        GEMINI_API_KEY_SECRET,
175        "Gemini search, media annotation, agents, audio transcription, and image generation/editing",
176    )?;
177    let telegram_bot_token =
178        resolve_optional_secret(&vault, TELEGRAM_BOT_TOKEN_SECRET, "Telegram relay")?
179            .map(kcode_tg_kennedy_bot::BotToken::new)
180            .transpose()?;
181    let crates_io_key =
182        resolve_required_secret(&vault, CRATES_IO_KEY_SECRET, "Rust library publication")?;
183    let kweb_config = kweb_config(&vault)?;
184    let codex_catalog_cache =
185        kcode_codex_runtime::CatalogCache::new(kcode_codex_runtime::DEFAULT_CODEX_EXECUTABLE);
186    let (kmap, system_roots) =
187        kcode_kennedy_roots::open(&args.kweb_root, kweb_config, &args.user_database)?;
188    let speech_classifier = SpeechClassifier::open(SPEECH_CLASSIFICATION_DATABASE_PATH)
189        .with_context(|| {
190            format!("opening speaker-classification database {SPEECH_CLASSIFICATION_DATABASE_PATH}")
191        })?;
192    let speech_classifier = Arc::new(speech_classifier);
193    let dev_tools = kcode_dev_tools::Service::open(kcode_dev_tools::Config {
194        rust_libraries_root: args.rust_libs_root.clone(),
195        web_libraries_root: args.web_libs_root.clone(),
196        web_publications_root: args.web_libs_published_root.clone(),
197        rust_binaries_root: args.rust_bins_root.clone(),
198        rust_binary_publications_root: args.rust_bin_artifacts_root.clone(),
199        crates_io_registry_token: crates_io_key,
200    })
201    .map_err(anyhow::Error::new)
202    .with_context(|| {
203        format!(
204            "opening managed Kcode development roots under {}",
205            args.rust_libs_root
206                .parent()
207                .unwrap_or(Path::new("."))
208                .display()
209        )
210    })?;
211    let web_publications_root = dev_tools.web_publications_root().to_path_buf();
212    let telegram_identity = std::sync::Arc::new(kcode_telegram_identity::Directory::open(
213        &args.user_database,
214        &args.telegram_bootstrap_username,
215    )?);
216    let history_service =
217        kcode_session_history::SessionHistory::open(kcode_session_history::Config {
218            directory: args.session_directory,
219            completed_list: args.session_history_file,
220            provider_cost_compatibility: Some(
221                kcode_intelligence_chatend::provider_cost_compatibility(),
222            ),
223        })?;
224    let (intelligence_service, intelligence_runtime) =
225        kcode_intelligence_router::open(kcode_intelligence_router::Config {
226            openai_api_key,
227            gemini_api_key,
228            codex_catalog_cache,
229            receipt_directory: args.intelligence_usage_directory,
230        })
231        .await?;
232    let agent_runtime = kcode_agent_runtime::AgentRuntime::new(intelligence_service.clone());
233    let telegram_runtime = kcode_tg_kennedy_bot::open(kcode_tg_kennedy_bot::Config {
234        database: args.telegram_database,
235        bot_token: telegram_bot_token,
236        identity_sink: telegram_identity.clone(),
237        max_voice_bytes: args.telegram_max_voice_bytes,
238    })
239    .await?;
240    let telegram_service = telegram_runtime.service();
241    let chunk_intelligence = intelligence_service.clone();
242    let transcribe_chunk: kcode_audio_ingress::AudioChunkCall = Arc::new(move |request| {
243        let intelligence = chunk_intelligence.clone();
244        Box::pin(async move {
245            let user = intelligence
246                .for_user(request.user_id)
247                .map_err(audio_intelligence_error)?;
248            let media = kcode_intelligence_router::Media::audio(
249                request.audio_ogg,
250                "audio-chunk.ogg",
251                "audio/ogg",
252            )
253            .map_err(audio_intelligence_error)?;
254            user.analyze_audio(kcode_intelligence_router::AudioAnalysisRequest {
255                operation: "transcribe_chunk".into(),
256                prompt: request.prompt,
257                model: request.model,
258                media,
259                schema: request.schema,
260                max_output_tokens: request.max_output_tokens,
261                operation_id: uuid::Uuid::new_v4(),
262                parent_operation_id: None,
263            })
264            .await
265            .map(|response| response.value.text)
266            .map_err(audio_intelligence_error)
267        })
268    });
269    let text_intelligence = intelligence_service.clone();
270    let generate_text: kcode_audio_ingress::TextGenerationCall = Arc::new(move |request| {
271        let intelligence = text_intelligence.clone();
272        Box::pin(async move {
273            let reasoning_effort = match request.reasoning_effort.as_str() {
274                "xhigh" => kcode_intelligence_router::ReasoningEffort::XHigh,
275                _ => {
276                    return Err(kcode_audio_ingress::IntelligenceError::new(
277                        "AudioIngress requested an unsupported reasoning effort.",
278                        false,
279                    ));
280                }
281            };
282            let user = intelligence
283                .for_user(request.user_id)
284                .map_err(audio_intelligence_error)?;
285            user.generate_text(kcode_intelligence_router::TextGenerationRequest {
286                operation: request.operation,
287                prompt: request.prompt,
288                model: request.model,
289                reasoning_effort,
290                timeout: request.timeout,
291                operation_id: uuid::Uuid::new_v4(),
292                parent_operation_id: None,
293            })
294            .await
295            .map(|response| response.value.text)
296            .map_err(audio_intelligence_error)
297        })
298    });
299    let audio_transcriber =
300        kcode_audio_ingress::AudioTranscriber::new(transcribe_chunk, generate_text);
301    let audio_state_database = args.audio_ingress_directory.join("state.sqlite3");
302    migrate_audio_ingress_database(&args.legacy_audio_ingress_database, &audio_state_database)?;
303    let audio = kcode_audio_ingress::AudioIngress::open(
304        &args.audio_ingress_directory,
305        audio_transcriber,
306        Arc::clone(&speech_classifier),
307    )
308    .await?;
309    let audio_coordinator = kcode_audio_session_ingress::Coordinator::new(
310        audio,
311        history_service.clone(),
312        kcode_audio_session_ingress::Config {
313            user_id: system_roots.user.to_string(),
314            effective_context_tokens: intelligence_runtime.context_window_tokens,
315        },
316    )?;
317    let http_router = kcode_http_api::router(kcode_http_api::Config {
318        kmap: kmap.clone(),
319        user_root_node_id: system_roots.user,
320        kennedy_root_node_id: system_roots.kennedy,
321        telegram: telegram_service.clone(),
322        session_history: history_service.clone(),
323        audio_ingress: audio_coordinator.clone(),
324        audio_max_upload_bytes: args.audio_ingress_max_upload_bytes,
325        web_publications_root,
326    })?;
327    let orchestration_config = kcode_kennedy_orchestration::Config {
328        system_prompts_directory: args.system_prompts_dir.clone(),
329        user_root_node_id: system_roots.user.to_string(),
330        kennedy_root_node_id: system_roots.kennedy.to_string(),
331        telegram_max_media_bytes: args.telegram_max_voice_bytes,
332        runtime_model: kcode_kennedy_orchestration::RuntimeModel::from_intelligence(
333            intelligence_runtime,
334        ),
335    };
336    let telegram_sessions = kcode_telegram_session_coordinator::Service::new(
337        telegram_service.clone(),
338        telegram_identity.clone(),
339    );
340    let session_service =
341        kcode_kennedy_sessions::Service::new(kcode_kennedy_sessions::Capabilities {
342            kmap: kmap.clone(),
343            intelligence: intelligence_service.clone(),
344            agents: agent_runtime,
345            history: history_service.clone(),
346            speech_classifier,
347            dev_tools: dev_tools.clone(),
348            telegram: telegram_sessions,
349        });
350    let orchestration_api = kcode_kennedy_orchestration::Api::new(
351        &orchestration_config,
352        kcode_kennedy_orchestration::LocalServices {
353            kmap: kmap.clone(),
354            intelligence: intelligence_service,
355            history: history_service.clone(),
356            audio: audio_coordinator,
357            directory: telegram_identity.clone(),
358            dev_tools,
359            telegram: telegram_service,
360        },
361    );
362    let orchestration_worker = kcode_kennedy_orchestration::build(
363        orchestration_config,
364        orchestration_api,
365        session_service,
366    );
367    let directory_roots = kcode_kennedy_roots::DirectoryRoots::new(
368        kmap,
369        telegram_identity,
370        args.telegram_bootstrap_username.clone(),
371        system_roots.user,
372        orchestration_worker.writer().clone(),
373    );
374    let telegram_session_runtime = Arc::new(kcode_kennedy_telegram_runtime::Runtime::new(
375        kcode_kennedy_telegram_runtime::Config {
376            telegram_max_media_bytes: args.telegram_max_voice_bytes,
377            telegram_web_user_handle: args.telegram_bootstrap_username,
378        },
379        orchestration_worker.clone(),
380        directory_roots,
381    ));
382    tokio::try_join!(
383        serve_http(kweb_listener, http_router),
384        telegram_runtime.run(),
385        kcode_kennedy_orchestration::run(orchestration_worker),
386        telegram_session_runtime.run(),
387    )?;
388    Ok(())
389}
390
391async fn serve_http(listener: tokio::net::TcpListener, router: axum::Router) -> anyhow::Result<()> {
392    tracing::info!(address=%listener.local_addr()?, "Kennedy main HTTP server ready");
393    axum::serve(listener, router).await?;
394    Ok(())
395}
396
397fn audio_intelligence_error(
398    error: kcode_intelligence_router::Error,
399) -> kcode_audio_ingress::IntelligenceError {
400    let retryable = error.retryable();
401    kcode_audio_ingress::IntelligenceError::new(error.message(), retryable)
402}
403
404fn ensure_runtime_parent_directories(args: &Args, vault_path: &Path) -> anyhow::Result<()> {
405    for path in [
406        vault_path,
407        &args.kweb_root,
408        &args.conversation_history_database,
409        &args.session_directory,
410        &args.session_history_file,
411        &args.telegram_database,
412        &args.user_database,
413        Path::new(SPEECH_CLASSIFICATION_DATABASE_PATH),
414        &args.legacy_audio_ingress_database,
415        &args.audio_ingress_directory,
416        &args.intelligence_usage_directory,
417        &args.rust_libs_root,
418        &args.web_libs_root,
419        &args.web_libs_published_root,
420        &args.rust_bins_root,
421        &args.rust_bin_artifacts_root,
422    ] {
423        let Some(parent) = path.parent().filter(|value| !value.as_os_str().is_empty()) else {
424            continue;
425        };
426        if parent.exists() {
427            continue;
428        }
429        let mut builder = std::fs::DirBuilder::new();
430        builder.recursive(true);
431        #[cfg(unix)]
432        {
433            use std::os::unix::fs::DirBuilderExt;
434            builder.mode(0o700);
435        }
436        builder
437            .create(parent)
438            .with_context(|| format!("creating runtime data directory {}", parent.display()))?;
439    }
440    Ok(())
441}
442
443fn migrate_audio_ingress_database(legacy: &Path, current: &Path) -> anyhow::Result<()> {
444    if current.exists() || !legacy.exists() {
445        return Ok(());
446    }
447    if let Some(parent) = current.parent() {
448        std::fs::create_dir_all(parent)
449            .with_context(|| format!("creating AudioIngress root {}", parent.display()))?;
450    }
451    let source = rusqlite::Connection::open(legacy)
452        .with_context(|| format!("opening legacy AudioIngress database {}", legacy.display()))?;
453    source
454        .execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")
455        .context("checkpointing legacy AudioIngress database")?;
456    source
457        .backup(rusqlite::MAIN_DB, current, None)
458        .context("copying legacy AudioIngress database into its persistence root")?;
459    let destination = rusqlite::Connection::open(current)
460        .with_context(|| format!("opening AudioIngress database {}", current.display()))?;
461    destination
462        .execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")
463        .context("syncing migrated AudioIngress database")?;
464    tracing::info!(
465        source = %legacy.display(),
466        destination = %current.display(),
467        "Migrated AudioIngress database into its owned persistence root"
468    );
469    Ok(())
470}
471
472pub async fn maintenance_guard(
473    bind: &str,
474    purpose: &str,
475) -> anyhow::Result<tokio::net::TcpListener> {
476    tokio::net::TcpListener::bind(bind).await.with_context(|| {
477        format!("binding maintenance lock {bind}; stop the running Kennedy server before {purpose}")
478    })
479}
480
481fn kweb_config(vault: &CredentialVault) -> anyhow::Result<KwebConfig> {
482    let encoded_key = resolve_required_secret(
483        vault,
484        KWEB_WRITER_SIGNING_KEY_SECRET,
485        "Kweb mutation signing",
486    )?;
487    let mut signing_key = Zeroizing::new([0_u8; 32]);
488    let decoded = hex::decode(encoded_key.trim())
489        .context("Kweb writer signing key must be 64 lowercase hexadecimal characters")?;
490    *signing_key = decoded
491        .try_into()
492        .map_err(|_| anyhow::anyhow!("Kweb writer signing key must decode to exactly 32 bytes"))?;
493    let encoded_writers =
494        resolve_required_secret(vault, KWEB_WRITERS_SECRET, "Kweb writer authorization")?;
495    let writers_by_priority = encoded_writers
496        .split(',')
497        .map(str::trim)
498        .filter(|value| !value.is_empty())
499        .map(WriterId::from_str)
500        .collect::<Result<Vec<_>, _>>()
501        .map_err(anyhow::Error::new)
502        .context("decoding the ordered Kweb writer whitelist")?;
503    anyhow::ensure!(
504        !writers_by_priority.is_empty(),
505        "the Kweb writer whitelist is empty"
506    );
507    Ok(KwebConfig {
508        signing_key: *signing_key,
509        writers_by_priority,
510        gossip: Arc::new(NoopGossip),
511    })
512}
513
514fn resolve_optional_secret(
515    vault: &CredentialVault,
516    configured_name: &str,
517    purpose: &str,
518) -> anyhow::Result<Option<String>> {
519    let name = configured_name.trim();
520    if name.is_empty() {
521        return Ok(None);
522    }
523    let secret = vault.secret(name)?;
524    if secret.is_none() {
525        tracing::warn!(secret_name=name, %purpose, "configured Kennedy secret is not present in the vault");
526    }
527    Ok(secret.map(|value| value.expose_secret().to_owned()))
528}
529
530fn resolve_required_secret(
531    vault: &CredentialVault,
532    configured_name: &str,
533    purpose: &str,
534) -> anyhow::Result<String> {
535    let name = configured_name.trim();
536    if name.is_empty() {
537        anyhow::bail!("{purpose} requires a configured Kennedy secret name");
538    }
539    vault
540        .secret(name)?
541        .map(|value| value.expose_secret().to_owned())
542        .with_context(|| {
543            format!(
544                "{purpose} requires Kennedy secret '{name}'; store it with `kennedy-server secrets set {name}`"
545            )
546        })
547}
548
549fn manage_secrets(command: SecretsCommand, vault_path: &Path) -> anyhow::Result<()> {
550    match command {
551        SecretsCommand::Set { name } => {
552            let (mut vault, passphrase) = unlock_for_edit(vault_path)?;
553            let value = prompt_confirmed_value(&format!("Value for {name}: "))?;
554            vault.set(&name, value)?;
555            vault.save(vault_path, &passphrase)?;
556            println!("Stored Kennedy secret '{name}'.");
557        }
558        SecretsCommand::Remove { name } => {
559            if !vault_path.exists() {
560                println!("No Kennedy credential vault exists yet.");
561                return Ok(());
562            }
563            let passphrase = prompt_passphrase("Unlock Kennedy credential vault: ")?;
564            let mut vault = CredentialVault::unlock(vault_path, passphrase.clone())?;
565            if vault.remove(&name)? {
566                vault.save(vault_path, &passphrase)?;
567                println!("Removed Kennedy secret '{name}'.");
568            } else {
569                println!("Kennedy secret '{name}' was not configured.");
570            }
571        }
572        SecretsCommand::List => {
573            if !vault_path.exists() {
574                println!("No Kennedy credential vault exists yet.");
575                return Ok(());
576            }
577            let passphrase = prompt_passphrase("Unlock Kennedy credential vault: ")?;
578            let vault = CredentialVault::unlock(vault_path, passphrase)?;
579            let names = vault.names().collect::<Vec<_>>();
580            if names.is_empty() {
581                println!("The Kennedy credential vault contains no secrets.");
582            } else {
583                println!("Configured Kennedy secrets:");
584                for name in names {
585                    println!("- {name}");
586                }
587            }
588        }
589        SecretsCommand::ChangePassphrase => {
590            if !vault_path.exists() {
591                println!("No Kennedy credential vault exists yet.");
592                return Ok(());
593            }
594            let old = prompt_passphrase("Unlock Kennedy credential vault: ")?;
595            let vault = CredentialVault::unlock(vault_path, old)?;
596            let new = prompt_new_vault_passphrase()?;
597            vault.save(vault_path, &new)?;
598            println!("Changed the Kennedy credential vault passphrase.");
599        }
600    }
601    Ok(())
602}
603
604fn unlock_for_edit(path: &Path) -> anyhow::Result<(CredentialVault, SecretString)> {
605    if path.exists() {
606        let passphrase = prompt_passphrase("Unlock Kennedy credential vault: ")?;
607        let vault = CredentialVault::unlock(path, passphrase.clone())?;
608        Ok((vault, passphrase))
609    } else {
610        let passphrase = prompt_new_vault_passphrase()?;
611        Ok((CredentialVault::empty(), passphrase))
612    }
613}
614
615fn prompt_passphrase(prompt: &str) -> anyhow::Result<SecretString> {
616    let mut value = rpassword::prompt_password(prompt)?;
617    if value.is_empty() {
618        value.zeroize();
619        anyhow::bail!("the credential vault passphrase cannot be empty");
620    }
621    Ok(SecretString::from(value))
622}
623
624fn prompt_new_vault_passphrase() -> anyhow::Result<SecretString> {
625    let mut first = rpassword::prompt_password("Create Kennedy credential vault passphrase: ")?;
626    let mut second = rpassword::prompt_password("Confirm credential vault passphrase: ")?;
627    if first.is_empty() || first != second {
628        first.zeroize();
629        second.zeroize();
630        anyhow::bail!("credential vault passphrases were empty or did not match");
631    }
632    second.zeroize();
633    Ok(SecretString::from(first))
634}
635
636fn prompt_confirmed_value(prompt: &str) -> anyhow::Result<String> {
637    let mut first = rpassword::prompt_password(prompt)?;
638    let mut second = rpassword::prompt_password("Confirm secret value: ")?;
639    if first.is_empty() || first != second {
640        first.zeroize();
641        second.zeroize();
642        anyhow::bail!("secret values were empty or did not match");
643    }
644    second.zeroize();
645    Ok(first)
646}
647
648#[cfg(test)]
649mod tests {
650    use super::*;
651
652    #[test]
653    fn secret_names_are_stable_code_defaults() {
654        assert_eq!(OPENAI_API_KEY_SECRET, "openai-api-key");
655        assert_eq!(GEMINI_API_KEY_SECRET, "gemini-api-key");
656        assert_eq!(TELEGRAM_BOT_TOKEN_SECRET, "telegram-bot-token");
657        assert_eq!(CRATES_IO_KEY_SECRET, "cratesio-key");
658        assert_eq!(KWEB_WRITER_SIGNING_KEY_SECRET, "kweb-writer-signing-key");
659        assert_eq!(KWEB_WRITERS_SECRET, "kweb-writers-by-priority");
660    }
661
662    #[test]
663    fn persistent_path_defaults_are_under_data() {
664        let args = Args::try_parse_from(["kennedy-server"]).unwrap();
665        for path in [
666            &args.vault_path,
667            &args.kweb_root,
668            &args.conversation_history_database,
669            &args.session_directory,
670            &args.session_history_file,
671            &args.telegram_database,
672            &args.user_database,
673            &args.legacy_audio_ingress_database,
674            &args.audio_ingress_directory,
675            &args.intelligence_usage_directory,
676            &args.rust_libs_root,
677            &args.web_libs_root,
678            &args.web_libs_published_root,
679            &args.rust_bins_root,
680            &args.rust_bin_artifacts_root,
681        ] {
682            assert!(
683                path.starts_with("./data"),
684                "persistent default is outside data/: {}",
685                path.display()
686            );
687        }
688        for path in [
689            &args.rust_libs_root,
690            &args.web_libs_root,
691            &args.web_libs_published_root,
692            &args.rust_bins_root,
693            &args.rust_bin_artifacts_root,
694        ] {
695            assert!(
696                path.starts_with("./data/kcode"),
697                "managed Kcode default is outside data/kcode/: {}",
698                path.display()
699            );
700        }
701        assert_eq!(
702            args.system_prompts_dir,
703            PathBuf::from("./KennedyServer/runtime/system-prompts")
704        );
705    }
706
707    #[test]
708    fn native_orchestration_remains_a_rust_backend_concern() {
709        assert_eq!(
710            std::any::type_name::<kcode_kennedy_orchestration::Session>(),
711            "kcode_kennedy_sessions::Session"
712        );
713    }
714
715    #[tokio::test]
716    async fn unified_dev_tools_service_opens_all_roots_and_routes_three_source_kinds() {
717        let directory = std::env::temp_dir().join(format!(
718            "kennedy-dev-tools-open-test-{}",
719            uuid::Uuid::new_v4()
720        ));
721        let rust_libraries = directory.join("kcode-rust-libs");
722        let web_libraries = directory.join("kcode-web-libs");
723        let web_publications = directory.join("kcode-web-libs-published");
724        let rust_binaries = directory.join("kcode-rust-bins");
725        let rust_binary_artifacts = directory.join("kcode-rust-bin-artifacts");
726        let service = kcode_dev_tools::Service::open(kcode_dev_tools::Config {
727            rust_libraries_root: rust_libraries.clone(),
728            web_libraries_root: web_libraries.clone(),
729            web_publications_root: web_publications.clone(),
730            rust_binaries_root: rust_binaries.clone(),
731            rust_binary_publications_root: rust_binary_artifacts.clone(),
732            crates_io_registry_token: "test-token".into(),
733        })
734        .unwrap();
735
736        assert_eq!(
737            service.web_libraries_root(),
738            std::fs::canonicalize(&web_libraries).unwrap()
739        );
740        assert_eq!(
741            service.web_publications_root(),
742            std::fs::canonicalize(&web_publications).unwrap()
743        );
744        for path in [
745            rust_libraries,
746            web_libraries,
747            web_publications,
748            rust_binaries,
749            rust_binary_artifacts,
750        ] {
751            assert!(
752                path.is_dir(),
753                "managed root was not created: {}",
754                path.display()
755            );
756        }
757        for (create, open, write, name, path, kind) in [
758            (
759                kcode_dev_tools::CREATE_RUST_LIB_TOOL,
760                kcode_dev_tools::OPEN_RUST_LIB_TOOL,
761                kcode_dev_tools::WRITE_FILE_FREEFORM_RUST_LIB_TOOL,
762                "kennedy-test-lib",
763                "src/extra.rs",
764                kcode_dev_tools::ManagedSourceKind::RustLibrary,
765            ),
766            (
767                kcode_dev_tools::CREATE_WEB_LIB_TOOL,
768                kcode_dev_tools::OPEN_WEB_LIB_TOOL,
769                kcode_dev_tools::WRITE_FILE_FREEFORM_WEB_LIB_TOOL,
770                "kennedy-test-web",
771                "extra.js",
772                kcode_dev_tools::ManagedSourceKind::WebLibrary,
773            ),
774            (
775                kcode_dev_tools::CREATE_RUST_BIN_TOOL,
776                kcode_dev_tools::OPEN_RUST_BIN_TOOL,
777                kcode_dev_tools::WRITE_FILE_FREEFORM_RUST_BIN_TOOL,
778                "kennedy-test-bin",
779                "src/extra.rs",
780                kcode_dev_tools::ManagedSourceKind::RustBinary,
781            ),
782        ] {
783            let created = service
784                .execute(
785                    "create-session",
786                    create,
787                    serde_json::json!({"name":name}),
788                    Vec::new(),
789                )
790                .await
791                .unwrap();
792            assert_eq!(created.snapshot.unwrap().kind, kind);
793            let written = service
794                .execute(
795                    "create-session",
796                    write,
797                    serde_json::json!({
798                        "name":name,
799                        "path":path,
800                        "contents":"// Kennedy managed source\n",
801                    }),
802                    Vec::new(),
803                )
804                .await
805                .unwrap();
806            assert_eq!(written.snapshot.unwrap().kind, kind);
807
808            let open_result = service
809                .execute(
810                    "open-session",
811                    open,
812                    serde_json::json!({"name":name}),
813                    Vec::new(),
814                )
815                .await
816                .unwrap();
817            assert_eq!(open_result.snapshot.unwrap().kind, kind);
818        }
819        let asset = service
820            .execute(
821                "create-session",
822                kcode_dev_tools::ATTACH_OBJECT_WEB_LIB_TOOL,
823                serde_json::json!({
824                    "name":"kennedy-test-web",
825                    "path":"assets/fonts/display.woff2",
826                    "objectId":"pending:1",
827                }),
828                vec![vec![0, 159, 146, 150, 255]],
829            )
830            .await
831            .unwrap();
832        let snapshot = asset.snapshot.unwrap();
833        assert_eq!(
834            snapshot.kind,
835            kcode_dev_tools::ManagedSourceKind::WebLibrary
836        );
837        assert!(snapshot.text.contains("Asset: assets/fonts/display.woff2"));
838        assert!(snapshot.text.contains("Bytes: 5"));
839        assert!(!snapshot.text.contains("SHA-256:"));
840        assert_eq!(service.release("create-session").await.unwrap(), 3);
841        assert_eq!(service.release("open-session").await.unwrap(), 3);
842        drop(service);
843        std::fs::remove_dir_all(directory).unwrap();
844    }
845
846    #[test]
847    fn missing_optional_secret_disables_only_its_feature() {
848        let vault = CredentialVault::empty();
849        assert!(
850            resolve_optional_secret(&vault, "openai-api-key", "transcription")
851                .unwrap()
852                .is_none()
853        );
854        assert!(
855            resolve_optional_secret(&vault, "", "disabled")
856                .unwrap()
857                .is_none()
858        );
859    }
860
861    #[test]
862    fn required_secret_must_be_present() {
863        let mut vault = CredentialVault::empty();
864        let error =
865            resolve_required_secret(&vault, CRATES_IO_KEY_SECRET, "publication").unwrap_err();
866        assert!(error.to_string().contains(CRATES_IO_KEY_SECRET));
867
868        vault
869            .set(CRATES_IO_KEY_SECRET, "test-crates-io-key".into())
870            .unwrap();
871        assert_eq!(
872            resolve_required_secret(&vault, CRATES_IO_KEY_SECRET, "publication").unwrap(),
873            "test-crates-io-key"
874        );
875    }
876
877    #[test]
878    fn legacy_audio_database_is_copied_once_into_the_persistence_root() {
879        let directory = std::env::temp_dir().join(format!(
880            "kennedy-audio-migration-test-{}",
881            uuid::Uuid::new_v4()
882        ));
883        std::fs::create_dir(&directory).unwrap();
884        let legacy = directory.join("legacy.sqlite3");
885        let current = directory.join("audio-ingress/state.sqlite3");
886        let source = rusqlite::Connection::open(&legacy).unwrap();
887        source
888            .execute_batch("CREATE TABLE marker(value TEXT NOT NULL);")
889            .unwrap();
890        source
891            .execute("INSERT INTO marker(value) VALUES('legacy')", [])
892            .unwrap();
893        drop(source);
894
895        migrate_audio_ingress_database(&legacy, &current).unwrap();
896        let migrated = rusqlite::Connection::open(&current).unwrap();
897        let value: String = migrated
898            .query_row("SELECT value FROM marker", [], |row| row.get(0))
899            .unwrap();
900        assert_eq!(value, "legacy");
901        migrated
902            .execute("UPDATE marker SET value='current'", [])
903            .unwrap();
904        drop(migrated);
905
906        migrate_audio_ingress_database(&legacy, &current).unwrap();
907        let value: String = rusqlite::Connection::open(&current)
908            .unwrap()
909            .query_row("SELECT value FROM marker", [], |row| row.get(0))
910            .unwrap();
911        assert_eq!(value, "current");
912        std::fs::remove_dir_all(directory).unwrap();
913    }
914
915    #[tokio::test]
916    async fn occupied_kweb_address_prevents_server_from_opening_persistent_state() {
917        let directory =
918            std::env::temp_dir().join(format!("kennedy-server-lock-test-{}", uuid::Uuid::new_v4()));
919        std::fs::create_dir(&directory).unwrap();
920        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
921        let bind = listener.local_addr().unwrap().to_string();
922        let vault = directory.join("vault.age");
923        let kmap = directory.join("kweb");
924        let conversations = directory.join("conversations.sqlite3");
925        let telegram = directory.join("telegram.sqlite3");
926        let users = directory.join("users.sqlite3");
927        let audio = directory.join("audio.sqlite3");
928        let audio_media = directory.join("audio-media");
929        let args = Args {
930            vault_path: vault.clone(),
931            command: None,
932            kweb_bind: bind,
933            kweb_root: kmap.clone(),
934            conversation_history_database: conversations.clone(),
935            session_directory: directory.join("sessions"),
936            session_history_file: directory.join("session-history.txt"),
937            telegram_database: telegram.clone(),
938            user_database: users.clone(),
939            legacy_audio_ingress_database: audio.clone(),
940            audio_ingress_directory: audio_media.clone(),
941            intelligence_usage_directory: directory.join("intelligence-usage"),
942            rust_libs_root: directory.join("rust-libs"),
943            web_libs_root: directory.join("kcode-web-libs"),
944            web_libs_published_root: directory.join("kcode-web-libs-published"),
945            rust_bins_root: directory.join("kcode-rust-bins"),
946            rust_bin_artifacts_root: directory.join("kcode-rust-bin-artifacts"),
947            system_prompts_dir: directory.join("prompts"),
948            telegram_bootstrap_username: "@test".to_owned(),
949            telegram_max_voice_bytes: 1024,
950            audio_ingress_max_upload_bytes: 1024,
951        };
952
953        let error = run_server(args, vault.clone()).await.unwrap_err();
954        assert!(error.to_string().contains("binding Kweb listener"));
955        assert!(!vault.exists());
956        assert!(!kmap.exists());
957        assert!(!conversations.exists());
958        assert!(!telegram.exists());
959        assert!(!users.exists());
960        assert!(!audio.exists());
961        assert!(!audio_media.exists());
962        std::fs::remove_dir_all(directory).unwrap();
963    }
964}