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:
@@ -31,6 +31,19 @@
|
||||
},
|
||||
"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": {
|
||||
"description": "Last selected grouping in Agent Command Center.",
|
||||
"enum": [
|
||||
@@ -7504,6 +7517,14 @@
|
||||
},
|
||||
"description": "Base config deserialized from ~/.akode/config.toml.",
|
||||
"properties": {
|
||||
"agent": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/definitions/AgentToml"
|
||||
}
|
||||
],
|
||||
"description": "Settings for the main agent loop (e.g. loop protection)."
|
||||
},
|
||||
"agents": {
|
||||
"allOf": [
|
||||
{
|
||||
|
||||
@@ -604,7 +604,10 @@ impl ModelClient {
|
||||
/// Replace the per-model settings used for new requests (after a config reload).
|
||||
pub(crate) fn set_model_settings(
|
||||
&self,
|
||||
settings: std::collections::BTreeMap<String, akode_model_provider_info::ProviderModelSettings>,
|
||||
settings: std::collections::BTreeMap<
|
||||
String,
|
||||
akode_model_provider_info::ProviderModelSettings,
|
||||
>,
|
||||
) {
|
||||
*self
|
||||
.state
|
||||
|
||||
@@ -692,6 +692,9 @@ pub enum ThreadStoreConfig {
|
||||
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.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Config {
|
||||
@@ -1218,6 +1221,10 @@ pub struct Config {
|
||||
/// Default: `300000` (5 minutes).
|
||||
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.
|
||||
pub thread_unload_delay: Duration,
|
||||
|
||||
@@ -4213,6 +4220,11 @@ impl Config {
|
||||
.as_ref()
|
||||
.and_then(|agents| agents.interrupt_message)
|
||||
.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
|
||||
.background_terminal_max_timeout
|
||||
.unwrap_or(DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS)
|
||||
@@ -4814,6 +4826,7 @@ impl Config {
|
||||
tool_registry,
|
||||
code_mode,
|
||||
background_terminal_max_timeout,
|
||||
max_repeated_failures,
|
||||
thread_unload_delay,
|
||||
ghost_snapshot,
|
||||
multi_agent_v2,
|
||||
|
||||
@@ -120,8 +120,10 @@ impl Session {
|
||||
.then(|| self.build_effective_session_config(&state.session_configuration));
|
||||
state.session_configuration.original_config_do_not_use = Arc::clone(&config);
|
||||
if refresh_model_settings {
|
||||
state.session_configuration.model_info_overrides.context_windows =
|
||||
config.model_context_windows();
|
||||
state
|
||||
.session_configuration
|
||||
.model_info_overrides
|
||||
.context_windows = config.model_context_windows();
|
||||
self.services
|
||||
.model_client
|
||||
.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 submission::Submission;
|
||||
mod input_queue;
|
||||
mod loop_guard;
|
||||
mod mcp;
|
||||
mod mcp_prewarm;
|
||||
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 {
|
||||
super::async_compaction::take_ready(&sess, &turn_context).await
|
||||
} 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(deprecated)]
|
||||
#[instrument(level = "trace",
|
||||
@@ -1685,6 +1736,9 @@ async fn run_sampling_request(
|
||||
sess.clone_history().await
|
||||
};
|
||||
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 {
|
||||
sampled_through_sequence: Some(history.input_sequence()),
|
||||
..step_context.as_ref().clone()
|
||||
|
||||
@@ -118,6 +118,8 @@ pub(crate) struct SessionState {
|
||||
pub(crate) current_time_reminder: CurrentTimeReminderState,
|
||||
pub(crate) pending_session_start_sources: VecDeque<akode_hooks::SessionStartSource>,
|
||||
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 {
|
||||
@@ -168,6 +170,7 @@ impl SessionState {
|
||||
current_time_reminder: CurrentTimeReminderState::default(),
|
||||
pending_session_start_sources: VecDeque::new(),
|
||||
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 dir = tempdir()?;
|
||||
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");
|
||||
std::fs::create_dir(&snapshot_dir)?;
|
||||
let snapshot = snapshot_dir.join("snapshot.sh");
|
||||
std::fs::write(
|
||||
&snapshot,
|
||||
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(),
|
||||
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 mut env = HashMap::from([
|
||||
(
|
||||
"OPENAI_API_KEY".to_string(),
|
||||
"sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_".to_string(),
|
||||
"GH_TOKEN".to_string(),
|
||||
"ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".to_string(),
|
||||
),
|
||||
(
|
||||
"AUTH_HEADER".to_string(),
|
||||
"Bearer sk-proj-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
|
||||
.to_string(),
|
||||
"Bearer ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".to_string(),
|
||||
),
|
||||
("GITHUB_TOKEN".to_string(), String::new()),
|
||||
("NPM_TOKEN".to_string(), String::new()),
|
||||
("BASH_ENV".to_string(), startup.display().to_string()),
|
||||
("ENV".to_string(), startup.display().to_string()),
|
||||
]);
|
||||
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();
|
||||
assert!(dummy.starts_with("ghp_") && !dummy.contains("abcdefghijklmnopqrstuvwxyzABCDEF"));
|
||||
assert!(!dummy_alias.contains("abcdefghijklmnopqrstuvwxyzABCDEF"));
|
||||
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();
|
||||
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();
|
||||
absent_alias_env.remove("AUTH_HEADER");
|
||||
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_eq!(
|
||||
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());
|
||||
@@ -850,7 +851,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
||||
"-c"
|
||||
}
|
||||
.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,
|
||||
Some(snapshot),
|
||||
@@ -875,7 +876,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
||||
Ok(String::from_utf8(output.stdout)?)
|
||||
};
|
||||
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();
|
||||
std::fs::write(
|
||||
&posix_snapshot,
|
||||
@@ -1059,9 +1060,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
||||
let bash_posix_command = vec![
|
||||
bash_posix_path.clone(),
|
||||
"-c".to_string(),
|
||||
format!(
|
||||
"'{bash_posix_path}' -ic 'printf \"%s|%s\" \"$OPENAI_API_KEY\" \"${{ENV-unset}}\"'"
|
||||
),
|
||||
format!("'{bash_posix_path}' -ic 'printf \"%s|%s\" \"$GH_TOKEN\" \"${{ENV-unset}}\"'"),
|
||||
];
|
||||
let mut tilde_env = env.clone();
|
||||
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() {
|
||||
std::fs::write(
|
||||
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");
|
||||
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![
|
||||
renamed_zsh.display().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(
|
||||
&command,
|
||||
@@ -1212,7 +1211,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
||||
let system_startup_zsh = system_startup_dir.join("zsh");
|
||||
akode_utils_cargo_bin::write_executable(
|
||||
&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();
|
||||
permissions.set_mode(0o700);
|
||||
@@ -1232,7 +1231,7 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
||||
system_startup_zsh.display().to_string(),
|
||||
"-c".to_string(),
|
||||
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(
|
||||
@@ -1258,13 +1257,13 @@ async fn snapshot_wrapper_replays_dummy_and_preserves_unbrokered_credentials() -
|
||||
"{expected_canonical}\n{expected_alias}\nunset\nunset\nunset\n"
|
||||
))
|
||||
.unwrap_or_else(|| panic!("unexpected system startup output: {stdout}"));
|
||||
assert!(!stdout.contains("sk-system-startup-secret"));
|
||||
assert!(!stdout.contains("ghp_system_startup_secret"));
|
||||
assert!(
|
||||
!exported_env
|
||||
.split('\0')
|
||||
.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 [
|
||||
|
||||
Reference in New Issue
Block a user