Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
691
akode-rs/ext/goal/src/accounting.rs
Normal file
691
akode-rs/ext/goal/src/accounting.rs
Normal file
@@ -0,0 +1,691 @@
|
||||
use akode_extension_api::ToolCallOutcome;
|
||||
use akode_extension_api::ToolName;
|
||||
use akode_protocol::config_types::ModeKind;
|
||||
use akode_protocol::items::AgentMessageContent;
|
||||
use akode_protocol::items::TurnItem;
|
||||
use akode_protocol::models::MessagePhase;
|
||||
use akode_protocol::protocol::TokenUsage;
|
||||
use akode_state::ThreadGoalStatus;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::AtomicI64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::SemaphorePermit;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct GoalAccountingState {
|
||||
inner: Mutex<GoalAccountingInner>,
|
||||
progress_accounting_lock: Semaphore,
|
||||
// Serialize turn-start accounting with stopping a deferred interrupted turn.
|
||||
// Never hold this lock while submitting a turn or awaiting the goal-state permit.
|
||||
turn_start_lock: Semaphore,
|
||||
descendant_token_usage: AtomicI64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct GoalAccountingInner {
|
||||
current_turn_id: Option<String>,
|
||||
interrupted_turn_id: Option<String>,
|
||||
turns: HashMap<String, GoalTurnAccounting>,
|
||||
wall_clock: GoalWallClockAccounting,
|
||||
budget_limit_reported_goal_id: Option<String>,
|
||||
execution_failure_goal_id: Option<String>,
|
||||
consecutive_execution_failure_turns: u8,
|
||||
automatic_goal_turn_id: Option<String>,
|
||||
consecutive_empty_turns: u8,
|
||||
last_accounted_descendant_token_usage: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct GoalTurnAccounting {
|
||||
current_token_usage: TokenUsage,
|
||||
last_accounted_token_usage: TokenUsage,
|
||||
active_goal_id: Option<String>,
|
||||
account_tokens: bool,
|
||||
failed_execution: bool,
|
||||
successful_tool: bool,
|
||||
empty_final: bool,
|
||||
has_activity: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct GoalWallClockAccounting {
|
||||
last_accounted_at: Instant,
|
||||
active_goal_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct GoalProgressSnapshot {
|
||||
pub(crate) current_token_usage: TokenUsage,
|
||||
current_descendant_token_usage: i64,
|
||||
pub(crate) expected_goal_id: String,
|
||||
pub(crate) time_delta_seconds: i64,
|
||||
pub(crate) token_delta: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct IdleGoalProgressSnapshot {
|
||||
current_descendant_token_usage: i64,
|
||||
pub(crate) expected_goal_id: String,
|
||||
pub(crate) time_delta_seconds: i64,
|
||||
pub(crate) token_delta: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum BudgetLimitedGoalDisposition {
|
||||
KeepActive,
|
||||
ClearActive,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct RecordedTokenDelta {
|
||||
pub(crate) turn_delta: i64,
|
||||
pub(crate) thread_unflushed_delta: i64,
|
||||
}
|
||||
|
||||
impl GoalAccountingState {
|
||||
pub(crate) fn start_turn(
|
||||
&self,
|
||||
turn_id: impl Into<String>,
|
||||
collaboration_mode: ModeKind,
|
||||
token_usage_at_turn_start: &TokenUsage,
|
||||
) {
|
||||
let turn_id = turn_id.into();
|
||||
let mut inner = self.inner();
|
||||
if let Some(interrupted) = inner.interrupted_turn_id.take() {
|
||||
inner.turns.remove(&interrupted);
|
||||
inner.consecutive_empty_turns = 0;
|
||||
}
|
||||
inner.current_turn_id = Some(turn_id.clone());
|
||||
inner.turns.insert(
|
||||
turn_id,
|
||||
GoalTurnAccounting::new(
|
||||
token_usage_at_turn_start.clone(),
|
||||
!matches!(collaboration_mode, ModeKind::Plan),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn current_turn_id(&self) -> Option<String> {
|
||||
self.inner().current_turn_id.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn interrupted_turn_id(&self) -> Option<String> {
|
||||
self.inner().interrupted_turn_id.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn record_tool_outcome(
|
||||
&self,
|
||||
turn_id: &str,
|
||||
tool_name: &ToolName,
|
||||
outcome: ToolCallOutcome,
|
||||
) {
|
||||
let mut inner = self.inner();
|
||||
inner.consecutive_empty_turns = 0;
|
||||
let Some(turn) = inner.turns.get_mut(turn_id) else {
|
||||
return;
|
||||
};
|
||||
turn.has_activity = true;
|
||||
if turn.active_goal_id.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
match outcome {
|
||||
ToolCallOutcome::Completed { success: true } => {
|
||||
turn.successful_tool = true;
|
||||
inner.execution_failure_goal_id = None;
|
||||
inner.consecutive_execution_failure_turns = 0;
|
||||
}
|
||||
ToolCallOutcome::Failed {
|
||||
handler_executed: true,
|
||||
} if tool_name.is_default_namespace() && tool_name.name == "exec" => {
|
||||
turn.failed_execution = true;
|
||||
}
|
||||
ToolCallOutcome::Completed { success: false }
|
||||
| ToolCallOutcome::Failed { .. }
|
||||
| ToolCallOutcome::Blocked
|
||||
| ToolCallOutcome::Aborted => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn execution_failure_goal(&self, turn_id: &str) -> Option<String> {
|
||||
let mut inner = self.inner();
|
||||
let turn = inner.turns.get(turn_id)?;
|
||||
let goal_id = turn.active_goal_id.clone()?;
|
||||
if turn.successful_tool {
|
||||
return None;
|
||||
}
|
||||
if !turn.failed_execution {
|
||||
return None;
|
||||
}
|
||||
|
||||
if inner.execution_failure_goal_id.as_deref() != Some(goal_id.as_str()) {
|
||||
inner.execution_failure_goal_id = Some(goal_id.clone());
|
||||
inner.consecutive_execution_failure_turns = 0;
|
||||
}
|
||||
inner.consecutive_execution_failure_turns =
|
||||
inner.consecutive_execution_failure_turns.saturating_add(1);
|
||||
(inner.consecutive_execution_failure_turns >= 3).then_some(goal_id)
|
||||
}
|
||||
|
||||
pub(crate) fn record_item(&self, turn_id: &str, item: &TurnItem) {
|
||||
let mut inner = self.inner();
|
||||
let Some(turn) = inner.turns.get_mut(turn_id) else {
|
||||
return;
|
||||
};
|
||||
match item {
|
||||
TurnItem::AgentMessage(message) => {
|
||||
let has_text = message.content.iter().any(|content| match content {
|
||||
AgentMessageContent::Text { text } => !text.trim().is_empty(),
|
||||
});
|
||||
turn.has_activity |= has_text || message.questions.is_some();
|
||||
turn.empty_final |=
|
||||
!has_text && matches!(message.phase, Some(MessagePhase::FinalAnswer) | None);
|
||||
}
|
||||
TurnItem::Reasoning(reasoning) => {
|
||||
turn.has_activity |= reasoning
|
||||
.summary_text
|
||||
.iter()
|
||||
.any(|text| !text.trim().is_empty());
|
||||
}
|
||||
TurnItem::UserMessage(_)
|
||||
| TurnItem::FunctionCallOutput(_)
|
||||
| TurnItem::HookPrompt(_)
|
||||
| TurnItem::Plan(_)
|
||||
| TurnItem::CommandExecution(_)
|
||||
| TurnItem::DynamicToolCall(_)
|
||||
| TurnItem::CollabAgentToolCall(_)
|
||||
| TurnItem::SubAgentActivity(_)
|
||||
| TurnItem::WebSearch(_)
|
||||
| TurnItem::ImageView(_)
|
||||
| TurnItem::Extension(_)
|
||||
| TurnItem::ImageGeneration(_)
|
||||
| TurnItem::EnteredReviewMode(_)
|
||||
| TurnItem::ExitedReviewMode(_)
|
||||
| TurnItem::FileChange(_)
|
||||
| TurnItem::McpToolCall(_)
|
||||
| TurnItem::ContextCompaction(_) => turn.has_activity = true,
|
||||
}
|
||||
if turn.has_activity {
|
||||
inner.consecutive_empty_turns = 0;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mark_goal_continuation(&self, turn_id: String) {
|
||||
self.inner().automatic_goal_turn_id = Some(turn_id);
|
||||
}
|
||||
|
||||
pub(crate) fn reset_empty_responses(&self) {
|
||||
let mut inner = self.inner();
|
||||
inner.automatic_goal_turn_id = None;
|
||||
inner.consecutive_empty_turns = 0;
|
||||
}
|
||||
|
||||
/// Evaluated under the goal-state permit after automatic admission records its turn ID.
|
||||
pub(crate) fn empty_response_goal(&self, turn_id: &str) -> Option<String> {
|
||||
let mut inner = self.inner();
|
||||
let interrupted = inner.interrupted_turn_id.as_deref() == Some(turn_id);
|
||||
if interrupted {
|
||||
inner.interrupted_turn_id = None;
|
||||
}
|
||||
let automatic = inner.automatic_goal_turn_id.as_deref() == Some(turn_id);
|
||||
let turn = inner.turns.get_mut(turn_id)?;
|
||||
let goal_id = turn.active_goal_id.clone()?;
|
||||
let empty = automatic && !turn.has_activity && (turn.empty_final || interrupted);
|
||||
turn.empty_final = false;
|
||||
if !empty {
|
||||
inner.consecutive_empty_turns = 0;
|
||||
return None;
|
||||
}
|
||||
inner.consecutive_empty_turns = inner.consecutive_empty_turns.saturating_add(1);
|
||||
(inner.consecutive_empty_turns >= 3).then_some(goal_id)
|
||||
}
|
||||
|
||||
/// Acquires the per-thread progress-accounting permit.
|
||||
///
|
||||
/// Hold the returned permit from before taking a progress snapshot until after the persistent
|
||||
/// usage write has succeeded and the snapshot has been marked accounted. This serializes
|
||||
/// concurrent tool-completion hooks so only one hook can charge a given token or time delta.
|
||||
pub(crate) async fn progress_accounting_permit(
|
||||
&self,
|
||||
) -> Result<SemaphorePermit<'_>, tokio::sync::AcquireError> {
|
||||
self.progress_accounting_lock.acquire().await
|
||||
}
|
||||
|
||||
pub(crate) async fn turn_start_permit(
|
||||
&self,
|
||||
) -> Result<SemaphorePermit<'_>, tokio::sync::AcquireError> {
|
||||
self.turn_start_lock.acquire().await
|
||||
}
|
||||
|
||||
pub(crate) fn current_active_goal_id_for_turn(&self, turn_id: &str) -> Option<String> {
|
||||
let inner = self.inner();
|
||||
if inner
|
||||
.current_turn_id
|
||||
.as_deref()
|
||||
.or(inner.interrupted_turn_id.as_deref())
|
||||
!= Some(turn_id)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let turn = inner.turns.get(turn_id)?;
|
||||
if !turn.account_tokens {
|
||||
return None;
|
||||
}
|
||||
turn.active_goal_id.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn record_token_usage(
|
||||
&self,
|
||||
turn_id: impl Into<String>,
|
||||
total_usage: &TokenUsage,
|
||||
) -> Option<RecordedTokenDelta> {
|
||||
let turn_id = turn_id.into();
|
||||
let mut inner = self.inner();
|
||||
let turn = inner.turns.get_mut(&turn_id)?;
|
||||
turn.current_token_usage = total_usage.clone();
|
||||
if !turn.account_tokens {
|
||||
return None;
|
||||
}
|
||||
|
||||
let delta = turn.token_delta_since_last_accounting();
|
||||
if delta <= 0 {
|
||||
return None;
|
||||
}
|
||||
Some(RecordedTokenDelta {
|
||||
turn_delta: delta,
|
||||
thread_unflushed_delta: inner.thread_unflushed_token_delta(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn record_descendant_token_usage(&self, usage: &TokenUsage) {
|
||||
let delta = goal_token_delta_for_usage(usage);
|
||||
if delta > 0 {
|
||||
self.descendant_token_usage
|
||||
.fetch_add(delta, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mark_turn_goal_active(&self, turn_id: &str, goal_id: impl Into<String>) {
|
||||
let mut inner = self.inner();
|
||||
let goal_id = goal_id.into();
|
||||
if inner.budget_limit_reported_goal_id.as_deref() != Some(goal_id.as_str()) {
|
||||
inner.budget_limit_reported_goal_id = None;
|
||||
}
|
||||
if let Some(turn) = inner.turns.get_mut(turn_id) {
|
||||
turn.active_goal_id = Some(goal_id.clone());
|
||||
if inner.current_turn_id.as_deref() == Some(turn_id) {
|
||||
if inner.wall_clock.active_goal_id.as_deref() != Some(goal_id.as_str()) {
|
||||
inner.consecutive_empty_turns = 0;
|
||||
inner.last_accounted_descendant_token_usage =
|
||||
self.descendant_token_usage.load(Ordering::Relaxed);
|
||||
}
|
||||
inner.wall_clock.mark_active_goal(goal_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mark_current_turn_goal_active(
|
||||
&self,
|
||||
goal_id: impl Into<String>,
|
||||
) -> Option<String> {
|
||||
let mut inner = self.inner();
|
||||
let turn_id = inner.current_turn_id.clone()?;
|
||||
let goal_id = goal_id.into();
|
||||
if inner.budget_limit_reported_goal_id.as_deref() != Some(goal_id.as_str()) {
|
||||
inner.budget_limit_reported_goal_id = None;
|
||||
}
|
||||
let goal_changed = inner.wall_clock.active_goal_id.as_deref() != Some(goal_id.as_str());
|
||||
let turn = inner.turns.get_mut(turn_id.as_str())?;
|
||||
if turn.active_goal_id.as_deref() != Some(goal_id.as_str()) {
|
||||
turn.failed_execution = false;
|
||||
turn.successful_tool = false;
|
||||
}
|
||||
turn.active_goal_id = Some(goal_id.clone());
|
||||
if goal_changed {
|
||||
turn.reset_baseline_to_current();
|
||||
inner.automatic_goal_turn_id = None;
|
||||
inner.consecutive_empty_turns = 0;
|
||||
inner.last_accounted_descendant_token_usage =
|
||||
self.descendant_token_usage.load(Ordering::Relaxed);
|
||||
}
|
||||
inner.wall_clock.mark_active_goal(goal_id);
|
||||
Some(turn_id)
|
||||
}
|
||||
|
||||
pub(crate) fn mark_idle_goal_active(&self, goal_id: impl Into<String>) {
|
||||
let mut inner = self.inner();
|
||||
let goal_id = goal_id.into();
|
||||
if inner.budget_limit_reported_goal_id.as_deref() != Some(goal_id.as_str()) {
|
||||
inner.budget_limit_reported_goal_id = None;
|
||||
}
|
||||
if inner.wall_clock.active_goal_id.as_deref() != Some(goal_id.as_str()) {
|
||||
inner.consecutive_empty_turns = 0;
|
||||
inner.last_accounted_descendant_token_usage =
|
||||
self.descendant_token_usage.load(Ordering::Relaxed);
|
||||
}
|
||||
inner.wall_clock.mark_active_goal(goal_id);
|
||||
}
|
||||
|
||||
pub(crate) fn clear_current_turn_goal(&self) -> Option<String> {
|
||||
let mut inner = self.inner();
|
||||
let turn_id = inner.current_turn_id.clone()?;
|
||||
if let Some(turn) = inner.turns.get_mut(turn_id.as_str()) {
|
||||
turn.active_goal_id = None;
|
||||
}
|
||||
inner.wall_clock.clear_active_goal();
|
||||
inner.budget_limit_reported_goal_id = None;
|
||||
inner.execution_failure_goal_id = None;
|
||||
inner.consecutive_execution_failure_turns = 0;
|
||||
inner.automatic_goal_turn_id = None;
|
||||
inner.consecutive_empty_turns = 0;
|
||||
Some(turn_id)
|
||||
}
|
||||
|
||||
pub(crate) fn clear_active_goal(&self) {
|
||||
let mut inner = self.inner();
|
||||
if let Some(turn_id) = inner.current_turn_id.clone()
|
||||
&& let Some(turn) = inner.turns.get_mut(turn_id.as_str())
|
||||
{
|
||||
turn.active_goal_id = None;
|
||||
}
|
||||
inner.wall_clock.clear_active_goal();
|
||||
inner.budget_limit_reported_goal_id = None;
|
||||
inner.execution_failure_goal_id = None;
|
||||
inner.consecutive_execution_failure_turns = 0;
|
||||
inner.automatic_goal_turn_id = None;
|
||||
inner.consecutive_empty_turns = 0;
|
||||
}
|
||||
|
||||
pub(crate) fn progress_snapshot(&self, turn_id: &str) -> Option<GoalProgressSnapshot> {
|
||||
let inner = self.inner();
|
||||
let turn = inner.turns.get(turn_id)?;
|
||||
if !turn.account_tokens {
|
||||
return None;
|
||||
}
|
||||
let expected_goal_id = turn.active_goal_id()?;
|
||||
let current_descendant_token_usage = self.descendant_token_usage.load(Ordering::Relaxed);
|
||||
let descendant_token_delta = current_descendant_token_usage
|
||||
.saturating_sub(inner.last_accounted_descendant_token_usage);
|
||||
let token_delta = turn
|
||||
.token_delta_since_last_accounting()
|
||||
.saturating_add(descendant_token_delta);
|
||||
let time_delta_seconds =
|
||||
if inner.wall_clock.active_goal_id.as_deref() == Some(expected_goal_id.as_str()) {
|
||||
inner.wall_clock.time_delta_since_last_accounting()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if time_delta_seconds == 0 && token_delta <= 0 {
|
||||
return None;
|
||||
}
|
||||
Some(GoalProgressSnapshot {
|
||||
current_token_usage: turn.current_token_usage.clone(),
|
||||
current_descendant_token_usage,
|
||||
expected_goal_id,
|
||||
time_delta_seconds,
|
||||
token_delta,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn idle_progress_snapshot(&self) -> Option<IdleGoalProgressSnapshot> {
|
||||
let inner = self.inner();
|
||||
let expected_goal_id = inner.wall_clock.active_goal_id.clone()?;
|
||||
let time_delta_seconds = inner.wall_clock.time_delta_since_last_accounting();
|
||||
let current_descendant_token_usage = self.descendant_token_usage.load(Ordering::Relaxed);
|
||||
let token_delta = current_descendant_token_usage
|
||||
.saturating_sub(inner.last_accounted_descendant_token_usage);
|
||||
if time_delta_seconds == 0 && token_delta <= 0 {
|
||||
return None;
|
||||
}
|
||||
Some(IdleGoalProgressSnapshot {
|
||||
current_descendant_token_usage,
|
||||
expected_goal_id,
|
||||
time_delta_seconds,
|
||||
token_delta,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn mark_progress_accounted_for_status(
|
||||
&self,
|
||||
turn_id: &str,
|
||||
snapshot: &GoalProgressSnapshot,
|
||||
status: ThreadGoalStatus,
|
||||
budget_limited_goal_disposition: BudgetLimitedGoalDisposition,
|
||||
) {
|
||||
let clear_active_goal = should_clear_active_goal(status, budget_limited_goal_disposition);
|
||||
let mut inner = self.inner();
|
||||
if let Some(turn) = inner.turns.get_mut(turn_id) {
|
||||
turn.last_accounted_token_usage = snapshot.current_token_usage.clone();
|
||||
if clear_active_goal {
|
||||
turn.active_goal_id = None;
|
||||
}
|
||||
}
|
||||
inner.last_accounted_descendant_token_usage = snapshot.current_descendant_token_usage;
|
||||
inner.wall_clock.mark_accounted(snapshot.time_delta_seconds);
|
||||
if clear_active_goal {
|
||||
inner.wall_clock.clear_active_goal();
|
||||
}
|
||||
if status != ThreadGoalStatus::BudgetLimited {
|
||||
inner.budget_limit_reported_goal_id = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn interrupt_turn(&self, turn_id: &str) {
|
||||
let mut inner = self.inner();
|
||||
if inner.current_turn_id.as_deref() == Some(turn_id) {
|
||||
// Abort can run on the submission loop: defer evaluation until idle so
|
||||
// it never waits for the goal-state permit held by automatic admission.
|
||||
inner.current_turn_id = None;
|
||||
inner.interrupted_turn_id = Some(turn_id.to_string());
|
||||
} else {
|
||||
inner.turns.remove(turn_id);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish_turn(&self, turn_id: &str) {
|
||||
let mut inner = self.inner();
|
||||
inner.turns.remove(turn_id);
|
||||
if inner.current_turn_id.as_deref() == Some(turn_id) {
|
||||
inner.current_turn_id = None;
|
||||
}
|
||||
if inner.interrupted_turn_id.as_deref() == Some(turn_id) {
|
||||
inner.interrupted_turn_id = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mark_idle_progress_accounted_for_status(
|
||||
&self,
|
||||
snapshot: &IdleGoalProgressSnapshot,
|
||||
status: ThreadGoalStatus,
|
||||
budget_limited_goal_disposition: BudgetLimitedGoalDisposition,
|
||||
) {
|
||||
let clear_active_goal = should_clear_active_goal(status, budget_limited_goal_disposition);
|
||||
let mut inner = self.inner();
|
||||
inner.last_accounted_descendant_token_usage = snapshot.current_descendant_token_usage;
|
||||
inner.wall_clock.mark_accounted(snapshot.time_delta_seconds);
|
||||
if clear_active_goal {
|
||||
inner.wall_clock.clear_active_goal();
|
||||
}
|
||||
if status != ThreadGoalStatus::BudgetLimited {
|
||||
inner.budget_limit_reported_goal_id = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn reset_idle_progress_baseline_and_clear_active_goal(&self) {
|
||||
let mut inner = self.inner();
|
||||
inner.wall_clock.reset_baseline();
|
||||
inner.wall_clock.clear_active_goal();
|
||||
inner.budget_limit_reported_goal_id = None;
|
||||
}
|
||||
|
||||
pub(crate) fn mark_budget_limit_reported_if_new(&self, goal_id: &str) -> bool {
|
||||
let mut inner = self.inner();
|
||||
if inner.budget_limit_reported_goal_id.as_deref() == Some(goal_id) {
|
||||
return false;
|
||||
}
|
||||
inner.budget_limit_reported_goal_id = Some(goal_id.to_string());
|
||||
true
|
||||
}
|
||||
|
||||
fn inner(&self) -> std::sync::MutexGuard<'_, GoalAccountingInner> {
|
||||
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GoalAccountingState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
inner: Mutex::new(GoalAccountingInner::default()),
|
||||
progress_accounting_lock: Semaphore::new(/*permits*/ 1),
|
||||
turn_start_lock: Semaphore::new(/*permits*/ 1),
|
||||
descendant_token_usage: AtomicI64::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn token_delta_since_last_accounting(last: &TokenUsage, current: &TokenUsage) -> i64 {
|
||||
let delta = TokenUsage {
|
||||
input_tokens: current.input_tokens.saturating_sub(last.input_tokens),
|
||||
cached_input_tokens: current
|
||||
.cached_input_tokens
|
||||
.saturating_sub(last.cached_input_tokens),
|
||||
cache_write_input_tokens: current
|
||||
.cache_write_input_tokens
|
||||
.saturating_sub(last.cache_write_input_tokens),
|
||||
output_tokens: current.output_tokens.saturating_sub(last.output_tokens),
|
||||
reasoning_output_tokens: current
|
||||
.reasoning_output_tokens
|
||||
.saturating_sub(last.reasoning_output_tokens),
|
||||
total_tokens: current.total_tokens.saturating_sub(last.total_tokens),
|
||||
codex_rollout_budget_units: None,
|
||||
};
|
||||
goal_token_delta_for_usage(&delta)
|
||||
}
|
||||
|
||||
pub(crate) fn goal_token_delta_for_usage(usage: &TokenUsage) -> i64 {
|
||||
usage
|
||||
.input_tokens
|
||||
.saturating_sub(usage.cached_input_tokens)
|
||||
.saturating_add(usage.output_tokens.max(0))
|
||||
}
|
||||
|
||||
impl Default for GoalAccountingInner {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
current_turn_id: None,
|
||||
interrupted_turn_id: None,
|
||||
turns: HashMap::new(),
|
||||
wall_clock: GoalWallClockAccounting::new(),
|
||||
budget_limit_reported_goal_id: None,
|
||||
execution_failure_goal_id: None,
|
||||
consecutive_execution_failure_turns: 0,
|
||||
automatic_goal_turn_id: None,
|
||||
consecutive_empty_turns: 0,
|
||||
last_accounted_descendant_token_usage: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GoalAccountingInner {
|
||||
fn thread_unflushed_token_delta(&self) -> i64 {
|
||||
self.turns
|
||||
.values()
|
||||
.filter(|turn| turn.account_tokens)
|
||||
.fold(0_i64, |total, turn| {
|
||||
total.saturating_add(turn.token_delta_since_last_accounting().max(0))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl GoalTurnAccounting {
|
||||
fn new(current_token_usage: TokenUsage, account_tokens: bool) -> Self {
|
||||
Self {
|
||||
last_accounted_token_usage: current_token_usage.clone(),
|
||||
current_token_usage,
|
||||
active_goal_id: None,
|
||||
account_tokens,
|
||||
failed_execution: false,
|
||||
successful_tool: false,
|
||||
empty_final: false,
|
||||
has_activity: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn active_goal_id(&self) -> Option<String> {
|
||||
self.active_goal_id.clone()
|
||||
}
|
||||
|
||||
fn reset_baseline_to_current(&mut self) {
|
||||
self.last_accounted_token_usage = self.current_token_usage.clone();
|
||||
}
|
||||
|
||||
fn token_delta_since_last_accounting(&self) -> i64 {
|
||||
token_delta_since_last_accounting(
|
||||
&self.last_accounted_token_usage,
|
||||
&self.current_token_usage,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl GoalWallClockAccounting {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
last_accounted_at: Instant::now(),
|
||||
active_goal_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn time_delta_since_last_accounting(&self) -> i64 {
|
||||
i64::try_from(self.last_accounted_at.elapsed().as_secs()).unwrap_or(i64::MAX)
|
||||
}
|
||||
|
||||
fn mark_accounted(&mut self, accounted_seconds: i64) {
|
||||
if accounted_seconds <= 0 {
|
||||
return;
|
||||
}
|
||||
let advance = Duration::from_secs(u64::try_from(accounted_seconds).unwrap_or(u64::MAX));
|
||||
self.last_accounted_at = self
|
||||
.last_accounted_at
|
||||
.checked_add(advance)
|
||||
.unwrap_or_else(Instant::now);
|
||||
}
|
||||
|
||||
fn reset_baseline(&mut self) {
|
||||
self.last_accounted_at = Instant::now();
|
||||
}
|
||||
|
||||
fn mark_active_goal(&mut self, goal_id: impl Into<String>) {
|
||||
let goal_id = goal_id.into();
|
||||
if self.active_goal_id.as_deref() != Some(goal_id.as_str()) {
|
||||
self.reset_baseline();
|
||||
self.active_goal_id = Some(goal_id);
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_active_goal(&mut self) {
|
||||
self.active_goal_id = None;
|
||||
self.reset_baseline();
|
||||
}
|
||||
}
|
||||
|
||||
fn should_clear_active_goal(
|
||||
status: ThreadGoalStatus,
|
||||
budget_limited_goal_disposition: BudgetLimitedGoalDisposition,
|
||||
) -> bool {
|
||||
match status {
|
||||
ThreadGoalStatus::Active => false,
|
||||
ThreadGoalStatus::BudgetLimited => matches!(
|
||||
budget_limited_goal_disposition,
|
||||
BudgetLimitedGoalDisposition::ClearActive
|
||||
),
|
||||
ThreadGoalStatus::Paused
|
||||
| ThreadGoalStatus::Blocked
|
||||
| ThreadGoalStatus::UsageLimited
|
||||
| ThreadGoalStatus::Complete => true,
|
||||
}
|
||||
}
|
||||
377
akode-rs/ext/goal/src/api.rs
Normal file
377
akode-rs/ext/goal/src/api.rs
Normal file
@@ -0,0 +1,377 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::Weak;
|
||||
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_protocol::protocol::ThreadGoal;
|
||||
use akode_protocol::protocol::ThreadGoalStatus;
|
||||
use akode_protocol::protocol::ThreadGoalUpdatedEvent;
|
||||
use akode_protocol::protocol::validate_thread_goal_objective;
|
||||
use akode_rollout::RolloutItem;
|
||||
|
||||
use crate::runtime::GoalRuntimeHandle;
|
||||
use crate::runtime::PreviousGoalSnapshot;
|
||||
use crate::tool::fill_empty_thread_preview_if_possible;
|
||||
use crate::tool::protocol_goal_from_state;
|
||||
use crate::tool::state_status_from_protocol;
|
||||
use crate::tool::validate_goal_budget;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum GoalServiceError {
|
||||
InvalidRequest(String),
|
||||
Internal(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for GoalServiceError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidRequest(message) | Self::Internal(message) => f.write_str(message),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for GoalServiceError {}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GoalObjectiveUpdate<'a> {
|
||||
Keep,
|
||||
Set(&'a str),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GoalTokenBudgetUpdate {
|
||||
Keep,
|
||||
Set(Option<i64>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct GoalSetRequest<'a> {
|
||||
pub thread_id: ThreadId,
|
||||
pub objective: GoalObjectiveUpdate<'a>,
|
||||
pub status: Option<ThreadGoalStatus>,
|
||||
pub token_budget: GoalTokenBudgetUpdate,
|
||||
pub max_goal_token_budget: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GoalSetOutcome {
|
||||
pub goal: ThreadGoal,
|
||||
state_goal: akode_state::ThreadGoal,
|
||||
previous_goal: Option<PreviousGoalSnapshot>,
|
||||
}
|
||||
|
||||
impl GoalSetOutcome {
|
||||
pub fn thread_goal_updated_item(&self) -> RolloutItem {
|
||||
RolloutItem::EventMsg(EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
|
||||
thread_id: self.goal.thread_id,
|
||||
turn_id: None,
|
||||
goal: self.goal.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn apply_runtime_effects(&self, goal_service: &GoalService) {
|
||||
if let Some(runtime) = goal_service.runtime_for_thread(self.goal.thread_id)
|
||||
&& let Err(err) = runtime
|
||||
.apply_external_goal_set(self.state_goal.clone(), self.previous_goal.clone())
|
||||
.await
|
||||
{
|
||||
tracing::warn!("failed to apply external goal status runtime effects: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct GoalService {
|
||||
runtimes: Mutex<HashMap<String, Weak<GoalRuntimeHandle>>>,
|
||||
}
|
||||
|
||||
impl GoalService {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Restores persisted goal state into the registered runtime for `thread_id`.
|
||||
pub async fn restore_thread_runtime_after_resume(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
) -> Result<(), GoalServiceError> {
|
||||
let runtime = self.runtime_for_thread(thread_id).ok_or_else(|| {
|
||||
GoalServiceError::Internal(format!(
|
||||
"goal runtime is unavailable for thread {thread_id}"
|
||||
))
|
||||
})?;
|
||||
runtime
|
||||
.restore_after_resume()
|
||||
.await
|
||||
.map_err(GoalServiceError::Internal)
|
||||
}
|
||||
|
||||
/// Flushes any in-flight goal accounting before a fork copies the source goal snapshot.
|
||||
pub async fn flush_thread_goal_progress_for_fork(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
) -> Result<(), GoalServiceError> {
|
||||
let Some(runtime) = self.runtime_for_thread(thread_id) else {
|
||||
return Ok(());
|
||||
};
|
||||
let _goal_state_permit = runtime
|
||||
.goal_state_permit()
|
||||
.await
|
||||
.map_err(GoalServiceError::Internal)?;
|
||||
runtime
|
||||
.prepare_external_goal_mutation()
|
||||
.await
|
||||
.map_err(GoalServiceError::Internal)
|
||||
}
|
||||
|
||||
pub async fn get_thread_goal(
|
||||
&self,
|
||||
state_db: &akode_state::StateRuntime,
|
||||
thread_id: ThreadId,
|
||||
) -> Result<Option<ThreadGoal>, GoalServiceError> {
|
||||
state_db
|
||||
.thread_goals()
|
||||
.get_thread_goal(thread_id)
|
||||
.await
|
||||
.map(|goal| goal.map(protocol_goal_from_state))
|
||||
.map_err(|err| GoalServiceError::Internal(format!("failed to read thread goal: {err}")))
|
||||
}
|
||||
|
||||
/// Records the user's instruction after validation and before changing goal state.
|
||||
/// The recording future runs under the runtime's goal mutation permit; failure leaves
|
||||
/// the goal unchanged. Recorded user intent remains valid if the database write fails.
|
||||
pub async fn set_thread_goal(
|
||||
&self,
|
||||
state_db: &akode_state::StateRuntime,
|
||||
request: GoalSetRequest<'_>,
|
||||
record_user_instruction: impl Future<Output = Result<(), GoalServiceError>> + Send,
|
||||
) -> Result<GoalSetOutcome, GoalServiceError> {
|
||||
let GoalSetRequest {
|
||||
thread_id,
|
||||
objective,
|
||||
status,
|
||||
token_budget,
|
||||
max_goal_token_budget,
|
||||
} = request;
|
||||
let status = status.map(state_status_from_protocol);
|
||||
let objective = match objective {
|
||||
GoalObjectiveUpdate::Keep => None,
|
||||
GoalObjectiveUpdate::Set(objective) => Some(objective.trim()),
|
||||
};
|
||||
let token_budget = match token_budget {
|
||||
GoalTokenBudgetUpdate::Keep => None,
|
||||
GoalTokenBudgetUpdate::Set(token_budget) => {
|
||||
Some(token_budget.or(max_goal_token_budget))
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(objective) = objective {
|
||||
validate_thread_goal_objective(objective).map_err(GoalServiceError::InvalidRequest)?;
|
||||
}
|
||||
if objective.is_some() || token_budget.is_some() {
|
||||
validate_goal_budget(token_budget.flatten(), max_goal_token_budget)
|
||||
.map_err(GoalServiceError::InvalidRequest)?;
|
||||
}
|
||||
|
||||
let runtime = self.runtime_for_thread(thread_id);
|
||||
// Hold this through the prepare/write window so idle continuation cannot
|
||||
// launch from goal state that this external mutation is about to change.
|
||||
let _goal_state_permit = match runtime.as_ref() {
|
||||
Some(runtime) => Some(
|
||||
runtime
|
||||
.goal_state_permit()
|
||||
.await
|
||||
.map_err(GoalServiceError::Internal)?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
if let Some(runtime) = runtime.as_ref()
|
||||
&& let Err(err) = runtime.prepare_external_goal_mutation().await
|
||||
{
|
||||
tracing::warn!("failed to prepare external goal mutation: {err}");
|
||||
}
|
||||
|
||||
let existing_goal = state_db
|
||||
.thread_goals()
|
||||
.get_thread_goal(thread_id)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
GoalServiceError::Internal(format!("failed to read thread goal: {err}"))
|
||||
})?;
|
||||
if objective.is_none() && existing_goal.is_none() {
|
||||
return Err(GoalServiceError::InvalidRequest(format!(
|
||||
"cannot update goal for thread {thread_id}: no goal exists"
|
||||
)));
|
||||
}
|
||||
record_user_instruction.await?;
|
||||
|
||||
let (goal, previous_goal) = if let Some(objective) = objective {
|
||||
if let Some(existing_goal) = existing_goal.as_ref() {
|
||||
let previous_goal = PreviousGoalSnapshot::from(existing_goal);
|
||||
state_db
|
||||
.thread_goals()
|
||||
.update_thread_goal(
|
||||
thread_id,
|
||||
akode_state::GoalUpdate {
|
||||
objective: Some(objective.to_string()),
|
||||
status,
|
||||
token_budget,
|
||||
expected_goal_id: Some(existing_goal.goal_id.clone()),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
GoalServiceError::Internal(format!("failed to update thread goal: {err}"))
|
||||
})?
|
||||
.ok_or_else(|| {
|
||||
GoalServiceError::InvalidRequest(format!(
|
||||
"cannot update goal for thread {thread_id}: no goal exists"
|
||||
))
|
||||
})
|
||||
.map(|goal| (goal, Some(previous_goal)))?
|
||||
} else {
|
||||
state_db
|
||||
.thread_goals()
|
||||
.replace_thread_goal(
|
||||
thread_id,
|
||||
objective,
|
||||
status.unwrap_or(akode_state::ThreadGoalStatus::Active),
|
||||
token_budget.flatten().or(max_goal_token_budget),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
GoalServiceError::Internal(format!("failed to replace thread goal: {err}"))
|
||||
})
|
||||
.map(|goal| (goal, None))?
|
||||
}
|
||||
} else {
|
||||
let existing_goal = existing_goal.ok_or_else(|| {
|
||||
GoalServiceError::InvalidRequest(format!(
|
||||
"cannot update goal for thread {thread_id}: no goal exists"
|
||||
))
|
||||
})?;
|
||||
let previous_goal = PreviousGoalSnapshot::from(&existing_goal);
|
||||
let expected_goal_id = existing_goal.goal_id.clone();
|
||||
state_db
|
||||
.thread_goals()
|
||||
.update_thread_goal(
|
||||
thread_id,
|
||||
akode_state::GoalUpdate {
|
||||
objective: None,
|
||||
status,
|
||||
token_budget,
|
||||
expected_goal_id: Some(expected_goal_id),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
GoalServiceError::Internal(format!("failed to update thread goal: {err}"))
|
||||
})?
|
||||
.ok_or_else(|| {
|
||||
GoalServiceError::InvalidRequest(format!(
|
||||
"cannot update goal for thread {thread_id}: no goal exists"
|
||||
))
|
||||
})
|
||||
.map(|goal| (goal, Some(previous_goal)))?
|
||||
};
|
||||
|
||||
if let Some(runtime) = runtime.as_ref() {
|
||||
runtime.clear_pending_turn_start_options().await;
|
||||
}
|
||||
|
||||
if objective.is_some() {
|
||||
fill_empty_thread_preview_if_possible(state_db, thread_id, &goal).await;
|
||||
}
|
||||
Ok(GoalSetOutcome {
|
||||
goal: protocol_goal_from_state(goal.clone()),
|
||||
state_goal: goal,
|
||||
previous_goal,
|
||||
})
|
||||
}
|
||||
|
||||
/// Records a clear instruction even when no goal exists, then deletes goal state under the mutation permit.
|
||||
pub async fn clear_thread_goal(
|
||||
&self,
|
||||
state_db: &akode_state::StateRuntime,
|
||||
thread_id: ThreadId,
|
||||
record_user_instruction: impl Future<Output = Result<(), GoalServiceError>> + Send,
|
||||
) -> Result<bool, GoalServiceError> {
|
||||
let runtime = self.runtime_for_thread(thread_id);
|
||||
// Hold this through the prepare/write window so idle continuation cannot
|
||||
// launch from goal state that this external mutation is about to change.
|
||||
let goal_state_permit = match runtime.as_ref() {
|
||||
Some(runtime) => Some(
|
||||
runtime
|
||||
.goal_state_permit()
|
||||
.await
|
||||
.map_err(GoalServiceError::Internal)?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
if let Some(runtime) = runtime.as_ref()
|
||||
&& let Err(err) = runtime.prepare_external_goal_mutation().await
|
||||
{
|
||||
tracing::warn!("failed to prepare external goal mutation: {err}");
|
||||
}
|
||||
|
||||
// A failed set can leave authorization in history without a goal row.
|
||||
record_user_instruction.await?;
|
||||
|
||||
let cleared_goal = state_db
|
||||
.thread_goals()
|
||||
.delete_thread_goal(thread_id)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
GoalServiceError::Internal(format!("failed to clear thread goal: {err}"))
|
||||
})?;
|
||||
let cleared = cleared_goal.is_some();
|
||||
if cleared && let Some(runtime) = runtime.as_ref() {
|
||||
runtime.clear_pending_turn_start_options().await;
|
||||
}
|
||||
drop(goal_state_permit);
|
||||
drop(runtime);
|
||||
|
||||
if let (Some(runtime), Some(goal)) = (self.runtime_for_thread(thread_id), cleared_goal)
|
||||
&& let Err(err) = runtime.apply_external_goal_clear(goal).await
|
||||
{
|
||||
tracing::warn!("failed to apply external goal clear runtime effects: {err}");
|
||||
}
|
||||
|
||||
Ok(cleared)
|
||||
}
|
||||
|
||||
pub(crate) fn register_runtime(&self, runtime: &Arc<GoalRuntimeHandle>) {
|
||||
self.runtimes()
|
||||
.insert(runtime.thread_id().to_string(), Arc::downgrade(runtime));
|
||||
}
|
||||
|
||||
pub(crate) fn unregister_runtime(&self, runtime: &Arc<GoalRuntimeHandle>) {
|
||||
let key = runtime.thread_id().to_string();
|
||||
let runtime = Arc::downgrade(runtime);
|
||||
let mut runtimes = self.runtimes();
|
||||
if runtimes
|
||||
.get(&key)
|
||||
.is_some_and(|registered| registered.ptr_eq(&runtime))
|
||||
{
|
||||
runtimes.remove(&key);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn runtime_for_thread(&self, thread_id: ThreadId) -> Option<Arc<GoalRuntimeHandle>> {
|
||||
let key = thread_id.to_string();
|
||||
let mut runtimes = self.runtimes();
|
||||
let runtime = runtimes.get(&key).and_then(Weak::upgrade);
|
||||
if runtime.is_none() {
|
||||
runtimes.remove(&key);
|
||||
}
|
||||
runtime
|
||||
}
|
||||
|
||||
fn runtimes(&self) -> std::sync::MutexGuard<'_, HashMap<String, Weak<GoalRuntimeHandle>>> {
|
||||
self.runtimes.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
34
akode-rs/ext/goal/src/events.rs
Normal file
34
akode-rs/ext/goal/src/events.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_extension_api::ExtensionEventSink;
|
||||
use akode_protocol::protocol::Event;
|
||||
use akode_protocol::protocol::EventMsg;
|
||||
use akode_protocol::protocol::ThreadGoal;
|
||||
use akode_protocol::protocol::ThreadGoalUpdatedEvent;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct GoalEventEmitter {
|
||||
sink: Arc<dyn ExtensionEventSink>,
|
||||
}
|
||||
|
||||
impl GoalEventEmitter {
|
||||
pub(crate) fn new(sink: Arc<dyn ExtensionEventSink>) -> Self {
|
||||
Self { sink }
|
||||
}
|
||||
|
||||
pub(crate) fn thread_goal_updated(
|
||||
&self,
|
||||
event_id: impl Into<String>,
|
||||
turn_id: Option<String>,
|
||||
goal: ThreadGoal,
|
||||
) {
|
||||
self.sink.emit(Event {
|
||||
id: event_id.into(),
|
||||
msg: EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
|
||||
thread_id: goal.thread_id,
|
||||
turn_id,
|
||||
goal,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
646
akode-rs/ext/goal/src/extension.rs
Normal file
646
akode-rs/ext/goal/src/extension.rs
Normal file
@@ -0,0 +1,646 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
use akode_core::ThreadManager;
|
||||
use akode_core::TurnStartOptions;
|
||||
use akode_extension_api::ConfigContributor;
|
||||
use akode_extension_api::ExtensionData;
|
||||
use akode_extension_api::ExtensionEventSink;
|
||||
use akode_extension_api::ExtensionFuture;
|
||||
use akode_extension_api::ExtensionRegistryBuilder;
|
||||
use akode_extension_api::ThreadIdleInput;
|
||||
use akode_extension_api::ThreadLifecycleContributor;
|
||||
use akode_extension_api::ThreadResumeInput;
|
||||
use akode_extension_api::ThreadStartInput;
|
||||
use akode_extension_api::ThreadStopInput;
|
||||
use akode_extension_api::TokenUsageContributor;
|
||||
use akode_extension_api::ToolCall;
|
||||
use akode_extension_api::ToolCallOutcome;
|
||||
use akode_extension_api::ToolContributor;
|
||||
use akode_extension_api::ToolExecutor;
|
||||
use akode_extension_api::ToolFinishInput;
|
||||
use akode_extension_api::ToolLifecycleContributor;
|
||||
use akode_extension_api::ToolLifecycleFuture;
|
||||
use akode_extension_api::TurnAbortInput;
|
||||
use akode_extension_api::TurnErrorInput;
|
||||
use akode_extension_api::TurnLifecycleContributor;
|
||||
use akode_extension_api::TurnStartInput;
|
||||
use akode_extension_api::TurnStopInput;
|
||||
use akode_otel::MetricsClient;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::items::TurnItem;
|
||||
use akode_protocol::protocol::CodexErrorInfo;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use akode_protocol::protocol::ThreadGoalStatus;
|
||||
use akode_protocol::protocol::TokenUsageInfo;
|
||||
|
||||
use crate::accounting::BudgetLimitedGoalDisposition;
|
||||
use crate::accounting::GoalAccountingState;
|
||||
use crate::api::GoalService;
|
||||
use crate::events::GoalEventEmitter;
|
||||
use crate::metrics::GoalMetrics;
|
||||
use crate::runtime::ActiveGoalStopReason;
|
||||
use crate::runtime::GoalRuntimeConfig;
|
||||
use crate::runtime::GoalRuntimeHandle;
|
||||
use crate::spec::CREATE_GOAL_TOOL_NAME;
|
||||
use crate::spec::UPDATE_GOAL_TOOL_NAME;
|
||||
use crate::steering::budget_limit_steering_item;
|
||||
use crate::tool::GoalToolExecutor;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GoalExtensionConfig {
|
||||
pub enabled: bool,
|
||||
pub max_goal_token_budget: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GoalExtension<C> {
|
||||
state_dbs: Arc<akode_state::StateRuntime>,
|
||||
event_emitter: GoalEventEmitter,
|
||||
metrics: GoalMetrics,
|
||||
thread_manager: Weak<ThreadManager>,
|
||||
goal_service: Arc<GoalService>,
|
||||
goal_config: Arc<dyn Fn(&C) -> GoalExtensionConfig + Send + Sync>,
|
||||
}
|
||||
|
||||
impl<C> std::fmt::Debug for GoalExtension<C> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("GoalExtension").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<C> GoalExtension<C> {
|
||||
pub(crate) fn new_with_host_capabilities(
|
||||
state_dbs: Arc<akode_state::StateRuntime>,
|
||||
event_sink: Arc<dyn ExtensionEventSink>,
|
||||
metrics_client: Option<MetricsClient>,
|
||||
thread_manager: Weak<ThreadManager>,
|
||||
goal_service: Arc<GoalService>,
|
||||
goal_config: impl Fn(&C) -> GoalExtensionConfig + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
Self {
|
||||
state_dbs,
|
||||
event_emitter: GoalEventEmitter::new(event_sink),
|
||||
metrics: GoalMetrics::new(metrics_client),
|
||||
thread_manager,
|
||||
goal_service,
|
||||
goal_config: Arc::new(goal_config),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C> ThreadLifecycleContributor<C> for GoalExtension<C>
|
||||
where
|
||||
C: Send + Sync + 'static,
|
||||
{
|
||||
fn on_thread_start<'a>(&'a self, input: ThreadStartInput<'a, C>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let config = (self.goal_config)(input.config);
|
||||
let enabled = config.enabled;
|
||||
let tools_visible_for_thread = !matches!(
|
||||
input.session_source,
|
||||
SessionSource::SubAgent(SubAgentSource::Review)
|
||||
);
|
||||
let tools_available_for_thread =
|
||||
input.persistent_thread_state_available && tools_visible_for_thread;
|
||||
input.thread_store.insert(config);
|
||||
let accounting_state = input
|
||||
.thread_store
|
||||
.get_or_init::<GoalAccountingState>(GoalAccountingState::default);
|
||||
let Ok(thread_id) = ThreadId::from_string(input.thread_store.level_id()) else {
|
||||
return;
|
||||
};
|
||||
let root_accounting_state = input
|
||||
.session_source
|
||||
.parent_thread_id()
|
||||
.or_else(|| {
|
||||
ThreadId::from_string(input.session_store.level_id())
|
||||
.ok()
|
||||
.filter(|_| input.session_source.is_non_root_agent())
|
||||
})
|
||||
.and_then(|parent_thread_id| {
|
||||
self.goal_service
|
||||
.runtime_for_thread(parent_thread_id)
|
||||
.or_else(|| {
|
||||
ThreadId::from_string(input.session_store.level_id())
|
||||
.ok()
|
||||
.and_then(|root_thread_id| {
|
||||
self.goal_service.runtime_for_thread(root_thread_id)
|
||||
})
|
||||
})
|
||||
})
|
||||
.map(|parent| {
|
||||
parent
|
||||
.root_accounting_state()
|
||||
.unwrap_or_else(|| parent.accounting_state())
|
||||
});
|
||||
let runtime = input.thread_store.get_or_init::<GoalRuntimeHandle>(|| {
|
||||
GoalRuntimeHandle::new(
|
||||
thread_id,
|
||||
Arc::clone(&self.state_dbs),
|
||||
self.event_emitter.clone(),
|
||||
self.metrics.clone(),
|
||||
self.thread_manager.clone(),
|
||||
accounting_state,
|
||||
GoalRuntimeConfig {
|
||||
enabled,
|
||||
tools_available_for_thread,
|
||||
tools_visible_for_thread,
|
||||
root_accounting_state,
|
||||
},
|
||||
)
|
||||
});
|
||||
runtime.set_enabled(enabled);
|
||||
self.goal_service.register_runtime(&runtime);
|
||||
})
|
||||
}
|
||||
|
||||
fn on_thread_resume<'a>(&'a self, input: ThreadResumeInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let Some(runtime) = goal_runtime_handle(input.thread_store) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Err(err) = runtime.restore_after_resume().await {
|
||||
tracing::warn!(
|
||||
"failed to restore goal runtime after thread resume for {}: {err}",
|
||||
runtime.thread_id()
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn on_thread_idle<'a>(&'a self, input: ThreadIdleInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let Some(runtime) = goal_runtime_handle(input.thread_store) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let accounting = runtime.accounting_state();
|
||||
if let Some(turn_id) = accounting.interrupted_turn_id() {
|
||||
if let Err(err) = runtime
|
||||
.stop_active_goal_for_turn(&turn_id, ActiveGoalStopReason::EmptyResponse)
|
||||
.await
|
||||
{
|
||||
tracing::warn!("failed to stop goal after interrupted empty turns: {err}");
|
||||
}
|
||||
accounting.finish_turn(&turn_id);
|
||||
}
|
||||
if let Err(err) = runtime.continue_if_idle().await {
|
||||
tracing::warn!(
|
||||
"failed to continue active goal for idle thread {}: {err}",
|
||||
runtime.thread_id()
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn on_thread_stop<'a>(&'a self, input: ThreadStopInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
if let Some(runtime) = goal_runtime_handle(input.thread_store) {
|
||||
self.goal_service.unregister_runtime(&runtime);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<C> ConfigContributor<C> for GoalExtension<C>
|
||||
where
|
||||
C: Send + Sync + 'static,
|
||||
{
|
||||
fn on_config_changed(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
_previous_config: &C,
|
||||
new_config: &C,
|
||||
) {
|
||||
let config = (self.goal_config)(new_config);
|
||||
let enabled = config.enabled;
|
||||
thread_store.insert(config);
|
||||
if let Some(runtime) = goal_runtime_handle(thread_store) {
|
||||
runtime.set_enabled(enabled);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C> TurnLifecycleContributor for GoalExtension<C>
|
||||
where
|
||||
C: Send + Sync + 'static,
|
||||
{
|
||||
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let Some(runtime) = goal_runtime_handle(input.thread_store) else {
|
||||
return;
|
||||
};
|
||||
if !runtime.is_enabled() {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(token_usage_at_turn_start) = input.token_usage_at_turn_start else {
|
||||
tracing::warn!("skipping goal turn accounting: token baseline unavailable");
|
||||
return;
|
||||
};
|
||||
|
||||
let accounting = runtime.accounting_state();
|
||||
let Ok(_turn_start_permit) = accounting.turn_start_permit().await else {
|
||||
return;
|
||||
};
|
||||
if let Err(err) = self
|
||||
.state_dbs
|
||||
.thread_goals()
|
||||
.clear_thread_goal_continuation_deferral(runtime.thread_id())
|
||||
.await
|
||||
{
|
||||
tracing::warn!("failed to clear deferred goal continuation: {err}");
|
||||
}
|
||||
|
||||
accounting.start_turn(
|
||||
input.turn_id,
|
||||
input.collaboration_mode.mode,
|
||||
token_usage_at_turn_start,
|
||||
);
|
||||
if matches!(
|
||||
input.collaboration_mode.mode,
|
||||
akode_protocol::config_types::ModeKind::Plan
|
||||
) {
|
||||
accounting.clear_current_turn_goal();
|
||||
return;
|
||||
}
|
||||
let Ok(goal) = self
|
||||
.state_dbs
|
||||
.thread_goals()
|
||||
.get_thread_goal(runtime.thread_id())
|
||||
.await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if let Some(goal) = goal
|
||||
&& matches!(
|
||||
goal.status,
|
||||
akode_state::ThreadGoalStatus::Active
|
||||
| akode_state::ThreadGoalStatus::BudgetLimited
|
||||
)
|
||||
{
|
||||
accounting.mark_turn_goal_active(input.turn_id, goal.goal_id);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn on_item_completed<'a>(
|
||||
&'a self,
|
||||
thread_store: &'a ExtensionData,
|
||||
turn_store: &'a ExtensionData,
|
||||
item: &'a TurnItem,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
if let Some(runtime) = goal_runtime_handle(thread_store)
|
||||
&& runtime.is_enabled()
|
||||
{
|
||||
runtime
|
||||
.accounting_state()
|
||||
.record_item(turn_store.level_id(), item);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn on_turn_stop<'a>(&'a self, input: TurnStopInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let Some(runtime) = goal_runtime_handle(input.thread_store) else {
|
||||
return;
|
||||
};
|
||||
if !runtime.is_enabled() {
|
||||
return;
|
||||
}
|
||||
|
||||
let turn_id = input.turn_store.level_id();
|
||||
if let Some(expected_goal_id) =
|
||||
runtime.accounting_state().execution_failure_goal(turn_id)
|
||||
&& let Err(err) = runtime
|
||||
.stop_active_goal_for_turn(
|
||||
turn_id,
|
||||
ActiveGoalStopReason::ExecutionUnavailable { expected_goal_id },
|
||||
)
|
||||
.await
|
||||
{
|
||||
input.thread_store.remove::<TurnStartOptions>();
|
||||
tracing::warn!(
|
||||
"failed to stop active goal after repeated execution failures for {turn_id}: {err}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
if let Err(err) = runtime
|
||||
.stop_active_goal_for_turn(turn_id, ActiveGoalStopReason::EmptyResponse)
|
||||
.await
|
||||
{
|
||||
input.thread_store.remove::<TurnStartOptions>();
|
||||
tracing::warn!("failed to stop goal after empty responses for {turn_id}: {err}");
|
||||
return;
|
||||
}
|
||||
if let Err(err) = runtime
|
||||
.account_active_goal_progress(
|
||||
turn_id,
|
||||
&format!("{turn_id}:turn-stop"),
|
||||
akode_state::GoalAccountingMode::ActiveOnly,
|
||||
BudgetLimitedGoalDisposition::ClearActive,
|
||||
)
|
||||
.await
|
||||
{
|
||||
input.thread_store.remove::<TurnStartOptions>();
|
||||
tracing::warn!(
|
||||
"failed to account active goal progress at turn stop for {turn_id}: {err}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let accounting = runtime.accounting_state();
|
||||
if accounting
|
||||
.current_active_goal_id_for_turn(turn_id)
|
||||
.is_some()
|
||||
&& let Some(options) = input.thread_store.get::<TurnStartOptions>()
|
||||
{
|
||||
input.thread_store.insert_if(
|
||||
TurnStartOptions {
|
||||
parent_turn_id: Some(turn_id.to_string()),
|
||||
..options.as_ref().clone()
|
||||
},
|
||||
|current| current.is_some(),
|
||||
);
|
||||
}
|
||||
accounting.finish_turn(turn_id);
|
||||
})
|
||||
}
|
||||
|
||||
fn on_turn_abort<'a>(&'a self, input: TurnAbortInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let Some(runtime) = goal_runtime_handle(input.thread_store) else {
|
||||
return;
|
||||
};
|
||||
if !runtime.is_enabled() {
|
||||
runtime.accounting_state().reset_empty_responses();
|
||||
return;
|
||||
}
|
||||
|
||||
let turn_id = input.turn_store.level_id();
|
||||
input.thread_store.remove::<TurnStartOptions>();
|
||||
if input.reason != akode_protocol::protocol::TurnAbortReason::Interrupted {
|
||||
runtime.accounting_state().reset_empty_responses();
|
||||
}
|
||||
if let Err(err) = runtime
|
||||
.account_active_goal_progress(
|
||||
turn_id,
|
||||
&format!("{turn_id}:turn-abort"),
|
||||
akode_state::GoalAccountingMode::ActiveOnly,
|
||||
BudgetLimitedGoalDisposition::ClearActive,
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
"failed to account active goal progress after turn abort for {turn_id}: {err}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let accounting = runtime.accounting_state();
|
||||
match input.reason {
|
||||
akode_protocol::protocol::TurnAbortReason::Interrupted => {
|
||||
accounting.interrupt_turn(turn_id);
|
||||
}
|
||||
akode_protocol::protocol::TurnAbortReason::Replaced
|
||||
| akode_protocol::protocol::TurnAbortReason::ReviewEnded
|
||||
| akode_protocol::protocol::TurnAbortReason::BudgetLimited => {
|
||||
accounting.finish_turn(turn_id);
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn on_turn_error<'a>(&'a self, input: TurnErrorInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let Some(runtime) = goal_runtime_handle(input.thread_store) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let reason = match input.error {
|
||||
CodexErrorInfo::UsageLimitExceeded => ActiveGoalStopReason::UsageLimit,
|
||||
// The turn has ended because the error was non-retryable or its
|
||||
// retries were exhausted. Block the goal to prevent automatic
|
||||
// continuation from looping and consuming tokens, as can happen
|
||||
// with compaction errors.
|
||||
_ => ActiveGoalStopReason::TurnError,
|
||||
};
|
||||
if let Err(err) = runtime
|
||||
.stop_active_goal_for_turn(input.turn_id, reason)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(
|
||||
error = ?input.error,
|
||||
"failed to stop active goal after turn error: {err}"
|
||||
);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<C> TokenUsageContributor for GoalExtension<C>
|
||||
where
|
||||
C: Send + Sync + 'static,
|
||||
{
|
||||
fn on_token_usage<'a>(
|
||||
&'a self,
|
||||
_session_store: &'a ExtensionData,
|
||||
thread_store: &'a ExtensionData,
|
||||
turn_store: &'a ExtensionData,
|
||||
token_usage: &'a TokenUsageInfo,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let Some(runtime) = goal_runtime_handle(thread_store) else {
|
||||
return;
|
||||
};
|
||||
if !runtime.is_enabled() {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(root_accounting_state) = runtime.root_accounting_state() {
|
||||
root_accounting_state.record_descendant_token_usage(&token_usage.last_token_usage);
|
||||
}
|
||||
let _ = runtime
|
||||
.accounting_state()
|
||||
.record_token_usage(turn_store.level_id(), &token_usage.total_token_usage);
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<C> ToolLifecycleContributor for GoalExtension<C>
|
||||
where
|
||||
C: Send + Sync + 'static,
|
||||
{
|
||||
fn on_tool_finish<'a>(&'a self, input: ToolFinishInput<'a>) -> ToolLifecycleFuture<'a> {
|
||||
Box::pin(async move {
|
||||
let Some(runtime) = goal_runtime_handle(input.thread_store) else {
|
||||
return;
|
||||
};
|
||||
if !runtime.is_enabled() {
|
||||
return;
|
||||
}
|
||||
runtime.accounting_state().record_tool_outcome(
|
||||
input.turn_id,
|
||||
input.tool_name,
|
||||
input.outcome,
|
||||
);
|
||||
if input.tool_name.is_default_namespace()
|
||||
&& input.tool_name.name == CREATE_GOAL_TOOL_NAME
|
||||
&& matches!(input.outcome, ToolCallOutcome::Completed { success: true })
|
||||
{
|
||||
input.thread_store.remove::<TurnStartOptions>();
|
||||
if let Ok(_goal_state_permit) = runtime.goal_state_permit().await
|
||||
&& let Some(thread_manager) = self.thread_manager.upgrade()
|
||||
&& let Ok(thread) = thread_manager.get_thread(runtime.thread_id()).await
|
||||
&& let Some(root_turn_id) = thread.active_turn_root(input.turn_id).await
|
||||
{
|
||||
input.thread_store.insert(TurnStartOptions {
|
||||
root_turn_id: Some(root_turn_id),
|
||||
parent_turn_id: Some(input.turn_id.to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
let should_count_for_goal_progress =
|
||||
tool_attempt_counts_for_goal_progress(input.outcome)
|
||||
&& !(input.tool_name.is_default_namespace()
|
||||
&& input.tool_name.name == UPDATE_GOAL_TOOL_NAME);
|
||||
if !should_count_for_goal_progress {
|
||||
return;
|
||||
}
|
||||
let turn_id = input.turn_id;
|
||||
let progress = match runtime
|
||||
.account_active_goal_progress(
|
||||
turn_id,
|
||||
input.call_id,
|
||||
akode_state::GoalAccountingMode::ActiveOnly,
|
||||
BudgetLimitedGoalDisposition::KeepActive,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Some(progress)) => progress,
|
||||
Ok(None) => return,
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
"failed to account active goal progress after tool finish for {turn_id}: {err}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let goal = progress.goal;
|
||||
if goal.status != ThreadGoalStatus::BudgetLimited {
|
||||
return;
|
||||
}
|
||||
if !runtime
|
||||
.accounting_state()
|
||||
.mark_budget_limit_reported_if_new(progress.goal_id.as_str())
|
||||
{
|
||||
return;
|
||||
}
|
||||
let item = budget_limit_steering_item(&goal);
|
||||
runtime.inject_active_turn_steering(item).await;
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<C> ToolContributor for GoalExtension<C>
|
||||
where
|
||||
C: Send + Sync + 'static,
|
||||
{
|
||||
fn tools(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
) -> Vec<
|
||||
Arc<dyn for<'call> akode_extension_api::ToolExecutor<akode_extension_api::ToolCall<'call>>>,
|
||||
> {
|
||||
let Some(runtime) = goal_runtime_handle(thread_store) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !runtime.tools_visible() {
|
||||
return Vec::new();
|
||||
}
|
||||
let max_goal_token_budget = thread_store
|
||||
.get::<GoalExtensionConfig>()
|
||||
.and_then(|config| config.max_goal_token_budget);
|
||||
|
||||
let tools = [
|
||||
GoalToolExecutor::get(
|
||||
runtime.thread_id(),
|
||||
Arc::clone(&self.state_dbs),
|
||||
runtime.accounting_state(),
|
||||
self.event_emitter.clone(),
|
||||
self.metrics.clone(),
|
||||
),
|
||||
GoalToolExecutor::create(
|
||||
&runtime,
|
||||
self.thread_manager.clone(),
|
||||
Arc::clone(&self.state_dbs),
|
||||
self.event_emitter.clone(),
|
||||
self.metrics.clone(),
|
||||
max_goal_token_budget,
|
||||
),
|
||||
GoalToolExecutor::update(
|
||||
runtime.thread_id(),
|
||||
Arc::clone(&self.state_dbs),
|
||||
runtime.accounting_state(),
|
||||
self.event_emitter.clone(),
|
||||
self.metrics.clone(),
|
||||
),
|
||||
];
|
||||
tools
|
||||
.into_iter()
|
||||
.map(|mut tool| {
|
||||
tool.execution_allowed = runtime.tools_available();
|
||||
Arc::new(tool) as Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn install_with_backend<C>(
|
||||
registry: &mut ExtensionRegistryBuilder<C>,
|
||||
state_dbs: Arc<akode_state::StateRuntime>,
|
||||
metrics_client: Option<MetricsClient>,
|
||||
thread_manager: Weak<ThreadManager>,
|
||||
goal_service: Arc<GoalService>,
|
||||
goal_config: impl Fn(&C) -> GoalExtensionConfig + Send + Sync + 'static,
|
||||
) where
|
||||
C: Send + Sync + 'static,
|
||||
{
|
||||
let extension = Arc::new(GoalExtension::new_with_host_capabilities(
|
||||
state_dbs,
|
||||
registry.event_sink(),
|
||||
metrics_client,
|
||||
thread_manager,
|
||||
Arc::clone(&goal_service),
|
||||
goal_config,
|
||||
));
|
||||
registry.thread_lifecycle_contributor(extension.clone());
|
||||
registry.config_contributor(extension.clone());
|
||||
registry.turn_lifecycle_contributor(extension.clone());
|
||||
registry.token_usage_contributor(extension.clone());
|
||||
registry.tool_lifecycle_contributor(extension.clone());
|
||||
registry.tool_contributor(extension);
|
||||
}
|
||||
|
||||
fn goal_runtime_handle(thread_store: &ExtensionData) -> Option<Arc<GoalRuntimeHandle>> {
|
||||
thread_store.get::<GoalRuntimeHandle>()
|
||||
}
|
||||
|
||||
fn tool_attempt_counts_for_goal_progress(outcome: ToolCallOutcome) -> bool {
|
||||
match outcome {
|
||||
ToolCallOutcome::Completed { .. } => true,
|
||||
ToolCallOutcome::Failed {
|
||||
handler_executed: true,
|
||||
} => true,
|
||||
ToolCallOutcome::Blocked
|
||||
| ToolCallOutcome::Failed {
|
||||
handler_executed: false,
|
||||
}
|
||||
| ToolCallOutcome::Aborted => false,
|
||||
}
|
||||
}
|
||||
27
akode-rs/ext/goal/src/lib.rs
Normal file
27
akode-rs/ext/goal/src/lib.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
//! Extension crate for the `/goal` feature.
|
||||
|
||||
mod accounting;
|
||||
mod api;
|
||||
mod events;
|
||||
mod extension;
|
||||
mod metrics;
|
||||
mod runtime;
|
||||
mod spec;
|
||||
mod steering;
|
||||
mod tool;
|
||||
|
||||
pub use api::GoalObjectiveUpdate;
|
||||
pub use api::GoalService;
|
||||
pub use api::GoalServiceError;
|
||||
pub use api::GoalSetOutcome;
|
||||
pub use api::GoalSetRequest;
|
||||
pub use api::GoalTokenBudgetUpdate;
|
||||
pub use extension::GoalExtension;
|
||||
pub use extension::GoalExtensionConfig;
|
||||
pub use extension::install_with_backend;
|
||||
pub use runtime::GoalRuntimeHandle;
|
||||
pub use runtime::PreviousGoalSnapshot;
|
||||
pub use spec::CREATE_GOAL_TOOL_NAME;
|
||||
pub use spec::GET_GOAL_TOOL_NAME;
|
||||
pub use spec::UPDATE_GOAL_TOOL_NAME;
|
||||
pub use tool::CreateGoalRequest;
|
||||
84
akode-rs/ext/goal/src/metrics.rs
Normal file
84
akode-rs/ext/goal/src/metrics.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
use akode_otel::GOAL_BLOCKED_METRIC;
|
||||
use akode_otel::GOAL_BUDGET_LIMITED_METRIC;
|
||||
use akode_otel::GOAL_COMPLETED_METRIC;
|
||||
use akode_otel::GOAL_CREATED_METRIC;
|
||||
use akode_otel::GOAL_DURATION_SECONDS_METRIC;
|
||||
use akode_otel::GOAL_RESUMED_METRIC;
|
||||
use akode_otel::GOAL_TOKEN_COUNT_METRIC;
|
||||
use akode_otel::GOAL_USAGE_LIMITED_METRIC;
|
||||
use akode_otel::MetricsClient;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct GoalMetrics {
|
||||
metrics_client: Option<MetricsClient>,
|
||||
}
|
||||
|
||||
impl GoalMetrics {
|
||||
pub(crate) fn new(metrics_client: Option<MetricsClient>) -> Self {
|
||||
Self { metrics_client }
|
||||
}
|
||||
|
||||
pub(crate) fn record_created(&self) {
|
||||
let Some(metrics_client) = self.metrics_client.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let _ = metrics_client.counter(GOAL_CREATED_METRIC, /*inc*/ 1, &[]);
|
||||
}
|
||||
|
||||
pub(crate) fn record_resumed(&self) {
|
||||
let Some(metrics_client) = self.metrics_client.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let _ = metrics_client.counter(GOAL_RESUMED_METRIC, /*inc*/ 1, &[]);
|
||||
}
|
||||
|
||||
pub(crate) fn record_resumed_if_status_changed(
|
||||
&self,
|
||||
previous_status: Option<akode_state::ThreadGoalStatus>,
|
||||
goal_status: akode_state::ThreadGoalStatus,
|
||||
) {
|
||||
if goal_status == akode_state::ThreadGoalStatus::Active
|
||||
&& matches!(
|
||||
previous_status,
|
||||
Some(
|
||||
akode_state::ThreadGoalStatus::Paused
|
||||
| akode_state::ThreadGoalStatus::Blocked
|
||||
| akode_state::ThreadGoalStatus::UsageLimited
|
||||
)
|
||||
)
|
||||
{
|
||||
self.record_resumed();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_terminal_if_status_changed(
|
||||
&self,
|
||||
previous_status: Option<akode_state::ThreadGoalStatus>,
|
||||
goal: &akode_state::ThreadGoal,
|
||||
) {
|
||||
if previous_status == Some(goal.status) {
|
||||
return;
|
||||
}
|
||||
|
||||
let counter = match goal.status {
|
||||
akode_state::ThreadGoalStatus::Blocked => GOAL_BLOCKED_METRIC,
|
||||
akode_state::ThreadGoalStatus::UsageLimited => GOAL_USAGE_LIMITED_METRIC,
|
||||
akode_state::ThreadGoalStatus::BudgetLimited => GOAL_BUDGET_LIMITED_METRIC,
|
||||
akode_state::ThreadGoalStatus::Complete => GOAL_COMPLETED_METRIC,
|
||||
akode_state::ThreadGoalStatus::Active | akode_state::ThreadGoalStatus::Paused => {
|
||||
return;
|
||||
}
|
||||
};
|
||||
let Some(metrics_client) = self.metrics_client.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let status_tag = [("status", goal.status.as_str())];
|
||||
let _ = metrics_client.counter(counter, /*inc*/ 1, &[]);
|
||||
let _ = metrics_client.histogram(GOAL_TOKEN_COUNT_METRIC, goal.tokens_used, &status_tag);
|
||||
let _ = metrics_client.histogram(
|
||||
GOAL_DURATION_SECONDS_METRIC,
|
||||
goal.time_used_seconds,
|
||||
&status_tag,
|
||||
);
|
||||
}
|
||||
}
|
||||
657
akode-rs/ext/goal/src/runtime.rs
Normal file
657
akode-rs/ext/goal/src/runtime.rs
Normal file
@@ -0,0 +1,657 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use akode_core::StartIfIdleSubmission;
|
||||
use akode_core::ThreadManager;
|
||||
use akode_core::TurnStartOptions;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use akode_protocol::protocol::ThreadGoal;
|
||||
|
||||
use crate::accounting::BudgetLimitedGoalDisposition;
|
||||
use crate::accounting::GoalAccountingState;
|
||||
use crate::events::GoalEventEmitter;
|
||||
use crate::metrics::GoalMetrics;
|
||||
use crate::steering::continuation_request;
|
||||
use crate::steering::objective_updated_steering_item;
|
||||
use crate::tool::protocol_goal_from_state;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::sync::SemaphorePermit;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GoalRuntimeHandle {
|
||||
inner: Arc<GoalRuntimeInner>,
|
||||
}
|
||||
|
||||
pub(crate) struct GoalRuntimeConfig {
|
||||
pub(crate) enabled: bool,
|
||||
pub(crate) tools_available_for_thread: bool,
|
||||
pub(crate) tools_visible_for_thread: bool,
|
||||
pub(crate) root_accounting_state: Option<Arc<GoalAccountingState>>,
|
||||
}
|
||||
|
||||
pub(crate) enum ActiveGoalStopReason {
|
||||
TurnError,
|
||||
UsageLimit,
|
||||
ExecutionUnavailable { expected_goal_id: String },
|
||||
EmptyResponse,
|
||||
}
|
||||
|
||||
struct GoalRuntimeInner {
|
||||
thread_id: ThreadId,
|
||||
state_dbs: Arc<akode_state::StateRuntime>,
|
||||
event_emitter: GoalEventEmitter,
|
||||
metrics: GoalMetrics,
|
||||
thread_manager: Weak<ThreadManager>,
|
||||
accounting_state: Arc<GoalAccountingState>,
|
||||
root_accounting_state: Option<Arc<GoalAccountingState>>,
|
||||
enabled: AtomicBool,
|
||||
tools_available_for_thread: bool,
|
||||
tools_visible_for_thread: bool,
|
||||
goal_state_lock: Semaphore,
|
||||
}
|
||||
|
||||
pub(crate) struct AccountedGoalProgress {
|
||||
pub(crate) goal: ThreadGoal,
|
||||
pub(crate) goal_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PreviousGoalSnapshot {
|
||||
pub goal_id: String,
|
||||
pub status: akode_state::ThreadGoalStatus,
|
||||
pub objective: String,
|
||||
}
|
||||
|
||||
impl From<&akode_state::ThreadGoal> for PreviousGoalSnapshot {
|
||||
fn from(goal: &akode_state::ThreadGoal) -> Self {
|
||||
Self {
|
||||
goal_id: goal.goal_id.clone(),
|
||||
status: goal.status,
|
||||
objective: goal.objective.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for GoalRuntimeHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("GoalRuntimeHandle").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl GoalRuntimeHandle {
|
||||
pub(crate) fn new(
|
||||
thread_id: ThreadId,
|
||||
state_dbs: Arc<akode_state::StateRuntime>,
|
||||
event_emitter: GoalEventEmitter,
|
||||
metrics: GoalMetrics,
|
||||
thread_manager: Weak<ThreadManager>,
|
||||
accounting_state: Arc<GoalAccountingState>,
|
||||
config: GoalRuntimeConfig,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(GoalRuntimeInner {
|
||||
thread_id,
|
||||
state_dbs,
|
||||
event_emitter,
|
||||
metrics,
|
||||
thread_manager,
|
||||
accounting_state,
|
||||
root_accounting_state: config.root_accounting_state,
|
||||
enabled: AtomicBool::new(config.enabled),
|
||||
tools_available_for_thread: config.tools_available_for_thread,
|
||||
tools_visible_for_thread: config.tools_visible_for_thread,
|
||||
goal_state_lock: Semaphore::new(/*permits*/ 1),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_enabled(&self, enabled: bool) {
|
||||
self.inner.enabled.store(enabled, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn is_enabled(&self) -> bool {
|
||||
self.inner.enabled.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(crate) fn tools_visible(&self) -> bool {
|
||||
self.is_enabled() && self.inner.tools_visible_for_thread
|
||||
}
|
||||
|
||||
pub(crate) fn tools_available(&self) -> bool {
|
||||
self.is_enabled() && self.inner.tools_available_for_thread
|
||||
}
|
||||
|
||||
pub(crate) fn thread_id(&self) -> ThreadId {
|
||||
self.inner.thread_id
|
||||
}
|
||||
|
||||
pub(crate) fn accounting_state(&self) -> Arc<GoalAccountingState> {
|
||||
Arc::clone(&self.inner.accounting_state)
|
||||
}
|
||||
|
||||
pub(crate) fn root_accounting_state(&self) -> Option<Arc<GoalAccountingState>> {
|
||||
self.inner.root_accounting_state.clone()
|
||||
}
|
||||
|
||||
pub(crate) async fn clear_pending_turn_start_options(&self) {
|
||||
let Some(thread_manager) = self.inner.thread_manager.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Ok(thread) = thread_manager.get_thread(self.inner.thread_id).await else {
|
||||
return;
|
||||
};
|
||||
thread.thread_extension_data().remove::<TurnStartOptions>();
|
||||
}
|
||||
|
||||
pub(crate) async fn goal_state_permit(&self) -> Result<SemaphorePermit<'_>, String> {
|
||||
self.inner
|
||||
.goal_state_lock
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
|
||||
pub async fn prepare_external_goal_mutation(&self) -> Result<(), String> {
|
||||
if !self.is_enabled() {
|
||||
return Ok(());
|
||||
}
|
||||
// Invalidate the old turn before the persisted objective/status changes.
|
||||
self.inner.accounting_state.reset_empty_responses();
|
||||
|
||||
if let Some(turn_id) = self.inner.accounting_state.current_turn_id() {
|
||||
self.account_active_goal_progress(
|
||||
turn_id.as_str(),
|
||||
&format!("{turn_id}:external-goal-mutation"),
|
||||
akode_state::GoalAccountingMode::ActiveOnly,
|
||||
BudgetLimitedGoalDisposition::ClearActive,
|
||||
)
|
||||
.await?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.account_idle_goal_progress(
|
||||
&format!("{}:external-goal-mutation", self.inner.thread_id),
|
||||
akode_state::GoalAccountingMode::ActiveOnly,
|
||||
BudgetLimitedGoalDisposition::ClearActive,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn apply_external_goal_set(
|
||||
&self,
|
||||
goal: akode_state::ThreadGoal,
|
||||
previous_goal: Option<PreviousGoalSnapshot>,
|
||||
) -> Result<(), String> {
|
||||
if !self.is_enabled() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.inner.accounting_state.reset_empty_responses();
|
||||
let replaced_existing_goal = previous_goal
|
||||
.as_ref()
|
||||
.is_some_and(|previous_goal| previous_goal.goal_id != goal.goal_id);
|
||||
if previous_goal.is_none() || replaced_existing_goal {
|
||||
self.inner.metrics.record_created();
|
||||
}
|
||||
let previous_status = previous_goal
|
||||
.as_ref()
|
||||
.and_then(|previous_goal| (!replaced_existing_goal).then_some(previous_goal.status));
|
||||
self.inner
|
||||
.metrics
|
||||
.record_resumed_if_status_changed(previous_status, goal.status);
|
||||
self.inner
|
||||
.metrics
|
||||
.record_terminal_if_status_changed(previous_status, &goal);
|
||||
let objective_changed = previous_goal.as_ref().is_some_and(|previous_goal| {
|
||||
!replaced_existing_goal && previous_goal.objective != goal.objective
|
||||
});
|
||||
match goal.status {
|
||||
akode_state::ThreadGoalStatus::Active => {
|
||||
if self.inner.accounting_state.current_turn_id().is_some() {
|
||||
let _ = self
|
||||
.inner
|
||||
.accounting_state
|
||||
.mark_current_turn_goal_active(goal.goal_id.clone());
|
||||
} else {
|
||||
self.inner
|
||||
.accounting_state
|
||||
.mark_idle_goal_active(goal.goal_id.clone());
|
||||
}
|
||||
if objective_changed {
|
||||
let item = objective_updated_steering_item(&protocol_goal_from_state(goal));
|
||||
self.inject_active_turn_steering(item).await;
|
||||
}
|
||||
self.continue_if_idle().await?;
|
||||
}
|
||||
akode_state::ThreadGoalStatus::BudgetLimited => {
|
||||
if self.inner.accounting_state.current_turn_id().is_none() {
|
||||
self.inner.accounting_state.clear_active_goal();
|
||||
}
|
||||
}
|
||||
akode_state::ThreadGoalStatus::Paused
|
||||
| akode_state::ThreadGoalStatus::Blocked
|
||||
| akode_state::ThreadGoalStatus::UsageLimited
|
||||
| akode_state::ThreadGoalStatus::Complete => {
|
||||
self.inner.accounting_state.clear_active_goal();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn apply_external_goal_clear(
|
||||
&self,
|
||||
_goal: akode_state::ThreadGoal,
|
||||
) -> Result<(), String> {
|
||||
if !self.is_enabled() {
|
||||
return Ok(());
|
||||
}
|
||||
self.inner.accounting_state.clear_active_goal();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn usage_limit_active_goal_for_turn(&self, turn_id: &str) -> Result<(), String> {
|
||||
self.stop_active_goal_for_turn(turn_id, ActiveGoalStopReason::UsageLimit)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Accounts the ending turn and stops its active goal after an error or repeated empty output.
|
||||
pub(crate) async fn stop_active_goal_for_turn(
|
||||
&self,
|
||||
turn_id: &str,
|
||||
reason: ActiveGoalStopReason,
|
||||
) -> Result<(), String> {
|
||||
if !self.is_enabled() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Hold this through accounting and the status update so external goal
|
||||
// mutations and idle continuation cannot interleave between them.
|
||||
let _goal_state_permit = self.goal_state_permit().await?;
|
||||
let accounting = &self.inner.accounting_state;
|
||||
let _turn_start_permit = if matches!(reason, ActiveGoalStopReason::EmptyResponse)
|
||||
&& accounting.interrupted_turn_id().as_deref() == Some(turn_id)
|
||||
{
|
||||
Some(
|
||||
accounting
|
||||
.turn_start_permit()
|
||||
.await
|
||||
.map_err(|err| err.to_string())?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some(accounting_goal_id) = self
|
||||
.inner
|
||||
.accounting_state
|
||||
.current_active_goal_id_for_turn(turn_id)
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
if let ActiveGoalStopReason::ExecutionUnavailable { expected_goal_id } = &reason
|
||||
&& accounting_goal_id != *expected_goal_id
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let (event_name, status, expected_goal_id) = match reason {
|
||||
ActiveGoalStopReason::TurnError => {
|
||||
("turn-error", akode_state::ThreadGoalStatus::Blocked, None)
|
||||
}
|
||||
ActiveGoalStopReason::UsageLimit => (
|
||||
"usage-limit",
|
||||
akode_state::ThreadGoalStatus::UsageLimited,
|
||||
None,
|
||||
),
|
||||
ActiveGoalStopReason::EmptyResponse => {
|
||||
let Some(expected_goal_id) = accounting.empty_response_goal(turn_id) else {
|
||||
return Ok(());
|
||||
};
|
||||
if accounting_goal_id != expected_goal_id {
|
||||
return Ok(());
|
||||
}
|
||||
(
|
||||
"empty-response",
|
||||
akode_state::ThreadGoalStatus::Blocked,
|
||||
Some(expected_goal_id),
|
||||
)
|
||||
}
|
||||
ActiveGoalStopReason::ExecutionUnavailable { expected_goal_id } => (
|
||||
"execution-unavailable",
|
||||
akode_state::ThreadGoalStatus::Blocked,
|
||||
Some(expected_goal_id),
|
||||
),
|
||||
};
|
||||
self.account_active_goal_progress(
|
||||
turn_id,
|
||||
&format!("{turn_id}:{event_name}-progress"),
|
||||
akode_state::GoalAccountingMode::ActiveOnly,
|
||||
BudgetLimitedGoalDisposition::ClearActive,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let Some(active_goal) = self
|
||||
.inner
|
||||
.state_dbs
|
||||
.thread_goals()
|
||||
.get_thread_goal(self.thread_id())
|
||||
.await
|
||||
.map_err(|err| err.to_string())?
|
||||
else {
|
||||
self.inner.accounting_state.clear_active_goal();
|
||||
return Ok(());
|
||||
};
|
||||
if expected_goal_id
|
||||
.as_ref()
|
||||
.is_some_and(|expected_goal_id| active_goal.goal_id != *expected_goal_id)
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let can_stop = active_goal.status == akode_state::ThreadGoalStatus::Active
|
||||
|| (active_goal.status == akode_state::ThreadGoalStatus::BudgetLimited
|
||||
&& status == akode_state::ThreadGoalStatus::UsageLimited);
|
||||
if !can_stop {
|
||||
self.inner.accounting_state.clear_active_goal();
|
||||
return Ok(());
|
||||
}
|
||||
let previous_status = Some(active_goal.status);
|
||||
let Some(goal) = self
|
||||
.inner
|
||||
.state_dbs
|
||||
.thread_goals()
|
||||
.update_thread_goal(
|
||||
self.thread_id(),
|
||||
akode_state::GoalUpdate {
|
||||
objective: None,
|
||||
status: Some(status),
|
||||
token_budget: None,
|
||||
expected_goal_id: Some(active_goal.goal_id),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|err| err.to_string())?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
self.inner
|
||||
.metrics
|
||||
.record_terminal_if_status_changed(previous_status, &goal);
|
||||
self.inner.accounting_state.clear_active_goal();
|
||||
let goal = protocol_goal_from_state(goal);
|
||||
self.inner.event_emitter.thread_goal_updated(
|
||||
format!("{turn_id}:{event_name}"),
|
||||
Some(turn_id.to_string()),
|
||||
goal,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn restore_after_resume(&self) -> Result<(), String> {
|
||||
if !self.is_enabled() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let goal = self
|
||||
.inner
|
||||
.state_dbs
|
||||
.thread_goals()
|
||||
.get_thread_goal(self.thread_id())
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
match goal {
|
||||
Some(goal) if goal.status == akode_state::ThreadGoalStatus::Active => {
|
||||
self.inner
|
||||
.accounting_state
|
||||
.mark_idle_goal_active(goal.goal_id);
|
||||
self.inner.metrics.record_resumed();
|
||||
}
|
||||
Some(_) | None => self.inner.accounting_state.clear_active_goal(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn continue_if_idle(&self) -> Result<(), String> {
|
||||
if !self.tools_available() {
|
||||
self.inner.accounting_state.clear_active_goal();
|
||||
return Ok(());
|
||||
}
|
||||
// Hold this through the read/start window so external set/clear cannot
|
||||
// change the goal after we read it but before the continuation launches.
|
||||
let _goal_state_permit = self.goal_state_permit().await?;
|
||||
|
||||
if self
|
||||
.inner
|
||||
.state_dbs
|
||||
.thread_goals()
|
||||
.has_thread_goal_continuation_deferral(self.thread_id())
|
||||
.await
|
||||
.map_err(|err| err.to_string())?
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let Some(thread_manager) = self.inner.thread_manager.upgrade() else {
|
||||
tracing::debug!("skipping goal continuation because thread manager is unavailable");
|
||||
return Ok(());
|
||||
};
|
||||
let Ok(thread) = thread_manager.get_thread(self.inner.thread_id).await else {
|
||||
tracing::debug!("skipping goal continuation because live thread is unavailable");
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let Some(goal) = self
|
||||
.inner
|
||||
.state_dbs
|
||||
.thread_goals()
|
||||
.get_thread_goal(self.thread_id())
|
||||
.await
|
||||
.map_err(|err| err.to_string())?
|
||||
else {
|
||||
self.inner.accounting_state.clear_active_goal();
|
||||
return Ok(());
|
||||
};
|
||||
if goal.status != akode_state::ThreadGoalStatus::Active {
|
||||
self.inner.accounting_state.clear_active_goal();
|
||||
return Ok(());
|
||||
}
|
||||
let start_options = thread
|
||||
.thread_extension_data()
|
||||
.get::<TurnStartOptions>()
|
||||
.map(|options| options.as_ref().clone())
|
||||
.unwrap_or_default();
|
||||
let request = continuation_request(
|
||||
&protocol_goal_from_state(goal),
|
||||
thread.config().await.update_plan_enabled,
|
||||
);
|
||||
|
||||
match thread
|
||||
.start_turn_if_idle(request.on_start(TurnStartOptions {
|
||||
turn_trigger: Some("goal".to_string()),
|
||||
..start_options
|
||||
}))
|
||||
.await
|
||||
{
|
||||
Ok(StartIfIdleSubmission::Started { turn_id, .. }) => {
|
||||
// Turn-stop evaluation takes the same permit, so even a fast response
|
||||
// cannot finish before this host-admitted continuation is identified.
|
||||
self.inner.accounting_state.mark_goal_continuation(turn_id);
|
||||
}
|
||||
Ok(StartIfIdleSubmission::NotSubmitted { reason }) => {
|
||||
tracing::debug!(
|
||||
?reason,
|
||||
"skipping goal continuation because automatic idle work was rejected"
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::debug!(
|
||||
%error,
|
||||
"skipping goal continuation because turn input submission failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let current_turn_is_goal_active = self
|
||||
.inner
|
||||
.accounting_state
|
||||
.current_turn_id()
|
||||
.or_else(|| self.inner.accounting_state.interrupted_turn_id())
|
||||
.is_some_and(|turn_id| {
|
||||
self.inner
|
||||
.accounting_state
|
||||
.current_active_goal_id_for_turn(turn_id.as_str())
|
||||
.is_some()
|
||||
});
|
||||
if !current_turn_is_goal_active {
|
||||
self.inner
|
||||
.accounting_state
|
||||
.reset_idle_progress_baseline_and_clear_active_goal();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn inject_active_turn_steering(&self, item: ResponseItem) {
|
||||
let Some(thread_manager) = self.inner.thread_manager.upgrade() else {
|
||||
tracing::debug!("skipping goal steering because thread manager is unavailable");
|
||||
return;
|
||||
};
|
||||
let Ok(thread) = thread_manager.get_thread(self.inner.thread_id).await else {
|
||||
tracing::debug!("skipping goal steering because live thread is unavailable");
|
||||
return;
|
||||
};
|
||||
if thread.inject_if_running(vec![item]).await.is_err() {
|
||||
tracing::debug!("skipping goal steering because no turn is active");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn account_active_goal_progress(
|
||||
&self,
|
||||
turn_id: &str,
|
||||
event_id: &str,
|
||||
mode: akode_state::GoalAccountingMode,
|
||||
budget_limited_goal_disposition: BudgetLimitedGoalDisposition,
|
||||
) -> Result<Option<AccountedGoalProgress>, String> {
|
||||
let accounting = self.accounting_state();
|
||||
let _accounting_permit = accounting
|
||||
.progress_accounting_permit()
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
let Some(snapshot) = accounting.progress_snapshot(turn_id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let previous_status = self
|
||||
.current_goal_status_for_metrics(Some(snapshot.expected_goal_id.as_str()))
|
||||
.await?;
|
||||
let outcome = self
|
||||
.inner
|
||||
.state_dbs
|
||||
.thread_goals()
|
||||
.account_thread_goal_usage(
|
||||
self.thread_id(),
|
||||
snapshot.time_delta_seconds,
|
||||
snapshot.token_delta,
|
||||
mode,
|
||||
Some(snapshot.expected_goal_id.as_str()),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
Ok(match outcome {
|
||||
akode_state::GoalAccountingOutcome::Updated(goal) => {
|
||||
let goal_id = goal.goal_id.clone();
|
||||
self.inner
|
||||
.metrics
|
||||
.record_terminal_if_status_changed(previous_status, &goal);
|
||||
accounting.mark_progress_accounted_for_status(
|
||||
turn_id,
|
||||
&snapshot,
|
||||
goal.status,
|
||||
budget_limited_goal_disposition,
|
||||
);
|
||||
let goal = protocol_goal_from_state(goal);
|
||||
self.inner.event_emitter.thread_goal_updated(
|
||||
event_id.to_string(),
|
||||
Some(turn_id.to_string()),
|
||||
goal.clone(),
|
||||
);
|
||||
Some(AccountedGoalProgress { goal, goal_id })
|
||||
}
|
||||
akode_state::GoalAccountingOutcome::Unchanged(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn account_idle_goal_progress(
|
||||
&self,
|
||||
event_id: &str,
|
||||
mode: akode_state::GoalAccountingMode,
|
||||
budget_limited_goal_disposition: BudgetLimitedGoalDisposition,
|
||||
) -> Result<Option<AccountedGoalProgress>, String> {
|
||||
let accounting = self.accounting_state();
|
||||
let _accounting_permit = accounting
|
||||
.progress_accounting_permit()
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
let Some(snapshot) = accounting.idle_progress_snapshot() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let previous_status = self
|
||||
.current_goal_status_for_metrics(Some(snapshot.expected_goal_id.as_str()))
|
||||
.await?;
|
||||
let outcome = self
|
||||
.inner
|
||||
.state_dbs
|
||||
.thread_goals()
|
||||
.account_thread_goal_usage(
|
||||
self.thread_id(),
|
||||
snapshot.time_delta_seconds,
|
||||
snapshot.token_delta,
|
||||
mode,
|
||||
Some(snapshot.expected_goal_id.as_str()),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
Ok(match outcome {
|
||||
akode_state::GoalAccountingOutcome::Updated(goal) => {
|
||||
let goal_id = goal.goal_id.clone();
|
||||
self.inner
|
||||
.metrics
|
||||
.record_terminal_if_status_changed(previous_status, &goal);
|
||||
accounting.mark_idle_progress_accounted_for_status(
|
||||
&snapshot,
|
||||
goal.status,
|
||||
budget_limited_goal_disposition,
|
||||
);
|
||||
let goal = protocol_goal_from_state(goal);
|
||||
self.inner.event_emitter.thread_goal_updated(
|
||||
event_id.to_string(),
|
||||
/*turn_id*/ None,
|
||||
goal.clone(),
|
||||
);
|
||||
Some(AccountedGoalProgress { goal, goal_id })
|
||||
}
|
||||
akode_state::GoalAccountingOutcome::Unchanged(_) => {
|
||||
accounting.reset_idle_progress_baseline_and_clear_active_goal();
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn current_goal_status_for_metrics(
|
||||
&self,
|
||||
expected_goal_id: Option<&str>,
|
||||
) -> Result<Option<akode_state::ThreadGoalStatus>, String> {
|
||||
let goal = self
|
||||
.inner
|
||||
.state_dbs
|
||||
.thread_goals()
|
||||
.get_thread_goal(self.thread_id())
|
||||
.await
|
||||
.map_err(|err| err.to_string())?;
|
||||
Ok(goal.and_then(|goal| {
|
||||
expected_goal_id
|
||||
.is_none_or(|expected_goal_id| goal.goal_id == expected_goal_id)
|
||||
.then_some(goal.status)
|
||||
}))
|
||||
}
|
||||
}
|
||||
94
akode-rs/ext/goal/src/spec.rs
Normal file
94
akode-rs/ext/goal/src/spec.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
//! Responses API tool definitions for persisted thread goals.
|
||||
|
||||
use akode_tools::JsonSchema;
|
||||
use akode_tools::ResponsesApiTool;
|
||||
use akode_tools::ToolSpec;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub const GET_GOAL_TOOL_NAME: &str = "get_goal";
|
||||
pub const CREATE_GOAL_TOOL_NAME: &str = "create_goal";
|
||||
pub const UPDATE_GOAL_TOOL_NAME: &str = "update_goal";
|
||||
|
||||
pub fn create_get_goal_tool() -> ToolSpec {
|
||||
ToolSpec::Function(ResponsesApiTool {
|
||||
name: GET_GOAL_TOOL_NAME.to_string(),
|
||||
description: "Get the current goal for this thread, including status, budgets, token and elapsed-time usage, and remaining token budget."
|
||||
.to_string(),
|
||||
strict: false,
|
||||
defer_loading: None,
|
||||
parameters: JsonSchema::object(BTreeMap::new(), Some(Vec::new()), Some(false.into())),
|
||||
output_schema: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn create_create_goal_tool() -> ToolSpec {
|
||||
let properties = BTreeMap::from([
|
||||
(
|
||||
"objective".to_string(),
|
||||
JsonSchema::string(Some(
|
||||
"Required. The concrete objective to start pursuing. This starts a new active goal when no goal exists or replaces the current goal when it is complete."
|
||||
.to_string(),
|
||||
)),
|
||||
),
|
||||
(
|
||||
"token_budget".to_string(),
|
||||
JsonSchema::integer(Some(
|
||||
"Positive token budget for the new goal. Omit unless explicitly requested."
|
||||
.to_string(),
|
||||
)),
|
||||
),
|
||||
]);
|
||||
|
||||
ToolSpec::Function(ResponsesApiTool {
|
||||
name: CREATE_GOAL_TOOL_NAME.to_string(),
|
||||
description: format!(
|
||||
r#"Create a goal only when explicitly requested by the user or system/developer instructions; do not infer goals from ordinary tasks.
|
||||
Set token_budget only when an explicit token budget is requested. Fails if an unfinished goal exists; use {UPDATE_GOAL_TOOL_NAME} only for status."#
|
||||
),
|
||||
strict: false,
|
||||
defer_loading: None,
|
||||
parameters: JsonSchema::object(
|
||||
properties,
|
||||
/*required*/ Some(vec!["objective".to_string()]),
|
||||
Some(false.into()),
|
||||
),
|
||||
output_schema: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn create_update_goal_tool() -> ToolSpec {
|
||||
let properties = BTreeMap::from([(
|
||||
"status".to_string(),
|
||||
JsonSchema::string_enum(
|
||||
vec![json!("complete"), json!("blocked"), json!("paused")],
|
||||
Some(
|
||||
"Required. `paused` requires an explicit user request. Set to `complete` only when the objective is achieved and no required work remains. Set to `blocked` only after the same blocking condition has recurred for at least three consecutive goal turns and the agent is at an impasse. After a previously blocked goal is resumed, the resumed run starts a fresh blocked audit."
|
||||
.to_string(),
|
||||
),
|
||||
),
|
||||
)]);
|
||||
|
||||
ToolSpec::Function(ResponsesApiTool {
|
||||
name: UPDATE_GOAL_TOOL_NAME.to_string(),
|
||||
description: r#"Update the existing goal.
|
||||
Set status to `paused` only at the user's explicit request to pause this goal, never on your own initiative. Ask if unclear; a later resume revokes that request. Report the returned status and stop goal work. Budget limits take precedence over pausing.
|
||||
Set status to `complete` only when the objective has actually been achieved and no required work remains.
|
||||
Set status to `blocked` only when the same blocking condition has repeated for at least three consecutive goal turns, counting the original/user-triggered turn and any automatic continuations, and the agent cannot make meaningful progress without user input or an external-state change.
|
||||
If the user resumes a goal that was previously marked `blocked`, treat the resumed run as a fresh blocked audit. If the same blocking condition then repeats for at least three consecutive resumed goal turns, set status to `blocked` again.
|
||||
Once the blocked threshold is satisfied, do not keep reporting that you are still blocked while leaving the goal active; set status to `blocked`.
|
||||
Do not use `blocked` merely because the work is hard, slow, uncertain, incomplete, or would benefit from clarification.
|
||||
Do not mark a goal complete merely because its budget is nearly exhausted or because you are stopping work.
|
||||
You cannot use this tool to resume, budget-limit, or usage-limit a goal; those status changes are controlled by the user or system.
|
||||
When marking a budgeted goal achieved with status `complete`, report the final token usage from the tool result to the user."#
|
||||
.to_string(),
|
||||
strict: false,
|
||||
defer_loading: None,
|
||||
parameters: JsonSchema::object(
|
||||
properties,
|
||||
/*required*/ Some(vec!["status".to_string()]),
|
||||
Some(false.into()),
|
||||
),
|
||||
output_schema: None,
|
||||
})
|
||||
}
|
||||
156
akode-rs/ext/goal/src/steering.rs
Normal file
156
akode-rs/ext/goal/src/steering.rs
Normal file
@@ -0,0 +1,156 @@
|
||||
use akode_core::TurnInput;
|
||||
use akode_core::TurnInputRequest;
|
||||
use akode_core::context::ContextualUserFragment;
|
||||
use akode_core::context::InternalContextSource;
|
||||
use akode_core::context::InternalModelContextFragment;
|
||||
use akode_prompts::without_update_plan_instructions;
|
||||
use akode_protocol::models::ResponseItem;
|
||||
use akode_protocol::protocol::AdditionalContextEntry;
|
||||
use akode_protocol::protocol::AdditionalContextKind;
|
||||
use akode_protocol::protocol::ThreadGoal;
|
||||
use akode_utils_template::Template;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
static CONTINUATION_PROMPT_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
parse_embedded_template(
|
||||
include_str!("../templates/goals/continuation.md"),
|
||||
"goals/continuation.md",
|
||||
)
|
||||
});
|
||||
|
||||
static CONTINUATION_PROMPT_WITHOUT_UPDATE_PLAN: LazyLock<Template> = LazyLock::new(|| {
|
||||
parse_embedded_template(
|
||||
&without_update_plan_instructions(include_str!("../templates/goals/continuation.md")),
|
||||
"goals/continuation.md",
|
||||
)
|
||||
});
|
||||
|
||||
static BUDGET_LIMIT_PROMPT_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
parse_embedded_template(
|
||||
include_str!("../templates/goals/budget_limit.md"),
|
||||
"goals/budget_limit.md",
|
||||
)
|
||||
});
|
||||
|
||||
static OBJECTIVE_UPDATED_PROMPT_TEMPLATE: LazyLock<Template> = LazyLock::new(|| {
|
||||
parse_embedded_template(
|
||||
include_str!("../templates/goals/objective_updated.md"),
|
||||
"goals/objective_updated.md",
|
||||
)
|
||||
});
|
||||
|
||||
fn parse_embedded_template(source: &str, template_name: &str) -> Template {
|
||||
match Template::parse(source) {
|
||||
Ok(template) => template,
|
||||
Err(err) => panic!("embedded template {template_name} is invalid: {err}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn budget_limit_steering_item(goal: &ThreadGoal) -> ResponseItem {
|
||||
goal_context_input_item(budget_limit_prompt(goal))
|
||||
}
|
||||
|
||||
pub(crate) fn objective_updated_steering_item(goal: &ThreadGoal) -> ResponseItem {
|
||||
goal_context_input_item(objective_updated_prompt(goal))
|
||||
}
|
||||
|
||||
pub(crate) const GOAL_OBJECTIVE_CONTEXT: &str = "goal_objective";
|
||||
|
||||
pub(crate) fn continuation_request(
|
||||
goal: &ThreadGoal,
|
||||
update_plan_enabled: bool,
|
||||
) -> TurnInputRequest {
|
||||
let steering = goal_context_input_item(continuation_prompt(goal, update_plan_enabled));
|
||||
TurnInputRequest::new(TurnInput::ResponseItem(steering)).with_additional_context(
|
||||
[(
|
||||
GOAL_OBJECTIVE_CONTEXT.to_owned(),
|
||||
AdditionalContextEntry::new(goal.objective.clone(), AdditionalContextKind::Untrusted),
|
||||
)]
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
fn goal_context_input_item(prompt: String) -> ResponseItem {
|
||||
ContextualUserFragment::into(InternalModelContextFragment::new(
|
||||
InternalContextSource::from_static("goal"),
|
||||
prompt,
|
||||
))
|
||||
}
|
||||
|
||||
fn continuation_prompt(goal: &ThreadGoal, update_plan_enabled: bool) -> String {
|
||||
let tokens_used = goal.tokens_used.to_string();
|
||||
let token_budget = goal
|
||||
.token_budget
|
||||
.map(|budget| budget.to_string())
|
||||
.unwrap_or_else(|| "none".to_string());
|
||||
let remaining_tokens = goal
|
||||
.token_budget
|
||||
.map(|budget| (budget - goal.tokens_used).max(0).to_string())
|
||||
.unwrap_or_else(|| "unbounded".to_string());
|
||||
|
||||
let template = if update_plan_enabled {
|
||||
&*CONTINUATION_PROMPT_TEMPLATE
|
||||
} else {
|
||||
&*CONTINUATION_PROMPT_WITHOUT_UPDATE_PLAN
|
||||
};
|
||||
template
|
||||
.render([
|
||||
("tokens_used", tokens_used.as_str()),
|
||||
("token_budget", token_budget.as_str()),
|
||||
("remaining_tokens", remaining_tokens.as_str()),
|
||||
])
|
||||
.unwrap_or_else(|err| {
|
||||
panic!("embedded goals/continuation.md template failed to render: {err}")
|
||||
})
|
||||
}
|
||||
|
||||
fn budget_limit_prompt(goal: &ThreadGoal) -> String {
|
||||
let objective = escape_xml_text(&goal.objective);
|
||||
let time_used_seconds = goal.time_used_seconds.to_string();
|
||||
let tokens_used = goal.tokens_used.to_string();
|
||||
let token_budget = goal
|
||||
.token_budget
|
||||
.map(|budget| budget.to_string())
|
||||
.unwrap_or_else(|| "none".to_string());
|
||||
|
||||
BUDGET_LIMIT_PROMPT_TEMPLATE
|
||||
.render([
|
||||
("objective", objective.as_str()),
|
||||
("time_used_seconds", time_used_seconds.as_str()),
|
||||
("tokens_used", tokens_used.as_str()),
|
||||
("token_budget", token_budget.as_str()),
|
||||
])
|
||||
.unwrap_or_else(|err| {
|
||||
panic!("embedded goals/budget_limit.md template failed to render: {err}")
|
||||
})
|
||||
}
|
||||
|
||||
fn objective_updated_prompt(goal: &ThreadGoal) -> String {
|
||||
let objective = escape_xml_text(&goal.objective);
|
||||
let tokens_used = goal.tokens_used.to_string();
|
||||
let (token_budget, remaining_tokens) = match goal.token_budget {
|
||||
Some(token_budget) => (
|
||||
token_budget.to_string(),
|
||||
(token_budget - goal.tokens_used).max(0).to_string(),
|
||||
),
|
||||
None => ("none".to_string(), "unknown".to_string()),
|
||||
};
|
||||
|
||||
OBJECTIVE_UPDATED_PROMPT_TEMPLATE
|
||||
.render([
|
||||
("objective", objective.as_str()),
|
||||
("tokens_used", tokens_used.as_str()),
|
||||
("token_budget", token_budget.as_str()),
|
||||
("remaining_tokens", remaining_tokens.as_str()),
|
||||
])
|
||||
.unwrap_or_else(|err| {
|
||||
panic!("embedded goals/objective_updated.md template failed to render: {err}")
|
||||
})
|
||||
}
|
||||
|
||||
fn escape_xml_text(input: &str) -> String {
|
||||
input
|
||||
.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
}
|
||||
531
akode-rs/ext/goal/src/tool.rs
Normal file
531
akode-rs/ext/goal/src/tool.rs
Normal file
@@ -0,0 +1,531 @@
|
||||
use akode_core::ThreadManager;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
use akode_extension_api::FunctionCallError;
|
||||
use akode_extension_api::JsonToolOutput;
|
||||
use akode_extension_api::ToolCall;
|
||||
use akode_extension_api::ToolExecutor;
|
||||
use akode_extension_api::ToolName;
|
||||
use akode_extension_api::ToolOutput;
|
||||
use akode_extension_api::ToolSpec;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::ThreadGoal;
|
||||
use akode_protocol::protocol::ThreadGoalStatus;
|
||||
use akode_protocol::protocol::validate_thread_goal_objective;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::accounting::BudgetLimitedGoalDisposition;
|
||||
use crate::accounting::GoalAccountingState;
|
||||
use crate::events::GoalEventEmitter;
|
||||
use crate::metrics::GoalMetrics;
|
||||
use crate::runtime::GoalRuntimeHandle;
|
||||
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;
|
||||
use crate::steering::GOAL_OBJECTIVE_CONTEXT;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct GoalToolExecutor {
|
||||
pub(crate) execution_allowed: bool,
|
||||
kind: GoalToolKind,
|
||||
thread_id: ThreadId,
|
||||
state_db: Arc<akode_state::StateRuntime>,
|
||||
accounting_state: Arc<GoalAccountingState>,
|
||||
event_emitter: GoalEventEmitter,
|
||||
metrics: GoalMetrics,
|
||||
max_goal_token_budget: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum GoalToolKind {
|
||||
Get,
|
||||
Create(Weak<ThreadManager>),
|
||||
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<akode_state::StateRuntime>,
|
||||
accounting_state: Arc<GoalAccountingState>,
|
||||
event_emitter: GoalEventEmitter,
|
||||
metrics: GoalMetrics,
|
||||
) -> Self {
|
||||
Self {
|
||||
kind: GoalToolKind::Get,
|
||||
execution_allowed: true,
|
||||
thread_id,
|
||||
state_db,
|
||||
accounting_state,
|
||||
event_emitter,
|
||||
metrics,
|
||||
max_goal_token_budget: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create(
|
||||
runtime: &GoalRuntimeHandle,
|
||||
thread_manager: Weak<ThreadManager>,
|
||||
state_db: Arc<akode_state::StateRuntime>,
|
||||
event_emitter: GoalEventEmitter,
|
||||
metrics: GoalMetrics,
|
||||
max_goal_token_budget: Option<i64>,
|
||||
) -> Self {
|
||||
Self {
|
||||
kind: GoalToolKind::Create(thread_manager),
|
||||
execution_allowed: true,
|
||||
thread_id: runtime.thread_id(),
|
||||
state_db,
|
||||
accounting_state: runtime.accounting_state(),
|
||||
event_emitter,
|
||||
metrics,
|
||||
max_goal_token_budget,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn update(
|
||||
thread_id: ThreadId,
|
||||
state_db: Arc<akode_state::StateRuntime>,
|
||||
accounting_state: Arc<GoalAccountingState>,
|
||||
event_emitter: GoalEventEmitter,
|
||||
metrics: GoalMetrics,
|
||||
) -> Self {
|
||||
Self {
|
||||
kind: GoalToolKind::Update,
|
||||
execution_allowed: true,
|
||||
thread_id,
|
||||
state_db,
|
||||
accounting_state,
|
||||
event_emitter,
|
||||
metrics,
|
||||
max_goal_token_budget: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'call> ToolExecutor<ToolCall<'call>> 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 supports_parallel_tool_calls(&self) -> bool {
|
||||
matches!(self.kind, GoalToolKind::Get)
|
||||
}
|
||||
|
||||
fn spec(&self) -> ToolSpec {
|
||||
match self.kind {
|
||||
GoalToolKind::Get => create_get_goal_tool(),
|
||||
GoalToolKind::Create(_) => create_create_goal_tool(),
|
||||
GoalToolKind::Update => create_update_goal_tool(),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle<'a>(
|
||||
&'a self,
|
||||
invocation: ToolCall<'call>,
|
||||
) -> akode_extension_api::ToolExecutorFuture<'a>
|
||||
where
|
||||
'call: 'a,
|
||||
{
|
||||
Box::pin(async move {
|
||||
if !self.execution_allowed {
|
||||
return Err(FunctionCallError::RespondToModel(
|
||||
"Goal tools require a persistent thread.".to_string(),
|
||||
));
|
||||
}
|
||||
match &self.kind {
|
||||
GoalToolKind::Get => self.handle_get(invocation).await,
|
||||
GoalToolKind::Create(thread_manager) => {
|
||||
self.handle_create(invocation, thread_manager).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<'_>,
|
||||
thread_manager: &Weak<ThreadManager>,
|
||||
) -> 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)?;
|
||||
request.token_budget = request.token_budget.or(self.max_goal_token_budget);
|
||||
validate_goal_budget(request.token_budget, self.max_goal_token_budget)
|
||||
.map_err(FunctionCallError::RespondToModel)?;
|
||||
|
||||
let goal = self
|
||||
.state_db
|
||||
.thread_goals()
|
||||
.insert_thread_goal(
|
||||
self.thread_id,
|
||||
request.objective.as_str(),
|
||||
akode_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 has an unfinished goal; complete the existing goal first"
|
||||
.to_string(),
|
||||
)
|
||||
})?;
|
||||
fill_empty_thread_preview_if_possible(self.state_db.as_ref(), self.thread_id, &goal).await;
|
||||
let turn_id = self
|
||||
.accounting_state
|
||||
.mark_current_turn_goal_active(goal.goal_id.clone());
|
||||
if let Some(manager) = thread_manager.upgrade()
|
||||
&& let Ok(thread) = manager.get_thread(self.thread_id).await
|
||||
{
|
||||
thread
|
||||
.inject_untrusted_context_for_turn(
|
||||
&invocation.turn_id,
|
||||
GOAL_OBJECTIVE_CONTEXT,
|
||||
goal.objective.clone(),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
self.metrics.record_created();
|
||||
let goal = protocol_goal_from_state(goal);
|
||||
self.emit_goal_updated_from_tool_call(&invocation, turn_id, 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 !matches!(
|
||||
args.status,
|
||||
ThreadGoalStatus::Complete | ThreadGoalStatus::Blocked | ThreadGoalStatus::Paused
|
||||
) {
|
||||
return Err(FunctionCallError::RespondToModel(
|
||||
"update_goal can only mark the existing goal complete, blocked, or paused at the user's explicit request; resume, budget-limited, and usage-limited status changes are controlled by the user or system"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
self.account_active_goal_progress(
|
||||
match args.status {
|
||||
ThreadGoalStatus::Complete => akode_state::GoalAccountingMode::ActiveOrComplete,
|
||||
ThreadGoalStatus::Blocked | ThreadGoalStatus::Paused => {
|
||||
akode_state::GoalAccountingMode::ActiveOrStopped
|
||||
}
|
||||
ThreadGoalStatus::Active
|
||||
| ThreadGoalStatus::UsageLimited
|
||||
| ThreadGoalStatus::BudgetLimited => unreachable!("status validated above"),
|
||||
},
|
||||
invocation.call_id.as_str(),
|
||||
BudgetLimitedGoalDisposition::ClearActive,
|
||||
)
|
||||
.await?;
|
||||
let previous_status = self
|
||||
.current_goal_status_for_metrics(/*expected_goal_id*/ None)
|
||||
.await?;
|
||||
let goal = self
|
||||
.state_db
|
||||
.thread_goals()
|
||||
.update_thread_goal(
|
||||
self.thread_id,
|
||||
akode_state::GoalUpdate {
|
||||
objective: None,
|
||||
status: Some(state_status_from_protocol(args.status)),
|
||||
token_budget: None,
|
||||
expected_goal_id: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
FunctionCallError::RespondToModel(format!("failed to update goal: {err}"))
|
||||
})?
|
||||
.ok_or_else(|| {
|
||||
FunctionCallError::RespondToModel(
|
||||
"cannot update goal because this thread has no goal".to_string(),
|
||||
)
|
||||
})?;
|
||||
self.metrics
|
||||
.record_terminal_if_status_changed(previous_status, &goal);
|
||||
let goal = protocol_goal_from_state(goal);
|
||||
let turn_id = self.accounting_state.clear_current_turn_goal();
|
||||
self.emit_goal_updated_from_tool_call(&invocation, turn_id, goal.clone());
|
||||
goal_response(
|
||||
Some(goal),
|
||||
if args.status == ThreadGoalStatus::Complete {
|
||||
CompletionBudgetReport::Include
|
||||
} else {
|
||||
CompletionBudgetReport::Omit
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn emit_goal_updated_from_tool_call(
|
||||
&self,
|
||||
invocation: &ToolCall<'_>,
|
||||
turn_id: Option<String>,
|
||||
goal: ThreadGoal,
|
||||
) {
|
||||
self.event_emitter
|
||||
.thread_goal_updated(invocation.call_id.clone(), turn_id, goal);
|
||||
}
|
||||
|
||||
async fn account_active_goal_progress(
|
||||
&self,
|
||||
mode: akode_state::GoalAccountingMode,
|
||||
event_id: &str,
|
||||
budget_limited_goal_disposition: BudgetLimitedGoalDisposition,
|
||||
) -> Result<Option<ThreadGoal>, FunctionCallError> {
|
||||
let Some(turn_id) = self.accounting_state.current_turn_id() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let _accounting_permit = self
|
||||
.accounting_state
|
||||
.progress_accounting_permit()
|
||||
.await
|
||||
.map_err(|err| {
|
||||
FunctionCallError::Fatal(format!(
|
||||
"goal progress accounting semaphore closed: {err}"
|
||||
))
|
||||
})?;
|
||||
let Some(snapshot) = self.accounting_state.progress_snapshot(turn_id.as_str()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let previous_status = self
|
||||
.current_goal_status_for_metrics(Some(snapshot.expected_goal_id.as_str()))
|
||||
.await?;
|
||||
let outcome = self
|
||||
.state_db
|
||||
.thread_goals()
|
||||
.account_thread_goal_usage(
|
||||
self.thread_id,
|
||||
snapshot.time_delta_seconds,
|
||||
snapshot.token_delta,
|
||||
mode,
|
||||
Some(snapshot.expected_goal_id.as_str()),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
FunctionCallError::RespondToModel(format!("failed to account goal progress: {err}"))
|
||||
})?;
|
||||
Ok(match outcome {
|
||||
akode_state::GoalAccountingOutcome::Updated(goal) => {
|
||||
self.metrics
|
||||
.record_terminal_if_status_changed(previous_status, &goal);
|
||||
self.accounting_state.mark_progress_accounted_for_status(
|
||||
turn_id.as_str(),
|
||||
&snapshot,
|
||||
goal.status,
|
||||
budget_limited_goal_disposition,
|
||||
);
|
||||
let goal = protocol_goal_from_state(goal);
|
||||
self.event_emitter.thread_goal_updated(
|
||||
event_id.to_string(),
|
||||
Some(turn_id),
|
||||
goal.clone(),
|
||||
);
|
||||
Some(goal)
|
||||
}
|
||||
akode_state::GoalAccountingOutcome::Unchanged(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn current_goal_status_for_metrics(
|
||||
&self,
|
||||
expected_goal_id: Option<&str>,
|
||||
) -> Result<Option<akode_state::ThreadGoalStatus>, FunctionCallError> {
|
||||
let goal = self
|
||||
.state_db
|
||||
.thread_goals()
|
||||
.get_thread_goal(self.thread_id)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
FunctionCallError::RespondToModel(format!(
|
||||
"failed to read goal metrics status: {err}"
|
||||
))
|
||||
})?;
|
||||
Ok(goal.and_then(|goal| {
|
||||
expected_goal_id
|
||||
.is_none_or(|expected_goal_id| goal.goal_id == expected_goal_id)
|
||||
.then_some(goal.status)
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
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()))
|
||||
}
|
||||
|
||||
pub(crate) fn validate_goal_budget(
|
||||
value: Option<i64>,
|
||||
max_goal_token_budget: Option<i64>,
|
||||
) -> Result<(), String> {
|
||||
if let Some(value) = value
|
||||
&& value <= 0
|
||||
{
|
||||
return Err("goal budgets must be positive when provided".to_string());
|
||||
}
|
||||
if let Some(value) = value
|
||||
&& let Some(max_goal_token_budget) = max_goal_token_budget
|
||||
&& value > max_goal_token_budget
|
||||
{
|
||||
return Err(format!(
|
||||
"goal token budget {value} exceeds the maximum allowed goal token budget of {max_goal_token_budget}"
|
||||
));
|
||||
}
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn fill_empty_thread_preview_if_possible(
|
||||
state_db: &akode_state::StateRuntime,
|
||||
thread_id: ThreadId,
|
||||
goal: &akode_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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn protocol_goal_from_state(goal: akode_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: akode_state::ThreadGoalStatus) -> ThreadGoalStatus {
|
||||
match status {
|
||||
akode_state::ThreadGoalStatus::Active => ThreadGoalStatus::Active,
|
||||
akode_state::ThreadGoalStatus::Paused => ThreadGoalStatus::Paused,
|
||||
akode_state::ThreadGoalStatus::Blocked => ThreadGoalStatus::Blocked,
|
||||
akode_state::ThreadGoalStatus::UsageLimited => ThreadGoalStatus::UsageLimited,
|
||||
akode_state::ThreadGoalStatus::BudgetLimited => ThreadGoalStatus::BudgetLimited,
|
||||
akode_state::ThreadGoalStatus::Complete => ThreadGoalStatus::Complete,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn state_status_from_protocol(
|
||||
status: ThreadGoalStatus,
|
||||
) -> akode_state::ThreadGoalStatus {
|
||||
match status {
|
||||
ThreadGoalStatus::Active => akode_state::ThreadGoalStatus::Active,
|
||||
ThreadGoalStatus::Paused => akode_state::ThreadGoalStatus::Paused,
|
||||
ThreadGoalStatus::Blocked => akode_state::ThreadGoalStatus::Blocked,
|
||||
ThreadGoalStatus::UsageLimited => akode_state::ThreadGoalStatus::UsageLimited,
|
||||
ThreadGoalStatus::BudgetLimited => akode_state::ThreadGoalStatus::BudgetLimited,
|
||||
ThreadGoalStatus::Complete => akode_state::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(),
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user