Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions app/src/features/chat/ContextMeter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export function ContextMeter({ bot, onLater }: { bot: Bot; onLater(text: string)
const near = usedTokens >= limit * NEAR;
const left = autoCompactTokens === null ? null : autoCompactTokens - usedTokens;
const claude = bot.agent === "claude";
// Claude Code and Codex answer a request to compact (spec 30).
const compactable = claude || bot.agent === "codex";
const running = bot.state === "idle" || bot.state === "busy" || bot.state === "needs_approval";

const compact = async () => {
Expand Down Expand Up @@ -77,17 +79,19 @@ export function ContextMeter({ bot, onLater }: { bot: Bot; onLater(text: string)
)}
</div>
<p className="mt-2 text-ink-soft text-sm">
{!claude
{!compactable
? m.estimate
: left === null
? m.noAuto
: left > 0
? m.autoLeft(tokens(left), tokens(autoCompactTokens ?? 0))
: m.autoNow}
: bot.agent === "codex"
? m.byItself
: left === null
? m.noAuto
: left > 0
? m.autoLeft(tokens(left), tokens(autoCompactTokens ?? 0))
: m.autoNow}
</p>
<p className="mt-1.5 text-muted text-xs">{m.about(bot.name)}</p>
{/* Only Claude Code answers a request to compact (spec 30). */}
{claude && (
{compactable && (
<div className="mt-3 border-line border-t pt-3">
<Button
size="sm"
Expand Down
23 changes: 23 additions & 0 deletions app/src/features/chat/agentBot.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,27 @@ describe("a Codex bot", () => {
fireEvent.click(screen.getByRole("button", { name: "Model: Default" }));
expect(await screen.findByRole("menu", { name: "Model" })).toBeDefined();
});

test("can compact its conversation, and says Codex does it by itself", async () => {
const fake = new FakeBotloft();
const crew = fake.addCrew("Ops");
const bot = fake.addBot(crew.id, "Cody");
fake.bot(bot.id).agent = "codex";
fake.setBotState(bot.id, "idle");
fake.setContext(bot.id, {
usedTokens: 90_000,
windowTokens: 258_400,
autoCompactTokens: null,
compacting: false,
updatedAt: 0,
});
renderApp(fake);
await crewOpened("Ops");
openBot("Cody");
await screen.findByRole("list", { name: "Messages" });
fireEvent.click(screen.getByRole("button", { name: /Conversation space/ }));
const panel = within(await screen.findByRole("dialog", { name: "Conversation space" }));
expect(panel.getByText(/Codex compacts it by itself/)).toBeDefined();
expect(panel.getByRole("button", { name: "Compact now" })).toBeDefined();
});
});
1 change: 1 addition & 0 deletions app/src/i18n/en/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ export const chat = {
autoLeft: (left: string, at: string) => `${left} left before it compacts by itself, at ${at}.`,
autoNow: "It is full enough to compact by itself on the next message.",
noAuto: "It does not compact by itself.",
byItself: "Codex compacts it by itself when it gets close to full.",
estimate:
"An estimate: this agent does not say how large its window is, so the size comes from its model family.",
compact: "Compact now",
Expand Down
1 change: 1 addition & 0 deletions app/src/i18n/es/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ export const chat: Messages["chat"] = {
autoLeft: (left: string, at: string) => `Faltan ${left} para que se compacte sola, en ${at}.`,
autoNow: "Ya está lo bastante llena para compactarse sola en el próximo mensaje.",
noAuto: "No se compacta sola.",
byItself: "Codex la compacta solo cuando se acerca a llenarse.",
estimate:
"Una estimación: este agente no dice el tamaño de su ventana, así que el tamaño sale de la familia del modelo.",
compact: "Compactar ahora",
Expand Down
1 change: 1 addition & 0 deletions app/src/i18n/pt-BR/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ export const chat: Messages["chat"] = {
`Faltam ${left} para ela se compactar sozinha, em ${at}.`,
autoNow: "Já está cheia o bastante para se compactar sozinha na próxima mensagem.",
noAuto: "Ela não se compacta sozinha.",
byItself: "O Codex compacta sozinho quando a conversa chega perto de encher.",
estimate:
"Uma estimativa: este agente não informa o tamanho da janela, então o tamanho vem da família do modelo.",
compact: "Compactar agora",
Expand Down
4 changes: 4 additions & 0 deletions crates/botloftd/src/agent/codex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ impl Agent for CodexAgent {
false
}

fn can_compact(&self) -> bool {
true
}

fn encode_turn(&self, _uuid: &str, turn: &Turn) -> Bytes {
// The wrapper turns this neutral line into a `turn/start`.
super::neutral_turn_with_images(turn)
Expand Down
117 changes: 114 additions & 3 deletions crates/botloftd/src/agent/codex_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ use std::path::PathBuf;
use std::sync::Arc;

use botloft_core::ids::BotId;
use botloft_core::protocol::{PermissionMode, TokenUsage};
use botloft_core::protocol::{
ChatBody, NoticeCode, NoticeItem, NoticeLevel, PermissionMode, TokenUsage,
};
use serde_json::{Value, json};

use super::OutputDecoder;
use super::codex_wire::{Answer, Shared};
use crate::approvals::{self, Verdict};
use crate::chat::sink;
use crate::chat::{items, sink};
use crate::state::Daemon;

/// Reads what the server prints and tells the daemon.
Expand All @@ -33,6 +35,10 @@ pub(super) struct CodexDecoder {
/// command, or the files a change touches.
commands: HashMap<String, String>,
changes: HashMap<String, Vec<(String, bool)>>,
/// When the usage limit resets, in Unix ms, from `account/rateLimits/updated`.
limit_resets_at: Option<i64>,
/// The running turn is a compaction: no line of its own for it.
compacting: bool,
}

impl CodexDecoder {
Expand All @@ -46,6 +52,8 @@ impl CodexDecoder {
base: (0, 0, 0, 0),
commands: HashMap::new(),
changes: HashMap::new(),
limit_resets_at: None,
compacting: false,
}
}
}
Expand Down Expand Up @@ -109,6 +117,7 @@ impl CodexDecoder {
Answer::Failed(message) => {
tracing::warn!(bot = %bot, "codex could not start a thread: {message:?}");
}
Answer::SignedOut => self.signed_out(daemon, bot, generation),
Answer::Lost | Answer::None => {}
}
}
Expand All @@ -133,7 +142,7 @@ impl CodexDecoder {
}
"mcpServer/elicitation/request" => {
let server = params["serverName"].as_str().unwrap_or("mcp");
let tool = params["_meta"]["tool_name"].as_str().unwrap_or("tool");
let tool = tool_in(params["message"].as_str().unwrap_or_default());
(
format!("mcp__{server}__{tool}"),
params["_meta"]["tool_params"].clone(),
Expand Down Expand Up @@ -206,6 +215,13 @@ impl CodexDecoder {
"item/started" => self.item_started(daemon, bot, generation, params),
"item/completed" => self.item_completed(daemon, bot, &params["item"]),
"thread/tokenUsage/updated" => self.token_usage(daemon, bot, &params["tokenUsage"]),
"account/rateLimits/updated" => {
// Seconds in Codex, milliseconds here.
self.limit_resets_at = params["rateLimits"]["primary"]["resetsAt"]
.as_i64()
.map(|seconds| seconds * 1000)
.or(self.limit_resets_at);
}
"turn/completed" => self.turn_completed(daemon, bot, generation, &params["turn"]),
_ => {}
}
Expand Down Expand Up @@ -260,6 +276,10 @@ impl CodexDecoder {
&json!({ "file_path": change["path"] }),
);
}
Some("contextCompaction") => {
self.compacting = true;
crate::context::status(daemon, bot, &json!({ "status": "compacting" }));
}
Some("mcpToolCall") => {
let name = format!(
"mcp__{}__{}",
Expand All @@ -276,6 +296,16 @@ impl CodexDecoder {
let id = item["id"].as_str().unwrap_or_default();
let ok = item["status"].as_str() == Some("completed");
match item["type"].as_str() {
Some("contextCompaction") => {
// The owner asked, or it was full and Codex did it by itself.
let asked = daemon.contexts.get(bot).is_some_and(|c| c.compacting);
let trigger = if asked { "manual" } else { "auto" };
crate::context::compacted(
daemon,
bot,
&json!({ "compact_metadata": { "trigger": trigger } }),
);
}
Some("agentMessage") => {
sink::reply(daemon, bot, item["text"].as_str().unwrap_or_default());
}
Expand Down Expand Up @@ -326,6 +356,26 @@ impl CodexDecoder {

fn turn_completed(&mut self, daemon: &Daemon, bot: &BotId, generation: u64, turn: &Value) {
let failed = turn["status"].as_str() != Some("completed");
// A compaction ends like a turn; its notice says what happened.
if std::mem::take(&mut self.compacting) && !failed {
self.usage_base();
self.shared.turn_done();
sink::finish_turn(daemon, bot, generation, false);
return;
}
match turn["error"]["codexErrorInfo"].as_str() {
Some("unauthorized") => {
self.signed_out(daemon, bot, generation);
self.shared.turn_done();
return;
}
Some("usageLimitExceeded") => {
self.limit_reached(daemon, bot, generation);
self.shared.turn_done();
return;
}
_ => {}
}
let error = failed.then(|| {
turn["error"]["message"]
.as_str()
Expand Down Expand Up @@ -353,6 +403,58 @@ impl CodexDecoder {
}
}

impl CodexDecoder {
/// What the thread used so far is the base of the next turn.
fn usage_base(&mut self) {
self.base = self.usage;
}

fn notice(&self, daemon: &Daemon, bot: &BotId, text: &str) {
items::add(
daemon,
bot,
ChatBody::Notice(NoticeItem {
level: NoticeLevel::Error,
code: Some(NoticeCode::TurnFailed),
text: text.to_owned(),
}),
);
}

/// Nobody is signed in to Codex: only the owner can fix that, so the bot
/// stops until they restart it (spec 7.3).
fn signed_out(&self, daemon: &Daemon, bot: &BotId, generation: u64) {
self.notice(
daemon,
bot,
"Codex is not signed in. Sign in to Codex (codex login), then restart this bot.",
);
daemon.supervisor.signed_out(bot, generation);
}

/// The account reached its usage limit: messages wait until it resets.
fn limit_reached(&self, daemon: &Daemon, bot: &BotId, generation: u64) {
self.notice(
daemon,
bot,
"Codex reached its usage limit. Messages wait until it resets.",
);
let until = self
.limit_resets_at
.unwrap_or_else(|| daemon.clock.now_ms() + 5 * 60 * 1000);
daemon.supervisor.rate_limited(bot, generation, until);
}
}

/// The tool a request of an MCP server is about: the name in quotes in its
/// message ("Allow the x MCP server to run tool \"y\"?").
fn tool_in(message: &str) -> &str {
message
.split_once("tool \"")
.and_then(|(_, rest)| rest.split_once('"'))
.map_or("tool", |(name, _)| name)
}

/// Whether the request goes ahead: the bot's mode, a rule of the bot, or the
/// owner (spec 10.1).
async fn decide(
Expand Down Expand Up @@ -383,6 +485,15 @@ async fn decide(
mod tests {
use super::*;

#[test]
fn the_tool_is_the_name_in_quotes_of_the_message() {
assert_eq!(
tool_in("Allow the linkedin MCP server to run tool \"read_profile\"?"),
"read_profile"
);
assert_eq!(tool_in("something else"), "tool");
}

#[test]
fn a_text_that_names_a_fenced_folder_is_caught_whatever_the_slashes_and_case() {
let fenced = vec![PathBuf::from(r"C:\Users\Ana\Botloft\Other")];
Expand Down
Loading
Loading