aKode 0.5.0: riepilogo della memoria a inizio sessione, sollecito alle azioni annunciate, daemon allineato al CLI
- ext/memoria: legge una volta per sessione la risorsa memoria://briefing (file di git status, budget di token, timeout breve), accetta solo un blocco <memoria_briefing> chiuso e limitato, lo inserisce dopo le istruzioni del plugin e lo tiene in cache per il thread (prefisso del prompt stabile). Impostazioni [memoria] briefing, briefing_timeout_ms, briefing_max_tokens. - Turno: se il modello chiude con un messaggio che annuncia un'azione senza chiamare strumenti, un solo sollecito per turno ([agent] announce_nudges, predefinito 1, 0 lo disattiva), con avviso visibile e test sui messaggi osservati con Qwen. - Daemon: sync_with_cli confronta l'eseguibile del CLI con il pacchetto del daemon e, se diverso, lo seleziona e riavvia solo quando non ci sono sessioni caricate; altrimenti avviso. Usato all'avvio della TUI, da `akode update`, da install.sh e da `akode app-server daemon update --from-cli --if-idle`. Prima un daemon preparato una volta restava alla versione vecchia (CLI 0.4.0 con app server 0.3.1). - Test: snapshot del doctor indipendenti dalla versione; snapshot della TUI aggiornati alla 0.5.0 e allo schema dei tool appiattiti della 0.4.0. - Versione 0.5.0 e sezione Novità nel README. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
208
akode-rs/app-server-daemon/src/cli_sync.rs
Normal file
208
akode-rs/app-server-daemon/src/cli_sync.rs
Normal file
@@ -0,0 +1,208 @@
|
||||
//! Keeps the managed daemon package in step with the CLI that is starting.
|
||||
//!
|
||||
//! aKode installs a new CLI package with `install.sh` or `akode update`, but the daemon runs
|
||||
//! from its own copy under `AKODE_HOME/packages/app-server-daemon`. Before this module a daemon
|
||||
//! prepared once (InstallMode::Missing) kept running that copy forever, so a new CLI talked to
|
||||
//! an old app server (seen with CLI 0.4.0 and app server 0.3.1). On startup the CLI now compares
|
||||
//! its executable with the selected daemon package and, when they differ, selects and restarts
|
||||
//! this CLI's package, unless the running app server still has sessions loaded: in that case
|
||||
//! nothing is interrupted and the caller shows a warning.
|
||||
|
||||
use anyhow::Result;
|
||||
|
||||
use crate::Daemon;
|
||||
use crate::client;
|
||||
use crate::managed_install;
|
||||
|
||||
/// Outcome of [`sync_with_cli`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum CliSync {
|
||||
/// No daemon package is selected yet: the next start installs this CLI's package.
|
||||
NotInstalled,
|
||||
/// The selected package runs the same executable as this CLI.
|
||||
UpToDate,
|
||||
/// The package of this CLI was selected (and a running daemon restarted).
|
||||
Updated {
|
||||
previous: Option<String>,
|
||||
version: String,
|
||||
},
|
||||
/// The daemon differs but still has sessions loaded: it was left running.
|
||||
Busy {
|
||||
running: Option<String>,
|
||||
cli: String,
|
||||
loaded_threads: usize,
|
||||
},
|
||||
/// The daemon differs but this CLI has no complete package to install (local build).
|
||||
NoPackage {
|
||||
selected: Option<String>,
|
||||
cli: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl CliSync {
|
||||
/// Warning to show to the user, if any (Italian, like the rest of the aKode UI).
|
||||
pub fn warning(&self) -> Option<String> {
|
||||
match self {
|
||||
CliSync::NotInstalled | CliSync::UpToDate => None,
|
||||
CliSync::Updated { previous, version } => Some(format!(
|
||||
"Server in background di aKode aggiornato{} alla versione {version}.",
|
||||
previous
|
||||
.as_deref()
|
||||
.map(|p| format!(" dalla {p}"))
|
||||
.unwrap_or_default()
|
||||
)),
|
||||
CliSync::Busy {
|
||||
running,
|
||||
cli,
|
||||
loaded_threads,
|
||||
} => Some(format!(
|
||||
"Il server in background di aKode è {} mentre questo aKode è {cli}: ha ancora {loaded_threads} {} aperte, quindi non è stato riavviato. Chiudi le altre sessioni e lancia `akode app-server daemon update --from-cli`.",
|
||||
running
|
||||
.as_deref()
|
||||
.map(|v| format!("alla versione {v}"))
|
||||
.unwrap_or_else(|| "di un'altra versione".to_string()),
|
||||
if *loaded_threads == 1 { "sessione" } else { "sessioni" }
|
||||
)),
|
||||
CliSync::NoPackage { selected, cli } => Some(format!(
|
||||
"Il server in background di aKode ({}) non corrisponde a questo aKode {cli}, che non è un pacchetto installato: usa `akode update` o install.sh.",
|
||||
selected.as_deref().unwrap_or("versione sconosciuta")
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What to do, from the observed state (kept pure for the tests).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Decision {
|
||||
NotInstalled,
|
||||
UpToDate,
|
||||
Install,
|
||||
Busy,
|
||||
NoPackage,
|
||||
}
|
||||
|
||||
pub(crate) fn decide(
|
||||
package_selected: bool,
|
||||
same_executable: bool,
|
||||
cli_has_package: bool,
|
||||
loaded_threads: Option<usize>,
|
||||
) -> Decision {
|
||||
if !package_selected {
|
||||
return Decision::NotInstalled;
|
||||
}
|
||||
if same_executable {
|
||||
return Decision::UpToDate;
|
||||
}
|
||||
if !cli_has_package {
|
||||
return Decision::NoPackage;
|
||||
}
|
||||
match loaded_threads {
|
||||
// Not running, or running with no session loaded: safe to replace and restart.
|
||||
None | Some(0) => Decision::Install,
|
||||
Some(_) => Decision::Busy,
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares this CLI with the managed daemon package and updates the package when it is safe.
|
||||
pub async fn sync_with_cli() -> Result<CliSync> {
|
||||
crate::ensure_supported_platform()?;
|
||||
let daemon = Daemon::from_environment()?;
|
||||
let selected = daemon.current_managed_codex_bin()?;
|
||||
let cli = env!("CARGO_PKG_VERSION").to_string();
|
||||
if !selected.is_file() {
|
||||
return Ok(CliSync::NotInstalled);
|
||||
}
|
||||
let running_exe = std::env::current_exe()?;
|
||||
let same = match (
|
||||
managed_install::executable_identity(&selected).await,
|
||||
managed_install::executable_identity(&running_exe).await,
|
||||
) {
|
||||
(Ok(a), Ok(b)) => a.same_contents(&b),
|
||||
_ => false,
|
||||
};
|
||||
let has_package = akode_install_context::InstallContext::current()
|
||||
.package_layout
|
||||
.is_some();
|
||||
let probe = client::probe(&daemon.socket_path).await.ok();
|
||||
let loaded = match &probe {
|
||||
// Unknown load on a running daemon counts as busy: never interrupt blindly.
|
||||
Some(_) if !same && has_package => Some(
|
||||
client::loaded_thread_count(&daemon.socket_path)
|
||||
.await
|
||||
.unwrap_or(usize::MAX),
|
||||
),
|
||||
Some(_) => Some(0),
|
||||
None => None,
|
||||
};
|
||||
let selected_version = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(5),
|
||||
managed_install::managed_codex_version(&selected),
|
||||
)
|
||||
.await
|
||||
.ok()
|
||||
.and_then(Result::ok);
|
||||
let running = probe.map(|p| p.app_server_version);
|
||||
match decide(true, same, has_package, loaded) {
|
||||
Decision::NotInstalled => Ok(CliSync::NotInstalled),
|
||||
Decision::UpToDate => Ok(CliSync::UpToDate),
|
||||
Decision::NoPackage => Ok(CliSync::NoPackage {
|
||||
selected: selected_version,
|
||||
cli,
|
||||
}),
|
||||
Decision::Busy => Ok(CliSync::Busy {
|
||||
running: running.or(selected_version),
|
||||
cli,
|
||||
loaded_threads: loaded.unwrap_or_default().min(999),
|
||||
}),
|
||||
Decision::Install => {
|
||||
let previous = running.or(selected_version);
|
||||
match crate::update_from_cli(|_| Ok(true)).await? {
|
||||
Some(_) => Ok(CliSync::Updated {
|
||||
previous,
|
||||
version: cli,
|
||||
}),
|
||||
None => Ok(CliSync::UpToDate),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn decides_only_safe_replacements() {
|
||||
assert_eq!(decide(false, false, true, None), Decision::NotInstalled);
|
||||
assert_eq!(decide(true, true, true, Some(3)), Decision::UpToDate);
|
||||
// A different daemon is replaced when stopped or idle...
|
||||
assert_eq!(decide(true, false, true, None), Decision::Install);
|
||||
assert_eq!(decide(true, false, true, Some(0)), Decision::Install);
|
||||
// ...but never while sessions are loaded (or their number is unknown).
|
||||
assert_eq!(decide(true, false, true, Some(1)), Decision::Busy);
|
||||
assert_eq!(decide(true, false, true, Some(usize::MAX)), Decision::Busy);
|
||||
// A local build without a package cannot be installed.
|
||||
assert_eq!(decide(true, false, false, None), Decision::NoPackage);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warnings() {
|
||||
assert_eq!(CliSync::UpToDate.warning(), None);
|
||||
let busy = CliSync::Busy {
|
||||
running: Some("0.3.1".into()),
|
||||
cli: "0.5.0".into(),
|
||||
loaded_threads: 2,
|
||||
}
|
||||
.warning()
|
||||
.expect("warning");
|
||||
assert!(busy.contains("0.3.1") && busy.contains("0.5.0") && busy.contains("--from-cli"));
|
||||
let updated = CliSync::Updated {
|
||||
previous: Some("0.3.1".into()),
|
||||
version: "0.5.0".into(),
|
||||
}
|
||||
.warning()
|
||||
.expect("warning");
|
||||
assert!(updated.contains("dalla 0.3.1") && updated.contains("0.5.0"));
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,54 @@ async fn probe_inner(socket_path: &Path) -> Result<ProbeInfo> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Threads loaded in the running app server (open sessions of any client). Used to avoid
|
||||
/// restarting a daemon that still serves work.
|
||||
pub(crate) async fn loaded_thread_count(socket_path: &Path) -> Result<usize> {
|
||||
timeout(CONTROL_SOCKET_RESPONSE_TIMEOUT * 3, async {
|
||||
let mut websocket = connect(socket_path).await?;
|
||||
initialize(&mut websocket, /*experimental_api*/ false).await?;
|
||||
send_message(
|
||||
&mut websocket,
|
||||
&JSONRPCMessage::Notification(JSONRPCNotification {
|
||||
method: "initialized".to_string(),
|
||||
params: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let id = RequestId::Integer(2);
|
||||
send_message(
|
||||
&mut websocket,
|
||||
&JSONRPCMessage::Request(JSONRPCRequest {
|
||||
id: id.clone(),
|
||||
method: "thread/loaded/list".to_string(),
|
||||
params: Some(serde_json::json!({})),
|
||||
trace: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let count = loop {
|
||||
match read_message(&mut websocket).await? {
|
||||
JSONRPCMessage::Response(response) if response.id == id => {
|
||||
break response
|
||||
.result
|
||||
.get("data")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.map(Vec::len)
|
||||
.context("thread/loaded/list returned no data")?;
|
||||
}
|
||||
JSONRPCMessage::Error(error) if error.id == id => {
|
||||
anyhow::bail!("thread/loaded/list failed: {}", error.error.message);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
};
|
||||
websocket.close(None).await.ok();
|
||||
Ok(count)
|
||||
})
|
||||
.await
|
||||
.context("timed out listing app-server threads")?
|
||||
}
|
||||
|
||||
pub(crate) async fn connect(socket_path: &Path) -> Result<WebSocketStream<UnixStream>> {
|
||||
connect_at(socket_path, "ws://localhost/").await
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
mod backend;
|
||||
mod background_command;
|
||||
mod cli_sync;
|
||||
pub use cli_sync::CliSync;
|
||||
pub use cli_sync::sync_with_cli;
|
||||
#[cfg(windows)]
|
||||
pub use backend::windows::DetachedLaunchRestricted;
|
||||
#[cfg(windows)]
|
||||
|
||||
Reference in New Issue
Block a user