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_speaker_system::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 = "@taek42")]
82 telegram_bootstrap_username: String,
83 #[arg(long, default_value_t = 20 * 1024 * 1024)]
84 telegram_max_voice_bytes: usize,
85 #[arg(long, default_value_t = 8 * 1024 * 1024 * 1024)]
86 audio_ingress_max_upload_bytes: usize,
87}
88
89#[derive(Subcommand, Debug)]
90enum Command {
91 Secrets {
93 #[command(subcommand)]
94 command: SecretsCommand,
95 },
96 KmapSize,
98}
99
100#[derive(Subcommand, Debug)]
101enum SecretsCommand {
102 Set { name: String },
104 Remove { name: String },
106 List,
108 ChangePassphrase,
110}
111
112#[tokio::main]
113pub async fn main() -> anyhow::Result<()> {
114 tracing_subscriber::fmt()
115 .with_env_filter(
116 tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
117 "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()
118 }),
119 )
120 .init();
121 rustls::crypto::ring::default_provider()
122 .install_default()
123 .map_err(|_| anyhow::anyhow!("installing TLS crypto provider"))?;
124 let mut args = Args::parse();
125 let vault_path = args.vault_path.clone();
126 match args.command.take() {
127 Some(Command::Secrets { command }) => {
128 let _maintenance_guard = tokio::net::TcpListener::bind(&args.kweb_bind)
129 .await
130 .with_context(|| {
131 format!(
132 "binding maintenance lock {}; stop the running Kennedy server before changing its credential vault",
133 args.kweb_bind
134 )
135 })?;
136 manage_secrets(command, &vault_path)
137 }
138 Some(Command::KmapSize) => {
139 let _maintenance_guard =
140 maintenance_guard(&args.kweb_bind, "measuring the Kweb").await?;
141 let passphrase = prompt_passphrase("Unlock Kennedy credential vault: ")?;
142 let vault = CredentialVault::unlock(&vault_path, passphrase)?;
143 let size = kcode_kmap_size::measure(&args.kweb_root, kweb_config(&vault)?)?;
144 println!("{}", kcode_kmap_size::render(&size));
145 Ok(())
146 }
147 None => run_server(args, vault_path).await,
148 }
149}
150
151async fn run_server(args: Args, vault_path: PathBuf) -> anyhow::Result<()> {
152 let kweb_listener = tokio::net::TcpListener::bind(&args.kweb_bind)
155 .await
156 .with_context(|| format!("binding Kweb listener {}", args.kweb_bind))?;
157 ensure_runtime_parent_directories(&args, &vault_path)?;
158 let vault = if vault_path.exists() {
159 let passphrase = prompt_passphrase("Unlock Kennedy credential vault: ")?;
160 CredentialVault::unlock(&vault_path, passphrase)?
161 } else {
162 tracing::warn!(path=%vault_path.display(), "Kennedy credential vault does not exist; secret-backed features are unavailable");
163 CredentialVault::empty()
164 };
165 let openai_api_key = resolve_optional_secret(
166 &vault,
167 OPENAI_API_KEY_SECRET,
168 "OpenAI transcription, media annotation, agents, and image generation/editing",
169 )?;
170 let gemini_api_key = resolve_optional_secret(
171 &vault,
172 GEMINI_API_KEY_SECRET,
173 "Gemini search, media annotation, agents, audio transcription, and image generation/editing",
174 )?;
175 let telegram_bot_token =
176 resolve_optional_secret(&vault, TELEGRAM_BOT_TOKEN_SECRET, "Telegram relay")?
177 .map(kcode_tg_kennedy_bot::BotToken::new)
178 .transpose()?;
179 let crates_io_key =
180 resolve_required_secret(&vault, CRATES_IO_KEY_SECRET, "Rust library publication")?;
181 let kweb_config = kweb_config(&vault)?;
182 let codex_catalog_cache =
183 kcode_codex_runtime::CatalogCache::new(kcode_codex_runtime::DEFAULT_CODEX_EXECUTABLE);
184 let (kmap, system_roots) =
185 kcode_kennedy_roots::open(&args.kweb_root, kweb_config, &args.user_database)?;
186 let (kmap_commands, kmap_command_runtime) =
187 kcode_kmap_command_lane::open(&args.user_database, kmap.clone())?;
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 temperature: None,
262 operation_id: uuid::Uuid::new_v4(),
263 parent_operation_id: None,
264 })
265 .await
266 .map(|response| response.value.text)
267 .map_err(audio_intelligence_error)
268 })
269 });
270 let text_intelligence = intelligence_service.clone();
271 let generate_text: kcode_audio_ingress::TextGenerationCall = Arc::new(move |request| {
272 let intelligence = text_intelligence.clone();
273 Box::pin(async move {
274 let reasoning_effort = match request.reasoning_effort.as_str() {
275 "xhigh" => kcode_intelligence_router::ReasoningEffort::XHigh,
276 _ => {
277 return Err(kcode_audio_ingress::IntelligenceError::new(
278 "AudioIngress requested an unsupported reasoning effort.",
279 false,
280 ));
281 }
282 };
283 let user = intelligence
284 .for_user(request.user_id)
285 .map_err(audio_intelligence_error)?;
286 user.generate_text(kcode_intelligence_router::TextGenerationRequest {
287 operation: request.operation,
288 prompt: request.prompt,
289 model: request.model,
290 reasoning_effort,
291 timeout: request.timeout,
292 operation_id: uuid::Uuid::new_v4(),
293 parent_operation_id: None,
294 })
295 .await
296 .map(|response| response.value.text)
297 .map_err(audio_intelligence_error)
298 })
299 });
300 let audio_transcriber =
301 kcode_audio_ingress::AudioTranscriber::new(transcribe_chunk, generate_text);
302 let audio_state_database = args.audio_ingress_directory.join("state.sqlite3");
303 migrate_audio_ingress_database(&args.legacy_audio_ingress_database, &audio_state_database)?;
304 let audio = kcode_audio_ingress::AudioIngress::open(
305 &args.audio_ingress_directory,
306 audio_transcriber,
307 Arc::clone(&speech_classifier),
308 )
309 .await?;
310 let audio_coordinator = kcode_audio_session_ingress::Coordinator::new(
311 audio,
312 history_service.clone(),
313 kcode_audio_session_ingress::Config {
314 user_id: system_roots.user.to_string(),
315 effective_context_tokens: intelligence_runtime.context_window_tokens,
316 },
317 )?;
318 let http_router = kcode_http_api::router(kcode_http_api::Config {
319 kmap: kmap.clone(),
320 kmap_commands,
321 user_root_node_id: system_roots.user,
322 kennedy_root_node_id: system_roots.kennedy,
323 telegram: telegram_service.clone(),
324 session_history: history_service.clone(),
325 audio_ingress: audio_coordinator.clone(),
326 audio_max_upload_bytes: args.audio_ingress_max_upload_bytes,
327 web_publications_root,
328 })?;
329 let orchestration_config = kcode_kennedy_orchestration::Config {
330 user_root_node_id: system_roots.user.to_string(),
331 kennedy_root_node_id: system_roots.kennedy.to_string(),
332 telegram_max_media_bytes: args.telegram_max_voice_bytes,
333 runtime_model: kcode_kennedy_orchestration::RuntimeModel::from_intelligence(
334 intelligence_runtime,
335 ),
336 };
337 let telegram_sessions = kcode_telegram_session_coordinator::Service::new(
338 telegram_service.clone(),
339 telegram_identity.clone(),
340 );
341 let session_service =
342 kcode_kennedy_sessions::Service::new(kcode_kennedy_sessions::Capabilities {
343 kmap: kmap.clone(),
344 intelligence: intelligence_service.clone(),
345 agents: agent_runtime,
346 history: history_service.clone(),
347 speech_classifier,
348 dev_tools: dev_tools.clone(),
349 telegram: telegram_sessions,
350 });
351 let orchestration_api = kcode_kennedy_orchestration::Api::new(
352 &orchestration_config,
353 kcode_kennedy_orchestration::LocalServices {
354 kmap: kmap.clone(),
355 intelligence: intelligence_service,
356 history: history_service.clone(),
357 audio: audio_coordinator,
358 directory: telegram_identity.clone(),
359 dev_tools,
360 telegram: telegram_service,
361 },
362 );
363 let orchestration_worker = kcode_kennedy_orchestration::build(
364 orchestration_config,
365 orchestration_api,
366 session_service,
367 );
368 let directory_roots = kcode_kennedy_roots::DirectoryRoots::new(
369 kmap,
370 telegram_identity,
371 args.telegram_bootstrap_username.clone(),
372 system_roots.user,
373 orchestration_worker.writer().clone(),
374 );
375 let telegram_session_runtime = Arc::new(kcode_kennedy_telegram_runtime::Runtime::new(
376 kcode_kennedy_telegram_runtime::Config {
377 telegram_max_media_bytes: args.telegram_max_voice_bytes,
378 telegram_web_user_handle: args.telegram_bootstrap_username,
379 },
380 orchestration_worker.clone(),
381 directory_roots,
382 ));
383 tokio::try_join!(
384 async {
385 kcode_http_api::serve(kweb_listener, http_router)
386 .await
387 .map_err(anyhow::Error::new)
388 },
389 telegram_runtime.run(),
390 kcode_kennedy_orchestration::run(orchestration_worker),
391 telegram_session_runtime.run(),
392 async { kmap_command_runtime.await.map_err(anyhow::Error::new) },
393 )?;
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 }
702
703 #[test]
704 fn native_orchestration_remains_a_rust_backend_concern() {
705 assert_eq!(
706 std::any::type_name::<kcode_kennedy_orchestration::Session>(),
707 "kcode_kennedy_sessions::Session"
708 );
709 }
710
711 #[tokio::test]
712 async fn unified_dev_tools_service_opens_all_roots_and_routes_three_source_kinds() {
713 let directory = std::env::temp_dir().join(format!(
714 "kennedy-dev-tools-open-test-{}",
715 uuid::Uuid::new_v4()
716 ));
717 let rust_libraries = directory.join("kcode-rust-libs");
718 let web_libraries = directory.join("kcode-web-libs");
719 let web_publications = directory.join("kcode-web-libs-published");
720 let rust_binaries = directory.join("kcode-rust-bins");
721 let rust_binary_artifacts = directory.join("kcode-rust-bin-artifacts");
722 let service = kcode_dev_tools::Service::open(kcode_dev_tools::Config {
723 rust_libraries_root: rust_libraries.clone(),
724 web_libraries_root: web_libraries.clone(),
725 web_publications_root: web_publications.clone(),
726 rust_binaries_root: rust_binaries.clone(),
727 rust_binary_publications_root: rust_binary_artifacts.clone(),
728 crates_io_registry_token: "test-token".into(),
729 })
730 .unwrap();
731
732 assert_eq!(
733 service.web_libraries_root(),
734 std::fs::canonicalize(&web_libraries).unwrap()
735 );
736 assert_eq!(
737 service.web_publications_root(),
738 std::fs::canonicalize(&web_publications).unwrap()
739 );
740 for path in [
741 rust_libraries,
742 web_libraries,
743 web_publications,
744 rust_binaries,
745 rust_binary_artifacts,
746 ] {
747 assert!(
748 path.is_dir(),
749 "managed root was not created: {}",
750 path.display()
751 );
752 }
753 for (create, open, write, name, path, kind) in [
754 (
755 kcode_dev_tools::CREATE_RUST_LIB_TOOL,
756 kcode_dev_tools::OPEN_RUST_LIB_TOOL,
757 kcode_dev_tools::WRITE_FILE_FREEFORM_RUST_LIB_TOOL,
758 "kennedy-test-lib",
759 "src/extra.rs",
760 kcode_dev_tools::ManagedSourceKind::RustLibrary,
761 ),
762 (
763 kcode_dev_tools::CREATE_WEB_LIB_TOOL,
764 kcode_dev_tools::OPEN_WEB_LIB_TOOL,
765 kcode_dev_tools::WRITE_FILE_FREEFORM_WEB_LIB_TOOL,
766 "kennedy-test-web",
767 "extra.js",
768 kcode_dev_tools::ManagedSourceKind::WebLibrary,
769 ),
770 (
771 kcode_dev_tools::CREATE_RUST_BIN_TOOL,
772 kcode_dev_tools::OPEN_RUST_BIN_TOOL,
773 kcode_dev_tools::WRITE_FILE_FREEFORM_RUST_BIN_TOOL,
774 "kennedy-test-bin",
775 "src/extra.rs",
776 kcode_dev_tools::ManagedSourceKind::RustBinary,
777 ),
778 ] {
779 let created = service
780 .execute(
781 "create-session",
782 create,
783 serde_json::json!({"name":name}),
784 Vec::new(),
785 )
786 .await
787 .unwrap();
788 assert_eq!(created.snapshot.unwrap().kind, kind);
789 let written = service
790 .execute(
791 "create-session",
792 write,
793 serde_json::json!({
794 "name":name,
795 "path":path,
796 "contents":"// Kennedy managed source\n",
797 }),
798 Vec::new(),
799 )
800 .await
801 .unwrap();
802 assert_eq!(written.snapshot.unwrap().kind, kind);
803
804 let open_result = service
805 .execute(
806 "open-session",
807 open,
808 serde_json::json!({"name":name}),
809 Vec::new(),
810 )
811 .await
812 .unwrap();
813 assert_eq!(open_result.snapshot.unwrap().kind, kind);
814 }
815 let asset = service
816 .execute(
817 "create-session",
818 kcode_dev_tools::ATTACH_OBJECT_WEB_LIB_TOOL,
819 serde_json::json!({
820 "name":"kennedy-test-web",
821 "path":"assets/fonts/display.woff2",
822 "objectId":"pending:1",
823 }),
824 vec![vec![0, 159, 146, 150, 255]],
825 )
826 .await
827 .unwrap();
828 let snapshot = asset.snapshot.unwrap();
829 assert_eq!(
830 snapshot.kind,
831 kcode_dev_tools::ManagedSourceKind::WebLibrary
832 );
833 assert!(snapshot.text.contains("Asset: assets/fonts/display.woff2"));
834 assert!(snapshot.text.contains("Bytes: 5"));
835 assert!(!snapshot.text.contains("SHA-256:"));
836 assert_eq!(service.release("create-session").await.unwrap(), 3);
837 assert_eq!(service.release("open-session").await.unwrap(), 3);
838 drop(service);
839 std::fs::remove_dir_all(directory).unwrap();
840 }
841
842 #[test]
843 fn missing_optional_secret_disables_only_its_feature() {
844 let vault = CredentialVault::empty();
845 assert!(
846 resolve_optional_secret(&vault, "openai-api-key", "transcription")
847 .unwrap()
848 .is_none()
849 );
850 assert!(
851 resolve_optional_secret(&vault, "", "disabled")
852 .unwrap()
853 .is_none()
854 );
855 }
856
857 #[test]
858 fn required_secret_must_be_present() {
859 let mut vault = CredentialVault::empty();
860 let error =
861 resolve_required_secret(&vault, CRATES_IO_KEY_SECRET, "publication").unwrap_err();
862 assert!(error.to_string().contains(CRATES_IO_KEY_SECRET));
863
864 vault
865 .set(CRATES_IO_KEY_SECRET, "test-crates-io-key".into())
866 .unwrap();
867 assert_eq!(
868 resolve_required_secret(&vault, CRATES_IO_KEY_SECRET, "publication").unwrap(),
869 "test-crates-io-key"
870 );
871 }
872
873 #[test]
874 fn legacy_audio_database_is_copied_once_into_the_persistence_root() {
875 let directory = std::env::temp_dir().join(format!(
876 "kennedy-audio-migration-test-{}",
877 uuid::Uuid::new_v4()
878 ));
879 std::fs::create_dir(&directory).unwrap();
880 let legacy = directory.join("legacy.sqlite3");
881 let current = directory.join("audio-ingress/state.sqlite3");
882 let source = rusqlite::Connection::open(&legacy).unwrap();
883 source
884 .execute_batch("CREATE TABLE marker(value TEXT NOT NULL);")
885 .unwrap();
886 source
887 .execute("INSERT INTO marker(value) VALUES('legacy')", [])
888 .unwrap();
889 drop(source);
890
891 migrate_audio_ingress_database(&legacy, ¤t).unwrap();
892 let migrated = rusqlite::Connection::open(¤t).unwrap();
893 let value: String = migrated
894 .query_row("SELECT value FROM marker", [], |row| row.get(0))
895 .unwrap();
896 assert_eq!(value, "legacy");
897 migrated
898 .execute("UPDATE marker SET value='current'", [])
899 .unwrap();
900 drop(migrated);
901
902 migrate_audio_ingress_database(&legacy, ¤t).unwrap();
903 let value: String = rusqlite::Connection::open(¤t)
904 .unwrap()
905 .query_row("SELECT value FROM marker", [], |row| row.get(0))
906 .unwrap();
907 assert_eq!(value, "current");
908 std::fs::remove_dir_all(directory).unwrap();
909 }
910
911 #[tokio::test]
912 async fn occupied_kweb_address_prevents_server_from_opening_persistent_state() {
913 let directory =
914 std::env::temp_dir().join(format!("kennedy-server-lock-test-{}", uuid::Uuid::new_v4()));
915 std::fs::create_dir(&directory).unwrap();
916 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
917 let bind = listener.local_addr().unwrap().to_string();
918 let vault = directory.join("vault.age");
919 let kmap = directory.join("kweb");
920 let conversations = directory.join("conversations.sqlite3");
921 let telegram = directory.join("telegram.sqlite3");
922 let users = directory.join("users.sqlite3");
923 let audio = directory.join("audio.sqlite3");
924 let audio_media = directory.join("audio-media");
925 let args = Args {
926 vault_path: vault.clone(),
927 command: None,
928 kweb_bind: bind,
929 kweb_root: kmap.clone(),
930 conversation_history_database: conversations.clone(),
931 session_directory: directory.join("sessions"),
932 session_history_file: directory.join("session-history.txt"),
933 telegram_database: telegram.clone(),
934 user_database: users.clone(),
935 legacy_audio_ingress_database: audio.clone(),
936 audio_ingress_directory: audio_media.clone(),
937 intelligence_usage_directory: directory.join("intelligence-usage"),
938 rust_libs_root: directory.join("rust-libs"),
939 web_libs_root: directory.join("kcode-web-libs"),
940 web_libs_published_root: directory.join("kcode-web-libs-published"),
941 rust_bins_root: directory.join("kcode-rust-bins"),
942 rust_bin_artifacts_root: directory.join("kcode-rust-bin-artifacts"),
943 telegram_bootstrap_username: "@test".to_owned(),
944 telegram_max_voice_bytes: 1024,
945 audio_ingress_max_upload_bytes: 1024,
946 };
947
948 let error = run_server(args, vault.clone()).await.unwrap_err();
949 assert!(error.to_string().contains("binding Kweb listener"));
950 assert!(!vault.exists());
951 assert!(!kmap.exists());
952 assert!(!conversations.exists());
953 assert!(!telegram.exists());
954 assert!(!users.exists());
955 assert!(!audio.exists());
956 assert!(!audio_media.exists());
957 std::fs::remove_dir_all(directory).unwrap();
958 }
959}