aKode 0.2.0: protezione dai loop, errori del server chiari, pulizia
- Protezione dai loop: se il modello ripete lo stesso comando con lo stesso errore 3 volte di fila il turno si ferma con un messaggio chiaro (e un suggerimento su /permissions per i blocchi della sandbox); configurabile con [agent] max_repeated_failures (0 = disattivata). - Errori dello stream: si mostra il messaggio del server invece di "stream closed before response.completed"; il contesto superato (llama.cpp, vLLM) diventa un messaggio in italiano; avviso una volta se il prompt iniziale supera la finestra del modello. - Pulizia: tolta la logica morta per le chiavi OpenAI nel credential broker (prefisso "sk-", watermark, prefissi ignorati); link alla documentazione OpenAI nella TUI sostituiti con il README del repository; test dello snapshot del broker adattato al token GitHub. - Versione 0.2.0 e sezione Novità nel README. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
15
README.md
15
README.md
@@ -99,6 +99,21 @@ akode exec "descrivi questo progetto"
|
|||||||
- **Rete in automatico:** nessun controllo aggiornamenti, annuncio, download di asset o sincronizzazione di plugin all'avvio.
|
- **Rete in automatico:** nessun controllo aggiornamenti, annuncio, download di asset o sincronizzazione di plugin all'avvio.
|
||||||
- **Feedback:** nessun upload a Sentry; resta solo il salvataggio locale.
|
- **Feedback:** nessun upload a Sentry; resta solo il salvataggio locale.
|
||||||
|
|
||||||
|
## Novità
|
||||||
|
|
||||||
|
### 0.2.0
|
||||||
|
|
||||||
|
- Nuovo pannello **/endpoint** (Endpoint │ Modelli │ Impostazioni) con impostazioni per modello, tra cui la lunghezza del contesto; `/model` serve solo a scegliere il modello.
|
||||||
|
- Nomi dei modelli abbreviati: se l'id è un percorso si mostra solo il nome del file senza estensione (all'API va sempre l'id completo).
|
||||||
|
- Primo avvio con l'indirizzo di SearXNG già proposto.
|
||||||
|
- Protezione dai loop: se il modello ripete lo stesso comando con lo stesso errore 3 volte di fila il turno si ferma, con un suggerimento su /permissions quando l'errore viene dalla sandbox (`[agent] max_repeated_failures`, 0 = disattivata).
|
||||||
|
- Errori del server chiari: si mostra il messaggio del server (per esempio il contesto superato di llama.cpp) invece di «stream closed before response.completed», e un avviso se il prompt iniziale supera la finestra del modello.
|
||||||
|
- Pulizia: tolta la logica morta per le chiavi OpenAI nel proxy di rete e i link alla documentazione OpenAI nella TUI.
|
||||||
|
|
||||||
|
### 0.1.0
|
||||||
|
|
||||||
|
- Prima release: installatore `install.sh` e `akode update`.
|
||||||
|
|
||||||
## Licenza
|
## Licenza
|
||||||
|
|
||||||
aKode deriva da OpenAI Codex CLI ed è rilasciato sotto la stessa [licenza Apache-2.0](LICENSE); vedi anche [NOTICE](NOTICE). Il codice è stato modificato in modo esteso: la cronologia git del repository documenta ogni modifica rispetto al commit di base `7874033`. "OpenAI" e "Codex" sono marchi dei rispettivi proprietari. aKode non è affiliato né approvato da OpenAI.
|
aKode deriva da OpenAI Codex CLI ed è rilasciato sotto la stessa [licenza Apache-2.0](LICENSE); vedi anche [NOTICE](NOTICE). Il codice è stato modificato in modo esteso: la cronologia git del repository documenta ogni modifica rispetto al commit di base `7874033`. "OpenAI" e "Codex" sono marchi dei rispettivi proprietari. aKode non è affiliato né approvato da OpenAI.
|
||||||
|
|||||||
314
akode-rs/Cargo.lock
generated
314
akode-rs/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -157,7 +157,7 @@ members = [
|
|||||||
resolver = "2"
|
resolver = "2"
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
# Track the edition for all workspace crates in one place. Individual
|
# Track the edition for all workspace crates in one place. Individual
|
||||||
# crates can still override this value, but keeping it here means new
|
# crates can still override this value, but keeping it here means new
|
||||||
# crates created with `cargo new -w ...` automatically inherit the 2024
|
# crates created with `cargo new -w ...` automatically inherit the 2024
|
||||||
|
|||||||
@@ -1372,7 +1372,6 @@ mod transcript_tests;
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::endpoint::realtime_websocket::protocol::RealtimeTranscriptEntry;
|
use crate::endpoint::realtime_websocket::protocol::RealtimeTranscriptEntry;
|
||||||
use crate::provider::RetryConfig;
|
|
||||||
use akode_http_client::OutboundProxyPolicy::ReqwestDefault;
|
use akode_http_client::OutboundProxyPolicy::ReqwestDefault;
|
||||||
use akode_protocol::protocol::RealtimeHandoffRequested;
|
use akode_protocol::protocol::RealtimeHandoffRequested;
|
||||||
use akode_protocol::protocol::RealtimeInputAudioSpeechStarted;
|
use akode_protocol::protocol::RealtimeInputAudioSpeechStarted;
|
||||||
@@ -2366,34 +2365,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn webrtc_frameless_sideband_ignores_provider_base_url() {
|
|
||||||
let client = test_client(Provider {
|
|
||||||
name: "chatgpt".to_string(),
|
|
||||||
base_url: "https://chatgpt.com/backend-api/codex".to_string(),
|
|
||||||
query_params: None,
|
|
||||||
headers: HeaderMap::new(),
|
|
||||||
retry: RetryConfig {
|
|
||||||
max_attempts: 0,
|
|
||||||
base_delay: Duration::ZERO,
|
|
||||||
retry_429: false,
|
|
||||||
retry_5xx: false,
|
|
||||||
retry_transport: false,
|
|
||||||
},
|
|
||||||
stream_idle_timeout: Duration::from_secs(5),
|
|
||||||
});
|
|
||||||
|
|
||||||
let url = client
|
|
||||||
.webrtc_sideband_url(
|
|
||||||
RealtimeEventParser::FramelessBidi,
|
|
||||||
RealtimeSessionMode::Conversational,
|
|
||||||
"rtc_test",
|
|
||||||
)
|
|
||||||
.expect("build ws url");
|
|
||||||
|
|
||||||
assert_eq!(url.as_str(), "wss://api.openai.com/v1/live/rtc_test");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn e2e_connect_and_exchange_events_against_mock_ws_server() {
|
async fn e2e_connect_and_exchange_events_against_mock_ws_server() {
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
|
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
|
||||||
|
|||||||
@@ -83,6 +83,9 @@ pub(crate) fn parse_terminal_provider_error(
|
|||||||
status: Option<StatusCode>,
|
status: Option<StatusCode>,
|
||||||
) -> Option<ApiError> {
|
) -> Option<ApiError> {
|
||||||
let error = error?;
|
let error = error?;
|
||||||
|
if let Some(message) = context_overflow_message(error) {
|
||||||
|
return Some(ApiError::InvalidRequest { message });
|
||||||
|
}
|
||||||
let code = error.get("code")?.as_str()?;
|
let code = error.get("code")?.as_str()?;
|
||||||
match (code, status) {
|
match (code, status) {
|
||||||
("budget_reached", None | Some(StatusCode::BAD_REQUEST)) => {
|
("budget_reached", None | Some(StatusCode::BAD_REQUEST)) => {
|
||||||
@@ -124,6 +127,69 @@ pub(crate) fn parse_terminal_provider_error(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the server's own message from a provider `error` value (an object with
|
||||||
|
/// `message`, or a bare string), when it has one.
|
||||||
|
pub(crate) fn provider_error_message(error: &Value) -> Option<String> {
|
||||||
|
let message = match error {
|
||||||
|
Value::String(message) => message.as_str(),
|
||||||
|
Value::Object(_) => error.get("message").and_then(Value::as_str)?,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
let message = message.trim();
|
||||||
|
(!message.is_empty()).then(|| message.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the error for a provider `error` value seen in the stream, keeping the server's
|
||||||
|
/// message instead of a generic "stream closed" error.
|
||||||
|
pub(crate) fn provider_stream_error(error: &Value) -> Option<ApiError> {
|
||||||
|
if let Some(error) = parse_terminal_provider_error(Some(error), /*status*/ None) {
|
||||||
|
return Some(error);
|
||||||
|
}
|
||||||
|
provider_error_message(error)
|
||||||
|
.map(|message| ApiError::Stream(format!("errore del server: {message}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recognizes context-overflow errors from OpenAI-compatible servers (llama.cpp, vLLM, ...)
|
||||||
|
/// and turns them into an actionable Italian message. The OpenAI `context_length_exceeded`
|
||||||
|
/// code keeps its dedicated handling (auto-compaction) and is not matched here.
|
||||||
|
pub(crate) fn context_overflow_message(error: &Value) -> Option<String> {
|
||||||
|
if error.get("code").and_then(Value::as_str) == Some("context_length_exceeded") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let is_overflow_type =
|
||||||
|
error.get("type").and_then(Value::as_str) == Some("exceed_context_size_error");
|
||||||
|
let message = provider_error_message(error).unwrap_or_default();
|
||||||
|
let lower = message.to_ascii_lowercase();
|
||||||
|
let mentions_overflow = [
|
||||||
|
"exceeds the available context size",
|
||||||
|
"maximum context length",
|
||||||
|
"context length exceeded",
|
||||||
|
"exceeds the context size",
|
||||||
|
"context size exceeded",
|
||||||
|
]
|
||||||
|
.iter()
|
||||||
|
.any(|needle| lower.contains(needle));
|
||||||
|
if !is_overflow_type && !mentions_overflow {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let n_ctx = error
|
||||||
|
.get("n_ctx")
|
||||||
|
.and_then(Value::as_i64)
|
||||||
|
.or_else(|| first_number(&message));
|
||||||
|
Some(match n_ctx {
|
||||||
|
Some(n_ctx) => format!(
|
||||||
|
"Il server ha superato il contesto ({n_ctx} token): aumenta il contesto del modello sul server e in /endpoint."
|
||||||
|
),
|
||||||
|
None => "Il server ha superato il contesto: aumenta il contesto del modello sul server e in /endpoint.".to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn first_number(text: &str) -> Option<i64> {
|
||||||
|
text.split(|c: char| !c.is_ascii_digit())
|
||||||
|
.find(|part| !part.is_empty())
|
||||||
|
.and_then(|part| part.parse().ok())
|
||||||
|
}
|
||||||
|
|
||||||
impl From<crate::AuthError> for ApiError {
|
impl From<crate::AuthError> for ApiError {
|
||||||
fn from(error: crate::AuthError) -> Self {
|
fn from(error: crate::AuthError) -> Self {
|
||||||
Self::Transport(error.into())
|
Self::Transport(error.into())
|
||||||
|
|||||||
@@ -34,7 +34,6 @@ pub use crate::common::MemorySummarizeInput;
|
|||||||
pub use crate::common::MemorySummarizeOutput;
|
pub use crate::common::MemorySummarizeOutput;
|
||||||
pub use crate::common::OpenAiVerbosity;
|
pub use crate::common::OpenAiVerbosity;
|
||||||
pub use crate::common::PromptCacheOptions;
|
pub use crate::common::PromptCacheOptions;
|
||||||
pub use crate::common::SamplingParams;
|
|
||||||
pub use crate::common::RawMemory;
|
pub use crate::common::RawMemory;
|
||||||
pub use crate::common::RawMemoryMetadata;
|
pub use crate::common::RawMemoryMetadata;
|
||||||
pub use crate::common::Reasoning;
|
pub use crate::common::Reasoning;
|
||||||
@@ -48,6 +47,7 @@ pub use crate::common::ResponseStream;
|
|||||||
pub use crate::common::ResponsesApiRequest;
|
pub use crate::common::ResponsesApiRequest;
|
||||||
pub use crate::common::ResponsesApiTools;
|
pub use crate::common::ResponsesApiTools;
|
||||||
pub use crate::common::ResponsesWsRequest;
|
pub use crate::common::ResponsesWsRequest;
|
||||||
|
pub use crate::common::SamplingParams;
|
||||||
pub use crate::common::StreamOptions;
|
pub use crate::common::StreamOptions;
|
||||||
pub use crate::common::TextControls;
|
pub use crate::common::TextControls;
|
||||||
pub use crate::common::WS_REQUEST_HEADER_TRACEPARENT_CLIENT_METADATA_KEY;
|
pub use crate::common::WS_REQUEST_HEADER_TRACEPARENT_CLIENT_METADATA_KEY;
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use crate::common::ResponseStream;
|
|||||||
use crate::common::SafetyBuffering;
|
use crate::common::SafetyBuffering;
|
||||||
use crate::common::SafetyBufferingTreatment;
|
use crate::common::SafetyBufferingTreatment;
|
||||||
use crate::error::ApiError;
|
use crate::error::ApiError;
|
||||||
use crate::error::parse_terminal_provider_error;
|
use crate::error::provider_stream_error;
|
||||||
use crate::guardian_assessment::parse_guardian_assessment;
|
use crate::guardian_assessment::parse_guardian_assessment;
|
||||||
use crate::rate_limits::parse_all_rate_limits;
|
use crate::rate_limits::parse_all_rate_limits;
|
||||||
use crate::safety_buffering::treatment_from_headers;
|
use crate::safety_buffering::treatment_from_headers;
|
||||||
@@ -329,9 +329,7 @@ pub fn process_responses_event(
|
|||||||
) -> std::result::Result<Option<ResponseEvent>, ResponsesEventError> {
|
) -> std::result::Result<Option<ResponseEvent>, ResponsesEventError> {
|
||||||
match event.kind.as_str() {
|
match event.kind.as_str() {
|
||||||
"error" => {
|
"error" => {
|
||||||
if let Some(error) =
|
if let Some(error) = event.error.as_ref().and_then(provider_stream_error) {
|
||||||
parse_terminal_provider_error(event.error.as_ref(), /*status*/ None)
|
|
||||||
{
|
|
||||||
return Err(ResponsesEventError::Api(error));
|
return Err(ResponsesEventError::Api(error));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -585,6 +583,19 @@ async fn process_sse_with_treatment(
|
|||||||
let event: ResponsesStreamEvent = match serde_json::from_str(&sse.data) {
|
let event: ResponsesStreamEvent = match serde_json::from_str(&sse.data) {
|
||||||
Ok(event) => event,
|
Ok(event) => event,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
// Some OpenAI-compatible servers (e.g. llama.cpp) send `{"error": {...}}`
|
||||||
|
// without a `type`; keep their message for when the stream ends.
|
||||||
|
if let Some(error) = serde_json::from_str::<Value>(&sse.data)
|
||||||
|
.ok()
|
||||||
|
.and_then(|value| value.get("error").and_then(provider_stream_error))
|
||||||
|
{
|
||||||
|
if matches!(error, ApiError::InvalidRequest { .. }) {
|
||||||
|
let _ = tx_event.send(Err(error)).await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
response_error = Some(error);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
debug!(
|
debug!(
|
||||||
error_category = ?e.classify(),
|
error_category = ?e.classify(),
|
||||||
error_line = e.line(),
|
error_line = e.line(),
|
||||||
@@ -634,6 +645,7 @@ async fn process_sse_with_treatment(
|
|||||||
ApiError::FlexUnavailable
|
ApiError::FlexUnavailable
|
||||||
| ApiError::SessionBudgetExceeded
|
| ApiError::SessionBudgetExceeded
|
||||||
| ApiError::ResponseIncomplete(_)
|
| ApiError::ResponseIncomplete(_)
|
||||||
|
| ApiError::InvalidRequest { .. }
|
||||||
) {
|
) {
|
||||||
let _ = tx_event.send(Err(error)).await;
|
let _ = tx_event.send(Err(error)).await;
|
||||||
return;
|
return;
|
||||||
|
|||||||
171
akode-rs/akode-api/tests/stream_errors.rs
Normal file
171
akode-rs/akode-api/tests/stream_errors.rs
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
//! Server errors in the Responses stream keep the server's own message.
|
||||||
|
#![allow(clippy::expect_used)]
|
||||||
|
|
||||||
|
use akode_api::ApiError;
|
||||||
|
use akode_api::AuthProvider;
|
||||||
|
use akode_api::Compression;
|
||||||
|
use akode_api::Provider;
|
||||||
|
use akode_api::ResponsesClient;
|
||||||
|
use akode_api::RetryConfig;
|
||||||
|
use akode_api::map_api_error;
|
||||||
|
use akode_client::ReqwestTransport;
|
||||||
|
use akode_http_client::HttpClientBuilder;
|
||||||
|
use futures::StreamExt;
|
||||||
|
use http::HeaderMap;
|
||||||
|
use pretty_assertions::assert_eq;
|
||||||
|
use serde_json::json;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
use wiremock::Mock;
|
||||||
|
use wiremock::MockServer;
|
||||||
|
use wiremock::ResponseTemplate;
|
||||||
|
use wiremock::matchers::method;
|
||||||
|
use wiremock::matchers::path;
|
||||||
|
|
||||||
|
const OVERFLOW: &str = "Il server ha superato il contesto (8192 token): aumenta il contesto del modello sul server e in /endpoint.";
|
||||||
|
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
struct NoAuth;
|
||||||
|
|
||||||
|
impl AuthProvider for NoAuth {
|
||||||
|
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), akode_api::AuthError> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client(server: &MockServer) -> ResponsesClient<ReqwestTransport> {
|
||||||
|
let transport = ReqwestTransport::from_http_client(
|
||||||
|
HttpClientBuilder::new()
|
||||||
|
.build_direct()
|
||||||
|
.expect("test HTTP client should build"),
|
||||||
|
);
|
||||||
|
let provider = Provider {
|
||||||
|
name: "llama".to_string(),
|
||||||
|
base_url: server.uri(),
|
||||||
|
query_params: None,
|
||||||
|
headers: HeaderMap::new(),
|
||||||
|
retry: RetryConfig {
|
||||||
|
max_attempts: 1,
|
||||||
|
base_delay: Duration::from_millis(1),
|
||||||
|
retry_429: false,
|
||||||
|
retry_5xx: false,
|
||||||
|
retry_transport: false,
|
||||||
|
},
|
||||||
|
stream_idle_timeout: Duration::from_secs(2),
|
||||||
|
};
|
||||||
|
ResponsesClient::new(transport, provider, Arc::new(NoAuth))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn llama_overflow_error() -> serde_json::Value {
|
||||||
|
json!({
|
||||||
|
"code": 400,
|
||||||
|
"message": "the request exceeds the available context size, try increasing it",
|
||||||
|
"type": "exceed_context_size_error",
|
||||||
|
"n_prompt_tokens": 9000,
|
||||||
|
"n_ctx": 8192
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn mount_sse(server: &MockServer, body: String) {
|
||||||
|
Mock::given(method("POST"))
|
||||||
|
.and(path("/responses"))
|
||||||
|
.respond_with(
|
||||||
|
ResponseTemplate::new(200)
|
||||||
|
.insert_header("content-type", "text/event-stream")
|
||||||
|
.set_body_string(body),
|
||||||
|
)
|
||||||
|
.mount(server)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn stream_error(server: &MockServer) -> ApiError {
|
||||||
|
let mut stream = client(server)
|
||||||
|
.stream(
|
||||||
|
json!({"model": "m"}),
|
||||||
|
HeaderMap::new(),
|
||||||
|
Compression::None,
|
||||||
|
/*turn_state*/ None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("stream should start");
|
||||||
|
while let Some(event) = stream.next().await {
|
||||||
|
if let Err(error) = event {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("stream ended without an error");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn llama_cpp_error_without_type_maps_to_context_message() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
let error = json!({ "error": llama_overflow_error() });
|
||||||
|
mount_sse(&server, format!("data: {error}\n\n")).await;
|
||||||
|
|
||||||
|
let error = stream_error(&server).await;
|
||||||
|
assert_eq!(map_api_error(error).to_string(), OVERFLOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn error_event_message_replaces_stream_closed() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
let event = json!({
|
||||||
|
"type": "error",
|
||||||
|
"error": { "message": "model crashed while loading" }
|
||||||
|
});
|
||||||
|
mount_sse(&server, format!("event: error\ndata: {event}\n\n")).await;
|
||||||
|
|
||||||
|
let error = stream_error(&server).await;
|
||||||
|
let message = error.to_string();
|
||||||
|
assert!(
|
||||||
|
message.contains("model crashed while loading"),
|
||||||
|
"unexpected error: {message}"
|
||||||
|
);
|
||||||
|
assert!(!message.contains("stream closed before response.completed"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn http_400_context_overflow_maps_to_context_message() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
Mock::given(method("POST"))
|
||||||
|
.and(path("/responses"))
|
||||||
|
.respond_with(
|
||||||
|
ResponseTemplate::new(400).set_body_json(json!({ "error": llama_overflow_error() })),
|
||||||
|
)
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let error = match client(&server)
|
||||||
|
.stream(
|
||||||
|
json!({"model": "m"}),
|
||||||
|
HeaderMap::new(),
|
||||||
|
Compression::None,
|
||||||
|
/*turn_state*/ None,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => panic!("request should fail"),
|
||||||
|
Err(error) => error,
|
||||||
|
};
|
||||||
|
assert_eq!(map_api_error(error).to_string(), OVERFLOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn openai_context_length_exceeded_keeps_dedicated_error() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
let event = json!({
|
||||||
|
"type": "response.failed",
|
||||||
|
"response": { "error": { "code": "context_length_exceeded", "message": "too long" } }
|
||||||
|
});
|
||||||
|
mount_sse(
|
||||||
|
&server,
|
||||||
|
format!("event: response.failed\ndata: {event}\n\n"),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let error = stream_error(&server).await;
|
||||||
|
assert!(
|
||||||
|
matches!(error, ApiError::ContextWindowExceeded),
|
||||||
|
"{error:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -498,6 +498,9 @@ pub struct ConfigToml {
|
|||||||
/// Agent-related settings (thread limits, etc.).
|
/// Agent-related settings (thread limits, etc.).
|
||||||
pub agents: Option<AgentsToml>,
|
pub agents: Option<AgentsToml>,
|
||||||
|
|
||||||
|
/// Settings for the main agent loop (e.g. loop protection).
|
||||||
|
pub agent: Option<AgentToml>,
|
||||||
|
|
||||||
/// Goal-related settings.
|
/// Goal-related settings.
|
||||||
pub goals: Option<GoalsToml>,
|
pub goals: Option<GoalsToml>,
|
||||||
|
|
||||||
@@ -771,6 +774,15 @@ pub struct GoalsToml {
|
|||||||
pub max_goal_token_budget: Option<NonZeroU64>,
|
pub max_goal_token_budget: Option<NonZeroU64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `[agent]` table: settings for the main agent loop.
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||||
|
#[schemars(deny_unknown_fields)]
|
||||||
|
pub struct AgentToml {
|
||||||
|
/// 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.
|
||||||
|
pub max_repeated_failures: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||||
#[schemars(deny_unknown_fields)]
|
#[schemars(deny_unknown_fields)]
|
||||||
pub struct AgentsToml {
|
pub struct AgentsToml {
|
||||||
|
|||||||
@@ -31,6 +31,19 @@
|
|||||||
},
|
},
|
||||||
"type": "object"
|
"type": "object"
|
||||||
},
|
},
|
||||||
|
"AgentToml": {
|
||||||
|
"additionalProperties": false,
|
||||||
|
"description": "`[agent]` table: settings for the main agent loop.",
|
||||||
|
"properties": {
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
"AgentsOverviewGrouping": {
|
"AgentsOverviewGrouping": {
|
||||||
"description": "Last selected grouping in Agent Command Center.",
|
"description": "Last selected grouping in Agent Command Center.",
|
||||||
"enum": [
|
"enum": [
|
||||||
@@ -7504,6 +7517,14 @@
|
|||||||
},
|
},
|
||||||
"description": "Base config deserialized from ~/.akode/config.toml.",
|
"description": "Base config deserialized from ~/.akode/config.toml.",
|
||||||
"properties": {
|
"properties": {
|
||||||
|
"agent": {
|
||||||
|
"allOf": [
|
||||||
|
{
|
||||||
|
"$ref": "#/definitions/AgentToml"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Settings for the main agent loop (e.g. loop protection)."
|
||||||
|
},
|
||||||
"agents": {
|
"agents": {
|
||||||
"allOf": [
|
"allOf": [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -604,7 +604,10 @@ impl ModelClient {
|
|||||||
/// Replace the per-model settings used for new requests (after a config reload).
|
/// Replace the per-model settings used for new requests (after a config reload).
|
||||||
pub(crate) fn set_model_settings(
|
pub(crate) fn set_model_settings(
|
||||||
&self,
|
&self,
|
||||||
settings: std::collections::BTreeMap<String, akode_model_provider_info::ProviderModelSettings>,
|
settings: std::collections::BTreeMap<
|
||||||
|
String,
|
||||||
|
akode_model_provider_info::ProviderModelSettings,
|
||||||
|
>,
|
||||||
) {
|
) {
|
||||||
*self
|
*self
|
||||||
.state
|
.state
|
||||||
|
|||||||
@@ -692,6 +692,9 @@ pub enum ThreadStoreConfig {
|
|||||||
InMemory { id: String },
|
InMemory { id: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Default for `[agent] max_repeated_failures`.
|
||||||
|
pub const DEFAULT_MAX_REPEATED_FAILURES: u32 = 3;
|
||||||
|
|
||||||
/// Application configuration loaded from disk and merged with overrides.
|
/// Application configuration loaded from disk and merged with overrides.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
@@ -1218,6 +1221,10 @@ pub struct Config {
|
|||||||
/// Default: `300000` (5 minutes).
|
/// Default: `300000` (5 minutes).
|
||||||
pub background_terminal_max_timeout: u64,
|
pub background_terminal_max_timeout: u64,
|
||||||
|
|
||||||
|
/// Loop protection: stop the turn after this many identical failed tool calls in a row
|
||||||
|
/// (`[agent] max_repeated_failures`). `0` disables the check.
|
||||||
|
pub max_repeated_failures: u32,
|
||||||
|
|
||||||
/// Idle timeout for unsubscribed app-server threads.
|
/// Idle timeout for unsubscribed app-server threads.
|
||||||
pub thread_unload_delay: Duration,
|
pub thread_unload_delay: Duration,
|
||||||
|
|
||||||
@@ -4213,6 +4220,11 @@ impl Config {
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|agents| agents.interrupt_message)
|
.and_then(|agents| agents.interrupt_message)
|
||||||
.unwrap_or(true);
|
.unwrap_or(true);
|
||||||
|
let max_repeated_failures = cfg
|
||||||
|
.agent
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|agent| agent.max_repeated_failures)
|
||||||
|
.unwrap_or(DEFAULT_MAX_REPEATED_FAILURES);
|
||||||
let background_terminal_max_timeout = cfg
|
let background_terminal_max_timeout = cfg
|
||||||
.background_terminal_max_timeout
|
.background_terminal_max_timeout
|
||||||
.unwrap_or(DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS)
|
.unwrap_or(DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS)
|
||||||
@@ -4814,6 +4826,7 @@ impl Config {
|
|||||||
tool_registry,
|
tool_registry,
|
||||||
code_mode,
|
code_mode,
|
||||||
background_terminal_max_timeout,
|
background_terminal_max_timeout,
|
||||||
|
max_repeated_failures,
|
||||||
thread_unload_delay,
|
thread_unload_delay,
|
||||||
ghost_snapshot,
|
ghost_snapshot,
|
||||||
multi_agent_v2,
|
multi_agent_v2,
|
||||||
|
|||||||
@@ -120,8 +120,10 @@ impl Session {
|
|||||||
.then(|| self.build_effective_session_config(&state.session_configuration));
|
.then(|| self.build_effective_session_config(&state.session_configuration));
|
||||||
state.session_configuration.original_config_do_not_use = Arc::clone(&config);
|
state.session_configuration.original_config_do_not_use = Arc::clone(&config);
|
||||||
if refresh_model_settings {
|
if refresh_model_settings {
|
||||||
state.session_configuration.model_info_overrides.context_windows =
|
state
|
||||||
config.model_context_windows();
|
.session_configuration
|
||||||
|
.model_info_overrides
|
||||||
|
.context_windows = config.model_context_windows();
|
||||||
self.services
|
self.services
|
||||||
.model_client
|
.model_client
|
||||||
.set_model_settings(config.model_provider.models.clone());
|
.set_model_settings(config.model_provider.models.clone());
|
||||||
|
|||||||
177
akode-rs/core/src/session/loop_guard.rs
Normal file
177
akode-rs/core/src/session/loop_guard.rs
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
//! Loop protection: stops a turn when the model keeps repeating the same failing tool call.
|
||||||
|
|
||||||
|
use akode_protocol::models::FunctionCallOutputPayload;
|
||||||
|
use akode_protocol::models::ResponseItem;
|
||||||
|
use serde_json::Value;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
pub(crate) const REPEATED_FAILURE_MESSAGE: &str =
|
||||||
|
"Il modello ripete lo stesso comando senza risultato: turno interrotto.";
|
||||||
|
pub(crate) const SANDBOX_HINT: &str =
|
||||||
|
"Sembra un blocco della sandbox: usa /permissions per concedere più accesso.";
|
||||||
|
|
||||||
|
/// Output lines that change between identical runs (timings, ids) and must not make two
|
||||||
|
/// failures look different.
|
||||||
|
const VOLATILE_PREFIXES: &[&str] = &[
|
||||||
|
"Wall time",
|
||||||
|
"Chunk ID",
|
||||||
|
"Process running with session ID",
|
||||||
|
"Original token count",
|
||||||
|
];
|
||||||
|
|
||||||
|
const SANDBOX_MARKERS: &[&str] = &[
|
||||||
|
"operation not permitted",
|
||||||
|
"unix bind fail",
|
||||||
|
"seatbelt",
|
||||||
|
"landlock",
|
||||||
|
"sandbox denied",
|
||||||
|
"denied by the sandbox",
|
||||||
|
"blocked by the sandbox",
|
||||||
|
];
|
||||||
|
|
||||||
|
struct ToolResult {
|
||||||
|
signature: String,
|
||||||
|
output: String,
|
||||||
|
failed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the message to show when the last `threshold` tool results of the current turn
|
||||||
|
/// (after the latest user message) are the same call with the same failure. `threshold == 0`
|
||||||
|
/// disables the check.
|
||||||
|
pub(crate) fn repeated_failure_message<'a>(
|
||||||
|
items: impl IntoIterator<Item = &'a ResponseItem>,
|
||||||
|
threshold: u32,
|
||||||
|
) -> Option<String> {
|
||||||
|
if threshold == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let results = turn_tool_results(items);
|
||||||
|
let last = results.last().filter(|result| result.failed)?;
|
||||||
|
let streak = results
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.take_while(|result| {
|
||||||
|
result.failed && result.signature == last.signature && result.output == last.output
|
||||||
|
})
|
||||||
|
.count();
|
||||||
|
if streak < threshold as usize {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let lower = last.output.to_lowercase();
|
||||||
|
let mut message = REPEATED_FAILURE_MESSAGE.to_string();
|
||||||
|
if SANDBOX_MARKERS.iter().any(|marker| lower.contains(marker)) {
|
||||||
|
message.push(' ');
|
||||||
|
message.push_str(SANDBOX_HINT);
|
||||||
|
}
|
||||||
|
Some(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
for item in items {
|
||||||
|
match item {
|
||||||
|
ResponseItem::Message { role, .. } if role == "user" => {
|
||||||
|
signatures.clear();
|
||||||
|
results.clear();
|
||||||
|
}
|
||||||
|
ResponseItem::FunctionCall {
|
||||||
|
name,
|
||||||
|
namespace,
|
||||||
|
arguments,
|
||||||
|
call_id,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
signatures.insert(
|
||||||
|
call_id.clone(),
|
||||||
|
call_signature(name, namespace.as_deref(), arguments),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
ResponseItem::CustomToolCall {
|
||||||
|
name,
|
||||||
|
namespace,
|
||||||
|
input,
|
||||||
|
call_id,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
signatures.insert(
|
||||||
|
call_id.clone(),
|
||||||
|
call_signature(name, namespace.as_deref(), input),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
ResponseItem::LocalShellCall {
|
||||||
|
call_id: Some(call_id),
|
||||||
|
action,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
signatures.insert(call_id.clone(), format!("local_shell:{action:?}"));
|
||||||
|
}
|
||||||
|
ResponseItem::FunctionCallOutput {
|
||||||
|
call_id: Some(call_id),
|
||||||
|
output,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
| ResponseItem::CustomToolCallOutput {
|
||||||
|
call_id, output, ..
|
||||||
|
} => {
|
||||||
|
if let Some(signature) = signatures.get(call_id) {
|
||||||
|
results.push(tool_result(signature.clone(), output));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
results
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Identifies a call: shell-like tools by their command only (so a changed timeout or
|
||||||
|
/// justification still counts as the same command), other tools by all their arguments.
|
||||||
|
fn call_signature(name: &str, namespace: Option<&str>, arguments: &str) -> String {
|
||||||
|
let tool = match namespace {
|
||||||
|
Some(namespace) => format!("{namespace}.{name}"),
|
||||||
|
None => name.to_string(),
|
||||||
|
};
|
||||||
|
let parsed = serde_json::from_str::<Value>(arguments).ok();
|
||||||
|
let command = parsed
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|value| value.get("command").or_else(|| value.get("cmd")));
|
||||||
|
match (command, parsed.as_ref()) {
|
||||||
|
(Some(command), _) => format!("{tool}:command={command}"),
|
||||||
|
(None, Some(value)) => format!("{tool}:{value}"),
|
||||||
|
(None, None) => format!("{tool}:{}", arguments.trim()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tool_result(signature: String, payload: &FunctionCallOutputPayload) -> ToolResult {
|
||||||
|
let text = payload.body.to_text().unwrap_or_default();
|
||||||
|
let output = text
|
||||||
|
.lines()
|
||||||
|
.filter(|line| {
|
||||||
|
!VOLATILE_PREFIXES
|
||||||
|
.iter()
|
||||||
|
.any(|prefix| line.trim_start().starts_with(prefix))
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n");
|
||||||
|
let failed = payload.success == Some(false) || has_nonzero_exit_code(&output);
|
||||||
|
ToolResult {
|
||||||
|
signature,
|
||||||
|
output,
|
||||||
|
failed,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_nonzero_exit_code(output: &str) -> bool {
|
||||||
|
output.lines().any(|line| {
|
||||||
|
let line = line.trim();
|
||||||
|
let code = line
|
||||||
|
.strip_prefix("Process exited with code ")
|
||||||
|
.or_else(|| line.strip_prefix("Exit code: "));
|
||||||
|
code.and_then(|code| code.trim().parse::<i64>().ok())
|
||||||
|
.is_some_and(|code| code != 0)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "loop_guard_tests.rs"]
|
||||||
|
mod tests;
|
||||||
133
akode-rs/core/src/session/loop_guard_tests.rs
Normal file
133
akode-rs/core/src/session/loop_guard_tests.rs
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
use super::*;
|
||||||
|
use akode_protocol::models::FunctionCallOutputBody;
|
||||||
|
use pretty_assertions::assert_eq;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn call(call_id: &str, command: &str, timeout_ms: u64) -> ResponseItem {
|
||||||
|
let arguments = json!({ "command": command, "timeout_ms": timeout_ms }).to_string();
|
||||||
|
serde_json::from_value(json!({
|
||||||
|
"type": "function_call",
|
||||||
|
"name": "shell_command",
|
||||||
|
"arguments": arguments,
|
||||||
|
"call_id": call_id,
|
||||||
|
}))
|
||||||
|
.expect("function call")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn output(call_id: &str, text: &str, success: Option<bool>) -> ResponseItem {
|
||||||
|
ResponseItem::FunctionCallOutput {
|
||||||
|
id: None,
|
||||||
|
call_id: Some(call_id.to_string()),
|
||||||
|
name: None,
|
||||||
|
namespace: None,
|
||||||
|
output: FunctionCallOutputPayload {
|
||||||
|
body: FunctionCallOutputBody::Text(text.to_string()),
|
||||||
|
success,
|
||||||
|
},
|
||||||
|
internal_chat_message_metadata_passthrough: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn user(text: &str) -> ResponseItem {
|
||||||
|
serde_json::from_value(json!({
|
||||||
|
"type": "message",
|
||||||
|
"role": "user",
|
||||||
|
"content": [{ "type": "input_text", "text": text }],
|
||||||
|
}))
|
||||||
|
.expect("user message")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exec_failure(wall: &str, error: &str) -> String {
|
||||||
|
format!("Wall time: {wall} seconds\nProcess exited with code 1\nOutput:\n{error}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn repeated(times: usize, error: &str) -> Vec<ResponseItem> {
|
||||||
|
let mut items = vec![user("avvia il server")];
|
||||||
|
for i in 0..times {
|
||||||
|
let id = format!("c{i}");
|
||||||
|
items.push(call(&id, "npm run dev", 1000 + i as u64));
|
||||||
|
items.push(output(&id, &exec_failure(&format!("0.{i}"), error), None));
|
||||||
|
}
|
||||||
|
items
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stops_after_three_identical_failures() {
|
||||||
|
let items = repeated(3, "Error: EADDRINUSE");
|
||||||
|
assert_eq!(
|
||||||
|
repeated_failure_message(&items, 3),
|
||||||
|
Some(REPEATED_FAILURE_MESSAGE.to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(repeated_failure_message(&items[..5], 3), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sandbox_denial_adds_permissions_hint() {
|
||||||
|
let items = repeated(3, "listen: unix bind fail: Operation not permitted");
|
||||||
|
assert_eq!(
|
||||||
|
repeated_failure_message(&items, 3),
|
||||||
|
Some(format!("{REPEATED_FAILURE_MESSAGE} {SANDBOX_HINT}"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn zero_threshold_disables_check() {
|
||||||
|
let items = repeated(5, "boom");
|
||||||
|
assert_eq!(repeated_failure_message(&items, 0), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn different_errors_or_success_break_the_streak() {
|
||||||
|
let mut items = repeated(2, "boom");
|
||||||
|
items.push(call("x", "npm run dev", 1));
|
||||||
|
items.push(output("x", &exec_failure("0.9", "other error"), None));
|
||||||
|
assert_eq!(repeated_failure_message(&items, 3), None);
|
||||||
|
|
||||||
|
let mut items = repeated(3, "boom");
|
||||||
|
items.push(call("ok", "npm run dev", 1));
|
||||||
|
items.push(output(
|
||||||
|
"ok",
|
||||||
|
"Process exited with code 0\nOutput:\nready",
|
||||||
|
None,
|
||||||
|
));
|
||||||
|
assert_eq!(repeated_failure_message(&items, 3), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn new_user_message_resets_the_streak() {
|
||||||
|
let mut items = repeated(2, "boom");
|
||||||
|
items.extend(repeated(1, "boom"));
|
||||||
|
assert_eq!(repeated_failure_message(&items, 3), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_failure_flag_counts_for_non_shell_tools() {
|
||||||
|
let mut items = vec![user("leggi")];
|
||||||
|
for i in 0..3 {
|
||||||
|
let id = format!("r{i}");
|
||||||
|
items.push(
|
||||||
|
serde_json::from_value(json!({
|
||||||
|
"type": "function_call",
|
||||||
|
"name": "read_file",
|
||||||
|
"arguments": "{\"path\":\"/etc/x\"}",
|
||||||
|
"call_id": id,
|
||||||
|
}))
|
||||||
|
.expect("function call"),
|
||||||
|
);
|
||||||
|
items.push(output(&id, "file not found", Some(false)));
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
repeated_failure_message(&items, 3),
|
||||||
|
Some(REPEATED_FAILURE_MESSAGE.to_string())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn prompt_over_context_warning_text() {
|
||||||
|
use crate::session::turn::prompt_over_context_message;
|
||||||
|
assert_eq!(prompt_over_context_message(4000, 8192), None);
|
||||||
|
assert_eq!(
|
||||||
|
prompt_over_context_message(9000, 8192),
|
||||||
|
Some("Il prompt iniziale (~9000 token) supera la finestra del modello (8192).".to_string())
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -254,6 +254,7 @@ mod submission;
|
|||||||
pub(crate) use reasoning_effort::RequestEffortUsage;
|
pub(crate) use reasoning_effort::RequestEffortUsage;
|
||||||
pub(crate) use submission::Submission;
|
pub(crate) use submission::Submission;
|
||||||
mod input_queue;
|
mod input_queue;
|
||||||
|
mod loop_guard;
|
||||||
mod mcp;
|
mod mcp;
|
||||||
mod mcp_prewarm;
|
mod mcp_prewarm;
|
||||||
mod mcp_refresh;
|
mod mcp_refresh;
|
||||||
|
|||||||
@@ -711,6 +711,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(),
|
||||||
|
turn_context.config.max_repeated_failures,
|
||||||
|
)
|
||||||
|
{
|
||||||
|
let event = EventMsg::Error(ErrorEvent {
|
||||||
|
misalignment: None,
|
||||||
|
message,
|
||||||
|
codex_error_info: Some(CodexErrorInfo::Other),
|
||||||
|
rejected_audio_file_ids: Vec::new(),
|
||||||
|
});
|
||||||
|
sess.send_event(&turn_context, event).await;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
let candidate = if needs_follow_up {
|
let candidate = if needs_follow_up {
|
||||||
super::async_compaction::take_ready(&sess, &turn_context).await
|
super::async_compaction::take_ready(&sess, &turn_context).await
|
||||||
} else {
|
} else {
|
||||||
@@ -1622,6 +1638,41 @@ pub(crate) fn build_prompt(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Warns once per session when the estimated prompt already exceeds the model window, so a
|
||||||
|
/// later server error about the context size is not a surprise.
|
||||||
|
async fn warn_if_prompt_exceeds_context_window(
|
||||||
|
sess: &Session,
|
||||||
|
turn_context: &TurnContext,
|
||||||
|
history: &crate::context_manager::ContextManager,
|
||||||
|
) {
|
||||||
|
let Some(window) = turn_context.model_info().resolved_context_window() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(estimated) = history.estimate_token_count(turn_context) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(message) = prompt_over_context_message(estimated, window) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
{
|
||||||
|
let mut state = sess.state.lock().await;
|
||||||
|
if state.prompt_over_context_warned {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state.prompt_over_context_warned = true;
|
||||||
|
}
|
||||||
|
sess.send_event(turn_context, EventMsg::Warning(WarningEvent { message }))
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn prompt_over_context_message(estimated: i64, window: i64) -> Option<String> {
|
||||||
|
(window > 0 && estimated > window).then(|| {
|
||||||
|
format!(
|
||||||
|
"Il prompt iniziale (~{estimated} token) supera la finestra del modello ({window})."
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
#[allow(deprecated)]
|
#[allow(deprecated)]
|
||||||
#[instrument(level = "trace",
|
#[instrument(level = "trace",
|
||||||
@@ -1685,6 +1736,9 @@ async fn run_sampling_request(
|
|||||||
sess.clone_history().await
|
sess.clone_history().await
|
||||||
};
|
};
|
||||||
let input_item_count = history.raw_items().len();
|
let input_item_count = history.raw_items().len();
|
||||||
|
if first_attempt {
|
||||||
|
warn_if_prompt_exceeds_context_window(&sess, &turn_context, &history).await;
|
||||||
|
}
|
||||||
let sampling_step_context = Arc::new(StepContext {
|
let sampling_step_context = Arc::new(StepContext {
|
||||||
sampled_through_sequence: Some(history.input_sequence()),
|
sampled_through_sequence: Some(history.input_sequence()),
|
||||||
..step_context.as_ref().clone()
|
..step_context.as_ref().clone()
|
||||||
|
|||||||
@@ -118,6 +118,8 @@ pub(crate) struct SessionState {
|
|||||||
pub(crate) current_time_reminder: CurrentTimeReminderState,
|
pub(crate) current_time_reminder: CurrentTimeReminderState,
|
||||||
pub(crate) pending_session_start_sources: VecDeque<akode_hooks::SessionStartSource>,
|
pub(crate) pending_session_start_sources: VecDeque<akode_hooks::SessionStartSource>,
|
||||||
initial_settings_pending: bool,
|
initial_settings_pending: bool,
|
||||||
|
/// Set once the "prompt exceeds the model window" warning has been shown.
|
||||||
|
pub(crate) prompt_over_context_warned: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SessionState {
|
impl SessionState {
|
||||||
@@ -168,6 +170,7 @@ impl SessionState {
|
|||||||
current_time_reminder: CurrentTimeReminderState::default(),
|
current_time_reminder: CurrentTimeReminderState::default(),
|
||||||
pending_session_start_sources: VecDeque::new(),
|
pending_session_start_sources: VecDeque::new(),
|
||||||
initial_settings_pending: true,
|
initial_settings_pending: true,
|
||||||
|
prompt_over_context_warned: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -768,14 +768,14 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
|||||||
let proxy = test_credential_broker_network_proxy().await?;
|
let proxy = test_credential_broker_network_proxy().await?;
|
||||||
let dir = tempdir()?;
|
let dir = tempdir()?;
|
||||||
let startup = dir.path().join("startup.sh");
|
let startup = dir.path().join("startup.sh");
|
||||||
std::fs::write(&startup, "export OPENAI_API_KEY='sk-startup-secret'\n")?;
|
std::fs::write(&startup, "export GH_TOKEN='ghp_startup_secret'\n")?;
|
||||||
let snapshot_dir = dir.path().join("snapshots");
|
let snapshot_dir = dir.path().join("snapshots");
|
||||||
std::fs::create_dir(&snapshot_dir)?;
|
std::fs::create_dir(&snapshot_dir)?;
|
||||||
let snapshot = snapshot_dir.join("snapshot.sh");
|
let snapshot = snapshot_dir.join("snapshot.sh");
|
||||||
std::fs::write(
|
std::fs::write(
|
||||||
&snapshot,
|
&snapshot,
|
||||||
format!(
|
format!(
|
||||||
"# Snapshot file\ncorp_auth() {{ printf '%s\\n%s\\n%s' \"$OPENAI_API_KEY\" \"${{GITHUB_TOKEN-unset}}\" \"$1\"; }}\nexport OPENAI_API_KEY='stale'\nexport GITHUB_TOKEN='ghp_snapshot_only'\nexport GH_HOST='github.example.com'\nexport BASH_ENV='{}'\nexport ENV='{}'\nexport ZDOTDIR='{}'\n",
|
"# Snapshot file\ncorp_auth() {{ printf '%s\\n%s\\n%s' \"$GH_TOKEN\" \"${{NPM_TOKEN-unset}}\" \"$1\"; }}\nexport GH_TOKEN='stale'\nexport NPM_TOKEN='npm_snapshot_only'\nexport GH_HOST='github.example.com'\nexport BASH_ENV='{}'\nexport ENV='{}'\nexport ZDOTDIR='{}'\n",
|
||||||
startup.display(),
|
startup.display(),
|
||||||
startup.display(),
|
startup.display(),
|
||||||
dir.path().display()
|
dir.path().display()
|
||||||
@@ -784,25 +784,26 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
|||||||
let (shell, snapshot) = shell_with_snapshot(ShellType::Bash, "/bin/bash", snapshot.abs());
|
let (shell, snapshot) = shell_with_snapshot(ShellType::Bash, "/bin/bash", snapshot.abs());
|
||||||
let mut env = HashMap::from([
|
let mut env = HashMap::from([
|
||||||
(
|
(
|
||||||
"OPENAI_API_KEY".to_string(),
|
"GH_TOKEN".to_string(),
|
||||||
"sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_".to_string(),
|
"ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".to_string(),
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
"AUTH_HEADER".to_string(),
|
"AUTH_HEADER".to_string(),
|
||||||
"Bearer sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
|
"Bearer ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".to_string(),
|
||||||
.to_string(),
|
|
||||||
),
|
),
|
||||||
("GITHUB_TOKEN".to_string(), String::new()),
|
("NPM_TOKEN".to_string(), String::new()),
|
||||||
("BASH_ENV".to_string(), startup.display().to_string()),
|
("BASH_ENV".to_string(), startup.display().to_string()),
|
||||||
("ENV".to_string(), startup.display().to_string()),
|
("ENV".to_string(), startup.display().to_string()),
|
||||||
]);
|
]);
|
||||||
proxy.apply_to_env(&mut env);
|
proxy.apply_to_env(&mut env);
|
||||||
let dummy = env["OPENAI_API_KEY"].clone();
|
let dummy = env["GH_TOKEN"].clone();
|
||||||
let dummy_alias = env["AUTH_HEADER"].clone();
|
let dummy_alias = env["AUTH_HEADER"].clone();
|
||||||
|
assert!(dummy.starts_with("ghp_") && !dummy.contains("abcdefghijklmnopqrstuvwxyzABCDEF"));
|
||||||
|
assert!(!dummy_alias.contains("abcdefghijklmnopqrstuvwxyzABCDEF"));
|
||||||
let mut alias_only_env = env.clone();
|
let mut alias_only_env = env.clone();
|
||||||
alias_only_env.remove("OPENAI_API_KEY");
|
alias_only_env.remove("GH_TOKEN");
|
||||||
let mut empty_canonical_env = env.clone();
|
let mut empty_canonical_env = env.clone();
|
||||||
empty_canonical_env.insert("OPENAI_API_KEY".to_string(), String::new());
|
empty_canonical_env.insert("GH_TOKEN".to_string(), String::new());
|
||||||
let mut absent_alias_env = env.clone();
|
let mut absent_alias_env = env.clone();
|
||||||
absent_alias_env.remove("AUTH_HEADER");
|
absent_alias_env.remove("AUTH_HEADER");
|
||||||
prepare_brokered_shell_snapshot_env(&mut env, Some(&snapshot), &shell);
|
prepare_brokered_shell_snapshot_env(&mut env, Some(&snapshot), &shell);
|
||||||
@@ -832,7 +833,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
|||||||
assert!(output.status.success(), "command failed: {output:?}");
|
assert!(output.status.success(), "command failed: {output:?}");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
String::from_utf8_lossy(&output.stdout),
|
String::from_utf8_lossy(&output.stdout),
|
||||||
format!("{dummy}\nghp_snapshot_only\ngithub.example.com")
|
format!("{dummy}\nnpm_snapshot_only\ngithub.example.com")
|
||||||
);
|
);
|
||||||
|
|
||||||
let (posix_shell, _) = shell_with_snapshot(ShellType::Sh, "/bin/sh", snapshot.clone());
|
let (posix_shell, _) = shell_with_snapshot(ShellType::Sh, "/bin/sh", snapshot.clone());
|
||||||
@@ -850,7 +851,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
|||||||
"-c"
|
"-c"
|
||||||
}
|
}
|
||||||
.to_string(),
|
.to_string(),
|
||||||
"/bin/sh -ic 'printf \"%s|%s\" \"$OPENAI_API_KEY\" \"${ENV-unset}\"'".to_string(),
|
"/bin/sh -ic 'printf \"%s|%s\" \"$GH_TOKEN\" \"${ENV-unset}\"'".to_string(),
|
||||||
],
|
],
|
||||||
shell,
|
shell,
|
||||||
Some(snapshot),
|
Some(snapshot),
|
||||||
@@ -875,7 +876,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
|||||||
Ok(String::from_utf8(output.stdout)?)
|
Ok(String::from_utf8(output.stdout)?)
|
||||||
};
|
};
|
||||||
let posix_startup = dir.path().join("posix-startup.sh");
|
let posix_startup = dir.path().join("posix-startup.sh");
|
||||||
std::fs::write(&posix_startup, "export OPENAI_API_KEY='sk-posix-secret'\n")?;
|
std::fs::write(&posix_startup, "export GH_TOKEN='ghp_posix_secret'\n")?;
|
||||||
let posix_snapshot = dir.path().join("posix-startup-snapshot.sh").abs();
|
let posix_snapshot = dir.path().join("posix-startup-snapshot.sh").abs();
|
||||||
std::fs::write(
|
std::fs::write(
|
||||||
&posix_snapshot,
|
&posix_snapshot,
|
||||||
@@ -1059,9 +1060,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
|||||||
let bash_posix_command = vec![
|
let bash_posix_command = vec![
|
||||||
bash_posix_path.clone(),
|
bash_posix_path.clone(),
|
||||||
"-c".to_string(),
|
"-c".to_string(),
|
||||||
format!(
|
format!("'{bash_posix_path}' -ic 'printf \"%s|%s\" \"$GH_TOKEN\" \"${{ENV-unset}}\"'"),
|
||||||
"'{bash_posix_path}' -ic 'printf \"%s|%s\" \"$OPENAI_API_KEY\" \"${{ENV-unset}}\"'"
|
|
||||||
),
|
|
||||||
];
|
];
|
||||||
let mut tilde_env = env.clone();
|
let mut tilde_env = env.clone();
|
||||||
tilde_env.insert("ENV".to_string(), "~/startup.sh".to_string());
|
tilde_env.insert("ENV".to_string(), "~/startup.sh".to_string());
|
||||||
@@ -1173,7 +1172,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
|||||||
if std::path::Path::new("/bin/zsh").exists() {
|
if std::path::Path::new("/bin/zsh").exists() {
|
||||||
std::fs::write(
|
std::fs::write(
|
||||||
dir.path().join(".zshenv"),
|
dir.path().join(".zshenv"),
|
||||||
"export OPENAI_API_KEY='sk-startup-secret'\n",
|
"export GH_TOKEN='ghp_startup_secret'\n",
|
||||||
)?;
|
)?;
|
||||||
let renamed_zsh = dir.path().join("zsh.exe");
|
let renamed_zsh = dir.path().join("zsh.exe");
|
||||||
std::os::unix::fs::symlink("/bin/zsh", &renamed_zsh)?;
|
std::os::unix::fs::symlink("/bin/zsh", &renamed_zsh)?;
|
||||||
@@ -1183,7 +1182,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
|||||||
let command = vec![
|
let command = vec![
|
||||||
renamed_zsh.display().to_string(),
|
renamed_zsh.display().to_string(),
|
||||||
"-lc".to_string(),
|
"-lc".to_string(),
|
||||||
"printf '%s\\n%s' \"$OPENAI_API_KEY\" \"$ZDOTDIR\"".to_string(),
|
"printf '%s\\n%s' \"$GH_TOKEN\" \"$ZDOTDIR\"".to_string(),
|
||||||
];
|
];
|
||||||
let rewritten = maybe_wrap_shell_lc_with_snapshot(
|
let rewritten = maybe_wrap_shell_lc_with_snapshot(
|
||||||
&command,
|
&command,
|
||||||
@@ -1212,7 +1211,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
|||||||
let system_startup_zsh = system_startup_dir.join("zsh");
|
let system_startup_zsh = system_startup_dir.join("zsh");
|
||||||
akode_utils_cargo_bin::write_executable(
|
akode_utils_cargo_bin::write_executable(
|
||||||
&system_startup_zsh,
|
&system_startup_zsh,
|
||||||
"#!/bin/sh\nexport OPENAI_API_KEY='sk-system-startup-secret'\nexport AUTH_HEADER='Bearer sk-system-startup-secret'\nexec /bin/zsh -ax \"$@\"\n",
|
"#!/bin/sh\nexport GH_TOKEN='ghp_system_startup_secret'\nexport AUTH_HEADER='Bearer ghp_system_startup_secret'\nexec /bin/zsh -ax \"$@\"\n",
|
||||||
)?;
|
)?;
|
||||||
let mut permissions = std::fs::metadata(&system_startup_zsh)?.permissions();
|
let mut permissions = std::fs::metadata(&system_startup_zsh)?.permissions();
|
||||||
permissions.set_mode(0o700);
|
permissions.set_mode(0o700);
|
||||||
@@ -1232,7 +1231,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
|||||||
system_startup_zsh.display().to_string(),
|
system_startup_zsh.display().to_string(),
|
||||||
"-c".to_string(),
|
"-c".to_string(),
|
||||||
format!(
|
format!(
|
||||||
"set +x\nprintf '%s\\n%s\\n%s\\n%s\\n%s\\n' \"${{OPENAI_API_KEY-unset}}\" \"${{AUTH_HEADER-unset}}\" \"${{{SNAPSHOT_BROKERED_VALUE_ENV_PREFIX}AUTH_HEADER-unset}}\" \"${{{SNAPSHOT_BROKERED_VALUE_ENV_PREFIX}OPENAI_API_KEY-unset}}\" \"${{{SNAPSHOT_BROKERED_UNSET_ENV_PREFIX}OPENAI_API_KEY-unset}}\"\nenv -0"
|
"set +x\nprintf '%s\\n%s\\n%s\\n%s\\n%s\\n' \"${{GH_TOKEN-unset}}\" \"${{AUTH_HEADER-unset}}\" \"${{{SNAPSHOT_BROKERED_VALUE_ENV_PREFIX}AUTH_HEADER-unset}}\" \"${{{SNAPSHOT_BROKERED_VALUE_ENV_PREFIX}GH_TOKEN-unset}}\" \"${{{SNAPSHOT_BROKERED_UNSET_ENV_PREFIX}GH_TOKEN-unset}}\"\nenv -0"
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
let system_rewritten = maybe_wrap_shell_lc_with_snapshot(
|
let system_rewritten = maybe_wrap_shell_lc_with_snapshot(
|
||||||
@@ -1258,13 +1257,13 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
|||||||
"{expected_canonical}\n{expected_alias}\nunset\nunset\nunset\n"
|
"{expected_canonical}\n{expected_alias}\nunset\nunset\nunset\n"
|
||||||
))
|
))
|
||||||
.unwrap_or_else(|| panic!("unexpected system startup output: {stdout}"));
|
.unwrap_or_else(|| panic!("unexpected system startup output: {stdout}"));
|
||||||
assert!(!stdout.contains("sk-system-startup-secret"));
|
assert!(!stdout.contains("ghp_system_startup_secret"));
|
||||||
assert!(
|
assert!(
|
||||||
!exported_env
|
!exported_env
|
||||||
.split('\0')
|
.split('\0')
|
||||||
.any(|entry| entry.starts_with("__CODEX_SNAPSHOT_PROXY_OVERRIDE_"))
|
.any(|entry| entry.starts_with("__CODEX_SNAPSHOT_PROXY_OVERRIDE_"))
|
||||||
);
|
);
|
||||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("sk-system-startup-secret"));
|
assert!(!String::from_utf8_lossy(&output.stderr).contains("ghp_system_startup_secret"));
|
||||||
}
|
}
|
||||||
|
|
||||||
for (bash_env, posix_env, zdotdir) in [
|
for (bash_env, posix_env, zdotdir) in [
|
||||||
|
|||||||
@@ -822,12 +822,6 @@ impl CredentialBroker {
|
|||||||
start,
|
start,
|
||||||
start + credential.len(),
|
start + credential.len(),
|
||||||
)
|
)
|
||||||
|| provider.ignored_credential_prefixes.iter().any(|ignored| {
|
|
||||||
credential.starts_with(ignored)
|
|
||||||
&& provider
|
|
||||||
.credential_watermark
|
|
||||||
.is_none_or(|watermark| !credential.contains(watermark))
|
|
||||||
})
|
|
||||||
|| provider.request_header_value(credential).is_none()
|
|| provider.request_header_value(credential).is_none()
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -251,71 +251,15 @@ pub(super) fn virtualize_text(
|
|||||||
offset = start + length;
|
offset = start + length;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let candidate = builtin_credential_candidate(provider, text, start);
|
let length = builtin_credential_candidate(provider, text, start).len();
|
||||||
let length = candidate.len();
|
|
||||||
if provider
|
|
||||||
.ignored_credential_prefixes
|
|
||||||
.iter()
|
|
||||||
.any(|prefix| candidate.starts_with(prefix))
|
|
||||||
&& provider
|
|
||||||
.credential_watermark
|
|
||||||
.is_none_or(|watermark| !candidate.contains(watermark))
|
|
||||||
{
|
|
||||||
let known_length = env
|
|
||||||
.values()
|
|
||||||
.filter(|known| {
|
|
||||||
known.len() >= provider.minimum_credential_len
|
|
||||||
&& candidate
|
|
||||||
.strip_prefix(known.as_str())
|
|
||||||
.is_some_and(|suffix| {
|
|
||||||
provider.credential_prefixes.iter().any(|prefix| {
|
|
||||||
suffix.match_indices(prefix).any(|(offset, _)| {
|
|
||||||
suffix.len() - offset
|
|
||||||
>= provider.minimum_credential_len
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.map(String::len)
|
|
||||||
.min();
|
|
||||||
let embedded_supported = provider
|
|
||||||
.credential_prefixes
|
|
||||||
.iter()
|
|
||||||
.flat_map(|prefix| candidate.match_indices(prefix))
|
|
||||||
.filter_map(|(offset, _)| {
|
|
||||||
(offset > 0
|
|
||||||
&& candidate.len() - offset >= provider.minimum_credential_len
|
|
||||||
&& !provider
|
|
||||||
.ignored_credential_prefixes
|
|
||||||
.iter()
|
|
||||||
.any(|ignored| candidate[offset..].starts_with(ignored)))
|
|
||||||
.then_some(offset)
|
|
||||||
})
|
|
||||||
.min();
|
|
||||||
offset = start
|
|
||||||
+ known_length
|
|
||||||
.into_iter()
|
|
||||||
.chain(embedded_supported)
|
|
||||||
.min()
|
|
||||||
.unwrap_or(length);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let end = start + length;
|
let end = start + length;
|
||||||
let credential = &text[start..end];
|
if length >= provider.minimum_credential_len {
|
||||||
let ignored_credential_match =
|
|
||||||
ignored_credential_match(provider, text, start, credential);
|
|
||||||
if length >= provider.minimum_credential_len && !ignored_credential_match {
|
|
||||||
replacements.add(std::iter::once(start..end), "", /*dummy*/ None);
|
replacements.add(std::iter::once(start..end), "", /*dummy*/ None);
|
||||||
text.replace_range(start..end, &"\0".repeat(length));
|
text.replace_range(start..end, &"\0".repeat(length));
|
||||||
offset = end;
|
offset = end;
|
||||||
allowed = false;
|
allowed = false;
|
||||||
} else {
|
} else {
|
||||||
offset = start
|
offset = start + length;
|
||||||
+ if ignored_credential_match {
|
|
||||||
prefix.len()
|
|
||||||
} else {
|
|
||||||
length
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -405,60 +349,6 @@ pub(super) fn is_operational_path_match(text: &str, start: usize, end: usize) ->
|
|||||||
path.has_root() || path.components().count() > 1 || value.contains('\\')
|
path.has_root() || path.components().count() > 1 || value.contains('\\')
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ignored_credential_match(
|
|
||||||
provider: &providers::CredentialProvider,
|
|
||||||
text: &str,
|
|
||||||
start: usize,
|
|
||||||
credential: &str,
|
|
||||||
) -> bool {
|
|
||||||
provider
|
|
||||||
.ignored_credential_prefixes
|
|
||||||
.iter()
|
|
||||||
.any(|prefix| credential.starts_with(prefix))
|
|
||||||
&& provider
|
|
||||||
.credential_watermark
|
|
||||||
.is_none_or(|watermark| !credential.contains(watermark))
|
|
||||||
|| credential.starts_with("sk-")
|
|
||||||
&& provider
|
|
||||||
.credential_watermark
|
|
||||||
.is_none_or(|watermark| !credential.contains(watermark))
|
|
||||||
&& credential[3..].split(['-', '_']).any(|segment| {
|
|
||||||
segment.len() == 64
|
|
||||||
&& segment.bytes().all(|byte| byte.is_ascii_hexdigit())
|
|
||||||
&& credential
|
|
||||||
.find(segment)
|
|
||||||
.is_some_and(|offset| offset < provider.minimum_credential_len)
|
|
||||||
})
|
|
||||||
&& text[..start]
|
|
||||||
.rsplit(|character: char| {
|
|
||||||
character.is_ascii() && !character.is_ascii_alphanumeric()
|
|
||||||
})
|
|
||||||
.next()
|
|
||||||
.is_some_and(|word| {
|
|
||||||
((1..=3).contains(&word.len())
|
|
||||||
|| word
|
|
||||||
.get(word.len().saturating_sub(2)..)
|
|
||||||
.is_some_and(|suffix| {
|
|
||||||
suffix.eq_ignore_ascii_case("di")
|
|
||||||
|| suffix.eq_ignore_ascii_case("ta")
|
|
||||||
&& !word.eq_ignore_ascii_case("data")
|
|
||||||
})
|
|
||||||
|| credential.strip_prefix("sk-").is_some_and(|hash| {
|
|
||||||
hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit())
|
|
||||||
}))
|
|
||||||
&& word.bytes().all(|byte| byte.is_ascii_alphabetic())
|
|
||||||
&& text[..start]
|
|
||||||
.rsplit_once(['/', '\\'])
|
|
||||||
.is_some_and(|(_, component)| {
|
|
||||||
component.chars().all(|character| {
|
|
||||||
!character.is_ascii()
|
|
||||||
|| character.is_ascii_alphanumeric()
|
|
||||||
|| matches!(character, '_' | '-')
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn recognized_credential_match<'a>(
|
pub(super) fn recognized_credential_match<'a>(
|
||||||
provider: &providers::CredentialProvider,
|
provider: &providers::CredentialProvider,
|
||||||
value: &'a str,
|
value: &'a str,
|
||||||
@@ -466,30 +356,8 @@ pub(super) fn recognized_credential_match<'a>(
|
|||||||
start: usize,
|
start: usize,
|
||||||
) -> Option<&'a str> {
|
) -> Option<&'a str> {
|
||||||
let credential = builtin_credential_candidate(provider, value, start);
|
let credential = builtin_credential_candidate(provider, value, start);
|
||||||
let length = credential.len();
|
(credential.len() >= provider.minimum_credential_len || !virtualized.contains(credential))
|
||||||
let enclosing_start = value.as_bytes()[..start]
|
|
||||||
.iter()
|
|
||||||
.rposition(|byte| !byte.is_ascii_alphanumeric() && !matches!(byte, b'_' | b'-'))
|
|
||||||
.map_or(0, |offset| offset + 1);
|
|
||||||
let enclosing = &value[enclosing_start..start + length];
|
|
||||||
(length >= provider.minimum_credential_len || !virtualized.contains(credential))
|
|
||||||
.then_some(credential)
|
.then_some(credential)
|
||||||
.filter(|credential| !ignored_credential_match(provider, value, start, credential))
|
|
||||||
.filter(|_| {
|
|
||||||
!provider.ignored_credential_prefixes.iter().any(|prefix| {
|
|
||||||
enclosing.match_indices(prefix).any(|(offset, _)| {
|
|
||||||
let ignored = &enclosing[offset..];
|
|
||||||
offset <= start - enclosing_start
|
|
||||||
&& ignored_credential_match(
|
|
||||||
provider,
|
|
||||||
value,
|
|
||||||
enclosing_start + offset,
|
|
||||||
ignored,
|
|
||||||
)
|
|
||||||
&& virtualized.contains(ignored)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn builtin_credential_candidate<'a>(
|
pub(super) fn builtin_credential_candidate<'a>(
|
||||||
|
|||||||
@@ -18,8 +18,6 @@ type TranslateRequestHeader = fn(&HeaderMap, &str, &str) -> Option<HeaderValue>;
|
|||||||
pub(super) struct CredentialProvider {
|
pub(super) struct CredentialProvider {
|
||||||
pub(super) context_env_vars: &'static [&'static str],
|
pub(super) context_env_vars: &'static [&'static str],
|
||||||
pub(super) credential_prefixes: &'static [&'static str],
|
pub(super) credential_prefixes: &'static [&'static str],
|
||||||
pub(super) ignored_credential_prefixes: &'static [&'static str],
|
|
||||||
pub(super) credential_watermark: Option<&'static str>,
|
|
||||||
pub(super) minimum_credential_len: usize,
|
pub(super) minimum_credential_len: usize,
|
||||||
sources: &'static [CredentialSource],
|
sources: &'static [CredentialSource],
|
||||||
dummy_value: fn(&str) -> String,
|
dummy_value: fn(&str) -> String,
|
||||||
|
|||||||
@@ -22,8 +22,6 @@ const GITHUB_CLOUD_HOST_SUFFIXES: &[&str] = &[".ghe.com"];
|
|||||||
pub(super) static PROVIDER: CredentialProvider = CredentialProvider {
|
pub(super) static PROVIDER: CredentialProvider = CredentialProvider {
|
||||||
context_env_vars: &[GH_HOST_ENV_VAR],
|
context_env_vars: &[GH_HOST_ENV_VAR],
|
||||||
credential_prefixes: GITHUB_TOKEN_PREFIXES,
|
credential_prefixes: GITHUB_TOKEN_PREFIXES,
|
||||||
ignored_credential_prefixes: &[],
|
|
||||||
credential_watermark: None,
|
|
||||||
minimum_credential_len: GITHUB_TOKEN_MIN_LEN,
|
minimum_credential_len: GITHUB_TOKEN_MIN_LEN,
|
||||||
sources: &[
|
sources: &[
|
||||||
CredentialSource {
|
CredentialSource {
|
||||||
|
|||||||
@@ -379,6 +379,7 @@ async fn new_config(
|
|||||||
tool_registry: Default::default(),
|
tool_registry: Default::default(),
|
||||||
code_mode: Default::default(),
|
code_mode: Default::default(),
|
||||||
background_terminal_max_timeout: 300_000,
|
background_terminal_max_timeout: 300_000,
|
||||||
|
max_repeated_failures: 3,
|
||||||
thread_unload_delay: std::time::Duration::from_secs(/*secs*/ 60),
|
thread_unload_delay: std::time::Duration::from_secs(/*secs*/ 60),
|
||||||
ghost_snapshot: GhostSnapshotConfig::default(),
|
ghost_snapshot: GhostSnapshotConfig::default(),
|
||||||
multi_agent_v2: MultiAgentV2Config::default(),
|
multi_agent_v2: MultiAgentV2Config::default(),
|
||||||
|
|||||||
@@ -133,7 +133,8 @@ impl App {
|
|||||||
if let Some(effort) = outcome.active_effort.clone()
|
if let Some(effort) = outcome.active_effort.clone()
|
||||||
&& outcome.activate.is_none()
|
&& outcome.activate.is_none()
|
||||||
{
|
{
|
||||||
self.app_event_tx.send(AppEvent::UpdateReasoningEffort(effort));
|
self.app_event_tx
|
||||||
|
.send(AppEvent::UpdateReasoningEffort(effort));
|
||||||
}
|
}
|
||||||
if let Some((provider_id, model)) = outcome.activate {
|
if let Some((provider_id, model)) = outcome.activate {
|
||||||
self.switch_provider(app_server, provider_id, model).await;
|
self.switch_provider(app_server, provider_id, model).await;
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
---
|
---
|
||||||
source: tui/src/app/daemon_menu_tests.rs
|
source: tui/src/app/daemon_menu_tests.rs
|
||||||
assertion_line: 125
|
|
||||||
expression: "render_bottom_popup(&app.chat_widget,\nwidth).replace(r\"C:\\cli-build\\bin\\codex\", \"/x/cli-build/bin/akode\")"
|
expression: "render_bottom_popup(&app.chat_widget,\nwidth).replace(r\"C:\\cli-build\\bin\\codex\", \"/x/cli-build/bin/akode\")"
|
||||||
---
|
---
|
||||||
Agent command center Group: Project g
|
Agent command center Group: Project g
|
||||||
@@ -11,7 +10,7 @@ expression: "render_bottom_popup(&app.chat_widget,\nwidth).replace(r\"C:\\cli-bu
|
|||||||
│
|
│
|
||||||
|
|
||||||
Update daemon and exit aKode?
|
Update daemon and exit aKode?
|
||||||
Use this CLI package v0.1.0 from /x/cli-build/bin/akode. Copy the
|
Use this CLI package v0.2.0 from /x/cli-build/bin/akode. Copy the
|
||||||
complete package and pin it against automatic updates.
|
complete package and pin it against automatic updates.
|
||||||
This may restart the daemon and interrupt active or queued work.
|
This may restart the daemon and interrupt active or queued work.
|
||||||
Codex exits to update in this terminal. Relaunch it afterward.
|
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:
|
enabled:
|
||||||
|
|
||||||
▄▄████▄▄ aKode v0.1.0
|
▄▄████▄▄ aKode v0.2.0
|
||||||
██▀▀██▀▀██ GPT-5.6-Sol · mock
|
██▀▀██▀▀██ GPT-5.6-Sol · mock
|
||||||
██▄▄██▄▄██ /tmp/project
|
██▄▄██▄▄██ /tmp/project
|
||||||
██▀████▀██
|
██▀████▀██
|
||||||
@@ -50,7 +50,7 @@ enabled:
|
|||||||
---
|
---
|
||||||
disabled:
|
disabled:
|
||||||
|
|
||||||
▄▄████▄▄ aKode v0.1.0
|
▄▄████▄▄ aKode v0.2.0
|
||||||
██▀▀██▀▀██ GPT-5.6-Sol · mock
|
██▀▀██▀▀██ GPT-5.6-Sol · mock
|
||||||
██▄▄██▄▄██ /tmp/project
|
██▄▄██▄▄██ /tmp/project
|
||||||
██▀████▀██
|
██▀████▀██
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
---
|
---
|
||||||
source: tui/src/app/tests.rs
|
source: tui/src/app/tests.rs
|
||||||
assertion_line: 9263
|
|
||||||
expression: rendered
|
expression: rendered
|
||||||
---
|
---
|
||||||
|
|
||||||
▄▄████▄▄ aKode v0.1.0
|
▄▄████▄▄ aKode v0.2.0
|
||||||
██▀▀██▀▀██ gpt-test · mock
|
██▀▀██▀▀██ gpt-test · mock
|
||||||
██▄▄██▄▄██ <thread cwd>
|
██▄▄██▄▄██ <thread cwd>
|
||||||
██▀████▀██
|
██▀████▀██
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
---
|
---
|
||||||
source: tui/src/app/tests/realtime_requests.rs
|
source: tui/src/app/tests/realtime_requests.rs
|
||||||
assertion_line: 898
|
|
||||||
expression: "normalize_voice_snapshot_directory(&rendered, &app.config.cwd)"
|
expression: "normalize_voice_snapshot_directory(&rendered, &app.config.cwd)"
|
||||||
---
|
---
|
||||||
|
|
||||||
▄▄████▄▄ aKode v0.1.0
|
▄▄████▄▄ aKode v0.2.0
|
||||||
██▀▀██▀▀██ gpt-test · mock
|
██▀▀██▀▀██ gpt-test · mock
|
||||||
██▄▄██▄▄██ /tmp/project
|
██▄▄██▄▄██ /tmp/project
|
||||||
██▀████▀██
|
██▀████▀██
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
---
|
---
|
||||||
source: tui/src/app/tests/realtime_requests.rs
|
source: tui/src/app/tests/realtime_requests.rs
|
||||||
assertion_line: 1106
|
|
||||||
expression: "normalize_voice_snapshot_directory(&rendered, &app.config.cwd)"
|
expression: "normalize_voice_snapshot_directory(&rendered, &app.config.cwd)"
|
||||||
---
|
---
|
||||||
|
|
||||||
▄▄████▄▄ aKode v0.1.0
|
▄▄████▄▄ aKode v0.2.0
|
||||||
██▀▀██▀▀██ gpt-test · mock
|
██▀▀██▀▀██ gpt-test · mock
|
||||||
██▄▄██▄▄██ /tmp/project
|
██▄▄██▄▄██ /tmp/project
|
||||||
██▀████▀██
|
██▀████▀██
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ Restored owner:
|
|||||||
|
|
||||||
127.0.0.1:9 · gpt-test · /tmp/project ctx 0% · -- t/s
|
127.0.0.1:9 · gpt-test · /tmp/project ctx 0% · -- t/s
|
||||||
|
|
||||||
▄▄████▄▄ aKode v0.1.0
|
▄▄████▄▄ aKode v0.2.0
|
||||||
██▀▀██▀▀██ gpt-test · mock
|
██▀▀██▀▀██ gpt-test · mock
|
||||||
██▄▄██▄▄██ /tmp/project
|
██▄▄██▄▄██ /tmp/project
|
||||||
██▀████▀██
|
██▀████▀██
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
---
|
---
|
||||||
source: tui/src/app/tests/realtime_requests.rs
|
source: tui/src/app/tests/realtime_requests.rs
|
||||||
assertion_line: 723
|
|
||||||
expression: "normalize_voice_snapshot_directory(&rendered, &app.config.cwd)"
|
expression: "normalize_voice_snapshot_directory(&rendered, &app.config.cwd)"
|
||||||
---
|
---
|
||||||
|
|
||||||
▄▄████▄▄ aKode v0.1.0
|
▄▄████▄▄ aKode v0.2.0
|
||||||
██▀▀██▀▀██ gpt-test · mock
|
██▀▀██▀▀██ gpt-test · mock
|
||||||
██▄▄██▄▄██ /tmp/project
|
██▄▄██▄▄██ /tmp/project
|
||||||
██▀████▀██
|
██▀████▀██
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
source: tui/src/app/tests/new_session_tests.rs
|
source: tui/src/app/tests/new_session_tests.rs
|
||||||
expression: "normalize_snapshot_paths(render_bottom_popup(&app.chat_widget, 80))"
|
expression: "normalize_snapshot_paths(render_bottom_popup(&app.chat_widget, 80))"
|
||||||
---
|
---
|
||||||
▄▄████▄▄ aKode v0.1.0
|
▄▄████▄▄ aKode v0.2.0
|
||||||
██▀▀██▀▀██ loading · mock
|
██▀▀██▀▀██ loading · mock
|
||||||
██▄▄██▄▄██ /tmp/project
|
██▄▄██▄▄██ /tmp/project
|
||||||
██▀████▀██
|
██▀████▀██
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: "normalize_snapshot_paths(normalize_agent_center_snapshot(snapshots.
|
|||||||
---
|
---
|
||||||
80 columns
|
80 columns
|
||||||
|
|
||||||
▄▄████▄▄ aKode v0.1.0
|
▄▄████▄▄ aKode v0.2.0
|
||||||
██▀▀██▀▀██ gpt-test · mock
|
██▀▀██▀▀██ gpt-test · mock
|
||||||
██▄▄██▄▄██ /tmp/project
|
██▄▄██▄▄██ /tmp/project
|
||||||
██▀████▀██
|
██▀████▀██
|
||||||
@@ -26,7 +26,7 @@ expression: "normalize_snapshot_paths(normalize_agent_center_snapshot(snapshots.
|
|||||||
|
|
||||||
32 columns
|
32 columns
|
||||||
|
|
||||||
▄▄████▄▄ aKode v0.1.0
|
▄▄████▄▄ aKode v0.2.0
|
||||||
██▀▀██▀▀██ gpt-test · mock
|
██▀▀██▀▀██ gpt-test · mock
|
||||||
██▄▄██▄▄██ /tmp/project
|
██▄▄██▄▄██ /tmp/project
|
||||||
██▀████▀██
|
██▀████▀██
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ use super::popup_consts::MAX_POPUP_ROWS;
|
|||||||
use super::scroll_state::ScrollState;
|
use super::scroll_state::ScrollState;
|
||||||
use super::selection_popup_common::GenericDisplayRow;
|
use super::selection_popup_common::GenericDisplayRow;
|
||||||
|
|
||||||
const MEMORIES_DOC_URL: &str = "https://developers.openai.com/codex/memories";
|
const MEMORIES_DOC_URL: &str = "https://git.difonzo.net/andrea/aKode";
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
enum MemoriesSetting {
|
enum MemoriesSetting {
|
||||||
|
|||||||
@@ -165,7 +165,7 @@ use tracing::warn;
|
|||||||
|
|
||||||
const DEFAULT_MODEL_DISPLAY_NAME: &str = "loading";
|
const DEFAULT_MODEL_DISPLAY_NAME: &str = "loading";
|
||||||
const MEMORIES_ENABLE_NOTICE: &str = "Memories will be enabled in the next session.";
|
const MEMORIES_ENABLE_NOTICE: &str = "Memories will be enabled in the next session.";
|
||||||
const MEMORIES_DOC_URL: &str = "https://developers.openai.com/codex/memories";
|
const MEMORIES_DOC_URL: &str = "https://git.difonzo.net/andrea/aKode";
|
||||||
const PLAN_MODE_REASONING_SCOPE_TITLE: &str = "Apply reasoning change";
|
const PLAN_MODE_REASONING_SCOPE_TITLE: &str = "Apply reasoning change";
|
||||||
const PLAN_MODE_REASONING_SCOPE_PLAN_ONLY: &str = "Apply to Plan mode override";
|
const PLAN_MODE_REASONING_SCOPE_PLAN_ONLY: &str = "Apply to Plan mode override";
|
||||||
const PLAN_MODE_REASONING_SCOPE_ALL_MODES: &str = "Apply to global default and Plan mode override";
|
const PLAN_MODE_REASONING_SCOPE_ALL_MODES: &str = "Apply to global default and Plan mode override";
|
||||||
|
|||||||
@@ -10,5 +10,5 @@ expression: "render_bottom_popup(&chat, 80)"
|
|||||||
this thread
|
this thread
|
||||||
2. Not now Keep memories disabled
|
2. Not now Keep memories disabled
|
||||||
|
|
||||||
Learn more: https://developers.openai.com/codex/memories
|
Learn more: https://git.difonzo.net/andrea/aKode
|
||||||
enter select · esc back
|
enter select · esc back
|
||||||
|
|||||||
@@ -12,6 +12,6 @@ expression: popup
|
|||||||
existing threads
|
existing threads
|
||||||
|
|
||||||
|
|
||||||
Learn more: https://developers.openai.com/codex/memories
|
Learn more: https://git.difonzo.net/andrea/aKode
|
||||||
|
|
||||||
space toggle · enter save/select · esc cancel
|
space toggle · enter save/select · esc cancel
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ source: tui/src/chatwidget/tests/permissions.rs
|
|||||||
expression: popup
|
expression: popup
|
||||||
---
|
---
|
||||||
Set up the aKode agent sandbox to protect your files and control network access. Learn more
|
Set up the aKode agent sandbox to protect your files and control network access. Learn more
|
||||||
<https://developers.openai.com/codex/windows>
|
<https://git.difonzo.net/andrea/aKode>
|
||||||
|
|
||||||
|
|
||||||
› 1. Set up default sandbox (requires Administrator permissions)
|
› 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
|
Your organization requires the default aKode agent sandbox to continue. Set it up to protect your files and control
|
||||||
network access.
|
network access.
|
||||||
Learn more <https://developers.openai.com/codex/windows>
|
Learn more <https://git.difonzo.net/andrea/aKode>
|
||||||
|
|
||||||
|
|
||||||
› 1. Set up default sandbox (requires Administrator permissions)
|
› 1. Set up default sandbox (requires Administrator permissions)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ expression: popup
|
|||||||
Couldn't set up your sandbox with Administrator permissions
|
Couldn't set up your sandbox with Administrator permissions
|
||||||
|
|
||||||
Your organization requires the default sandbox before aKode can continue.
|
Your organization requires the default sandbox before aKode can continue.
|
||||||
Learn more <https://developers.openai.com/codex/windows>
|
Learn more <https://git.difonzo.net/andrea/aKode>
|
||||||
|
|
||||||
|
|
||||||
› 1. Try setting up admin sandbox again
|
› 1. Try setting up admin sandbox again
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ source: tui/src/chatwidget/tests/permissions.rs
|
|||||||
expression: "render_bottom_popup(&chat, 100)"
|
expression: "render_bottom_popup(&chat, 100)"
|
||||||
---
|
---
|
||||||
Set up the aKode agent sandbox to protect your files and control network access. Learn more
|
Set up the aKode agent sandbox to protect your files and control network access. Learn more
|
||||||
<https://developers.openai.com/codex/windows>
|
<https://git.difonzo.net/andrea/aKode>
|
||||||
|
|
||||||
|
|
||||||
› 1. Use non-admin sandbox (higher risk if prompt injected)
|
› 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]
|
#[tokio::test]
|
||||||
async fn windows_sandbox_help_links_keep_complete_wrapped_destinations() {
|
async fn windows_sandbox_help_links_keep_complete_wrapped_destinations() {
|
||||||
let url = "https://developers.openai.com/codex/windows";
|
let url = "https://git.difonzo.net/andrea/aKode";
|
||||||
for fallback in [false, true] {
|
for fallback in [false, true] {
|
||||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
let preset = builtin_approval_presets()
|
let preset = builtin_approval_presets()
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ expression: visible
|
|||||||
Set up the aKode agent sandbox to
|
Set up the aKode agent sandbox to
|
||||||
protect your files and control
|
protect your files and control
|
||||||
network access. Learn more
|
network access. Learn more
|
||||||
<https://developers.openai.com/codex
|
<https://git.difonzo.net/andrea/aKod
|
||||||
/windows>
|
e>
|
||||||
|
|
||||||
|
|
||||||
› 1. Set up default sandbox (requires
|
› 1. Set up default sandbox (requires
|
||||||
|
|||||||
@@ -35,12 +35,12 @@ impl ChatWidget {
|
|||||||
header.push(*Box::new(
|
header.push(*Box::new(
|
||||||
crate::terminal_hyperlinks::HyperlinkText::new(if allow_unelevated {
|
crate::terminal_hyperlinks::HyperlinkText::new(if allow_unelevated {
|
||||||
vec![
|
vec![
|
||||||
line!["Set up the aKode agent sandbox to protect your files and control network access. Learn more <https://developers.openai.com/codex/windows>"],
|
line!["Set up the aKode agent sandbox to protect your files and control network access. Learn more <https://git.difonzo.net/andrea/aKode>"],
|
||||||
]
|
]
|
||||||
} else {
|
} else {
|
||||||
vec![
|
vec![
|
||||||
line!["Your organization requires the default aKode agent sandbox to continue. Set it up to protect your files and control network access."],
|
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://developers.openai.com/codex/windows>"],
|
line!["Learn more <https://git.difonzo.net/andrea/aKode>"],
|
||||||
]
|
]
|
||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
@@ -164,9 +164,7 @@ impl ChatWidget {
|
|||||||
"Your organization requires the default sandbox before aKode can continue."
|
"Your organization requires the default sandbox before aKode can continue."
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
lines.push(line![
|
lines.push(line!["Learn more <https://git.difonzo.net/andrea/aKode>"]);
|
||||||
"Learn more <https://developers.openai.com/codex/windows>"
|
|
||||||
]);
|
|
||||||
|
|
||||||
let mut header = ColumnRenderable::new();
|
let mut header = ColumnRenderable::new();
|
||||||
header.push(crate::terminal_hyperlinks::HyperlinkText::new(lines));
|
header.push(crate::terminal_hyperlinks::HyperlinkText::new(lines));
|
||||||
|
|||||||
@@ -207,10 +207,12 @@ fn parse_setting(setting: Setting, text: &str) -> Result<Option<serde_json::Valu
|
|||||||
}
|
}
|
||||||
let number = || text.replace(',', ".").parse::<f64>().ok();
|
let number = || text.replace(',', ".").parse::<f64>().ok();
|
||||||
match setting {
|
match setting {
|
||||||
Setting::Context | Setting::MaxOutput => match text.replace(['.', '_', ' '], "").parse::<i64>() {
|
Setting::Context | Setting::MaxOutput => {
|
||||||
Ok(value) if value > 0 => Ok(Some(serde_json::json!(value))),
|
match text.replace(['.', '_', ' '], "").parse::<i64>() {
|
||||||
_ => Err("Inserisci un numero intero di token maggiore di zero.".to_string()),
|
Ok(value) if value > 0 => Ok(Some(serde_json::json!(value))),
|
||||||
},
|
_ => Err("Inserisci un numero intero di token maggiore di zero.".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
Setting::Temperature => match number() {
|
Setting::Temperature => match number() {
|
||||||
Some(value) if (0.0..=2.0).contains(&value) => Ok(Some(serde_json::json!(value))),
|
Some(value) if (0.0..=2.0).contains(&value) => Ok(Some(serde_json::json!(value))),
|
||||||
_ => Err("La temperatura va da 0 a 2.".to_string()),
|
_ => Err("La temperatura va da 0 a 2.".to_string()),
|
||||||
@@ -230,13 +232,19 @@ pub(crate) fn model_setting_path(provider_id: &str, model: &str, key: &str) -> S
|
|||||||
format!("model_providers.{provider_id}.models.\"{quoted}\".{key}")
|
format!("model_providers.{provider_id}.models.\"{quoted}\".{key}")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_setting(settings: &mut ProviderModelSettings, setting: Setting, value: &Option<serde_json::Value>) {
|
fn apply_setting(
|
||||||
|
settings: &mut ProviderModelSettings,
|
||||||
|
setting: Setting,
|
||||||
|
value: &Option<serde_json::Value>,
|
||||||
|
) {
|
||||||
let value = value.as_ref();
|
let value = value.as_ref();
|
||||||
match setting {
|
match setting {
|
||||||
Setting::Context => settings.context_window = value.and_then(serde_json::Value::as_i64),
|
Setting::Context => settings.context_window = value.and_then(serde_json::Value::as_i64),
|
||||||
Setting::Temperature => settings.temperature = value.and_then(serde_json::Value::as_f64),
|
Setting::Temperature => settings.temperature = value.and_then(serde_json::Value::as_f64),
|
||||||
Setting::TopP => settings.top_p = value.and_then(serde_json::Value::as_f64),
|
Setting::TopP => settings.top_p = value.and_then(serde_json::Value::as_f64),
|
||||||
Setting::MaxOutput => settings.max_output_tokens = value.and_then(serde_json::Value::as_u64),
|
Setting::MaxOutput => {
|
||||||
|
settings.max_output_tokens = value.and_then(serde_json::Value::as_u64)
|
||||||
|
}
|
||||||
Setting::Reasoning => {
|
Setting::Reasoning => {
|
||||||
settings.reasoning_effort =
|
settings.reasoning_effort =
|
||||||
value.and_then(|value| serde_json::from_value(value.clone()).ok());
|
value.and_then(|value| serde_json::from_value(value.clone()).ok());
|
||||||
@@ -384,7 +392,12 @@ impl EndpointPanel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
fn set_models_for_test(&mut self, provider_id: &str, list: setup_net::ModelList, props: Option<i64>) {
|
fn set_models_for_test(
|
||||||
|
&mut self,
|
||||||
|
provider_id: &str,
|
||||||
|
list: setup_net::ModelList,
|
||||||
|
props: Option<i64>,
|
||||||
|
) {
|
||||||
self.tasks = FuturesUnordered::new();
|
self.tasks = FuturesUnordered::new();
|
||||||
self.models.insert(
|
self.models.insert(
|
||||||
provider_id.to_string(),
|
provider_id.to_string(),
|
||||||
@@ -540,9 +553,8 @@ impl EndpointPanel {
|
|||||||
}
|
}
|
||||||
self.outcome.config_changed = true;
|
self.outcome.config_changed = true;
|
||||||
if self.is_active(&provider_id, Some(&model)) && setting == Setting::Reasoning {
|
if self.is_active(&provider_id, Some(&model)) && setting == Setting::Reasoning {
|
||||||
self.outcome.active_effort = Some(
|
self.outcome.active_effort =
|
||||||
value.and_then(|value| serde_json::from_value(value).ok()),
|
Some(value.and_then(|value| serde_json::from_value(value).ok()));
|
||||||
);
|
|
||||||
}
|
}
|
||||||
self.notice = Some(Notice::Ok(format!("{} salvato.", setting.label())));
|
self.notice = Some(Notice::Ok(format!("{} salvato.", setting.label())));
|
||||||
}
|
}
|
||||||
@@ -607,7 +619,10 @@ impl EndpointPanel {
|
|||||||
info,
|
info,
|
||||||
typed_key: None,
|
typed_key: None,
|
||||||
});
|
});
|
||||||
self.ctx.setup.existing_provider_ids.insert(provider_id.clone());
|
self.ctx
|
||||||
|
.setup
|
||||||
|
.existing_provider_ids
|
||||||
|
.insert(provider_id.clone());
|
||||||
self.ctx.endpoints.len() - 1
|
self.ctx.endpoints.len() - 1
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -706,9 +721,10 @@ impl EndpointPanel {
|
|||||||
let Some(entry) = self.endpoint().cloned() else {
|
let Some(entry) = self.endpoint().cloned() else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let model = self
|
let model = self.selected_model().or_else(|| {
|
||||||
.selected_model()
|
self.loaded()
|
||||||
.or_else(|| self.loaded().and_then(|(list, _)| list.models.first().cloned()));
|
.and_then(|(list, _)| list.models.first().cloned())
|
||||||
|
});
|
||||||
let Some(model) = model else {
|
let Some(model) = model else {
|
||||||
self.notice = Some(Notice::Error(
|
self.notice = Some(Notice::Error(
|
||||||
"Elenco dei modelli non disponibile: non so quale modello usare.".to_string(),
|
"Elenco dei modelli non disponibile: non so quale modello usare.".to_string(),
|
||||||
@@ -757,10 +773,7 @@ impl EndpointPanel {
|
|||||||
.position(|effort| *effort == settings.reasoning_effort)
|
.position(|effort| *effort == settings.reasoning_effort)
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
let next = EFFORTS[(current + 1) % EFFORTS.len()].clone();
|
let next = EFFORTS[(current + 1) % EFFORTS.len()].clone();
|
||||||
self.save_setting(
|
self.save_setting(setting, next.map(|effort| serde_json::json!(effort)));
|
||||||
setting,
|
|
||||||
next.map(|effort| serde_json::json!(effort)),
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let text = match setting {
|
let text = match setting {
|
||||||
@@ -857,7 +870,10 @@ async fn delete_endpoint(
|
|||||||
)],
|
)],
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
for mode in [AuthCredentialsStoreMode::File, AuthCredentialsStoreMode::Keyring] {
|
for mode in [
|
||||||
|
AuthCredentialsStoreMode::File,
|
||||||
|
AuthCredentialsStoreMode::Keyring,
|
||||||
|
] {
|
||||||
let store = akode_login::configured_provider_api_key_store(&codex_home, mode);
|
let store = akode_login::configured_provider_api_key_store(&codex_home, mode);
|
||||||
if let Err(error) = store.delete(&provider_id) {
|
if let Err(error) = store.delete(&provider_id) {
|
||||||
tracing::warn!("could not remove a provider API key: {error}");
|
tracing::warn!("could not remove a provider API key: {error}");
|
||||||
@@ -927,7 +943,11 @@ impl KeyboardHandler for EndpointPanel {
|
|||||||
}
|
}
|
||||||
KeyCode::Tab | KeyCode::Right => self.move_column(true),
|
KeyCode::Tab | KeyCode::Right => self.move_column(true),
|
||||||
KeyCode::BackTab | KeyCode::Left => self.move_column(false),
|
KeyCode::BackTab | KeyCode::Left => self.move_column(false),
|
||||||
KeyCode::Up | KeyCode::Down | KeyCode::PageUp | KeyCode::PageDown | KeyCode::Home
|
KeyCode::Up
|
||||||
|
| KeyCode::Down
|
||||||
|
| KeyCode::PageUp
|
||||||
|
| KeyCode::PageDown
|
||||||
|
| KeyCode::Home
|
||||||
| KeyCode::End => {
|
| KeyCode::End => {
|
||||||
self.move_row(key.code);
|
self.move_row(key.code);
|
||||||
}
|
}
|
||||||
@@ -964,8 +984,7 @@ impl KeyboardHandler for EndpointPanel {
|
|||||||
Column::Settings => match key.code {
|
Column::Settings => match key.code {
|
||||||
KeyCode::Enter => self.start_edit(),
|
KeyCode::Enter => self.start_edit(),
|
||||||
KeyCode::Backspace | KeyCode::Delete => {
|
KeyCode::Backspace | KeyCode::Delete => {
|
||||||
if let Some(setting) = self.settings_rows().get(self.setting_idx).copied()
|
if let Some(setting) = self.settings_rows().get(self.setting_idx).copied() {
|
||||||
{
|
|
||||||
self.save_setting(setting, None);
|
self.save_setting(setting, None);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1040,7 +1059,9 @@ impl EndpointPanel {
|
|||||||
Column::Endpoints => ("Endpoint".to_string(), String::new()),
|
Column::Endpoints => ("Endpoint".to_string(), String::new()),
|
||||||
Column::Models => (
|
Column::Models => (
|
||||||
"Modelli".to_string(),
|
"Modelli".to_string(),
|
||||||
self.endpoint().map(|e| e.label().to_string()).unwrap_or_default(),
|
self.endpoint()
|
||||||
|
.map(|e| e.label().to_string())
|
||||||
|
.unwrap_or_default(),
|
||||||
),
|
),
|
||||||
Column::Settings => (
|
Column::Settings => (
|
||||||
"Impostazioni".to_string(),
|
"Impostazioni".to_string(),
|
||||||
@@ -1210,7 +1231,10 @@ impl EndpointPanel {
|
|||||||
.global_context_window
|
.global_context_window
|
||||||
.map(|window| format!("{window} (globale)"))
|
.map(|window| format!("{window} (globale)"))
|
||||||
.unwrap_or_else(|| "predefinito".to_string());
|
.unwrap_or_else(|| "predefinito".to_string());
|
||||||
let mut spans = vec![set(settings.context_window.map(|v| v.to_string()), fallback)];
|
let mut spans = vec![set(
|
||||||
|
settings.context_window.map(|v| v.to_string()),
|
||||||
|
fallback,
|
||||||
|
)];
|
||||||
if let Some(window) = self.server_window(model) {
|
if let Some(window) = self.server_window(model) {
|
||||||
spans.push(format!(" (server {window})").dim());
|
spans.push(format!(" (server {window})").dim());
|
||||||
}
|
}
|
||||||
@@ -1232,10 +1256,9 @@ impl EndpointPanel {
|
|||||||
settings.reasoning_effort.as_ref().map(effort_label),
|
settings.reasoning_effort.as_ref().map(effort_label),
|
||||||
"predefinito".to_string(),
|
"predefinito".to_string(),
|
||||||
)],
|
)],
|
||||||
Setting::DisplayName => vec![set(
|
Setting::DisplayName => {
|
||||||
settings.display_name.clone(),
|
vec![set(settings.display_name.clone(), short_model_name(model))]
|
||||||
short_model_name(model),
|
}
|
||||||
)],
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1279,7 +1302,11 @@ impl EndpointPanel {
|
|||||||
|
|
||||||
fn hints(&self) -> Vec<(&'static str, &'static str)> {
|
fn hints(&self) -> Vec<(&'static str, &'static str)> {
|
||||||
if self.editing.is_some() {
|
if self.editing.is_some() {
|
||||||
return vec![("invio", "salva"), ("vuoto", "predefinito"), ("esc", "annulla")];
|
return vec![
|
||||||
|
("invio", "salva"),
|
||||||
|
("vuoto", "predefinito"),
|
||||||
|
("esc", "annulla"),
|
||||||
|
];
|
||||||
}
|
}
|
||||||
if self.confirm_delete {
|
if self.confirm_delete {
|
||||||
return vec![("invio", "elimina"), ("esc", "annulla")];
|
return vec![("invio", "elimina"), ("esc", "annulla")];
|
||||||
@@ -1315,10 +1342,15 @@ impl EndpointPanel {
|
|||||||
|
|
||||||
fn notice_line(&self, width: usize) -> Line<'static> {
|
fn notice_line(&self, width: usize) -> Line<'static> {
|
||||||
if self.confirm_delete {
|
if self.confirm_delete {
|
||||||
let name = self.endpoint().map(|e| e.label().to_string()).unwrap_or_default();
|
let name = self
|
||||||
|
.endpoint()
|
||||||
|
.map(|e| e.label().to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
return truncate_line(
|
return truncate_line(
|
||||||
Line::from(Span::styled(
|
Line::from(Span::styled(
|
||||||
format!("Eliminare l'endpoint «{name}» e la sua chiave? invio conferma · esc annulla"),
|
format!(
|
||||||
|
"Eliminare l'endpoint «{name}» e la sua chiave? invio conferma · esc annulla"
|
||||||
|
),
|
||||||
status_style(StatusTone::Attention),
|
status_style(StatusTone::Attention),
|
||||||
)),
|
)),
|
||||||
width,
|
width,
|
||||||
@@ -1374,7 +1406,9 @@ impl WidgetRef for &EndpointPanel {
|
|||||||
// Title row with the close hint on the right.
|
// Title row with the close hint on the right.
|
||||||
let title = "Modelli ed endpoint";
|
let title = "Modelli ed endpoint";
|
||||||
let close = "esc chiudi";
|
let close = "esc chiudi";
|
||||||
let gap = w.saturating_sub(display_width(title) + display_width(close)).max(2);
|
let gap = w
|
||||||
|
.saturating_sub(display_width(title) + display_width(close))
|
||||||
|
.max(2);
|
||||||
put(
|
put(
|
||||||
truncate_line(
|
truncate_line(
|
||||||
Line::from(vec![
|
Line::from(vec![
|
||||||
|
|||||||
@@ -442,7 +442,7 @@ pub(crate) fn empty_mcp_output() -> WebHyperlinkHistoryCell {
|
|||||||
let mut docs_line = HyperlinkLine::new(Line::from(" See the "));
|
let mut docs_line = HyperlinkLine::new(Line::from(" See the "));
|
||||||
docs_line.push_span(
|
docs_line.push_span(
|
||||||
"MCP docs".underlined(),
|
"MCP docs".underlined(),
|
||||||
Some("https://developers.openai.com/codex/mcp"),
|
Some("https://git.difonzo.net/andrea/aKode"),
|
||||||
);
|
);
|
||||||
docs_line.push_span(" to configure them.".into(), /*destination*/ None);
|
docs_line.push_span(" to configure them.".into(), /*destination*/ None);
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
---
|
---
|
||||||
source: tui/src/history_cell/tests.rs
|
source: tui/src/history_cell/tests.rs
|
||||||
assertion_line: 796
|
|
||||||
expression: rendered
|
expression: rendered
|
||||||
---
|
---
|
||||||
|
|
||||||
▄▄████▄▄ aKode v0.1.0
|
▄▄████▄▄ aKode v0.2.0
|
||||||
██▀▀██▀▀██ gpt-5 · mock
|
██▀▀██▀▀██ gpt-5 · mock
|
||||||
██▄▄██▄▄██ /tmp/project
|
██▄▄██▄▄██ /tmp/project
|
||||||
██▀████▀██
|
██▀████▀██
|
||||||
|
|||||||
@@ -424,7 +424,7 @@ fn composite_cell_preserves_child_web_links() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn empty_mcp_output_preserves_docs_hyperlink() {
|
fn empty_mcp_output_preserves_docs_hyperlink() {
|
||||||
let destination = "https://developers.openai.com/codex/mcp";
|
let destination = "https://git.difonzo.net/andrea/aKode";
|
||||||
let cell: Box<dyn HistoryCell> = Box::new(empty_mcp_output());
|
let cell: Box<dyn HistoryCell> = Box::new(empty_mcp_output());
|
||||||
|
|
||||||
insta::assert_snapshot!(render_lines(&cell.display_lines(/*width*/ 80)).join("\n"), @r"
|
insta::assert_snapshot!(render_lines(&cell.display_lines(/*width*/ 80)).join("\n"), @r"
|
||||||
|
|||||||
@@ -164,6 +164,7 @@ pub(crate) mod live_wrap;
|
|||||||
mod local_settings;
|
mod local_settings;
|
||||||
mod rendered_selection;
|
mod rendered_selection;
|
||||||
pub use live_wrap::RowBuilder;
|
pub use live_wrap::RowBuilder;
|
||||||
|
mod endpoint_panel;
|
||||||
mod managed_new_thread_defaults;
|
mod managed_new_thread_defaults;
|
||||||
mod markdown;
|
mod markdown;
|
||||||
mod markdown_render;
|
mod markdown_render;
|
||||||
@@ -172,7 +173,6 @@ mod markdown_text_merge;
|
|||||||
mod mention_codec;
|
mod mention_codec;
|
||||||
mod model_catalog;
|
mod model_catalog;
|
||||||
mod model_display;
|
mod model_display;
|
||||||
mod endpoint_panel;
|
|
||||||
mod model_migration;
|
mod model_migration;
|
||||||
mod motion;
|
mod motion;
|
||||||
mod multi_agents;
|
mod multi_agents;
|
||||||
|
|||||||
@@ -32,7 +32,9 @@ pub(crate) fn set_display_names_from_config(config: &Config) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
*DISPLAY_NAMES.write().unwrap_or_else(PoisonError::into_inner) = Some(names);
|
*DISPLAY_NAMES
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(PoisonError::into_inner) = Some(names);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether `model` is a local file path rather than a plain or `vendor/model` id.
|
/// Whether `model` is a local file path rather than a plain or `vendor/model` id.
|
||||||
@@ -93,7 +95,10 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert_eq!(short_model_name("C:\\models\\qwen3.gguf"), "qwen3");
|
assert_eq!(short_model_name("C:\\models\\qwen3.gguf"), "qwen3");
|
||||||
assert_eq!(short_model_name("flint.gguf"), "flint");
|
assert_eq!(short_model_name("flint.gguf"), "flint");
|
||||||
assert_eq!(short_model_name("qwen/qwen3-coder:free"), "qwen/qwen3-coder:free");
|
assert_eq!(
|
||||||
|
short_model_name("qwen/qwen3-coder:free"),
|
||||||
|
"qwen/qwen3-coder:free"
|
||||||
|
);
|
||||||
assert_eq!(short_model_name("qwen3.6-35b-a3b"), "qwen3.6-35b-a3b");
|
assert_eq!(short_model_name("qwen3.6-35b-a3b"), "qwen3.6-35b-a3b");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -295,7 +295,11 @@ impl SetupWizard {
|
|||||||
} else {
|
} else {
|
||||||
Page::Welcome
|
Page::Welcome
|
||||||
};
|
};
|
||||||
let searx_url = ctx.searx_url.as_deref().map(ProviderInput::from).unwrap_or_default();
|
let searx_url = ctx
|
||||||
|
.searx_url
|
||||||
|
.as_deref()
|
||||||
|
.map(ProviderInput::from)
|
||||||
|
.unwrap_or_default();
|
||||||
let searx_focus = usize::from(ctx.searx_url.is_some());
|
let searx_focus = usize::from(ctx.searx_url.is_some());
|
||||||
Self {
|
Self {
|
||||||
request_frame,
|
request_frame,
|
||||||
@@ -513,9 +517,10 @@ impl SetupWizard {
|
|||||||
self.go(Page::Test);
|
self.go(Page::Test);
|
||||||
self.test = CheckState::Running;
|
self.test = CheckState::Running;
|
||||||
let base = self.base_url.clone();
|
let base = self.base_url.clone();
|
||||||
let key = self
|
let key = self.api_key().or_else(|| {
|
||||||
.api_key()
|
self.endpoint_edit()
|
||||||
.or_else(|| self.endpoint_edit().and_then(|edit| edit.stored_key.clone()));
|
.and_then(|edit| edit.stored_key.clone())
|
||||||
|
});
|
||||||
self.pending = Some(Box::pin(async move {
|
self.pending = Some(Box::pin(async move {
|
||||||
Outcome::Check(setup_net::fetch_models(base, key).await)
|
Outcome::Check(setup_net::fetch_models(base, key).await)
|
||||||
}));
|
}));
|
||||||
@@ -532,7 +537,10 @@ impl SetupWizard {
|
|||||||
let prefix = format!("model_providers.{provider_id}");
|
let prefix = format!("model_providers.{provider_id}");
|
||||||
let mut edits = vec![
|
let mut edits = vec![
|
||||||
replace_config_value(format!("{prefix}.name"), serde_json::json!(name)),
|
replace_config_value(format!("{prefix}.name"), serde_json::json!(name)),
|
||||||
replace_config_value(format!("{prefix}.base_url"), serde_json::json!(self.base_url)),
|
replace_config_value(
|
||||||
|
format!("{prefix}.base_url"),
|
||||||
|
serde_json::json!(self.base_url),
|
||||||
|
),
|
||||||
];
|
];
|
||||||
if self.endpoint_edit().is_none() {
|
if self.endpoint_edit().is_none() {
|
||||||
edits.push(replace_config_value(
|
edits.push(replace_config_value(
|
||||||
@@ -1328,7 +1336,14 @@ impl SetupWizard {
|
|||||||
Page::Endpoint => vec![
|
Page::Endpoint => vec![
|
||||||
("tab/↑/↓", "campo"),
|
("tab/↑/↓", "campo"),
|
||||||
("invio", "avanti"),
|
("invio", "avanti"),
|
||||||
("esc", if self.endpoint_mode() { "annulla" } else { "indietro" }),
|
(
|
||||||
|
"esc",
|
||||||
|
if self.endpoint_mode() {
|
||||||
|
"annulla"
|
||||||
|
} else {
|
||||||
|
"indietro"
|
||||||
|
},
|
||||||
|
),
|
||||||
],
|
],
|
||||||
Page::Model if self.models == ModelsState::Loading => vec![("esc", "indietro")],
|
Page::Model if self.models == ModelsState::Loading => vec![("esc", "indietro")],
|
||||||
Page::Model if self.model_input_active() => {
|
Page::Model if self.model_input_active() => {
|
||||||
@@ -1614,7 +1629,9 @@ impl SetupWizard {
|
|||||||
lines.push(Line::default());
|
lines.push(Line::default());
|
||||||
match &self.test {
|
match &self.test {
|
||||||
CheckState::Idle | CheckState::Running if self.endpoint_mode() => {
|
CheckState::Idle | CheckState::Running if self.endpoint_mode() => {
|
||||||
lines.push(Line::from("Richiesta dell'elenco dei modelli (/models)…".dim()));
|
lines.push(Line::from(
|
||||||
|
"Richiesta dell'elenco dei modelli (/models)…".dim(),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
CheckState::Ok if self.endpoint_mode() => {
|
CheckState::Ok if self.endpoint_mode() => {
|
||||||
lines.push(Line::from(vec![
|
lines.push(Line::from(vec![
|
||||||
|
|||||||
@@ -487,8 +487,13 @@ fn endpoint_mode_edits_keep_the_key_out_of_config() {
|
|||||||
type_text(&mut wizard, SECRET);
|
type_text(&mut wizard, SECRET);
|
||||||
wizard.base_url = "https://mega-link.cloud/v1".to_string();
|
wizard.base_url = "https://mega-link.cloud/v1".to_string();
|
||||||
let edits = wizard.endpoint_config_edits("giulio", "Giulio", true);
|
let edits = wizard.endpoint_config_edits("giulio", "Giulio", true);
|
||||||
let json = serde_json::to_string(&edits.iter().map(|e| (&e.key_path, &e.value)).collect::<Vec<_>>())
|
let json = serde_json::to_string(
|
||||||
.expect("serialize");
|
&edits
|
||||||
|
.iter()
|
||||||
|
.map(|e| (&e.key_path, &e.value))
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
)
|
||||||
|
.expect("serialize");
|
||||||
assert!(!json.contains(SECRET));
|
assert!(!json.contains(SECRET));
|
||||||
assert!(json.contains("model_providers.giulio.api_key"));
|
assert!(json.contains("model_providers.giulio.api_key"));
|
||||||
assert!(!json.contains("model_providers.giulio.models"));
|
assert!(!json.contains("model_providers.giulio.models"));
|
||||||
@@ -509,5 +514,10 @@ fn configured_searxng_is_prefilled_and_kept() {
|
|||||||
let text = render(&wizard, 80, 14);
|
let text = render(&wizard, 80, 14);
|
||||||
assert!(text.contains("http://192.168.40.57:8080"));
|
assert!(text.contains("http://192.168.40.57:8080"));
|
||||||
assert!(text.contains("› [ Mantieni ]"));
|
assert!(text.contains("› [ Mantieni ]"));
|
||||||
assert!(wizard.config_edits("p", "P", false).iter().all(|e| e.key_path != "web_search"));
|
assert!(
|
||||||
|
wizard
|
||||||
|
.config_edits("p", "P", false)
|
||||||
|
.iter()
|
||||||
|
.all(|e| e.key_path != "web_search")
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ expression: rendered
|
|||||||
|
|
||||||
Scegli i colori; potrai cambiarli con /theme.
|
Scegli i colori; potrai cambiarli con /theme.
|
||||||
|
|
||||||
1. Automatico │ ▄▄████▄▄ aKode v0.1.0
|
1. Automatico │ ▄▄████▄▄ aKode v0.2.0
|
||||||
2. Scuro │ ██▀▀██▀▀██ qwen3.6-35b-a3b
|
2. Scuro │ ██▀▀██▀▀██ qwen3.6-35b-a3b
|
||||||
3. Chiaro │ ██▄▄██▄▄██ ~/progetto
|
3. Chiaro │ ██▄▄██▄▄██ ~/progetto
|
||||||
4. Alto contrasto │ ██▀████▀██
|
4. Alto contrasto │ ██▀████▀██
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ expression: rendered
|
|||||||
|
|
||||||
Scegli i colori; potrai cambiarli con /theme.
|
Scegli i colori; potrai cambiarli con /theme.
|
||||||
|
|
||||||
1. Automatico │ ▄▄████▄▄ aKode v0.1.0
|
1. Automatico │ ▄▄████▄▄ aKode v0.2.0
|
||||||
2. Scuro │ ██▀▀██▀▀██ qwen3.6-35b-a3b
|
2. Scuro │ ██▀▀██▀▀██ qwen3.6-35b-a3b
|
||||||
3. Chiaro │ ██▄▄██▄▄██ ~/progetto
|
3. Chiaro │ ██▄▄██▄▄██ ~/progetto
|
||||||
4. Alto contrasto │ ██▀████▀██
|
4. Alto contrasto │ ██▀████▀██
|
||||||
|
|||||||
@@ -88,7 +88,10 @@ async fn configured_welcome_opt_out_disables_splash() -> anyhow::Result<()> {
|
|||||||
// aKode: the splash is opt-in (`[tui.effects] welcome = true`).
|
// aKode: the splash is opt-in (`[tui.effects] welcome = true`).
|
||||||
("", false),
|
("", false),
|
||||||
("[tui.effects]\nwelcome = true\n", true),
|
("[tui.effects]\nwelcome = true\n", true),
|
||||||
("[tui]\nanimations = false\n[tui.effects]\nwelcome = true\n", false),
|
(
|
||||||
|
"[tui]\nanimations = false\n[tui.effects]\nwelcome = true\n",
|
||||||
|
false,
|
||||||
|
),
|
||||||
("[tui.effects]\nwelcome = false\n", false),
|
("[tui.effects]\nwelcome = false\n", false),
|
||||||
(
|
(
|
||||||
"[tui]\nanimations = false\n[tui.effects]\nwelcome = false\n",
|
"[tui]\nanimations = false\n[tui.effects]\nwelcome = false\n",
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex (reasoning none, summaries auto)
|
Model: gpt-5.1-codex (reasoning none, summaries auto)
|
||||||
Directory: [[workspace]]
|
Directory: [[workspace]]
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
---
|
---
|
||||||
source: tui/src/status/tests.rs
|
source: tui/src/status/tests.rs
|
||||||
assertion_line: 1270
|
|
||||||
expression: sanitized
|
expression: sanitized
|
||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex (reasoning none, summaries auto)
|
Model: gpt-5.1-codex (reasoning none, summaries auto)
|
||||||
Directory: [[workspace]]
|
Directory: [[workspace]]
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||||
Directory: [[workspace]]
|
Directory: [[workspace]]
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||||
Directory: [[workspace]]
|
Directory: [[workspace]]
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex-max (reasoning high, summaries detailed)
|
Model: gpt-5.1-codex-max (reasoning high, summaries detailed)
|
||||||
Directory: [[workspace]]
|
Directory: [[workspace]]
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Server: Local background server
|
Server: Local background server
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Server: unix:///tmp/codex-home/app-server-control/app-server-
|
Server: unix:///tmp/codex-home/app-server-control/app-server-
|
||||||
control.sock (v0.133.0)
|
control.sock (v0.133.0)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||||
Directory: [[workspace]]
|
Directory: [[workspace]]
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||||
Directory: [[workspace]]
|
Directory: [[workspace]]
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||||
Directory: [[workspace]]
|
Directory: [[workspace]]
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||||
Directory: [[workspace]]
|
Directory: [[workspace]]
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||||
Directory: [[workspace]]
|
Directory: [[workspace]]
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
---
|
---
|
||||||
source: tui/src/status/tests.rs
|
source: tui/src/status/tests.rs
|
||||||
assertion_line: 1079
|
|
||||||
expression: sanitized
|
expression: sanitized
|
||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: ガパガパガパガ
|
Model: ガパガパガパガ
|
||||||
パ-model (reasoning
|
パ-model (reasoning
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex-max (reasoning high, summaries
|
Model: gpt-5.1-codex-max (reasoning high, summaries
|
||||||
detailed)
|
detailed)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex-max (reasoning medium, summaries auto)
|
Model: gpt-5.1-codex-max (reasoning medium, summaries auto)
|
||||||
Directory: [[workspace]]
|
Directory: [[workspace]]
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ expression: sanitized
|
|||||||
---
|
---
|
||||||
/status
|
/status
|
||||||
|
|
||||||
>_ aKode (v0.1.0)
|
>_ aKode (v0.2.0)
|
||||||
|
|
||||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||||
Directory: [[workspace]]
|
Directory: [[workspace]]
|
||||||
|
|||||||
Reference in New Issue
Block a user