mirror of
https://github.com/openai/codex.git
synced 2026-11-09 20:50:33 +00:00
## Why `ext/goal` already had the tool specs and contributor wiring for `/goal`, but the installed tools still depended on a placeholder backend that always errored. That meant the extension could not actually own goal persistence even though the dedicated `thread_goals` store already exists. This change wires the extension tools directly to the dedicated goal store so the extension can create, read, and complete goals against real state instead of falling back to host-side placeholders. ## What changed - make `install_with_backend(...)` require `Arc<codex_state::StateRuntime>` so goal storage is always available when the extension is installed - remove the unused no-backend/public backend abstraction from `ext/goal` and have the tool executors talk directly to `StateRuntime` - map `thread_goals` rows into the existing protocol response shape for `get_goal`, `create_goal`, and `update_goal` - preserve current thread-list behavior by filling an empty thread preview from the goal objective when a goal is created through the extension path - add integration coverage for the installed tool surface, including successful goal creation and duplicate-create rejection ## Testing - `cargo test -p codex-goal-extension`
335 lines
11 KiB
Rust
335 lines
11 KiB
Rust
use std::sync::Arc;
|
|
|
|
use async_trait::async_trait;
|
|
use codex_extension_api::FunctionCallError;
|
|
use codex_extension_api::JsonToolOutput;
|
|
use codex_extension_api::ToolCall;
|
|
use codex_extension_api::ToolExecutor;
|
|
use codex_extension_api::ToolName;
|
|
use codex_extension_api::ToolOutput;
|
|
use codex_extension_api::ToolSpec;
|
|
use codex_protocol::ThreadId;
|
|
use codex_protocol::protocol::ThreadGoal;
|
|
use codex_protocol::protocol::ThreadGoalStatus;
|
|
use codex_protocol::protocol::validate_thread_goal_objective;
|
|
use serde::Deserialize;
|
|
use serde::Serialize;
|
|
|
|
use crate::events::GoalEventEmitter;
|
|
use crate::spec::CREATE_GOAL_TOOL_NAME;
|
|
use crate::spec::GET_GOAL_TOOL_NAME;
|
|
use crate::spec::UPDATE_GOAL_TOOL_NAME;
|
|
use crate::spec::create_create_goal_tool;
|
|
use crate::spec::create_get_goal_tool;
|
|
use crate::spec::create_update_goal_tool;
|
|
|
|
#[derive(Clone)]
|
|
pub(crate) struct GoalToolExecutor {
|
|
kind: GoalToolKind,
|
|
thread_id: ThreadId,
|
|
state_db: Arc<codex_state::StateRuntime>,
|
|
event_emitter: GoalEventEmitter,
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
enum GoalToolKind {
|
|
Get,
|
|
Create,
|
|
Update,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub struct CreateGoalRequest {
|
|
pub objective: String,
|
|
pub token_budget: Option<i64>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
struct UpdateGoalArgs {
|
|
status: ThreadGoalStatus,
|
|
}
|
|
|
|
#[derive(Debug, PartialEq, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
struct GoalToolResponse {
|
|
goal: Option<ThreadGoal>,
|
|
remaining_tokens: Option<i64>,
|
|
completion_budget_report: Option<String>,
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
enum CompletionBudgetReport {
|
|
Include,
|
|
Omit,
|
|
}
|
|
|
|
impl GoalToolExecutor {
|
|
pub(crate) fn get(
|
|
thread_id: ThreadId,
|
|
state_db: Arc<codex_state::StateRuntime>,
|
|
event_emitter: GoalEventEmitter,
|
|
) -> Self {
|
|
Self {
|
|
kind: GoalToolKind::Get,
|
|
thread_id,
|
|
state_db,
|
|
event_emitter,
|
|
}
|
|
}
|
|
|
|
pub(crate) fn create(
|
|
thread_id: ThreadId,
|
|
state_db: Arc<codex_state::StateRuntime>,
|
|
event_emitter: GoalEventEmitter,
|
|
) -> Self {
|
|
Self {
|
|
kind: GoalToolKind::Create,
|
|
thread_id,
|
|
state_db,
|
|
event_emitter,
|
|
}
|
|
}
|
|
|
|
pub(crate) fn update(
|
|
thread_id: ThreadId,
|
|
state_db: Arc<codex_state::StateRuntime>,
|
|
event_emitter: GoalEventEmitter,
|
|
) -> Self {
|
|
Self {
|
|
kind: GoalToolKind::Update,
|
|
thread_id,
|
|
state_db,
|
|
event_emitter,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl ToolExecutor<ToolCall> for GoalToolExecutor {
|
|
fn tool_name(&self) -> ToolName {
|
|
ToolName::plain(match self.kind {
|
|
GoalToolKind::Get => GET_GOAL_TOOL_NAME,
|
|
GoalToolKind::Create => CREATE_GOAL_TOOL_NAME,
|
|
GoalToolKind::Update => UPDATE_GOAL_TOOL_NAME,
|
|
})
|
|
}
|
|
|
|
fn spec(&self) -> Option<ToolSpec> {
|
|
Some(match self.kind {
|
|
GoalToolKind::Get => create_get_goal_tool(),
|
|
GoalToolKind::Create => create_create_goal_tool(),
|
|
GoalToolKind::Update => create_update_goal_tool(),
|
|
})
|
|
}
|
|
|
|
async fn handle(&self, invocation: ToolCall) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
|
|
match self.kind {
|
|
GoalToolKind::Get => self.handle_get(invocation).await,
|
|
GoalToolKind::Create => self.handle_create(invocation).await,
|
|
GoalToolKind::Update => self.handle_update(invocation).await,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl GoalToolExecutor {
|
|
async fn handle_get(
|
|
&self,
|
|
invocation: ToolCall,
|
|
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
|
|
let _ = invocation.function_arguments()?;
|
|
let goal = self
|
|
.state_db
|
|
.thread_goals()
|
|
.get_thread_goal(self.thread_id)
|
|
.await
|
|
.map(|goal| goal.map(protocol_goal_from_state))
|
|
.map_err(|err| {
|
|
FunctionCallError::RespondToModel(format!("failed to read goal: {err}"))
|
|
})?;
|
|
goal_response(goal, CompletionBudgetReport::Omit)
|
|
}
|
|
|
|
async fn handle_create(
|
|
&self,
|
|
invocation: ToolCall,
|
|
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
|
|
let mut request: CreateGoalRequest = parse_arguments(invocation.function_arguments()?)?;
|
|
request.objective = request.objective.trim().to_string();
|
|
validate_thread_goal_objective(&request.objective)
|
|
.map_err(FunctionCallError::RespondToModel)?;
|
|
validate_goal_budget(request.token_budget).map_err(FunctionCallError::RespondToModel)?;
|
|
|
|
let goal = self
|
|
.state_db
|
|
.thread_goals()
|
|
.insert_thread_goal(
|
|
self.thread_id,
|
|
request.objective.as_str(),
|
|
codex_state::ThreadGoalStatus::Active,
|
|
request.token_budget,
|
|
)
|
|
.await
|
|
.map_err(|err| FunctionCallError::RespondToModel(format!("failed to create goal: {err}")))?
|
|
.ok_or_else(|| {
|
|
FunctionCallError::RespondToModel(
|
|
"cannot create a new goal because this thread already has a goal; use update_goal only when the existing goal is complete"
|
|
.to_string(),
|
|
)
|
|
})?;
|
|
fill_empty_thread_preview_if_possible(self.state_db.as_ref(), self.thread_id, &goal).await;
|
|
let goal = protocol_goal_from_state(goal);
|
|
self.emit_goal_updated_from_tool_call(&invocation, goal.clone());
|
|
goal_response(Some(goal), CompletionBudgetReport::Omit)
|
|
}
|
|
|
|
async fn handle_update(
|
|
&self,
|
|
invocation: ToolCall,
|
|
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
|
|
let args: UpdateGoalArgs = parse_arguments(invocation.function_arguments()?)?;
|
|
if args.status != ThreadGoalStatus::Complete {
|
|
return Err(FunctionCallError::RespondToModel(
|
|
"update_goal can only mark the existing goal complete; pause, resume, and budget-limited status changes are controlled by the user or system"
|
|
.to_string(),
|
|
));
|
|
}
|
|
|
|
// TODO: update_goal needs a host callback before completion to flush
|
|
// final active-turn accounting with budget steering suppressed.
|
|
let goal = self
|
|
.state_db
|
|
.thread_goals()
|
|
.update_thread_goal(
|
|
self.thread_id,
|
|
codex_state::GoalUpdate {
|
|
objective: None,
|
|
status: Some(codex_state::ThreadGoalStatus::Complete),
|
|
token_budget: None,
|
|
expected_goal_id: None,
|
|
},
|
|
)
|
|
.await
|
|
.map_err(|err| {
|
|
FunctionCallError::RespondToModel(format!("failed to complete goal: {err}"))
|
|
})?
|
|
.map(protocol_goal_from_state)
|
|
.ok_or_else(|| {
|
|
FunctionCallError::RespondToModel(
|
|
"cannot update goal because this thread has no goal".to_string(),
|
|
)
|
|
})?;
|
|
self.emit_goal_updated_from_tool_call(&invocation, goal.clone());
|
|
goal_response(Some(goal), CompletionBudgetReport::Include)
|
|
}
|
|
|
|
fn emit_goal_updated_from_tool_call(&self, invocation: &ToolCall, goal: ThreadGoal) {
|
|
// TODO: ToolCall should expose the current turn submission id so goal
|
|
// tool events can set ThreadGoalUpdatedEvent.turn_id exactly as core
|
|
// does today. Until then, correlate the event with the tool call id.
|
|
self.event_emitter.thread_goal_updated(
|
|
invocation.call_id.clone(),
|
|
/*turn_id*/ None,
|
|
goal,
|
|
);
|
|
}
|
|
}
|
|
|
|
fn parse_arguments<T>(arguments: &str) -> Result<T, FunctionCallError>
|
|
where
|
|
T: for<'de> Deserialize<'de>,
|
|
{
|
|
serde_json::from_str(arguments)
|
|
.map_err(|err| FunctionCallError::RespondToModel(err.to_string()))
|
|
}
|
|
|
|
fn validate_goal_budget(value: Option<i64>) -> Result<(), String> {
|
|
if let Some(value) = value
|
|
&& value <= 0
|
|
{
|
|
return Err("goal budgets must be positive when provided".to_string());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn goal_response(
|
|
goal: Option<ThreadGoal>,
|
|
completion_budget_report: CompletionBudgetReport,
|
|
) -> Result<Box<dyn ToolOutput>, FunctionCallError> {
|
|
let value = serde_json::to_value(GoalToolResponse::new(goal, completion_budget_report))
|
|
.map_err(|err| FunctionCallError::Fatal(err.to_string()))?;
|
|
Ok(Box::new(JsonToolOutput::new(value)))
|
|
}
|
|
|
|
impl GoalToolResponse {
|
|
fn new(goal: Option<ThreadGoal>, report_mode: CompletionBudgetReport) -> Self {
|
|
let remaining_tokens = goal.as_ref().and_then(|goal| {
|
|
goal.token_budget
|
|
.map(|budget| (budget - goal.tokens_used).max(0))
|
|
});
|
|
let completion_budget_report = match report_mode {
|
|
CompletionBudgetReport::Include => goal
|
|
.as_ref()
|
|
.filter(|goal| goal.status == ThreadGoalStatus::Complete)
|
|
.and_then(completion_budget_report),
|
|
CompletionBudgetReport::Omit => None,
|
|
};
|
|
Self {
|
|
goal,
|
|
remaining_tokens,
|
|
completion_budget_report,
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn fill_empty_thread_preview_if_possible(
|
|
state_db: &codex_state::StateRuntime,
|
|
thread_id: ThreadId,
|
|
goal: &codex_state::ThreadGoal,
|
|
) {
|
|
if let Err(err) = state_db
|
|
.set_thread_preview_if_empty(thread_id, goal.objective.as_str())
|
|
.await
|
|
{
|
|
tracing::warn!(
|
|
"failed to set empty thread preview from goal objective for {thread_id}: {err}"
|
|
);
|
|
}
|
|
}
|
|
|
|
fn protocol_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadGoal {
|
|
ThreadGoal {
|
|
thread_id: goal.thread_id,
|
|
objective: goal.objective,
|
|
status: protocol_status_from_state(goal.status),
|
|
token_budget: goal.token_budget,
|
|
tokens_used: goal.tokens_used,
|
|
time_used_seconds: goal.time_used_seconds,
|
|
created_at: goal.created_at.timestamp(),
|
|
updated_at: goal.updated_at.timestamp(),
|
|
}
|
|
}
|
|
|
|
fn protocol_status_from_state(status: codex_state::ThreadGoalStatus) -> ThreadGoalStatus {
|
|
match status {
|
|
codex_state::ThreadGoalStatus::Active => ThreadGoalStatus::Active,
|
|
codex_state::ThreadGoalStatus::Paused => ThreadGoalStatus::Paused,
|
|
codex_state::ThreadGoalStatus::Blocked => ThreadGoalStatus::Blocked,
|
|
codex_state::ThreadGoalStatus::UsageLimited => ThreadGoalStatus::UsageLimited,
|
|
codex_state::ThreadGoalStatus::BudgetLimited => ThreadGoalStatus::BudgetLimited,
|
|
codex_state::ThreadGoalStatus::Complete => ThreadGoalStatus::Complete,
|
|
}
|
|
}
|
|
|
|
fn completion_budget_report(goal: &ThreadGoal) -> Option<String> {
|
|
if goal.token_budget.is_none() && goal.time_used_seconds <= 0 {
|
|
None
|
|
} else {
|
|
Some(
|
|
"Goal achieved. Report final usage from this tool result's structured goal fields. If `goal.tokenBudget` is present, include token usage from `goal.tokensUsed` and `goal.tokenBudget`. If `goal.timeUsedSeconds` is greater than 0, summarize elapsed time in a concise, human-friendly form appropriate to the response language."
|
|
.to_string(),
|
|
)
|
|
}
|
|
}
|