Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1c278642de | ||
|
|
0460c74f38 | ||
|
|
4e1f551b84 |
20
README.md
20
README.md
@@ -4,7 +4,7 @@
|
||||
|
||||
È un fork di [OpenAI Codex CLI](https://github.com/openai/codex) (Apache-2.0). Da Codex eredita l'interfaccia a terminale, l'esecuzione dei comandi in sandbox, la modifica dei file con patch, MCP, skill, plugin locali e la modalità non interattiva `exec`. Ha però tolto tutto ciò che dipende dai servizi di OpenAI.
|
||||
|
||||
> **Uso privato.** Questo repository (`git.difonzo.net/andrea/aKode`) non è distribuito né pubblicato.
|
||||
> **Uso privato.** Questo repository (`git.difonzo.net/andrea/imeai-aKode`) non è distribuito né pubblicato.
|
||||
|
||||
---
|
||||
|
||||
@@ -30,13 +30,13 @@ Il comando è `akode`, la configurazione sta in `~/.akode` (oppure nella cartell
|
||||
## Installazione (macOS Apple Silicon)
|
||||
|
||||
```bash
|
||||
curl -fsSL https://git.difonzo.net/andrea/aKode/raw/branch/main/install.sh | sh
|
||||
curl -fsSL https://git.difonzo.net/andrea/imeai-aKode/raw/branch/main/install.sh | sh
|
||||
```
|
||||
|
||||
Variante più prudente: scarica lo script, leggilo e poi eseguilo.
|
||||
|
||||
```bash
|
||||
curl -fsSLO https://git.difonzo.net/andrea/aKode/raw/branch/main/install.sh
|
||||
curl -fsSLO https://git.difonzo.net/andrea/imeai-aKode/raw/branch/main/install.sh
|
||||
less install.sh
|
||||
sh install.sh
|
||||
```
|
||||
@@ -128,6 +128,20 @@ Il token sta nell'archivio delle chiavi (`provider_api_key_store`, id `telegram-
|
||||
|
||||
## Novità
|
||||
|
||||
### 0.9.0
|
||||
|
||||
- **Cache del prompt più stabile** (misure sul server imeAI):
|
||||
- ordine fisso dei blocchi di contesto: prima le sezioni uguali in ogni sessione (`<skills_instructions>`, permessi), poi quelle che dipendono dal repository o dalla sessione (`<code_map>`, riepilogo della memoria). Prima `<code_map>` stava subito dopo le istruzioni di sistema: c'era o mancava a seconda che l'indice fosse pronto, e cambiava da un repository all'altro, invalidando tutto il resto;
|
||||
- strumenti in ordine stabile: prima quelli di aKode, poi quelli con namespace (server MCP, sotto-agenti), ciascuno per nome; nella sessione resta l'ordine della prima richiesta e gli strumenti che arrivano dopo finiscono in coda, mai in mezzo;
|
||||
- server MCP: la prima richiesta di una sessione aspetta fino a 5 s (prima 1 s) i server ancora in avvio, così l'elenco degli strumenti è completo dall'inizio (`mcp_optional_startup_grace_ms`).
|
||||
- **Attese lunghe dei server locali**: ogni byte ricevuto conta come segno di vita, compresi i commenti SSE e gli eventi `imeai.queue` e `imeai.prefill` del gateway (prima i commenti non azzeravano il timer). Il timeout di inattività vale anche per l'attesa della prima risposta (prima illimitata) ed è di 30 minuti per i server locali (loopback, rete privata, `.local`, `.lan`), 5 minuti per gli altri; si cambia con `stream_idle_timeout_ms` del provider. Niente più keepalive TCP: reqwest chiudeva dopo 60 s una connessione muta quando le sonde non tornavano indietro (succede attraverso NetBird), e una lettura del prompt più lunga di un minuto ripartiva da capo; misurato sul server: prima richiesta a freddo di 82 s arrivata alla fine senza ripetizioni.
|
||||
- **Repository rinominato** in `git.difonzo.net/andrea/imeai-aKode`: installatore, `akode update` e link aggiornati; il vecchio indirizzo risponde con un redirect.
|
||||
- **Compattazione più leggera**: prima del riassunto, l'output degli strumenti più vecchi (tutti tranne gli ultimi 3, sopra i 400 caratteri) diventa un segnaposto breve; le chiamate restano visibili. Il prompt del riassunto si accorcia di molto, e su CPU ogni token in meno è tempo in meno. La compattazione usa sempre il provider configurato (verificato, con un test).
|
||||
- **Protezione dai loop, in stile Gemini CLI**, insieme a `[agent] max_repeated_failures`:
|
||||
- `[agent] max_identical_tool_calls` (5): stessa chiamata con gli stessi argomenti per 5 volte di fila, qualunque sia il risultato; esclusi gli strumenti di attesa (`write_stdin`, `wait_agent`);
|
||||
- `[agent] max_repeated_text` (10): lo stesso pezzo di testo ripetuto 10 volte di seguito mentre arriva, nella risposta o nel ragionamento; esclusi i blocchi di codice e i separatori. La risposta si ferma subito invece di andare avanti fino al limite di token.
|
||||
- **Cancellazioni ricorsive protette**: `rm -r`/`rm -rf` e `find … -delete` della radice, della home, della radice del repository, della cartella di lavoro, di percorsi fuori dalla cartella di lavoro o calcolati a runtime (`$VAR`, `$(…)`, `xargs`) chiedono sempre la conferma dell'utente, anche con regole che li permetterebbero; in accesso completo, dove nessuno può confermare, vengono rifiutati.
|
||||
|
||||
### 0.8.0
|
||||
|
||||
- **Grafo del codice** (memoria di imeAI, fase 4): aKode indicizza in locale il repository della cartella di lavoro con tree-sitter e git, senza modello e senza mandare il codice da nessuna parte. Linguaggi: Rust, TypeScript/TSX/JavaScript, Python, Go, Swift, Bash; di TOML, JSON e YAML solo la struttura (sezioni e chiavi). Indice SQLite per repository in `~/.akode/code-graph/`, fuori dal checkout; aggiornamento incrementale da `git diff` rispetto all'ultimo commit indicizzato più `git status` (su akode-rs: prima indicizzazione 4,2 s, aggiornamenti 57-150 ms).
|
||||
|
||||
316
akode-rs/Cargo.lock
generated
316
akode-rs/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -158,7 +158,7 @@ members = [
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
# Track the edition for all workspace crates in one place. Individual
|
||||
# crates can still override this value, but keeping it here means new
|
||||
# crates created with `cargo new -w ...` automatically inherit the 2024
|
||||
|
||||
@@ -132,9 +132,12 @@ impl<T: HttpTransport> ResponsesClient<T> {
|
||||
Compression::Zstd => RequestCompression::Zstd,
|
||||
};
|
||||
|
||||
let stream_response = self
|
||||
.session
|
||||
.stream_encoded_json_with(
|
||||
let idle_timeout = self.session.provider().stream_idle_timeout;
|
||||
// Local servers may send the headers only with the first token, after reading the whole
|
||||
// prompt: the wait is bounded by the same (generous, configurable) idle timeout.
|
||||
let stream_response = tokio::time::timeout(
|
||||
idle_timeout,
|
||||
self.session.stream_encoded_json_with(
|
||||
Method::POST,
|
||||
"/responses",
|
||||
extra_headers,
|
||||
@@ -146,12 +149,19 @@ impl<T: HttpTransport> ResponsesClient<T> {
|
||||
);
|
||||
req.compression = request_compression;
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ApiError::Stream(format!(
|
||||
"nessuna risposta dal server entro {} s (stream_idle_timeout_ms)",
|
||||
idle_timeout.as_secs()
|
||||
))
|
||||
})??;
|
||||
|
||||
Ok(spawn_response_stream(
|
||||
stream_response,
|
||||
self.session.provider().stream_idle_timeout,
|
||||
idle_timeout,
|
||||
self.sse_telemetry.clone(),
|
||||
turn_state,
|
||||
))
|
||||
|
||||
@@ -25,7 +25,6 @@ use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::timeout;
|
||||
use tracing::debug;
|
||||
use tracing::trace;
|
||||
|
||||
@@ -536,6 +535,16 @@ async fn process_sse_with_treatment(
|
||||
telemetry: Option<Arc<dyn SseTelemetry>>,
|
||||
safety_buffering_treatment: SafetyBufferingTreatment,
|
||||
) {
|
||||
// Any bytes from the server are a sign of life: SSE comments (`: ...`) and events this
|
||||
// client does not use (`imeai.queue`, `imeai.prefill` while the server waits or reads the
|
||||
// prompt) restart the idle timer, even though the parser yields no event for comments.
|
||||
let last_activity = Arc::new(std::sync::Mutex::new(Instant::now()));
|
||||
let activity = Arc::clone(&last_activity);
|
||||
let stream = stream.inspect(move |chunk| {
|
||||
if chunk.is_ok() {
|
||||
*activity.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Instant::now();
|
||||
}
|
||||
});
|
||||
let mut stream = stream.eventsource();
|
||||
let mut response_error: Option<ApiError> = None;
|
||||
let mut last_server_model: Option<String> = None;
|
||||
@@ -545,7 +554,7 @@ async fn process_sse_with_treatment(
|
||||
let response = tokio::select! {
|
||||
biased;
|
||||
_ = tx_event.closed() => return,
|
||||
response = timeout(idle_timeout, stream.next()) => response,
|
||||
response = next_with_activity_timeout(&mut stream, &last_activity, idle_timeout) => response,
|
||||
};
|
||||
if let Some(t) = telemetry.as_ref() {
|
||||
t.on_sse_poll(&response, start.elapsed());
|
||||
@@ -580,6 +589,11 @@ async fn process_sse_with_treatment(
|
||||
|
||||
trace!("SSE event: {}", &sse.data);
|
||||
|
||||
if is_server_progress_event(&sse.event) {
|
||||
// Queue position and prompt-reading progress: only signs of life for this client.
|
||||
continue;
|
||||
}
|
||||
|
||||
let event: ResponsesStreamEvent = match serde_json::from_str(&sse.data) {
|
||||
Ok(event) => event,
|
||||
Err(e) => {
|
||||
@@ -656,6 +670,40 @@ async fn process_sse_with_treatment(
|
||||
}
|
||||
}
|
||||
|
||||
/// Progress events of local servers (imeAI gateway): `imeai.queue`, `imeai.prefill`, ...
|
||||
fn is_server_progress_event(event: &str) -> bool {
|
||||
event.starts_with("imeai.")
|
||||
}
|
||||
|
||||
/// Waits for the next SSE event; fails only after `idle_timeout` without any bytes at all, so
|
||||
/// keep-alive comments and progress events keep a long prompt read alive.
|
||||
async fn next_with_activity_timeout<S>(
|
||||
stream: &mut S,
|
||||
last_activity: &std::sync::Mutex<Instant>,
|
||||
idle_timeout: Duration,
|
||||
) -> Result<Option<S::Item>, tokio::time::error::Elapsed>
|
||||
where
|
||||
S: futures::Stream + Unpin,
|
||||
{
|
||||
loop {
|
||||
let since = *last_activity
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let deadline = since + idle_timeout;
|
||||
match tokio::time::timeout_at(deadline, stream.next()).await {
|
||||
Ok(item) => return Ok(item),
|
||||
Err(elapsed) => {
|
||||
let latest = *last_activity
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if latest == since {
|
||||
return Err(elapsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "responses_error_tests.rs"]
|
||||
mod error_tests;
|
||||
@@ -1049,6 +1097,62 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Byte stream that sends `chunks` with `gap` of silence before each one, then waits forever.
|
||||
fn paced_stream(chunks: Vec<&'static str>, gap: Duration) -> ByteStream {
|
||||
let stream = stream::iter(chunks).then(move |chunk| async move {
|
||||
tokio::time::sleep(gap).await;
|
||||
Ok::<Bytes, TransportError>(Bytes::from(chunk))
|
||||
});
|
||||
Box::pin(stream.chain(stream::pending()))
|
||||
}
|
||||
|
||||
async fn collect_until_closed(stream: ByteStream) -> Vec<Result<ResponseEvent, ApiError>> {
|
||||
let (tx, mut rx) = mpsc::channel::<Result<ResponseEvent, ApiError>>(16);
|
||||
tokio::spawn(process_sse(stream, tx, idle_timeout(), /*telemetry*/ None));
|
||||
let mut events = Vec::new();
|
||||
while let Some(ev) = rx.recv().await {
|
||||
events.push(ev);
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn keepalive_comments_and_progress_events_reset_the_idle_timer() {
|
||||
// 4 s of waiting and prompt reading with the 1 s idle timeout: each chunk arrives
|
||||
// after 600 ms, so only the bytes themselves keep the stream alive.
|
||||
let completed = r#"event: response.completed
|
||||
data: {"type":"response.completed","response":{"id":"resp1"}}
|
||||
|
||||
"#;
|
||||
let stream = paced_stream(
|
||||
vec![
|
||||
": in coda\n\n",
|
||||
"event: imeai.queue\ndata: {\"queued\":true,\"ahead\":1,\"position\":2}\n\n",
|
||||
": in coda\n\n",
|
||||
"event: imeai.prefill\ndata: {\"percent\":40,\"eta_s\":3.0}\n\n",
|
||||
"event: imeai.prefill\ndata: {\"percent\":90,\"eta_s\":0.5}\n\n",
|
||||
": attesa\n\n",
|
||||
completed,
|
||||
],
|
||||
Duration::from_millis(600),
|
||||
);
|
||||
|
||||
let events = collect_until_closed(stream).await;
|
||||
|
||||
assert_eq!(events.len(), 1, "{events:?}");
|
||||
assert_matches!(&events[0], Ok(ResponseEvent::Completed { response_id, .. }) if response_id == "resp1");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn silence_longer_than_idle_timeout_still_fails() {
|
||||
let stream = paced_stream(vec![": in coda\n\n"], Duration::from_millis(200));
|
||||
|
||||
let events = collect_until_closed(stream).await;
|
||||
|
||||
assert_eq!(events.len(), 1, "{events:?}");
|
||||
assert_matches!(&events[0], Err(ApiError::Stream(message)) if message.contains("idle timeout"));
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn rate_limit_error_preserves_retry_delay() {
|
||||
let raw_error = r#"{"type":"response.failed","sequence_number":3,"response":{"id":"resp_689bcf18d7f08194bf3440ba62fe05d803fee0cdac429894","object":"response","created_at":1755041560,"status":"failed","background":false,"error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5.1 in organization org-AAA on tokens per min (TPM): Limit 30000, Used 22999, Requested 12528. Please try again in 11.054s. Visit https://platform.openai.com/account/rate-limits to learn more."}, "usage":null,"user":null,"metadata":{}}}"#;
|
||||
|
||||
@@ -2455,13 +2455,13 @@ async fn capture_binding_shares_optional_startup_grace_across_connection_sets()
|
||||
|
||||
let first_started = tokio::time::Instant::now();
|
||||
let first = tokio::time::timeout(
|
||||
Duration::from_millis(1500),
|
||||
crate::mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE + Duration::from_millis(500),
|
||||
capture_binding(&create_connection_set()),
|
||||
)
|
||||
.await
|
||||
.expect("the first thread should receive the optional startup grace");
|
||||
assert!(first.tools().is_empty());
|
||||
assert_eq!(first_started.elapsed(), Duration::from_secs(1));
|
||||
assert_eq!(first_started.elapsed(), crate::mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE);
|
||||
|
||||
let second = tokio::time::timeout(
|
||||
Duration::from_millis(1),
|
||||
@@ -2491,13 +2491,13 @@ async fn capture_binding_shares_optional_startup_grace_across_connection_sets()
|
||||
|
||||
let restored_started = tokio::time::Instant::now();
|
||||
let restored = tokio::time::timeout(
|
||||
Duration::from_millis(1500),
|
||||
crate::mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE + Duration::from_millis(500),
|
||||
capture_binding(&create_connection_set()),
|
||||
)
|
||||
.await
|
||||
.expect("restoring the startup grace should create a fresh deadline");
|
||||
assert!(restored.tools().is_empty());
|
||||
assert_eq!(restored_started.elapsed(), Duration::from_secs(1));
|
||||
assert_eq!(restored_started.elapsed(), crate::mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE);
|
||||
|
||||
let mut updated_config = crate::mcp::tests::test_mcp_config(std::env::temp_dir());
|
||||
updated_config.optional_mcp_startup_grace = Duration::from_millis(250);
|
||||
@@ -2553,13 +2553,13 @@ async fn capture_binding_shares_optional_startup_grace_across_connection_sets()
|
||||
for _ in 0..2 {
|
||||
let started = tokio::time::Instant::now();
|
||||
let binding = tokio::time::timeout(
|
||||
Duration::from_millis(1500),
|
||||
crate::mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE + Duration::from_millis(500),
|
||||
capture_binding(&create_connection_set()),
|
||||
)
|
||||
.await
|
||||
.expect("non-cacheable servers should keep their per-thread startup grace");
|
||||
assert!(binding.tools().is_empty());
|
||||
assert_eq!(started.elapsed(), Duration::from_secs(1));
|
||||
assert_eq!(started.elapsed(), crate::mcp::DEFAULT_OPTIONAL_MCP_STARTUP_GRACE);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -186,8 +186,11 @@ pub struct McpConfig {
|
||||
pub mcp_server_catalog: ResolvedMcpCatalog,
|
||||
}
|
||||
|
||||
/// Default amount of time a tool catalog capture waits for optional MCP servers.
|
||||
pub const DEFAULT_OPTIONAL_MCP_STARTUP_GRACE: Duration = Duration::from_secs(1);
|
||||
/// Default amount of time the first tool catalog capture of a session waits for optional MCP
|
||||
/// servers. The wait happens once per session: with the complete tool list in the first
|
||||
/// request, the prompt prefix cached by local servers stays valid (tools that still arrive
|
||||
/// later are appended at the end of the list).
|
||||
pub const DEFAULT_OPTIONAL_MCP_STARTUP_GRACE: Duration = Duration::from_secs(5);
|
||||
|
||||
impl McpConfig {
|
||||
/// Resolves enabled runtime servers against the exact attachment permissions being published.
|
||||
|
||||
@@ -8,13 +8,13 @@ use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const LATEST_PATH: &str = "/api/v1/repos/andrea/aKode/releases/latest";
|
||||
const LATEST_PATH: &str = "/api/v1/repos/andrea/imeai-aKode/releases/latest";
|
||||
|
||||
fn akode_update(akode_home: &Path, server: &MockServer) -> Result<assert_cmd::Command> {
|
||||
let mut cmd = assert_cmd::Command::new(akode_utils_cargo_bin::cargo_bin("akode")?);
|
||||
cmd.env("AKODE_HOME", akode_home).args([
|
||||
"-c",
|
||||
&format!("update.repo_url=\"{}/andrea/aKode\"", server.uri()),
|
||||
&format!("update.repo_url=\"{}/andrea/imeai-aKode\"", server.uri()),
|
||||
"update",
|
||||
]);
|
||||
Ok(cmd)
|
||||
|
||||
@@ -795,6 +795,13 @@ pub struct AgentToml {
|
||||
/// the tests") without calling any tool, send it one short reminder and let it continue,
|
||||
/// at most this many times per turn. Default: 1. `0` disables the reminder.
|
||||
pub announce_nudges: Option<u32>,
|
||||
/// Stop the turn when the model calls the same tool with the same arguments this many
|
||||
/// times in a row, whatever the result (polling tools such as `write_stdin` excluded).
|
||||
/// Default: 5. `0` disables the check.
|
||||
pub max_identical_tool_calls: Option<u32>,
|
||||
/// Stop the answer while it streams when the same piece of text repeats this many times
|
||||
/// back to back (code blocks excluded). Default: 10. `0` disables the check.
|
||||
pub max_repeated_text: Option<u32>,
|
||||
}
|
||||
|
||||
/// `[memoria]` table: session-start briefing and session delivery of the imeAI `memoria` plugin.
|
||||
|
||||
@@ -226,7 +226,7 @@ pub enum HistoryPersistence {
|
||||
}
|
||||
|
||||
/// Public Gitea repository that publishes aKode releases.
|
||||
pub const DEFAULT_UPDATE_REPO_URL: &str = "https://git.difonzo.net/andrea/aKode";
|
||||
pub const DEFAULT_UPDATE_REPO_URL: &str = "https://git.difonzo.net/andrea/imeai-aKode";
|
||||
|
||||
/// `[update]`: where `akode update` looks for releases and whether the TUI checks on startup.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)]
|
||||
|
||||
@@ -41,11 +41,23 @@
|
||||
"minimum": 0.0,
|
||||
"type": "integer"
|
||||
},
|
||||
"max_identical_tool_calls": {
|
||||
"description": "Stop the turn when the model calls the same tool with the same arguments this many times in a row, whatever the result (polling tools such as `write_stdin` excluded). Default: 5. `0` disables the check.",
|
||||
"format": "uint32",
|
||||
"minimum": 0.0,
|
||||
"type": "integer"
|
||||
},
|
||||
"max_repeated_failures": {
|
||||
"description": "Stop the turn when the model repeats the same tool call and gets the same failure this many times in a row. Default: 3. `0` disables the check.",
|
||||
"format": "uint32",
|
||||
"minimum": 0.0,
|
||||
"type": "integer"
|
||||
},
|
||||
"max_repeated_text": {
|
||||
"description": "Stop the answer while it streams when the same piece of text repeats this many times back to back (code blocks excluded). Default: 10. `0` disables the check.",
|
||||
"format": "uint32",
|
||||
"minimum": 0.0,
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
@@ -3234,7 +3246,7 @@
|
||||
"type": "boolean"
|
||||
},
|
||||
"stream_idle_timeout_ms": {
|
||||
"description": "Idle timeout (in milliseconds) to wait for activity on a streaming response before treating the connection as lost.",
|
||||
"description": "Idle timeout (in milliseconds) to wait for activity on a streaming response before treating the connection as lost. It also bounds the wait for the first response (headers). Any bytes count as activity, including SSE comments and progress events. Defaults to 5 minutes, or 30 minutes for local servers.",
|
||||
"format": "uint64",
|
||||
"minimum": 0.0,
|
||||
"type": "integer"
|
||||
|
||||
@@ -205,6 +205,8 @@ struct ModelClientState {
|
||||
cached_websocket_session: StdMutex<WebsocketSession>,
|
||||
/// Last full tool list used for sampling, retained across turns and connection resets.
|
||||
last_inference_tools: StdMutex<Option<Arc<[ToolSpec]>>>,
|
||||
/// Order of the tool definitions sent in this session (stable for the prompt cache).
|
||||
tool_order: crate::tool_order::ToolOrder,
|
||||
/// Per-model settings of the provider (sampling values), refreshed with the user config.
|
||||
model_settings: StdMutex<
|
||||
std::collections::BTreeMap<String, akode_model_provider_info::ProviderModelSettings>,
|
||||
@@ -591,6 +593,7 @@ impl ModelClient {
|
||||
disable_websockets: AtomicBool::new(false),
|
||||
cached_websocket_session: StdMutex::new(WebsocketSession::default()),
|
||||
last_inference_tools: StdMutex::new(None),
|
||||
tool_order: crate::tool_order::ToolOrder::default(),
|
||||
model_settings,
|
||||
}),
|
||||
prompt_cache_key_policy: PromptCacheKey::default(),
|
||||
@@ -1100,8 +1103,10 @@ impl ModelClient {
|
||||
// aKode talks only to OpenAI-compatible servers, which accept function tools only:
|
||||
// namespaces (MCP servers, multi-agent tools) are flattened to `<namespace>__<tool>`,
|
||||
// and past calls are replayed with the same flat names.
|
||||
if self.state.provider.capabilities().tool_namespaces {
|
||||
Some(create_tools_raw_json_for_responses_api(&prompt.tools)?.into())
|
||||
// The tool list is sent in a stable order (see `tool_order`): local servers cache
|
||||
// the prompt prefix, and templates render the tools near its top.
|
||||
let raw = if self.state.provider.capabilities().tool_namespaces {
|
||||
create_tools_raw_json_for_responses_api(&prompt.tools)?
|
||||
} else {
|
||||
for item in &mut input {
|
||||
if let ResponseItem::FunctionCall { name, namespace, .. } = item
|
||||
@@ -1110,8 +1115,13 @@ impl ModelClient {
|
||||
*name = format!("{ns}{FLAT_NAMESPACE_SEPARATOR}{name}");
|
||||
}
|
||||
}
|
||||
Some(create_flat_tools_raw_json_for_responses_api(&prompt.tools)?.into())
|
||||
}
|
||||
create_flat_tools_raw_json_for_responses_api(&prompt.tools)?
|
||||
};
|
||||
let mut tools: Vec<serde_json::Value> = serde_json::from_str(raw.get())?;
|
||||
self.state.tool_order.apply(&mut tools);
|
||||
let raw: Arc<serde_json::value::RawValue> =
|
||||
serde_json::value::to_raw_value(&tools).map(Arc::from)?;
|
||||
Some(raw.into())
|
||||
};
|
||||
if !prompt.base_instructions.text.is_empty() {
|
||||
let mut instructions = ContextualUserFragment::into(BaseInstructionsFragment(
|
||||
|
||||
@@ -265,6 +265,15 @@ async fn run_compact_task_inner_impl(
|
||||
sess.services
|
||||
.executed_tool_calls
|
||||
.attach_to_compaction_prompt(&mut turn_input);
|
||||
// The summarizer does not need the raw output of old tool calls: a short placeholder
|
||||
// keeps the call visible and the compaction prompt much shorter.
|
||||
let cleared = crate::tool_output_clearing::clear_old_tool_outputs(
|
||||
&mut turn_input,
|
||||
crate::tool_output_clearing::KEEP_RECENT_TOOL_OUTPUTS,
|
||||
);
|
||||
if cleared > 0 {
|
||||
tracing::info!(cleared_chars = cleared, "old tool outputs cleared before compaction");
|
||||
}
|
||||
let turn_input_len = turn_input.len();
|
||||
let base_instructions = if turn_input
|
||||
.iter()
|
||||
|
||||
@@ -696,6 +696,12 @@ pub const DEFAULT_MAX_REPEATED_FAILURES: u32 = 3;
|
||||
/// Default for `[agent] announce_nudges`.
|
||||
pub const DEFAULT_ANNOUNCE_NUDGES: u32 = 1;
|
||||
|
||||
/// Default for `[agent] max_identical_tool_calls` (the threshold of Gemini CLI).
|
||||
pub const DEFAULT_MAX_IDENTICAL_TOOL_CALLS: u32 = 5;
|
||||
|
||||
/// Default for `[agent] max_repeated_text` (the threshold of Gemini CLI).
|
||||
pub const DEFAULT_MAX_REPEATED_TEXT: u32 = 10;
|
||||
|
||||
/// Session delivery of the `memoria` plugin (`[memoria] deliver_sessions`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct MemoriaDeliveryConfig {
|
||||
@@ -1283,6 +1289,14 @@ pub struct Config {
|
||||
/// (`[agent] announce_nudges`). `0` disables it.
|
||||
pub announce_nudges: u32,
|
||||
|
||||
/// Loop protection: stop the turn after this many identical tool calls in a row, whatever
|
||||
/// the result (`[agent] max_identical_tool_calls`). `0` disables the check.
|
||||
pub max_identical_tool_calls: u32,
|
||||
|
||||
/// Loop protection: stop a streaming answer that repeats the same text this many times
|
||||
/// back to back (`[agent] max_repeated_text`). `0` disables the check.
|
||||
pub max_repeated_text: u32,
|
||||
|
||||
/// Session-start briefing of the `memoria` plugin (`[memoria]`).
|
||||
pub memoria_briefing: MemoriaBriefingConfig,
|
||||
|
||||
@@ -4293,6 +4307,16 @@ impl Config {
|
||||
.as_ref()
|
||||
.and_then(|agent| agent.announce_nudges)
|
||||
.unwrap_or(DEFAULT_ANNOUNCE_NUDGES);
|
||||
let max_identical_tool_calls = cfg
|
||||
.agent
|
||||
.as_ref()
|
||||
.and_then(|agent| agent.max_identical_tool_calls)
|
||||
.unwrap_or(DEFAULT_MAX_IDENTICAL_TOOL_CALLS);
|
||||
let max_repeated_text = cfg
|
||||
.agent
|
||||
.as_ref()
|
||||
.and_then(|agent| agent.max_repeated_text)
|
||||
.unwrap_or(DEFAULT_MAX_REPEATED_TEXT);
|
||||
let memoria_briefing = {
|
||||
let defaults = MemoriaBriefingConfig::default();
|
||||
let toml = cfg.memoria.clone().unwrap_or_default();
|
||||
@@ -4935,6 +4959,8 @@ impl Config {
|
||||
background_terminal_max_timeout,
|
||||
max_repeated_failures,
|
||||
announce_nudges,
|
||||
max_identical_tool_calls,
|
||||
max_repeated_text,
|
||||
memoria_briefing,
|
||||
memoria_delivery,
|
||||
memoria_anchors,
|
||||
|
||||
@@ -41,6 +41,8 @@ mod compact_retained_tool_outputs;
|
||||
mod compact_token_budget;
|
||||
pub mod compaction_metadata;
|
||||
mod merge_system_messages;
|
||||
mod tool_order;
|
||||
mod tool_output_clearing;
|
||||
mod thread_startup_metadata;
|
||||
pub use akode_network_proxy::EnvironmentNetworkPolicy;
|
||||
pub use akode_network_proxy::NetworkDomainPermission;
|
||||
|
||||
@@ -503,24 +503,7 @@ impl CodexResponsesMetadata {
|
||||
/// (`localhost`, 127.0.0.0/8, `::1`), private IPv4 (10/8, 172.16/12, 192.168/16) and
|
||||
/// `.local`/`.lan` hosts. Remote services (OpenRouter and similar) and an unset base URL do not.
|
||||
pub(crate) fn provider_shares_client_identity(base_url: Option<&str>) -> bool {
|
||||
let Some(base_url) = base_url else {
|
||||
return false;
|
||||
};
|
||||
let Ok(url) = url::Url::parse(base_url.trim()) else {
|
||||
return false;
|
||||
};
|
||||
match url.host() {
|
||||
Some(url::Host::Ipv4(ip)) => ip.is_loopback() || ip.is_private(),
|
||||
Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
|
||||
Some(url::Host::Domain(host)) => {
|
||||
let host = host.trim_end_matches('.').to_ascii_lowercase();
|
||||
host == "localhost"
|
||||
|| host.ends_with(".localhost")
|
||||
|| host.ends_with(".local")
|
||||
|| host.ends_with(".lan")
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
base_url.is_some_and(akode_model_provider_info::is_local_base_url)
|
||||
}
|
||||
|
||||
pub(crate) fn subagent_header_value(session_source: &SessionSource) -> Option<String> {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
//! Loop protection: stops a turn when the model keeps repeating the same failing tool call.
|
||||
//! Loop protection: stops a turn when the model keeps repeating the same failing tool call,
|
||||
//! the same tool call whatever its result, or the same text while it streams (the last two in
|
||||
//! the style of Gemini CLI's loop detection).
|
||||
|
||||
use akode_protocol::models::FunctionCallOutputPayload;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
@@ -7,6 +9,10 @@ use std::collections::HashMap;
|
||||
|
||||
pub(crate) const REPEATED_FAILURE_MESSAGE: &str =
|
||||
"Il modello ripete lo stesso comando senza risultato: turno interrotto.";
|
||||
pub(crate) const IDENTICAL_CALLS_MESSAGE: &str =
|
||||
"Il modello ripete la stessa chiamata a strumento con gli stessi argomenti: turno interrotto.";
|
||||
pub(crate) const REPEATED_TEXT_MESSAGE: &str =
|
||||
"Il modello ripete lo stesso testo: risposta interrotta.";
|
||||
pub(crate) const SANDBOX_HINT: &str =
|
||||
"Sembra un blocco della sandbox: usa /permissions per concedere più accesso.";
|
||||
|
||||
@@ -66,6 +72,179 @@ pub(crate) fn repeated_failure_message<'a>(
|
||||
Some(message)
|
||||
}
|
||||
|
||||
/// Tools that are legitimately called again with the same arguments: polling a running
|
||||
/// process or waiting for sub-agents.
|
||||
const POLLING_TOOLS: &[&str] = &["write_stdin", "wait_agent", "wait"];
|
||||
|
||||
/// Returns the message to show when the model made the same tool call (same tool, same
|
||||
/// arguments) in `threshold` consecutive responses of the current turn, whatever the result.
|
||||
/// Calls of one response (a parallel batch, with no output in between) count once.
|
||||
/// `threshold == 0` disables the check.
|
||||
pub(crate) fn identical_calls_message<'a>(
|
||||
items: impl IntoIterator<Item = &'a ResponseItem>,
|
||||
threshold: u32,
|
||||
) -> Option<String> {
|
||||
if threshold == 0 {
|
||||
return None;
|
||||
}
|
||||
// One entry per response with tool calls: `Some(signature)` when all its calls are the
|
||||
// same, `None` when they differ.
|
||||
let mut steps: Vec<Option<(String, String)>> = Vec::new();
|
||||
let mut batch: Vec<(String, String)> = Vec::new();
|
||||
let flush = |batch: &mut Vec<(String, String)>, steps: &mut Vec<Option<(String, String)>>| {
|
||||
if let Some(first) = batch.first().cloned() {
|
||||
let same = batch.iter().all(|(_, signature)| *signature == first.1);
|
||||
steps.push(same.then_some(first));
|
||||
}
|
||||
batch.clear();
|
||||
};
|
||||
for item in items {
|
||||
match item {
|
||||
ResponseItem::Message { role, .. } if role == "user" => {
|
||||
batch.clear();
|
||||
steps.clear();
|
||||
}
|
||||
ResponseItem::FunctionCall {
|
||||
name,
|
||||
namespace,
|
||||
arguments,
|
||||
..
|
||||
} => batch.push((name.clone(), call_signature(name, namespace.as_deref(), arguments))),
|
||||
ResponseItem::CustomToolCall {
|
||||
name,
|
||||
namespace,
|
||||
input,
|
||||
..
|
||||
} => batch.push((name.clone(), call_signature(name, namespace.as_deref(), input))),
|
||||
ResponseItem::LocalShellCall { action, .. } => {
|
||||
batch.push(("local_shell".to_string(), format!("local_shell:{action:?}")));
|
||||
}
|
||||
ResponseItem::FunctionCallOutput { .. } | ResponseItem::CustomToolCallOutput { .. } => {
|
||||
flush(&mut batch, &mut steps);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
flush(&mut batch, &mut steps);
|
||||
let (last_name, last) = steps.last()?.as_ref()?;
|
||||
if POLLING_TOOLS
|
||||
.iter()
|
||||
.any(|tool| last_name == tool || last_name.ends_with(&format!("__{tool}")))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let streak = steps
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|step| step.as_ref().is_some_and(|(_, signature)| signature == last))
|
||||
.count();
|
||||
(streak >= threshold as usize).then(|| IDENTICAL_CALLS_MESSAGE.to_string())
|
||||
}
|
||||
|
||||
/// Length of the text window compared while streaming.
|
||||
const TEXT_CHUNK: usize = 50;
|
||||
/// Shorter repeated units are dividers (`=====`, `|---|`), not loops.
|
||||
const MIN_REPEATED_UNIT: usize = 20;
|
||||
/// Beyond this size the stream is no longer checked (memory bound).
|
||||
const MAX_CHECKED_TEXT: usize = 200_000;
|
||||
|
||||
/// Detects a model stuck repeating the same text while it streams: the same unit of text
|
||||
/// (at least [`MIN_REPEATED_UNIT`] characters, with letters or digits) repeated `threshold`
|
||||
/// times back to back. Code blocks reset the check, since code repeats legitimately.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct TextLoopDetector {
|
||||
threshold: usize,
|
||||
text: String,
|
||||
next: usize,
|
||||
positions: HashMap<u64, Vec<usize>>,
|
||||
in_code: bool,
|
||||
}
|
||||
|
||||
impl TextLoopDetector {
|
||||
/// `threshold == 0` disables the check.
|
||||
pub(crate) fn new(threshold: u32) -> Self {
|
||||
Self {
|
||||
threshold: threshold as usize,
|
||||
text: String::new(),
|
||||
next: 0,
|
||||
positions: HashMap::new(),
|
||||
in_code: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a streamed delta; returns true when the text has started looping.
|
||||
pub(crate) fn push(&mut self, delta: &str) -> bool {
|
||||
if self.threshold < 2 || self.text.len() > MAX_CHECKED_TEXT {
|
||||
return false;
|
||||
}
|
||||
let fences = delta.matches("```").count();
|
||||
if fences > 0 {
|
||||
// Code repeats legitimately: skip it and start over after the closing fence.
|
||||
if fences % 2 == 1 {
|
||||
self.in_code = !self.in_code;
|
||||
}
|
||||
self.text.clear();
|
||||
self.positions.clear();
|
||||
self.next = 0;
|
||||
if !self.in_code {
|
||||
self.text
|
||||
.push_str(delta.rsplit("```").next().unwrap_or_default());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if self.in_code {
|
||||
return false;
|
||||
}
|
||||
self.text.push_str(delta);
|
||||
while self.next + TEXT_CHUNK <= self.text.len() {
|
||||
let start = self.next;
|
||||
self.next += 1;
|
||||
let end = start + TEXT_CHUNK;
|
||||
if !self.text.is_char_boundary(start) || !self.text.is_char_boundary(end) {
|
||||
continue;
|
||||
}
|
||||
let hash = {
|
||||
use std::hash::Hash;
|
||||
use std::hash::Hasher;
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
self.text[start..end].hash(&mut hasher);
|
||||
hasher.finish()
|
||||
};
|
||||
let positions = self.positions.entry(hash).or_default();
|
||||
positions.push(start);
|
||||
if positions.len() >= self.threshold
|
||||
&& is_back_to_back_repetition(
|
||||
&self.text,
|
||||
&positions[positions.len() - self.threshold..],
|
||||
)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `starts` are evenly spaced by a period of at least [`MIN_REPEATED_UNIT`] and the
|
||||
/// text of each period is identical and contains letters or digits.
|
||||
fn is_back_to_back_repetition(text: &str, starts: &[usize]) -> bool {
|
||||
let period = starts[1] - starts[0];
|
||||
if period < MIN_REPEATED_UNIT || starts.windows(2).any(|pair| pair[1] - pair[0] != period) {
|
||||
return false;
|
||||
}
|
||||
let first = starts[0];
|
||||
let Some(unit) = text.get(first..first + period) else {
|
||||
return false;
|
||||
};
|
||||
if !unit.chars().any(char::is_alphanumeric) {
|
||||
return false;
|
||||
}
|
||||
starts[1..]
|
||||
.iter()
|
||||
.all(|&start| text.get(start..start + period).is_none_or(|other| other == unit)
|
||||
&& text.get(start - period..start) == Some(unit))
|
||||
}
|
||||
|
||||
fn turn_tool_results<'a>(items: impl IntoIterator<Item = &'a ResponseItem>) -> Vec<ToolResult> {
|
||||
let mut signatures: HashMap<String, String> = HashMap::new();
|
||||
let mut results = Vec::new();
|
||||
|
||||
@@ -131,3 +131,110 @@ fn prompt_over_context_warning_text() {
|
||||
Some("Il prompt iniziale (~9000 token) supera la finestra del modello (8192).".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
fn named_call(call_id: &str, name: &str, arguments: serde_json::Value) -> ResponseItem {
|
||||
serde_json::from_value(json!({
|
||||
"type": "function_call",
|
||||
"name": name,
|
||||
"arguments": arguments.to_string(),
|
||||
"call_id": call_id,
|
||||
}))
|
||||
.expect("function call")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_calls_stop_the_turn_whatever_the_result() {
|
||||
let mut items = vec![user("leggi il file")];
|
||||
for index in 0..5 {
|
||||
let id = format!("c{index}");
|
||||
items.push(named_call(&id, "exec_command", json!({"cmd": "cat a.txt"})));
|
||||
items.push(output(&id, "contenuto", Some(true)));
|
||||
}
|
||||
assert_eq!(
|
||||
identical_calls_message(&items[..items.len() - 2], 5),
|
||||
None,
|
||||
"four calls are not a loop yet"
|
||||
);
|
||||
assert_eq!(
|
||||
identical_calls_message(&items, 5).as_deref(),
|
||||
Some(IDENTICAL_CALLS_MESSAGE)
|
||||
);
|
||||
assert_eq!(identical_calls_message(&items, 0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_arguments_polling_or_a_new_user_message_reset_identical_calls() {
|
||||
let mut items = vec![user("compila")];
|
||||
for index in 0..6 {
|
||||
let id = format!("p{index}");
|
||||
items.push(named_call(&id, "write_stdin", json!({"session_id": 1, "chars": ""})));
|
||||
items.push(output(&id, "in corso", Some(true)));
|
||||
}
|
||||
assert_eq!(identical_calls_message(&items, 5), None, "polling a process is not a loop");
|
||||
|
||||
let mut items = vec![user("cerca")];
|
||||
for index in 0..6 {
|
||||
let id = format!("s{index}");
|
||||
items.push(named_call(&id, "exec_command", json!({"cmd": format!("grep -n x{index} a")})));
|
||||
items.push(output(&id, "", Some(true)));
|
||||
}
|
||||
assert_eq!(identical_calls_message(&items, 5), None);
|
||||
|
||||
// One response with many identical parallel calls is a single step.
|
||||
let mut items = vec![user("aggiorna il piano")];
|
||||
for index in 0..8 {
|
||||
items.push(named_call(&format!("u{index}"), "update_plan", json!({"plan": []})));
|
||||
}
|
||||
for index in 0..8 {
|
||||
items.push(output(&format!("u{index}"), "ok", Some(true)));
|
||||
}
|
||||
assert_eq!(identical_calls_message(&items, 5), None);
|
||||
|
||||
let mut items = Vec::new();
|
||||
for index in 0..4 {
|
||||
let id = format!("a{index}");
|
||||
items.push(named_call(&id, "exec_command", json!({"cmd": "ls"})));
|
||||
items.push(output(&id, "a.txt", Some(true)));
|
||||
}
|
||||
items.push(user("ancora"));
|
||||
items.push(named_call("b", "exec_command", json!({"cmd": "ls"})));
|
||||
assert_eq!(identical_calls_message(&items, 5), None);
|
||||
}
|
||||
|
||||
fn stream_into(detector: &mut TextLoopDetector, text: &str, piece: usize) -> bool {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
chars
|
||||
.chunks(piece)
|
||||
.any(|chunk| detector.push(&chunk.iter().collect::<String>()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_sentence_while_streaming_is_a_loop() {
|
||||
let sentence = "Controllo di nuovo il file di configurazione principale. ";
|
||||
let mut detector = TextLoopDetector::new(10);
|
||||
assert!(stream_into(&mut detector, &sentence.repeat(12), 7));
|
||||
|
||||
let mut early = TextLoopDetector::new(10);
|
||||
assert!(!stream_into(&mut early, &sentence.repeat(8), 7), "8 repetitions are below the threshold");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_text_lists_dividers_and_code_are_not_loops() {
|
||||
let mut detector = TextLoopDetector::new(10);
|
||||
let list: String = (1..=40)
|
||||
.map(|index| format!("- Passo {index}: controlla il modulo m{index} e i suoi test.\n"))
|
||||
.collect();
|
||||
assert!(!stream_into(&mut detector, &list, 9));
|
||||
|
||||
let mut divider = TextLoopDetector::new(10);
|
||||
assert!(!stream_into(&mut divider, &format!("{}\n", "=".repeat(400)), 13));
|
||||
let mut table = TextLoopDetector::new(10);
|
||||
assert!(!stream_into(&mut table, &"|---|---|---|---|---|---|\n".repeat(30), 11));
|
||||
|
||||
let mut code = TextLoopDetector::new(10);
|
||||
let block = format!("```rust\n{}```\nFatto.", " assert_eq!(valore(), 1);\n".repeat(15));
|
||||
assert!(!stream_into(&mut code, &block, 6), "code is skipped");
|
||||
|
||||
let mut disabled = TextLoopDetector::new(0);
|
||||
assert!(!stream_into(&mut disabled, &"ripeto sempre la stessa frase lunga. ".repeat(30), 5));
|
||||
}
|
||||
|
||||
@@ -4800,6 +4800,11 @@ impl Session {
|
||||
developer_sections
|
||||
.push(DeveloperInstructions::new(developer_instructions).render_fragment());
|
||||
}
|
||||
// Extension blocks (`<code_map>`, memory briefing, ...) depend on the repository and the
|
||||
// session, so they go after the built-in sections (skills, permissions, ...) that are the
|
||||
// same for every session: the cached prompt prefix stays reusable across sessions and
|
||||
// the block order is fixed.
|
||||
let mut extension_sections = Vec::<RenderedFragment>::new();
|
||||
let context_contributors = self.services.extensions.context_contributors().to_vec();
|
||||
for contributor in &context_contributors {
|
||||
for fragment in contributor
|
||||
@@ -4814,7 +4819,7 @@ impl Session {
|
||||
context_window_hints.push(fragment.into_content());
|
||||
}
|
||||
PromptSlot::DeveloperPolicy | PromptSlot::DeveloperCapabilities => {
|
||||
developer_sections.push(fragment.into());
|
||||
extension_sections.push(fragment.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4831,7 +4836,7 @@ impl Session {
|
||||
})
|
||||
.await
|
||||
{
|
||||
developer_sections.push(fragment.into());
|
||||
extension_sections.push(fragment.into());
|
||||
}
|
||||
}
|
||||
// This is full-context metadata. Steady-state context diffs should not re-emit it.
|
||||
@@ -4940,6 +4945,7 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
developer_sections.append(&mut extension_sections);
|
||||
if let Some(developer_message) = crate::context_manager::updates::build_rendered_message(
|
||||
std::mem::take(&mut developer_sections),
|
||||
) {
|
||||
|
||||
@@ -712,12 +712,22 @@ pub(crate) async fn run_turn(
|
||||
);
|
||||
}
|
||||
|
||||
if needs_follow_up
|
||||
&& let Some(message) = super::loop_guard::repeated_failure_message(
|
||||
sess.clone_history().await.raw_items(),
|
||||
let loop_message = if needs_follow_up {
|
||||
let history = sess.clone_history().await;
|
||||
super::loop_guard::repeated_failure_message(
|
||||
history.raw_items(),
|
||||
turn_context.config.max_repeated_failures,
|
||||
)
|
||||
{
|
||||
.or_else(|| {
|
||||
super::loop_guard::identical_calls_message(
|
||||
history.raw_items(),
|
||||
turn_context.config.max_identical_tool_calls,
|
||||
)
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(message) = loop_message {
|
||||
let event = EventMsg::Error(ErrorEvent {
|
||||
misalignment: None,
|
||||
message,
|
||||
@@ -2776,6 +2786,11 @@ async fn try_run_sampling_request(
|
||||
let defer_streamed_turn_items_for_contributors =
|
||||
!sess.services.extensions.turn_item_contributors().is_empty();
|
||||
let mut active_item_is_streaming_to_client = false;
|
||||
// Loop protection on the streamed text (`[agent] max_repeated_text`): answer and reasoning.
|
||||
let mut answer_loop =
|
||||
super::loop_guard::TextLoopDetector::new(turn_context.config.max_repeated_text);
|
||||
let mut reasoning_loop =
|
||||
super::loop_guard::TextLoopDetector::new(turn_context.config.max_repeated_text);
|
||||
let receiving_span = trace_span!("receiving_stream");
|
||||
let outcome: CodexResult<SamplingRequestResult> = loop {
|
||||
if response_completed && resampling.accepted_output.is_empty() {
|
||||
@@ -3275,6 +3290,11 @@ async fn try_run_sampling_request(
|
||||
}
|
||||
}
|
||||
ResponseEvent::OutputTextDelta(delta) => {
|
||||
if answer_loop.push(&delta) {
|
||||
break Err(CodexErr::Fatal(
|
||||
super::loop_guard::REPEATED_TEXT_MESSAGE.to_string(),
|
||||
));
|
||||
}
|
||||
// In review child threads, suppress assistant text deltas; the
|
||||
// UI will show a selection popup from the final ReviewOutput.
|
||||
if let Some(active) = active_item.as_ref() {
|
||||
@@ -3404,6 +3424,11 @@ async fn try_run_sampling_request(
|
||||
delta,
|
||||
content_index,
|
||||
} => {
|
||||
if reasoning_loop.push(&delta) {
|
||||
break Err(CodexErr::Fatal(
|
||||
super::loop_guard::REPEATED_TEXT_MESSAGE.to_string(),
|
||||
));
|
||||
}
|
||||
if let Some(active) = active_item.as_ref() {
|
||||
if !active_item_is_streaming_to_client {
|
||||
continue;
|
||||
|
||||
172
akode-rs/core/src/tool_order.rs
Normal file
172
akode-rs/core/src/tool_order.rs
Normal file
@@ -0,0 +1,172 @@
|
||||
//! Stable order of the tool definitions sent to the provider.
|
||||
//!
|
||||
//! Local servers cache the prompt prefix, and chat templates render the tool list near the top
|
||||
//! of the prompt: a different order, or a tool inserted in the middle, invalidates the cached
|
||||
//! prompt from that point on. The list is therefore sorted (top-level tools first, then
|
||||
//! namespaced ones such as MCP servers, each by name), and within a session the order of the
|
||||
//! first request is kept: tools that appear later (an MCP server that finished starting after
|
||||
//! the first request) are appended at the end, never in the middle.
|
||||
|
||||
use akode_tools::FLAT_NAMESPACE_SEPARATOR;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Order memory of one session: tool keys in the order they were first sent.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct ToolOrder {
|
||||
seen: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
impl ToolOrder {
|
||||
/// Reorders `tools` (JSON tool definitions) in place: known tools in their first-seen order,
|
||||
/// new tools after them in canonical order. Namespace members are sorted by name.
|
||||
pub(crate) fn apply(&self, tools: &mut Vec<Value>) {
|
||||
for tool in tools.iter_mut() {
|
||||
if let Some(members) = tool.get_mut("tools").and_then(Value::as_array_mut) {
|
||||
members.sort_by(|a, b| tool_key(a).cmp(&tool_key(b)));
|
||||
}
|
||||
}
|
||||
tools.sort_by(|a, b| canonical_key(a).cmp(&canonical_key(b)));
|
||||
|
||||
let mut seen = self
|
||||
.seen
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let position: HashMap<String, usize> = seen
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, key)| (key.clone(), index))
|
||||
.collect();
|
||||
let (mut known, new): (Vec<Value>, Vec<Value>) = std::mem::take(tools)
|
||||
.into_iter()
|
||||
.partition(|tool| position.contains_key(&tool_key(tool)));
|
||||
known.sort_by_key(|tool| position.get(&tool_key(tool)).copied().unwrap_or(usize::MAX));
|
||||
for tool in &new {
|
||||
seen.push(tool_key(tool));
|
||||
}
|
||||
known.extend(new);
|
||||
*tools = known;
|
||||
}
|
||||
}
|
||||
|
||||
/// Name of a tool definition (`name`, or `type` for hosted tools such as `web_search`).
|
||||
fn tool_key(tool: &Value) -> String {
|
||||
match tool.get("name").and_then(Value::as_str) {
|
||||
Some(name) => name.to_string(),
|
||||
None => tool
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Top-level tools first, then namespaces and flattened namespace members, each by name.
|
||||
fn canonical_key(tool: &Value) -> (bool, String) {
|
||||
let key = tool_key(tool);
|
||||
let namespaced = tool.get("type").and_then(Value::as_str) == Some("namespace")
|
||||
|| key.contains(FLAT_NAMESPACE_SEPARATOR);
|
||||
(namespaced, key)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
fn names(tools: &[Value]) -> Vec<String> {
|
||||
tools.iter().map(tool_key).collect()
|
||||
}
|
||||
|
||||
fn function(name: &str) -> Value {
|
||||
json!({"type": "function", "name": name, "parameters": {}})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_tools_in_any_order_give_the_same_list() {
|
||||
let first = ToolOrder::default();
|
||||
let second = ToolOrder::default();
|
||||
let mut a = vec![
|
||||
function("exec_command"),
|
||||
function("memoria__memory_search"),
|
||||
function("apply_patch"),
|
||||
json!({"type": "web_search"}),
|
||||
function("request_user_input"),
|
||||
];
|
||||
let mut b = a.clone();
|
||||
b.reverse();
|
||||
|
||||
first.apply(&mut a);
|
||||
second.apply(&mut b);
|
||||
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(
|
||||
names(&a),
|
||||
vec![
|
||||
"apply_patch",
|
||||
"exec_command",
|
||||
"request_user_input",
|
||||
"web_search",
|
||||
"memoria__memory_search",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tools_that_appear_later_go_at_the_end() {
|
||||
let order = ToolOrder::default();
|
||||
let mut first = vec![function("exec_command"), function("apply_patch")];
|
||||
order.apply(&mut first);
|
||||
assert_eq!(names(&first), vec!["apply_patch", "exec_command"]);
|
||||
|
||||
// An MCP server finished starting, and a built-in tool that sorts first appeared too.
|
||||
let mut later = vec![
|
||||
function("memoria__memory_search"),
|
||||
function("exec_command"),
|
||||
function("apply_patch"),
|
||||
function("aaa_new_builtin"),
|
||||
function("list_mcp_resources"),
|
||||
];
|
||||
order.apply(&mut later);
|
||||
assert_eq!(
|
||||
names(&later),
|
||||
vec![
|
||||
"apply_patch",
|
||||
"exec_command",
|
||||
"aaa_new_builtin",
|
||||
"list_mcp_resources",
|
||||
"memoria__memory_search",
|
||||
]
|
||||
);
|
||||
|
||||
// The next request keeps that order exactly.
|
||||
let mut again = later.clone();
|
||||
again.reverse();
|
||||
order.apply(&mut again);
|
||||
assert_eq!(again, later);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_tools_do_not_move_the_others() {
|
||||
let order = ToolOrder::default();
|
||||
let mut first = vec![function("a"), function("b"), function("c")];
|
||||
order.apply(&mut first);
|
||||
let mut without_b = vec![function("c"), function("a")];
|
||||
order.apply(&mut without_b);
|
||||
assert_eq!(names(&without_b), vec!["a", "c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_members_are_sorted() {
|
||||
let order = ToolOrder::default();
|
||||
let mut tools = vec![json!({
|
||||
"type": "namespace",
|
||||
"name": "memoria",
|
||||
"tools": [function("z_tool"), function("a_tool")],
|
||||
})];
|
||||
order.apply(&mut tools);
|
||||
assert_eq!(names(tools[0]["tools"].as_array().unwrap()), vec!["a_tool", "z_tool"]);
|
||||
}
|
||||
}
|
||||
122
akode-rs/core/src/tool_output_clearing.rs
Normal file
122
akode-rs/core/src/tool_output_clearing.rs
Normal file
@@ -0,0 +1,122 @@
|
||||
//! Tool-output clearing before compaction.
|
||||
//!
|
||||
//! The raw output of old tool calls (file listings, logs, test runs) is the bulkiest and least
|
||||
//! useful part of a long history. Before the summary request, outputs older than the most
|
||||
//! recent ones are replaced by a short placeholder: the summarizer reads a much shorter prompt
|
||||
//! (on a CPU server every token of prompt is seconds of waiting) and still sees which tool was
|
||||
//! called with which arguments, since the calls themselves stay.
|
||||
|
||||
use akode_protocol::models::FunctionCallOutputBody;
|
||||
use akode_protocol::models::FunctionCallOutputPayload;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
|
||||
/// Most recent tool outputs kept verbatim.
|
||||
pub(crate) const KEEP_RECENT_TOOL_OUTPUTS: usize = 3;
|
||||
/// Outputs up to this size are kept: the placeholder would not save anything.
|
||||
const MIN_CLEARED_CHARS: usize = 400;
|
||||
|
||||
/// Replaces the body of tool outputs older than the last `keep_recent` with a placeholder.
|
||||
/// Returns the number of characters removed.
|
||||
pub(crate) fn clear_old_tool_outputs(items: &mut [ResponseItem], keep_recent: usize) -> usize {
|
||||
let outputs: Vec<usize> = items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, item)| output_payload(item).is_some())
|
||||
.map(|(index, _)| index)
|
||||
.collect();
|
||||
let old = outputs.len().saturating_sub(keep_recent);
|
||||
let mut removed = 0;
|
||||
for &index in &outputs[..old] {
|
||||
let Some(payload) = output_payload_mut(&mut items[index]) else {
|
||||
continue;
|
||||
};
|
||||
let size = body_chars(&payload.body);
|
||||
if size <= MIN_CLEARED_CHARS {
|
||||
continue;
|
||||
}
|
||||
let placeholder = format!(
|
||||
"[tool output cleared before compaction: {size} characters; run the tool again if it is still needed]"
|
||||
);
|
||||
removed += size.saturating_sub(placeholder.chars().count());
|
||||
payload.body = FunctionCallOutputBody::Text(placeholder);
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
fn output_payload(item: &ResponseItem) -> Option<&FunctionCallOutputPayload> {
|
||||
match item {
|
||||
ResponseItem::FunctionCallOutput { output, .. }
|
||||
| ResponseItem::CustomToolCallOutput { output, .. } => Some(output),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn output_payload_mut(item: &mut ResponseItem) -> Option<&mut FunctionCallOutputPayload> {
|
||||
match item {
|
||||
ResponseItem::FunctionCallOutput { output, .. }
|
||||
| ResponseItem::CustomToolCallOutput { output, .. } => Some(output),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn body_chars(body: &FunctionCallOutputBody) -> usize {
|
||||
match body {
|
||||
FunctionCallOutputBody::Text(text) => text.chars().count(),
|
||||
// Images and other items are bulky too: count them as text of their JSON size.
|
||||
FunctionCallOutputBody::ContentItems(items) => serde_json::to_string(items)
|
||||
.map(|json| json.chars().count())
|
||||
.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn output(call_id: &str, text: &str) -> ResponseItem {
|
||||
ResponseItem::FunctionCallOutput {
|
||||
id: None,
|
||||
call_id: Some(call_id.to_string()),
|
||||
name: None,
|
||||
namespace: None,
|
||||
output: FunctionCallOutputPayload::from_text(text.to_string()),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn text_of(item: &ResponseItem) -> String {
|
||||
output_payload(item)
|
||||
.and_then(|payload| payload.body.to_text())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_large_outputs_become_placeholders_and_recent_ones_stay() {
|
||||
let big = "x".repeat(5_000);
|
||||
let mut items = vec![
|
||||
output("c1", &big),
|
||||
output("c2", "short"),
|
||||
output("c3", &big),
|
||||
output("c4", &big),
|
||||
output("c5", &big),
|
||||
];
|
||||
|
||||
let removed = clear_old_tool_outputs(&mut items, 3);
|
||||
|
||||
assert!(text_of(&items[0]).starts_with("[tool output cleared before compaction: 5000 characters"));
|
||||
assert_eq!(text_of(&items[1]), "short");
|
||||
for item in &items[2..] {
|
||||
assert_eq!(text_of(item), big);
|
||||
}
|
||||
assert!(removed > 4_800, "{removed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_to_clear_with_few_outputs() {
|
||||
let big = "y".repeat(2_000);
|
||||
let mut items = vec![output("c1", &big), output("c2", &big)];
|
||||
assert_eq!(clear_old_tool_outputs(&mut items, 3), 0);
|
||||
assert_eq!(text_of(&items[0]), big);
|
||||
}
|
||||
}
|
||||
@@ -75,13 +75,14 @@ impl PreparedExecCommand {
|
||||
Some("windows") | Some(_) => DangerousCommandPlatform::Windows,
|
||||
None => DangerousCommandPlatform::host(),
|
||||
};
|
||||
session
|
||||
let approval_policy = step.settings.approval_policy();
|
||||
let requirement = session
|
||||
.services
|
||||
.exec_policy
|
||||
.create_exec_approval_requirement_for_shell(
|
||||
ExecApprovalRequest {
|
||||
command: &self.resolved.command,
|
||||
approval_policy: step.settings.approval_policy(),
|
||||
approval_policy,
|
||||
permission_profile: environment.permission_profile().clone(),
|
||||
environment_policy: environment.config().exec_policy.as_ref(),
|
||||
windows_sandbox_level: windows_sandbox_level_for_legacy_checks(
|
||||
@@ -99,7 +100,17 @@ impl PreparedExecCommand {
|
||||
configured_shell,
|
||||
command_platform,
|
||||
)
|
||||
.await
|
||||
.await;
|
||||
// POSIX shells only: the check parses `rm`/`find` and POSIX paths.
|
||||
if command_platform == DangerousCommandPlatform::Posix {
|
||||
return protect_recursive_deletion(
|
||||
requirement,
|
||||
&self.resolved.command,
|
||||
&self.cwd,
|
||||
approval_policy,
|
||||
);
|
||||
}
|
||||
requirement
|
||||
}
|
||||
|
||||
pub(crate) fn approval_action(
|
||||
@@ -316,3 +327,129 @@ impl<'a> ParsedExecCommand<'a> {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursive deletions of protected paths (root, home, repository root, working directory,
|
||||
/// anything outside it, run-time targets) always need a fresh human decision, whatever the
|
||||
/// sandbox, the approval mode or the rules; where nobody can be asked they are refused.
|
||||
fn protect_recursive_deletion(
|
||||
requirement: ExecApprovalRequirement,
|
||||
command: &[String],
|
||||
cwd: &PathUri,
|
||||
approval_policy: akode_protocol::protocol::AskForApproval,
|
||||
) -> ExecApprovalRequirement {
|
||||
use akode_shell_command::recursive_deletion::DeletionContext;
|
||||
use akode_shell_command::recursive_deletion::protected_recursive_deletion;
|
||||
|
||||
if matches!(requirement, ExecApprovalRequirement::Forbidden { .. }) {
|
||||
return requirement;
|
||||
}
|
||||
let Ok(cwd) = cwd.to_abs_path() else {
|
||||
return requirement;
|
||||
};
|
||||
let cwd = cwd.as_path().to_path_buf();
|
||||
let repo_root = cwd
|
||||
.ancestors()
|
||||
.find(|dir| dir.join(".git").exists())
|
||||
.map(Path::to_path_buf);
|
||||
let context = DeletionContext {
|
||||
home: dirs::home_dir(),
|
||||
repo_root,
|
||||
cwd,
|
||||
};
|
||||
let Some(reason) = protected_recursive_deletion(command, &context) else {
|
||||
return requirement;
|
||||
};
|
||||
tracing::warn!(%reason, "protected recursive deletion");
|
||||
// Like the other dangerous commands, the prompt is allowed in granular modes; only
|
||||
// `never` (full access without prompts) has nobody to ask.
|
||||
if matches!(approval_policy, akode_protocol::protocol::AskForApproval::Never) {
|
||||
ExecApprovalRequirement::Forbidden {
|
||||
reason: format!(
|
||||
"rifiutato: {reason}. aKode non esegue cancellazioni ricorsive di percorsi protetti senza la conferma dell'utente: chiedigli di farlo a mano, se serve davvero."
|
||||
),
|
||||
}
|
||||
} else if prompt_is_rejected_by_policy(approval_policy, /*prompt_is_rule*/ true).is_some() {
|
||||
// Granular modes that refuse rule prompts still ask for dangerous commands (as for
|
||||
// `rm -f`): a plain prompt with no reusable rule, so the user still decides.
|
||||
ExecApprovalRequirement::NeedsApproval {
|
||||
reason: Some(format!("{reason}: serve la tua conferma")),
|
||||
proposed_execpolicy_amendment: None,
|
||||
}
|
||||
} else {
|
||||
// A fresh human decision, never a saved rule or an automatic review.
|
||||
ExecApprovalRequirement::NeedsHumanApproval {
|
||||
reason: Some(format!("{reason}: serve la tua conferma")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod recursive_deletion_tests {
|
||||
use super::*;
|
||||
use akode_protocol::protocol::AskForApproval;
|
||||
|
||||
fn zsh(script: &str) -> Vec<String> {
|
||||
vec!["/bin/zsh".to_string(), "-lc".to_string(), script.to_string()]
|
||||
}
|
||||
|
||||
fn skip() -> ExecApprovalRequirement {
|
||||
ExecApprovalRequirement::Skip {
|
||||
bypass_sandbox: false,
|
||||
proposed_execpolicy_amendment: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn cwd() -> PathUri {
|
||||
let dir = std::env::temp_dir().join("akode-rm-guard");
|
||||
PathUri::from_host_native_path(dir).expect("cwd")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_access_refuses_and_other_modes_ask_a_human() {
|
||||
let home = zsh("rm -rf ~");
|
||||
assert!(matches!(
|
||||
protect_recursive_deletion(skip(), &home, &cwd(), AskForApproval::Never),
|
||||
ExecApprovalRequirement::Forbidden { reason } if reason.contains("cartella home")
|
||||
));
|
||||
assert!(matches!(
|
||||
protect_recursive_deletion(skip(), &home, &cwd(), AskForApproval::OnRequest),
|
||||
ExecApprovalRequirement::NeedsHumanApproval { reason: Some(reason) }
|
||||
if reason.contains("cartella home")
|
||||
));
|
||||
// Granular modes without rule prompts still ask (like the other dangerous commands).
|
||||
let granular = AskForApproval::Granular(akode_protocol::protocol::GranularApprovalConfig {
|
||||
sandbox_approval: false,
|
||||
rules: false,
|
||||
skill_approval: false,
|
||||
request_permissions: true,
|
||||
mcp_elicitations: true,
|
||||
});
|
||||
assert!(matches!(
|
||||
protect_recursive_deletion(skip(), &home, &cwd(), granular),
|
||||
ExecApprovalRequirement::NeedsApproval {
|
||||
proposed_execpolicy_amendment: None,
|
||||
..
|
||||
}
|
||||
));
|
||||
// Rules that would allow the command do not lift the protection.
|
||||
assert!(matches!(
|
||||
protect_recursive_deletion(skip(), &zsh("rm -rf $OUT/"), &cwd(), AskForApproval::OnRequest),
|
||||
ExecApprovalRequirement::NeedsHumanApproval { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_commands_keep_their_requirement() {
|
||||
assert!(matches!(
|
||||
protect_recursive_deletion(skip(), &zsh("rm -rf build"), &cwd(), AskForApproval::Never),
|
||||
ExecApprovalRequirement::Skip { .. }
|
||||
));
|
||||
let forbidden = ExecApprovalRequirement::Forbidden {
|
||||
reason: "blocked".to_string(),
|
||||
};
|
||||
assert!(matches!(
|
||||
protect_recursive_deletion(forbidden, &zsh("rm -rf /"), &cwd(), AskForApproval::OnRequest),
|
||||
ExecApprovalRequirement::Forbidden { reason } if reason == "blocked"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -940,10 +940,11 @@ async fn code_mode_only_restricts_prompt_tools() -> Result<()> {
|
||||
let first_body = resp_mock.single_request().body_json();
|
||||
assert_eq!(
|
||||
tool_names(&first_body),
|
||||
// Sorted by name: aKode keeps the tool list in a stable order.
|
||||
vec![
|
||||
"exec".to_string(),
|
||||
"wait".to_string(),
|
||||
"request_user_input".to_string(),
|
||||
"wait".to_string(),
|
||||
"web_search".to_string()
|
||||
]
|
||||
);
|
||||
@@ -3107,10 +3108,11 @@ if (!tool) {
|
||||
let first_body = resp_mock.single_request().body_json();
|
||||
assert_eq!(
|
||||
tool_names(&first_body),
|
||||
// Sorted by name: aKode keeps the tool list in a stable order.
|
||||
vec![
|
||||
"exec".to_string(),
|
||||
"wait".to_string(),
|
||||
"request_user_input".to_string(),
|
||||
"wait".to_string(),
|
||||
"web_search".to_string()
|
||||
]
|
||||
);
|
||||
|
||||
@@ -196,11 +196,13 @@ async fn remote_tool_mode_selector_overrides_feature_flags() -> Result<()> {
|
||||
let code_mode_only_body = response_body_for_remote_model(code_mode_only_model, |_| {}).await?;
|
||||
assert_eq!(
|
||||
tool_names(&code_mode_only_body),
|
||||
// aKode sends the tools sorted by name for a stable prompt prefix.
|
||||
vec![
|
||||
// Code-mode entrypoints.
|
||||
// Code-mode entrypoint.
|
||||
akode_code_mode::PUBLIC_TOOL_NAME.to_string(),
|
||||
akode_code_mode::WAIT_TOOL_NAME.to_string(),
|
||||
"request_user_input".to_string(),
|
||||
// Code-mode entrypoint.
|
||||
akode_code_mode::WAIT_TOOL_NAME.to_string(),
|
||||
// Hosted Responses tool.
|
||||
"web_search".to_string(),
|
||||
]
|
||||
|
||||
@@ -267,17 +267,18 @@ async fn prompt_tools_are_consistent_across_requests(
|
||||
.await?;
|
||||
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
|
||||
|
||||
let mut expected_tools_names = vec!["exec_command", "write_stdin"];
|
||||
// aKode sends the tools sorted by name (top-level tools before namespaced ones), so the
|
||||
// cached prompt prefix does not depend on the registration order.
|
||||
let mut expected_tools_names = vec![
|
||||
"apply_patch",
|
||||
"exec_command",
|
||||
"request_user_input",
|
||||
"tool_search",
|
||||
];
|
||||
if expected_update_plan_enabled {
|
||||
expected_tools_names.push("update_plan");
|
||||
}
|
||||
expected_tools_names.extend([
|
||||
"request_user_input",
|
||||
"apply_patch",
|
||||
"view_image",
|
||||
"tool_search",
|
||||
"web_search",
|
||||
]);
|
||||
expected_tools_names.extend(["view_image", "web_search", "write_stdin"]);
|
||||
let body0 = req1.single_request().body_json();
|
||||
|
||||
assert_eq!(req1.single_request().instructions_text(), base_instructions);
|
||||
|
||||
@@ -1779,7 +1779,9 @@ async fn ready_mcp_turn_skips_pending_optional_mcp_without_cached_tools() -> any
|
||||
.await
|
||||
.context("the calendar MCP server should finish starting before the first turn")??;
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(5), fixture.submit_turn("hello"))
|
||||
// The first turn waits for pending optional servers at most for the startup grace
|
||||
// (5 s in aKode, so the first request has the complete tool list), never longer.
|
||||
tokio::time::timeout(Duration::from_secs(15), fixture.submit_turn("hello"))
|
||||
.await
|
||||
.context("a pending optional MCP must not block the first turn")??;
|
||||
let body = response_mock.single_request().body_json();
|
||||
|
||||
@@ -15,16 +15,16 @@ Settings:
|
||||
stream: true
|
||||
text: {"verbosity":"low"}
|
||||
tool_choice: "auto"
|
||||
tools (9; hash=5edab7fdbfe2dd93):
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
- function/new_context: Catalog context guidance.; args=[]; hash=8d300f346fb11d84
|
||||
- function/get_context_remaining: Catalog context guidance.; args=[]; hash=802b1cf4a796b439
|
||||
tools (9; hash=f33c03d87ec35581):
|
||||
- custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/get_context_remaining: Catalog context guidance.; args=[]; hash=802b1cf4a796b439
|
||||
- function/new_context: Catalog context guidance.; args=[]; hash=8d300f346fb11d84
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
- tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- web_search; hash=f103e327c6870a46
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
-- request 1 (turn) --
|
||||
00:message/developer:
|
||||
<MODEL_INSTRUCTIONS>
|
||||
@@ -50,9 +50,9 @@ Settings:
|
||||
## Window 2 (after request 1)
|
||||
Settings: relative to window 1
|
||||
model: "context-tools-updated"
|
||||
tools (9; hash=829060c0abfc8021):
|
||||
~ function/new_context; args=[]; hash=b9263827b0adbb78
|
||||
tools (9; hash=07305d52033debdd):
|
||||
~ function/get_context_remaining; args=[]; hash=3e96d66806c56bdd
|
||||
~ function/new_context; args=[]; hash=b9263827b0adbb78
|
||||
-- request 2 (turn) --
|
||||
00:message/developer:
|
||||
<MODEL_INSTRUCTIONS>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
---
|
||||
source: core/tests/suite/scenarios_dynamic_tools.rs
|
||||
assertion_line: 173
|
||||
expression: "context_snapshot::format_request_history_snapshot(\"A pending release call survives replacement with deployment. The next step uses deployment. Replacement and clearing each survive restart.\",\n&requests,\n&ContextSnapshotOptions::default().rewrite_known_segments().include_request_settings(),)"
|
||||
---
|
||||
Scenario: A pending release call survives replacement with deployment. The next step uses deployment. Replacement and clearing each survive restart.
|
||||
@@ -16,16 +15,18 @@ Settings:
|
||||
stream: true
|
||||
text: {"verbosity":"low"}
|
||||
tool_choice: "auto"
|
||||
tools (10; hash=b0582dd610604bdb):
|
||||
tools (10; hash=99b5ba849261f041):
|
||||
- custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- function/release: Check release.; args=[]; hash=4c6f91a1a21d2a65
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
- function/request_user_input_async: Ask the user one or more questions during ongoing work. Use this tool only to request missing inf...; args=[questions]; hash=d6d74f33db330162
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- web_search; hash=f103e327c6870a46
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- namespace/clock: Tools for reading and waiting on time.; hash=a80435c7a3a3943f
|
||||
- function/curr_time
|
||||
- function/sleep
|
||||
- custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- namespace/collaboration: Tools for spawning and managing sub-agents.; hash=2c8d6295978dbe63
|
||||
- function/followup_task
|
||||
- function/interrupt_agent
|
||||
@@ -33,8 +34,6 @@ Settings:
|
||||
- function/send_message
|
||||
- function/spawn_agent
|
||||
- function/wait_agent
|
||||
- function/release: Check release.; args=[]; hash=4c6f91a1a21d2a65
|
||||
- web_search; hash=f103e327c6870a46
|
||||
-- request 1 (turn) --
|
||||
00:message/developer:
|
||||
<MODEL_INSTRUCTIONS>
|
||||
@@ -51,7 +50,7 @@ Settings:
|
||||
|
||||
## Window 2 (after request 1)
|
||||
Settings: relative to window 1
|
||||
tools (10; hash=d346da81584ec2d3):
|
||||
tools (10; hash=2f34710828e791df):
|
||||
- removed function/release
|
||||
+ function/deployment: Check deployment.; args=[]; hash=2e9a71e9a20e43ad
|
||||
-- request 2 (turn) --
|
||||
@@ -72,16 +71,37 @@ Settings: relative to window 1
|
||||
-- request 3 (turn) --
|
||||
08:function_call/deployment:{}
|
||||
09:function_call_output:Deployment ready.
|
||||
|
||||
## Window 3 (after request 3)
|
||||
Settings: relative to window 2
|
||||
tools (10; hash=966235d04fff4485):
|
||||
- order changed
|
||||
-- request 4 (turn) --
|
||||
00:message/developer:
|
||||
<MODEL_INSTRUCTIONS>
|
||||
01:message/developer[2]:
|
||||
[01] <PERMISSIONS_INSTRUCTIONS>
|
||||
[02] <COLLABORATION_MODE>
|
||||
02:message/developer:
|
||||
<MULTI_AGENT_ROLE>
|
||||
03:message/developer:
|
||||
<MULTI_AGENT_MODE>
|
||||
04:message/user:
|
||||
Check the release and deployment.
|
||||
05:configuration_update:reasoning={"effort":"low"}
|
||||
06:function_call/release:{}
|
||||
07:function_call_output:Release ready.
|
||||
08:function_call/deployment:{}
|
||||
09:function_call_output:Deployment ready.
|
||||
10:message/assistant:
|
||||
Both checks passed.
|
||||
11:message/user:
|
||||
Which check is available now?
|
||||
12:configuration_update:reasoning={"effort":"low"}
|
||||
|
||||
## Window 3 (after request 4)
|
||||
Settings: relative to window 2
|
||||
tools (9; hash=79c1c8bb10577e35):
|
||||
## Window 4 (after request 4)
|
||||
Settings: relative to window 3
|
||||
tools (9; hash=653a7a527be8666f):
|
||||
- removed function/deployment
|
||||
-- request 5 (turn) --
|
||||
00:message/developer:
|
||||
|
||||
@@ -15,14 +15,14 @@ Settings:
|
||||
stream: true
|
||||
text: {"verbosity":"low"}
|
||||
tool_choice: "auto"
|
||||
tools (7; hash=c8fad8866d479502):
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=7c8f464569dbaa9c
|
||||
tools (7; hash=ce2e8d0c67677152):
|
||||
- custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=7c8f464569dbaa9c
|
||||
- tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- web_search; hash=f103e327c6870a46
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
-- request 1 (turn) --
|
||||
00:message/developer:
|
||||
<MODEL_INSTRUCTIONS>
|
||||
|
||||
@@ -15,14 +15,14 @@ Settings:
|
||||
stream: true
|
||||
text: {"verbosity":"low"}
|
||||
tool_choice: "auto"
|
||||
tools (7; hash=4bc85f667bb09668):
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
tools (7; hash=764c6164350ee754):
|
||||
- custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
- tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- web_search; hash=f103e327c6870a46
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
-- request 1 (turn) --
|
||||
00:message/developer:
|
||||
You are Codex, a coding agent based on GPT-5. You and the user share one workspace, and your job is to c...rate with them until their goal is genuinely handled. [hash=2a3efec66e7f8963]
|
||||
|
||||
@@ -14,18 +14,18 @@ Settings:
|
||||
store: false
|
||||
stream: true
|
||||
tool_choice: "auto"
|
||||
tools (6; hash=1ea0fa9abde186d4):
|
||||
tools (6; hash=8cd55cc11303929a):
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- web_search; hash=8586237e354ee5ed
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- namespace/multi_agent_v1: Tools for spawning and managing sub-agents.; hash=94c598b3c6ca141b
|
||||
- function/close_agent
|
||||
- function/resume_agent
|
||||
- function/send_input
|
||||
- function/spawn_agent
|
||||
- function/wait_agent
|
||||
- web_search; hash=8586237e354ee5ed
|
||||
-- request 1 (turn) --
|
||||
00:message/developer:
|
||||
Test model instructions.
|
||||
|
||||
@@ -14,18 +14,18 @@ Settings:
|
||||
store: false
|
||||
stream: true
|
||||
tool_choice: "auto"
|
||||
tools (6; hash=d558f97965d6db2b):
|
||||
tools (6; hash=7a20be349fb5986f):
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- web_search; hash=8586237e354ee5ed
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- namespace/multi_agent_v1: Tools for spawning and managing sub-agents.; hash=6ac4ec60e68e50c0
|
||||
- function/close_agent
|
||||
- function/resume_agent
|
||||
- function/send_input
|
||||
- function/spawn_agent
|
||||
- function/wait_agent
|
||||
- web_search; hash=8586237e354ee5ed
|
||||
-- request 1 (turn) --
|
||||
00:message/developer:
|
||||
<MODEL_INSTRUCTIONS>
|
||||
@@ -39,7 +39,7 @@ Settings:
|
||||
## Window 2 (after request 1: input diverged at item 00)
|
||||
Settings: relative to window 1
|
||||
prompt_cache_key: "<PROMPT_CACHE_KEY 2>"
|
||||
tools (7; hash=7cc079a7a7aa5604):
|
||||
tools (7; hash=4cb623b0b7a8ea0a):
|
||||
+ custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
|
||||
-- request 2 (turn) --
|
||||
00:message/developer:
|
||||
@@ -54,7 +54,7 @@ Settings: relative to window 1
|
||||
## Window 3 (after request 2: input diverged at item 00)
|
||||
Settings: relative to window 2
|
||||
prompt_cache_key: "<PROMPT_CACHE_KEY 3>"
|
||||
tools (6; hash=d558f97965d6db2b):
|
||||
tools (6; hash=7a20be349fb5986f):
|
||||
- removed custom/apply_patch
|
||||
-- request 3 (turn) --
|
||||
00:message/developer:
|
||||
@@ -82,7 +82,7 @@ Settings: relative to window 3
|
||||
## Window 5 (after request 4: input diverged at item 00)
|
||||
Settings: relative to window 4
|
||||
prompt_cache_key: "<PROMPT_CACHE_KEY 5>"
|
||||
tools (7; hash=7cc079a7a7aa5604):
|
||||
tools (7; hash=4cb623b0b7a8ea0a):
|
||||
+ custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
|
||||
-- request 5 (turn) --
|
||||
00:message/developer:
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
---
|
||||
source: core/tests/suite/scenarios_skill_catalog_dedup.rs
|
||||
assertion_line: 518
|
||||
expression: "context_snapshot::format_context_snapshot(\"A repository skill appears after approval. The next turn withdraws it, then restores it after reapproval.\",\n&bodies.iter().map(context_snapshot::SnapshotEntry::body).collect::<Vec<_>>(),\n&ContextSnapshotOptions::default().include_request_settings(),)"
|
||||
---
|
||||
Scenario: A repository skill appears after approval. The next turn withdraws it, then restores it after reapproval.
|
||||
@@ -16,15 +15,15 @@ Settings:
|
||||
stream: true
|
||||
text: {"verbosity":"low"}
|
||||
tool_choice: "auto"
|
||||
tools (8; hash=b8620d538c3808d4):
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
- function/request_permissions: Request additional filesystem or network permissions from the user and wait for the client to gra...; args=[environment_id, permissions, reason]; hash=2ed084e2fc688abd
|
||||
tools (8; hash=9fd6c407aefab802):
|
||||
- custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/request_permissions: Request additional filesystem or network permissions from the user and wait for the client to gra...; args=[environment_id, permissions, reason]; hash=2ed084e2fc688abd
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
- tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- web_search; hash=f103e327c6870a46
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
-- request 1 (request) --
|
||||
00:message/developer:
|
||||
You are Codex, a coding agent based on GPT-5. You and the user share one workspace, and your job is to c...rate with them until their goal is genuinely handled. [hash=2a3efec66e7f8963]
|
||||
|
||||
@@ -15,17 +15,17 @@ Settings:
|
||||
stream: true
|
||||
text: {"verbosity":"low"}
|
||||
tool_choice: "auto"
|
||||
tools (10; hash=9f8074d045f3bd93):
|
||||
tools (10; hash=e36030ebe33fb877):
|
||||
- custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- function/list_mcp_resources: Lists resources provided by MCP servers. Resources allow servers to share data that provides cont...; args=[cursor, server]; hash=6792edaff13561bd
|
||||
- function/list_mcp_resource_templates: Lists resource templates provided by MCP servers. Parameterized resource templates allow servers ...; args=[cursor, server]; hash=60f17c90ef7a4ebb
|
||||
- function/list_mcp_resources: Lists resources provided by MCP servers. Resources allow servers to share data that provides cont...; args=[cursor, server]; hash=6792edaff13561bd
|
||||
- function/read_mcp_resource: Read a specific resource from an MCP server given the server name and resource URI.; args=[server, uri]; hash=24246896b39008ae
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
- custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- web_search; hash=f103e327c6870a46
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
-- request 1 (turn) --
|
||||
00:message/developer:
|
||||
<MODEL_INSTRUCTIONS>
|
||||
|
||||
@@ -15,15 +15,15 @@ Settings:
|
||||
stream: true
|
||||
text: {"verbosity":"low"}
|
||||
tool_choice: "auto"
|
||||
tools (7; hash=4be6331020d8f43a):
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
tools (7; hash=09449514b073027c):
|
||||
- custom/apply_patch: The `apply_patch` tool can be used to edit files. This is a FREEFORM tool, so do not wrap the pat...; hash=dea9f12b0111a4ba
|
||||
- function/exec_command: Runs a command in a PTY, returning output or a session ID for ongoing interaction.; args=[cmd, justification, login, max_output_tokens, prefix_rule, sandbox_permissions, shell, tty, workdir, yield_time_ms]; hash=c04108e51a8548c5
|
||||
- function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
|
||||
- tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7
|
||||
- function/view_image: View a local image file from the filesystem when visual inspection is needed. Use this for images...; args=[path]; hash=1908de9c0be7118a
|
||||
- function/write_stdin: Writes characters to an existing unified exec session and returns recent output.; args=[chars, max_output_tokens, session_id, yield_time_ms]; hash=7fb62d8a3e2df4e2
|
||||
- namespace/web: Tools in the web namespace.; hash=dd6e98ab1f4ddce6
|
||||
- function/run
|
||||
- tool_search: # Tool discovery Searches over deferred tool metadata with BM25 and exposes matching tools for t...; args=[limit, query]; hash=b573ed69c0b0e6c7
|
||||
-- request 1 (turn) --
|
||||
00:message/developer:
|
||||
<MODEL_INSTRUCTIONS>
|
||||
|
||||
@@ -370,7 +370,15 @@ impl HttpClientBuilder {
|
||||
}
|
||||
|
||||
fn base_reqwest_builder(self) -> reqwest::ClientBuilder {
|
||||
let mut builder = reqwest::Client::builder();
|
||||
// No TCP keepalive: reqwest probes after 15 s of silence, 3 times every 15 s, and drops
|
||||
// the connection when nobody answers. Some VPNs (NetBird towards the imeAI server) do
|
||||
// not pass the probes, so every response that started after more than 60 s (a local
|
||||
// model reading a long prompt) was cut and sent again from scratch. Dead streams are
|
||||
// detected by the provider's idle timeout instead.
|
||||
let mut builder = reqwest::Client::builder()
|
||||
.tcp_keepalive(None)
|
||||
.tcp_keepalive_interval(None)
|
||||
.tcp_keepalive_retries(None);
|
||||
#[cfg(windows)]
|
||||
if let Some(path) = self.windows_proxy_pipe_path {
|
||||
builder = builder.windows_named_pipe(path);
|
||||
|
||||
@@ -79,6 +79,10 @@ pub fn read_managed_residency_requirement() -> Option<ResidencyRequirement> {
|
||||
}
|
||||
|
||||
const DEFAULT_STREAM_IDLE_TIMEOUT_MS: u64 = 300_000;
|
||||
/// Local servers (loopback, private network, `.local`/`.lan`) read long prompts on CPU: a cold
|
||||
/// prompt of 15k tokens took more than 3 minutes before the first byte. They get a generous
|
||||
/// default, still overridable with `stream_idle_timeout_ms`.
|
||||
const DEFAULT_LOCAL_STREAM_IDLE_TIMEOUT_MS: u64 = 1_800_000;
|
||||
const DEFAULT_STREAM_MAX_RETRIES: u64 = 5;
|
||||
const DEFAULT_REQUEST_MAX_RETRIES: u64 = 4;
|
||||
const DEFAULT_CREDENTIAL_EXPORT_TIMEOUT_MS: u64 = 30_000;
|
||||
@@ -198,7 +202,9 @@ pub struct ModelProviderInfo {
|
||||
/// Number of times to retry reconnecting a dropped streaming response before failing.
|
||||
pub stream_max_retries: Option<u64>,
|
||||
/// Idle timeout (in milliseconds) to wait for activity on a streaming response before treating
|
||||
/// the connection as lost.
|
||||
/// the connection as lost. It also bounds the wait for the first response (headers). Any
|
||||
/// bytes count as activity, including SSE comments and progress events. Defaults to 5
|
||||
/// minutes, or 30 minutes for local servers.
|
||||
pub stream_idle_timeout_ms: Option<u64>,
|
||||
/// Maximum time (in milliseconds) to wait for a websocket connection attempt before treating
|
||||
/// it as failed.
|
||||
@@ -521,11 +527,23 @@ impl ModelProviderInfo {
|
||||
.min(MAX_STREAM_MAX_RETRIES)
|
||||
}
|
||||
|
||||
/// Effective idle timeout for streaming responses.
|
||||
/// Effective idle timeout for streaming responses (and for the first response).
|
||||
pub fn stream_idle_timeout(&self) -> Duration {
|
||||
self.stream_idle_timeout_ms
|
||||
.map(Duration::from_millis)
|
||||
.unwrap_or(Duration::from_millis(DEFAULT_STREAM_IDLE_TIMEOUT_MS))
|
||||
.unwrap_or_else(|| {
|
||||
Duration::from_millis(if self.is_local_endpoint() {
|
||||
DEFAULT_LOCAL_STREAM_IDLE_TIMEOUT_MS
|
||||
} else {
|
||||
DEFAULT_STREAM_IDLE_TIMEOUT_MS
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `base_url` points to this machine or the local network: loopback, private IPv4,
|
||||
/// `localhost`, `.localhost`, `.local`, `.lan`.
|
||||
pub fn is_local_endpoint(&self) -> bool {
|
||||
self.base_url.as_deref().is_some_and(is_local_base_url)
|
||||
}
|
||||
|
||||
/// Effective timeout for websocket connect attempts.
|
||||
@@ -656,3 +674,25 @@ pub fn create_oss_provider_with_base_url(base_url: &str, wire_api: WireApi) -> M
|
||||
#[cfg(test)]
|
||||
#[path = "model_provider_info_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
/// See [`ModelProviderInfo::is_local_endpoint`].
|
||||
pub fn is_local_base_url(base_url: &str) -> bool {
|
||||
let Ok(uri) = base_url.trim().parse::<http::Uri>() else {
|
||||
return false;
|
||||
};
|
||||
let Some(host) = uri.host() else {
|
||||
return false;
|
||||
};
|
||||
let host = host.trim_start_matches('[').trim_end_matches(']');
|
||||
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
|
||||
return match ip {
|
||||
std::net::IpAddr::V4(ip) => ip.is_loopback() || ip.is_private(),
|
||||
std::net::IpAddr::V6(ip) => ip.is_loopback(),
|
||||
};
|
||||
}
|
||||
let host = host.trim_end_matches('.').to_ascii_lowercase();
|
||||
host == "localhost"
|
||||
|| host.ends_with(".localhost")
|
||||
|| host.ends_with(".local")
|
||||
|| host.ends_with(".lan")
|
||||
}
|
||||
|
||||
@@ -505,3 +505,30 @@ display_name = "Flint"
|
||||
assert_eq!(settings.display_name.as_deref(), Some("Flint"));
|
||||
assert!(provider.model_settings("other").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_providers_get_a_generous_idle_timeout() {
|
||||
let provider = |base_url: &str| -> ModelProviderInfo {
|
||||
toml::from_str(&format!("name = \"x\"\nbase_url = \"{base_url}\"\n")).expect("provider")
|
||||
};
|
||||
for local in [
|
||||
"http://192.168.40.25:8080/v1",
|
||||
"http://127.0.0.1:8080/v1",
|
||||
"http://localhost:11434/v1",
|
||||
"http://[::1]:1234/v1",
|
||||
"http://imeai.lan/v1",
|
||||
] {
|
||||
assert_eq!(
|
||||
provider(local).stream_idle_timeout(),
|
||||
Duration::from_secs(30 * 60),
|
||||
"{local}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
provider("https://openrouter.ai/api/v1").stream_idle_timeout(),
|
||||
Duration::from_secs(5 * 60)
|
||||
);
|
||||
let mut configured = provider("http://192.168.40.25:8080/v1");
|
||||
configured.stream_idle_timeout_ms = Some(90_000);
|
||||
assert_eq!(configured.stream_idle_timeout(), Duration::from_secs(90));
|
||||
}
|
||||
|
||||
@@ -44,3 +44,22 @@ fn tool_namespaces_are_flattened_unless_the_provider_declares_them() {
|
||||
});
|
||||
assert!(ProviderCapabilities::from_config(&info).tool_namespaces);
|
||||
}
|
||||
|
||||
/// Compaction runs on the configured provider: local and self-hosted servers use the inline
|
||||
/// summary on their own `/responses` (never a remote compaction endpoint).
|
||||
#[test]
|
||||
fn local_providers_compact_inline_on_their_own_endpoint() {
|
||||
for (name, base_url) in [
|
||||
("imeAI", "http://192.168.40.25:8080/v1"),
|
||||
("ollama", "http://localhost:11434/v1"),
|
||||
("lmstudio", "http://localhost:1234/v1"),
|
||||
("openrouter", "https://openrouter.ai/api/v1"),
|
||||
] {
|
||||
let info = ModelProviderInfo::create_responses_provider(name, Some(base_url.to_string()));
|
||||
assert_eq!(
|
||||
ProviderCapabilities::from_config(&info).remote_compaction,
|
||||
RemoteCompactionSupport::Unsupported,
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,4 +6,5 @@ mod powershell_parser;
|
||||
mod powershell_tree_sitter;
|
||||
|
||||
pub mod is_dangerous_command;
|
||||
pub mod recursive_deletion;
|
||||
pub(crate) use powershell_tree_sitter::try_parse_powershell_commands;
|
||||
|
||||
358
akode-rs/shell-command/src/command_safety/recursive_deletion.rs
Normal file
358
akode-rs/shell-command/src/command_safety/recursive_deletion.rs
Normal file
@@ -0,0 +1,358 @@
|
||||
//! Path protection for recursive deletions (`rm -r`, `rm -rf`, `find ... -delete`).
|
||||
//!
|
||||
//! The worst documented agent accidents are recursive deletions generated by the agent itself:
|
||||
//! a wrong `~` expansion, an empty variable (`rm -rf $DIR/`), a cleanup that climbs out of the
|
||||
//! project. Pattern blocklists do not see variables; this check resolves each target against
|
||||
//! the working directory and protects, whatever the sandbox or approval mode:
|
||||
//! - the filesystem root and the home directory (and their ancestors);
|
||||
//! - the repository root and the working directory itself (and their ancestors);
|
||||
//! - anything outside the working directory;
|
||||
//! - targets that are only known at run time (variables, command substitution, `xargs`).
|
||||
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::bash::extract_bash_command;
|
||||
|
||||
/// Where the command runs.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DeletionContext {
|
||||
pub cwd: PathBuf,
|
||||
pub home: Option<PathBuf>,
|
||||
pub repo_root: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Returns why the command needs an explicit confirmation (or must be refused when nobody can
|
||||
/// confirm), or `None` when it does not recursively delete a protected path.
|
||||
pub fn protected_recursive_deletion(command: &[String], context: &DeletionContext) -> Option<String> {
|
||||
let script = match extract_bash_command(command) {
|
||||
Some((_, script)) => script.to_string(),
|
||||
None => shlex::try_join(command.iter().map(String::as_str))
|
||||
.unwrap_or_else(|_| command.join(" ")),
|
||||
};
|
||||
for segment in split_segments(&script) {
|
||||
let words = shlex::split(&segment).unwrap_or_else(|| {
|
||||
segment
|
||||
.split_whitespace()
|
||||
.map(ToString::to_string)
|
||||
.collect()
|
||||
});
|
||||
for targets in deletion_targets(&words) {
|
||||
if let Some(reason) = protected_targets(&targets, context) {
|
||||
return Some(reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Targets of the recursive deletions in one simple command. An empty list means the targets
|
||||
/// are not in the command line (for example `xargs rm -rf`).
|
||||
fn deletion_targets(words: &[String]) -> Vec<Vec<String>> {
|
||||
let mut found = Vec::new();
|
||||
for (index, word) in words.iter().enumerate() {
|
||||
match executable_name(strip_substitution(word)) {
|
||||
"rm" => {
|
||||
let args = &words[index + 1..];
|
||||
let mut recursive = false;
|
||||
let mut targets = Vec::new();
|
||||
let mut options_done = false;
|
||||
for arg in args {
|
||||
if !options_done && arg == "--" {
|
||||
options_done = true;
|
||||
} else if !options_done && arg == "--recursive" {
|
||||
recursive = true;
|
||||
} else if !options_done && arg.starts_with("--") {
|
||||
} else if !options_done && arg.starts_with('-') && arg.len() > 1 {
|
||||
recursive |= arg.contains('r') || arg.contains('R');
|
||||
} else {
|
||||
targets.push(arg.clone());
|
||||
}
|
||||
}
|
||||
if recursive {
|
||||
found.push(targets);
|
||||
}
|
||||
}
|
||||
"find" => {
|
||||
let args = &words[index + 1..];
|
||||
let deletes = args.iter().enumerate().any(|(position, arg)| {
|
||||
arg == "-delete"
|
||||
|| (matches!(arg.as_str(), "-exec" | "-execdir" | "-ok" | "-okdir")
|
||||
&& args
|
||||
.get(position + 1)
|
||||
.is_some_and(|next| executable_name(next) == "rm"))
|
||||
});
|
||||
if deletes {
|
||||
let roots: Vec<String> = args
|
||||
.iter()
|
||||
.take_while(|arg| !arg.starts_with('-') && *arg != "(" && *arg != "!")
|
||||
.cloned()
|
||||
.collect();
|
||||
found.push(if roots.is_empty() {
|
||||
vec![".".to_string()]
|
||||
} else {
|
||||
roots
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn protected_targets(targets: &[String], context: &DeletionContext) -> Option<String> {
|
||||
if targets.is_empty() {
|
||||
return Some(
|
||||
"cancellazione ricorsiva di percorsi non indicati nel comando (calcolati a runtime)"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
for target in targets {
|
||||
if target.starts_with('~') && target != "~" && !target.starts_with("~/") {
|
||||
return Some(format!(
|
||||
"cancellazione ricorsiva di `{target}`: colpisce la cartella home di un altro utente"
|
||||
));
|
||||
}
|
||||
let Some(path) = resolve(target, context) else {
|
||||
return Some(format!(
|
||||
"cancellazione ricorsiva di `{target}`, un percorso calcolato a runtime (variabile o sottocomando)"
|
||||
));
|
||||
};
|
||||
let cwd = normalize(&context.cwd);
|
||||
let what = if path == Path::new("/") {
|
||||
Some("la radice del filesystem".to_string())
|
||||
} else if context
|
||||
.home
|
||||
.as_ref()
|
||||
.is_some_and(|home| normalize(home).starts_with(&path))
|
||||
{
|
||||
Some("la cartella home".to_string())
|
||||
} else if context
|
||||
.repo_root
|
||||
.as_ref()
|
||||
.is_some_and(|root| normalize(root).starts_with(&path))
|
||||
{
|
||||
Some("la radice del repository".to_string())
|
||||
} else if cwd.starts_with(&path) {
|
||||
Some("la cartella di lavoro".to_string())
|
||||
} else if !path.starts_with(&cwd) {
|
||||
Some(format!("un percorso fuori dalla cartella di lavoro ({})", cwd.display()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(what) = what {
|
||||
return Some(format!(
|
||||
"cancellazione ricorsiva di `{target}`: colpisce {what}"
|
||||
));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Absolute, lexically normalized target; `None` when it depends on run-time values. A glob
|
||||
/// stands for the directory whose contents it matches (`~/*` is the home directory).
|
||||
fn resolve(target: &str, context: &DeletionContext) -> Option<PathBuf> {
|
||||
let home = context.home.as_ref();
|
||||
let expanded = if target == "~" {
|
||||
home?.clone()
|
||||
} else if let Some(rest) = target.strip_prefix("~/") {
|
||||
home?.join(rest)
|
||||
} else if let Some(rest) = target
|
||||
.strip_prefix("$HOME")
|
||||
.or_else(|| target.strip_prefix("${HOME}"))
|
||||
&& (rest.is_empty() || rest.starts_with('/'))
|
||||
{
|
||||
home?.join(rest.trim_start_matches('/'))
|
||||
} else {
|
||||
PathBuf::from(target)
|
||||
};
|
||||
let text = expanded.to_string_lossy();
|
||||
if text.contains('$') || text.contains('`') {
|
||||
return None;
|
||||
}
|
||||
let absolute = if expanded.is_absolute() {
|
||||
expanded
|
||||
} else {
|
||||
context.cwd.join(expanded)
|
||||
};
|
||||
// Cut at the first component with a glob: the deletion empties that directory.
|
||||
let mut path = PathBuf::new();
|
||||
for component in absolute.components() {
|
||||
let text = component.as_os_str().to_string_lossy();
|
||||
if text.contains(['*', '?', '[', '{']) {
|
||||
break;
|
||||
}
|
||||
path.push(component);
|
||||
}
|
||||
Some(normalize(&path))
|
||||
}
|
||||
|
||||
fn normalize(path: &Path) -> PathBuf {
|
||||
let mut out = PathBuf::new();
|
||||
for component in path.components() {
|
||||
match component {
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
out.pop();
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
if out.as_os_str().is_empty() {
|
||||
PathBuf::from("/")
|
||||
} else {
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn executable_name(word: &str) -> &str {
|
||||
word.rsplit('/').next().unwrap_or(word)
|
||||
}
|
||||
|
||||
/// `$(rm`, `` `rm ``, `(rm` and `{rm` start a command too.
|
||||
fn strip_substitution(word: &str) -> &str {
|
||||
word.trim_start_matches(['$', '(', '`', '{'])
|
||||
}
|
||||
|
||||
/// Splits a script into simple commands at `;`, `&`, `|`, newlines and parentheses outside
|
||||
/// quotes. Coarse on purpose: when in doubt it splits, and every piece is checked.
|
||||
fn split_segments(script: &str) -> Vec<String> {
|
||||
let mut segments = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut quote: Option<char> = None;
|
||||
let mut escaped = false;
|
||||
// Inside `${...}`: its closing brace does not end a command.
|
||||
let mut in_parameter = false;
|
||||
for ch in script.chars() {
|
||||
if escaped {
|
||||
current.push(ch);
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
if in_parameter {
|
||||
current.push(ch);
|
||||
in_parameter = ch != '}';
|
||||
continue;
|
||||
}
|
||||
if ch == '{' && quote != Some('\'') && current.ends_with('$') {
|
||||
current.push(ch);
|
||||
in_parameter = true;
|
||||
continue;
|
||||
}
|
||||
match (quote, ch) {
|
||||
(_, '\\') if quote != Some('\'') => {
|
||||
current.push(ch);
|
||||
escaped = true;
|
||||
}
|
||||
(Some(open), _) if ch == open => {
|
||||
current.push(ch);
|
||||
quote = None;
|
||||
}
|
||||
(Some(_), _) => current.push(ch),
|
||||
(None, '\'' | '"') => {
|
||||
current.push(ch);
|
||||
quote = Some(ch);
|
||||
}
|
||||
(None, ';' | '&' | '|' | '\n' | ')' | '}') => {
|
||||
segments.push(std::mem::take(&mut current));
|
||||
}
|
||||
(None, _) => current.push(ch),
|
||||
}
|
||||
}
|
||||
segments.push(current);
|
||||
segments
|
||||
.into_iter()
|
||||
.filter(|segment| !segment.trim().is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn context() -> DeletionContext {
|
||||
DeletionContext {
|
||||
cwd: PathBuf::from("/Users/andrea/progetto/sub"),
|
||||
home: Some(PathBuf::from("/Users/andrea")),
|
||||
repo_root: Some(PathBuf::from("/Users/andrea/progetto")),
|
||||
}
|
||||
}
|
||||
|
||||
fn zsh(script: &str) -> Vec<String> {
|
||||
vec!["/bin/zsh".to_string(), "-lc".to_string(), script.to_string()]
|
||||
}
|
||||
|
||||
fn check(script: &str) -> Option<String> {
|
||||
protected_recursive_deletion(&zsh(script), &context())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protects_root_home_repo_and_cwd() {
|
||||
for (script, what) in [
|
||||
("rm -rf /", "la radice del filesystem"),
|
||||
("rm -rf ~", "la cartella home"),
|
||||
("rm -rf ~/", "la cartella home"),
|
||||
("rm -rf $HOME", "la cartella home"),
|
||||
("rm -fr ${HOME}/", "la cartella home"),
|
||||
("rm -r /Users", "la cartella home"),
|
||||
("rm -rf ~/*", "la cartella home"),
|
||||
("rm -rf /Users/andrea/progetto", "la radice del repository"),
|
||||
("rm -rf ..", "la radice del repository"),
|
||||
("rm -rf .", "la cartella di lavoro"),
|
||||
("rm -rf *", "la cartella di lavoro"),
|
||||
("rm -rf ./", "la cartella di lavoro"),
|
||||
("sudo rm -Rf /", "la radice del filesystem"),
|
||||
("/bin/rm --recursive --force ~", "la cartella home"),
|
||||
("find ~ -name '*.tmp' -delete", "la cartella home"),
|
||||
("find / -exec rm -rf {} +", "la radice del filesystem"),
|
||||
] {
|
||||
let reason = check(script).unwrap_or_else(|| panic!("{script} not protected"));
|
||||
assert!(reason.contains(what), "{script}: {reason}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protects_outside_cwd_and_run_time_targets() {
|
||||
for script in [
|
||||
"rm -rf /tmp/build",
|
||||
"rm -rf ../../altro",
|
||||
"rm -rf ~/Documenti",
|
||||
"rm -rf ~utente",
|
||||
"rm -rf $DIR/",
|
||||
"rm -rf \"$BUILD_DIR\"",
|
||||
"rm -rf `pwd`/x",
|
||||
"cd x && rm -rf $(dirname a)/b",
|
||||
"ls | xargs rm -rf",
|
||||
"echo $(rm -rf ~)",
|
||||
"true; rm -rf /etc",
|
||||
] {
|
||||
assert!(check(script).is_some(), "{script} not protected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allows_deletions_inside_the_working_directory() {
|
||||
for script in [
|
||||
"rm -rf target",
|
||||
"rm -rf ./build dist/*.o",
|
||||
"rm -rf /Users/andrea/progetto/sub/cache",
|
||||
"rm -f file.txt /tmp/x",
|
||||
"rm -r -- node_modules",
|
||||
"find . -name '*.pyc' -print",
|
||||
"find build -name '*.o' -delete",
|
||||
"cargo clean && rm -rf out",
|
||||
"echo 'rm -rf /'",
|
||||
] {
|
||||
assert_eq!(check(script), None, "{script}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_argv_is_checked_too() {
|
||||
let command: Vec<String> = ["rm", "-rf", "/"].iter().map(ToString::to_string).collect();
|
||||
assert!(protected_recursive_deletion(&command, &context()).is_some());
|
||||
}
|
||||
}
|
||||
@@ -12,3 +12,4 @@ pub mod parse_command;
|
||||
pub mod powershell;
|
||||
|
||||
pub use command_safety::is_dangerous_command;
|
||||
pub use command_safety::recursive_deletion;
|
||||
|
||||
@@ -384,6 +384,8 @@ async fn new_config(
|
||||
code_mode: Default::default(),
|
||||
background_terminal_max_timeout: 300_000,
|
||||
max_repeated_failures: 3,
|
||||
max_identical_tool_calls: 5,
|
||||
max_repeated_text: 10,
|
||||
thread_unload_delay: std::time::Duration::from_secs(/*secs*/ 60),
|
||||
ghost_snapshot: GhostSnapshotConfig::default(),
|
||||
multi_agent_v2: MultiAgentV2Config::default(),
|
||||
|
||||
@@ -10,7 +10,7 @@ expression: "render_bottom_popup(&app.chat_widget,\nwidth).replace(r\"C:\\cli-bu
|
||||
│
|
||||
|
||||
Update daemon and exit aKode?
|
||||
Use this CLI package v0.8.0 from /x/cli-build/bin/akode. Copy the
|
||||
Use this CLI package v0.9.0 from /x/cli-build/bin/akode. Copy the
|
||||
complete package and pin it against automatic updates.
|
||||
This may restart the daemon and interrupt active or queued work.
|
||||
Codex exits to update in this terminal. Relaunch it afterward.
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: "format!(\"enabled:\\n{}\\n---\\ndisabled:\\n{}\", text(after), text
|
||||
---
|
||||
enabled:
|
||||
|
||||
▄▄████▄▄ aKode v0.8.0
|
||||
▄▄████▄▄ aKode v0.9.0
|
||||
██▀▀██▀▀██ GPT-5.6-Sol · mock
|
||||
██▄▄██▄▄██ /tmp/project
|
||||
██▀████▀██
|
||||
@@ -50,7 +50,7 @@ enabled:
|
||||
---
|
||||
disabled:
|
||||
|
||||
▄▄████▄▄ aKode v0.8.0
|
||||
▄▄████▄▄ aKode v0.9.0
|
||||
██▀▀██▀▀██ GPT-5.6-Sol · mock
|
||||
██▄▄██▄▄██ /tmp/project
|
||||
██▀████▀██
|
||||
|
||||
@@ -3,7 +3,7 @@ source: tui/src/app/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
|
||||
▄▄████▄▄ aKode v0.8.0
|
||||
▄▄████▄▄ aKode v0.9.0
|
||||
██▀▀██▀▀██ gpt-test · mock
|
||||
██▄▄██▄▄██ <thread cwd>
|
||||
██▀████▀██
|
||||
|
||||
@@ -3,7 +3,7 @@ source: tui/src/app/tests/realtime_requests.rs
|
||||
expression: "normalize_voice_snapshot_directory(&rendered, &app.config.cwd)"
|
||||
---
|
||||
|
||||
▄▄████▄▄ aKode v0.8.0
|
||||
▄▄████▄▄ aKode v0.9.0
|
||||
██▀▀██▀▀██ gpt-test · mock
|
||||
██▄▄██▄▄██ /tmp/project
|
||||
██▀████▀██
|
||||
|
||||
@@ -3,7 +3,7 @@ source: tui/src/app/tests/realtime_requests.rs
|
||||
expression: "normalize_voice_snapshot_directory(&rendered, &app.config.cwd)"
|
||||
---
|
||||
|
||||
▄▄████▄▄ aKode v0.8.0
|
||||
▄▄████▄▄ aKode v0.9.0
|
||||
██▀▀██▀▀██ gpt-test · mock
|
||||
██▄▄██▄▄██ /tmp/project
|
||||
██▀████▀██
|
||||
|
||||
@@ -14,7 +14,7 @@ Restored owner:
|
||||
|
||||
127.0.0.1:9 · gpt-test · /tmp/project ctx 0% · -- t/s
|
||||
|
||||
▄▄████▄▄ aKode v0.8.0
|
||||
▄▄████▄▄ aKode v0.9.0
|
||||
██▀▀██▀▀██ gpt-test · mock
|
||||
██▄▄██▄▄██ /tmp/project
|
||||
██▀████▀██
|
||||
|
||||
@@ -3,7 +3,7 @@ source: tui/src/app/tests/realtime_requests.rs
|
||||
expression: "normalize_voice_snapshot_directory(&rendered, &app.config.cwd)"
|
||||
---
|
||||
|
||||
▄▄████▄▄ aKode v0.8.0
|
||||
▄▄████▄▄ aKode v0.9.0
|
||||
██▀▀██▀▀██ gpt-test · mock
|
||||
██▄▄██▄▄██ /tmp/project
|
||||
██▀████▀██
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
source: tui/src/app/tests/new_session_tests.rs
|
||||
expression: "normalize_snapshot_paths(render_bottom_popup(&app.chat_widget, 80))"
|
||||
---
|
||||
▄▄████▄▄ aKode v0.8.0
|
||||
▄▄████▄▄ aKode v0.9.0
|
||||
██▀▀██▀▀██ loading · mock
|
||||
██▄▄██▄▄██ /tmp/project
|
||||
██▀████▀██
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: "normalize_snapshot_paths(normalize_agent_center_snapshot(snapshots.
|
||||
---
|
||||
80 columns
|
||||
|
||||
▄▄████▄▄ aKode v0.8.0
|
||||
▄▄████▄▄ aKode v0.9.0
|
||||
██▀▀██▀▀██ gpt-test · mock
|
||||
██▄▄██▄▄██ /tmp/project
|
||||
██▀████▀██
|
||||
@@ -26,7 +26,7 @@ expression: "normalize_snapshot_paths(normalize_agent_center_snapshot(snapshots.
|
||||
|
||||
32 columns
|
||||
|
||||
▄▄████▄▄ aKode v0.8.0
|
||||
▄▄████▄▄ aKode v0.9.0
|
||||
██▀▀██▀▀██ gpt-test · mock
|
||||
██▄▄██▄▄██ /tmp/project
|
||||
██▀████▀██
|
||||
|
||||
@@ -3,7 +3,7 @@ source: tui/src/chatwidget/tests/permissions.rs
|
||||
expression: popup
|
||||
---
|
||||
Set up the aKode agent sandbox to protect your files and control network access. Learn more
|
||||
<https://git.difonzo.net/andrea/aKode>
|
||||
<https://git.difonzo.net/andrea/imeai-aKode>
|
||||
|
||||
|
||||
› 1. Set up default sandbox (requires Administrator permissions)
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: "render_bottom_popup(&chat, 120)"
|
||||
---
|
||||
Your organization requires the default aKode agent sandbox to continue. Set it up to protect your files and control
|
||||
network access.
|
||||
Learn more <https://git.difonzo.net/andrea/aKode>
|
||||
Learn more <https://git.difonzo.net/andrea/imeai-aKode>
|
||||
|
||||
|
||||
› 1. Set up default sandbox (requires Administrator permissions)
|
||||
|
||||
@@ -5,7 +5,7 @@ expression: popup
|
||||
Couldn't set up your sandbox with Administrator permissions
|
||||
|
||||
Your organization requires the default sandbox before aKode can continue.
|
||||
Learn more <https://git.difonzo.net/andrea/aKode>
|
||||
Learn more <https://git.difonzo.net/andrea/imeai-aKode>
|
||||
|
||||
|
||||
› 1. Try setting up admin sandbox again
|
||||
|
||||
@@ -3,7 +3,7 @@ source: tui/src/chatwidget/tests/permissions.rs
|
||||
expression: "render_bottom_popup(&chat, 100)"
|
||||
---
|
||||
Set up the aKode agent sandbox to protect your files and control network access. Learn more
|
||||
<https://git.difonzo.net/andrea/aKode>
|
||||
<https://git.difonzo.net/andrea/imeai-aKode>
|
||||
|
||||
|
||||
› 1. Use non-admin sandbox (higher risk if prompt injected)
|
||||
|
||||
@@ -1006,7 +1006,7 @@ async fn startup_windows_sandbox_prompt_blocks_disallowed_unelevated_fallback()
|
||||
|
||||
#[tokio::test]
|
||||
async fn windows_sandbox_help_links_keep_complete_wrapped_destinations() {
|
||||
let url = "https://git.difonzo.net/andrea/aKode";
|
||||
let url = "https://git.difonzo.net/andrea/imeai-aKode";
|
||||
for fallback in [false, true] {
|
||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
let preset = builtin_approval_presets()
|
||||
|
||||
@@ -6,8 +6,8 @@ expression: visible
|
||||
Set up the aKode agent sandbox to
|
||||
protect your files and control
|
||||
network access. Learn more
|
||||
<https://git.difonzo.net/andrea/aKod
|
||||
e>
|
||||
<https://git.difonzo.net/andrea/imea
|
||||
i-aKode>
|
||||
|
||||
|
||||
› 1. Set up default sandbox (requires
|
||||
|
||||
@@ -35,12 +35,12 @@ impl ChatWidget {
|
||||
header.push(*Box::new(
|
||||
crate::terminal_hyperlinks::HyperlinkText::new(if allow_unelevated {
|
||||
vec![
|
||||
line!["Set up the aKode agent sandbox to protect your files and control network access. Learn more <https://git.difonzo.net/andrea/aKode>"],
|
||||
line!["Set up the aKode agent sandbox to protect your files and control network access. Learn more <https://git.difonzo.net/andrea/imeai-aKode>"],
|
||||
]
|
||||
} else {
|
||||
vec![
|
||||
line!["Your organization requires the default aKode agent sandbox to continue. Set it up to protect your files and control network access."],
|
||||
line!["Learn more <https://git.difonzo.net/andrea/aKode>"],
|
||||
line!["Learn more <https://git.difonzo.net/andrea/imeai-aKode>"],
|
||||
]
|
||||
}),
|
||||
));
|
||||
@@ -164,7 +164,7 @@ impl ChatWidget {
|
||||
"Your organization requires the default sandbox before aKode can continue."
|
||||
]);
|
||||
}
|
||||
lines.push(line!["Learn more <https://git.difonzo.net/andrea/aKode>"]);
|
||||
lines.push(line!["Learn more <https://git.difonzo.net/andrea/imeai-aKode>"]);
|
||||
|
||||
let mut header = ColumnRenderable::new();
|
||||
header.push(crate::terminal_hyperlinks::HyperlinkText::new(lines));
|
||||
|
||||
@@ -442,7 +442,7 @@ pub(crate) fn empty_mcp_output() -> WebHyperlinkHistoryCell {
|
||||
let mut docs_line = HyperlinkLine::new(Line::from(" See the "));
|
||||
docs_line.push_span(
|
||||
"MCP docs".underlined(),
|
||||
Some("https://git.difonzo.net/andrea/aKode"),
|
||||
Some("https://git.difonzo.net/andrea/imeai-aKode"),
|
||||
);
|
||||
docs_line.push_span(" to configure them.".into(), /*destination*/ None);
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ source: tui/src/history_cell/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
|
||||
▄▄████▄▄ aKode v0.8.0
|
||||
▄▄████▄▄ aKode v0.9.0
|
||||
██▀▀██▀▀██ gpt-5 · mock
|
||||
██▄▄██▄▄██ /tmp/project
|
||||
██▀████▀██
|
||||
|
||||
@@ -424,7 +424,7 @@ fn composite_cell_preserves_child_web_links() {
|
||||
|
||||
#[test]
|
||||
fn empty_mcp_output_preserves_docs_hyperlink() {
|
||||
let destination = "https://git.difonzo.net/andrea/aKode";
|
||||
let destination = "https://git.difonzo.net/andrea/imeai-aKode";
|
||||
let cell: Box<dyn HistoryCell> = Box::new(empty_mcp_output());
|
||||
|
||||
insta::assert_snapshot!(render_lines(&cell.display_lines(/*width*/ 80)).join("\n"), @r"
|
||||
|
||||
@@ -7,7 +7,7 @@ expression: rendered
|
||||
|
||||
Scegli i colori; potrai cambiarli con /theme.
|
||||
|
||||
1. Automatico │ ▄▄████▄▄ aKode v0.8.0
|
||||
1. Automatico │ ▄▄████▄▄ aKode v0.9.0
|
||||
2. Scuro │ ██▀▀██▀▀██ qwen3.6-35b-a3b
|
||||
3. Chiaro │ ██▄▄██▄▄██ ~/progetto
|
||||
4. Alto contrasto │ ██▀████▀██
|
||||
|
||||
@@ -7,7 +7,7 @@ expression: rendered
|
||||
|
||||
Scegli i colori; potrai cambiarli con /theme.
|
||||
|
||||
1. Automatico │ ▄▄████▄▄ aKode v0.8.0
|
||||
1. Automatico │ ▄▄████▄▄ aKode v0.9.0
|
||||
2. Scuro │ ██▀▀██▀▀██ qwen3.6-35b-a3b
|
||||
3. Chiaro │ ██▄▄██▄▄██ ~/progetto
|
||||
4. Alto contrasto │ ██▀████▀██
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex (reasoning none, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex (reasoning none, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning high, summaries detailed)
|
||||
Directory: [[workspace]]
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Server: Local background server
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Server: unix:///tmp/codex-home/app-server-control/app-server-
|
||||
control.sock (v0.133.0)
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: ガパガパガパガ
|
||||
パ-model (reasoning
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning high, summaries
|
||||
detailed)
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning medium, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
|
||||
@@ -4,7 +4,7 @@ expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ aKode (v0.8.0)
|
||||
>_ aKode (v0.9.0)
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
|
||||
@@ -7,10 +7,10 @@ use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const TARGET: &str = "aarch64-apple-darwin";
|
||||
const LATEST_PATH: &str = "/api/v1/repos/andrea/aKode/releases/latest";
|
||||
const LATEST_PATH: &str = "/api/v1/repos/andrea/imeai-aKode/releases/latest";
|
||||
|
||||
fn repo_url(server: &MockServer) -> String {
|
||||
format!("{}/andrea/aKode", server.uri())
|
||||
format!("{}/andrea/imeai-aKode", server.uri())
|
||||
}
|
||||
|
||||
fn client() -> reqwest::Client {
|
||||
@@ -70,22 +70,22 @@ fn installed_binary(dir: &Path) -> PathBuf {
|
||||
fn api_url_is_derived_from_repo_url() {
|
||||
for (repo, expected) in [
|
||||
(
|
||||
"https://git.difonzo.net/andrea/aKode",
|
||||
"https://git.difonzo.net/api/v1/repos/andrea/aKode/releases/latest",
|
||||
"https://git.difonzo.net/andrea/imeai-aKode",
|
||||
"https://git.difonzo.net/api/v1/repos/andrea/imeai-aKode/releases/latest",
|
||||
),
|
||||
(
|
||||
"https://git.difonzo.net/andrea/aKode.git/",
|
||||
"https://git.difonzo.net/api/v1/repos/andrea/aKode/releases/latest",
|
||||
"https://git.difonzo.net/andrea/imeai-aKode.git/",
|
||||
"https://git.difonzo.net/api/v1/repos/andrea/imeai-aKode/releases/latest",
|
||||
),
|
||||
(
|
||||
"https://example.com/gitea/andrea/aKode",
|
||||
"https://example.com/gitea/api/v1/repos/andrea/aKode/releases/latest",
|
||||
"https://example.com/gitea/andrea/imeai-aKode",
|
||||
"https://example.com/gitea/api/v1/repos/andrea/imeai-aKode/releases/latest",
|
||||
),
|
||||
] {
|
||||
assert_eq!(latest_release_api_url(repo).unwrap().as_str(), expected);
|
||||
}
|
||||
assert!(latest_release_api_url("https://git.difonzo.net/andrea").is_err());
|
||||
assert!(latest_release_api_url("ftp://git.difonzo.net/andrea/aKode").is_err());
|
||||
assert!(latest_release_api_url("ftp://git.difonzo.net/andrea/imeai-aKode").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Installatore di aKode.
|
||||
#
|
||||
# curl -fsSL https://git.difonzo.net/andrea/aKode/raw/branch/main/install.sh | sh
|
||||
# curl -fsSL https://git.difonzo.net/andrea/imeai-aKode/raw/branch/main/install.sh | sh
|
||||
#
|
||||
# Scarica l'ultima release (oppure quella indicata con AKODE_VERSION=x.y.z), ne verifica lo
|
||||
# SHA-256 e la installa in ~/.local/share/akode/package, con il comando in ~/.local/bin/akode.
|
||||
@@ -9,7 +9,7 @@
|
||||
set -eu
|
||||
|
||||
REPO_HOST="https://git.difonzo.net"
|
||||
REPO_PATH="andrea/aKode"
|
||||
REPO_PATH="andrea/imeai-aKode"
|
||||
API="$REPO_HOST/api/v1/repos/$REPO_PATH"
|
||||
|
||||
DATA_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/akode"
|
||||
|
||||
Reference in New Issue
Block a user