Include thread id in token budget context (#27663)

## Why

The token budget full-context fragment identifies the current context
window, but not the thread that owns that window. Including the thread
id makes the initial context-window metadata self-contained, and
`get_context_remaining` also needs to be usable from Code Mode without
forcing callers to parse the model-facing fragment string.

## What changed

- Include the session thread id in the initial `<token_budget>` context
fragment.
- Expose `get_context_remaining` as a Code Mode nested tool while
keeping `new_context` direct-model-only.
- Keep direct model-facing `get_context_remaining` output as the
existing `<token_budget>` text fragment.
- Return only `tokens_left` from the Code Mode structured result for
`get_context_remaining`.
- Update token-budget integration tests and add Code Mode coverage for
the structured result.

## Verification

- `just test -p codex-core token_budget`
- `just test -p codex-core
code_mode_get_context_remaining_returns_structured_result`
- `just test -p core_test_support redacted_text_mode_normalizes_uuids`
This commit is contained in:
pakrym-oai authored and GitHub committed 2026-06-11 15:10:29 -07:00
1 parent d23bb22f25
commit 7516eb5c70
8 files changed
+142 -28

No files matched your search

@@ -2,14 +2,59 @@ use crate::context::ContextualUserFragment;
use crate::function_tool::FunctionCallError;
use crate::tools::context::FunctionToolOutput;
use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolOutput;
use crate::tools::context::ToolPayload;
use crate::tools::context::boxed_tool_output;
use crate::tools::handlers::get_context_remaining_spec::GET_CONTEXT_REMAINING_TOOL_NAME;
use crate::tools::handlers::get_context_remaining_spec::create_get_context_remaining_tool;
use crate::tools::registry::CoreToolRuntime;
use crate::tools::registry::ToolExecutor;
use codex_protocol::models::ResponseInputItem;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
use serde_json::Value as JsonValue;
use serde_json::json;
#[derive(Debug, Clone)]
struct GetContextRemainingOutput {
tokens_left: Option<i64>,
}
impl GetContextRemainingOutput {
fn new(tokens_left: Option<i64>) -> Self {
Self { tokens_left }
}
fn fragment(&self) -> String {
match self.tokens_left {
Some(tokens_left) => {
crate::context::TokenBudgetRemainingContext::new(tokens_left).render()
}
None => crate::context::TokenBudgetRemainingContext::unknown().render(),
}
}
}
impl ToolOutput for GetContextRemainingOutput {
fn log_preview(&self) -> String {
self.fragment()
}
fn success_for_logging(&self) -> bool {
true
}
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
FunctionToolOutput::from_text(self.fragment(), Some(true))
.to_response_item(call_id, payload)
}
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
json!({
"tokens_left": self.tokens_left,
})
}
}
pub struct GetContextRemainingHandler;
@@ -31,22 +76,18 @@ impl ToolExecutor<ToolInvocation> for GetContextRemainingHandler {
}
let Some(model_context_window) = invocation.turn.model_context_window() else {
let fragment = crate::context::TokenBudgetRemainingContext::unknown().render();
return Ok(boxed_tool_output(FunctionToolOutput::from_text(
fragment,
Some(true),
return Ok(boxed_tool_output(GetContextRemainingOutput::new(
/*tokens_left*/ None,
)));
};
let active_context_tokens = invocation.session.get_total_token_usage().await.max(0);
let tokens_left = model_context_window
.saturating_sub(active_context_tokens)
.max(0);
let fragment = crate::context::TokenBudgetRemainingContext::new(tokens_left).render();
Ok(boxed_tool_output(FunctionToolOutput::from_text(
fragment,
Some(true),
)))
Ok(boxed_tool_output(GetContextRemainingOutput::new(Some(
tokens_left,
))))
})
}
}
@@ -1,6 +1,8 @@
use codex_tools::JsonSchema;
use codex_tools::ResponsesApiTool;
use codex_tools::ToolSpec;
use serde_json::Value;
use serde_json::json;
use std::collections::BTreeMap;
pub(crate) const GET_CONTEXT_REMAINING_TOOL_NAME: &str = "get_context_remaining";
@@ -12,6 +14,23 @@ pub fn create_get_context_remaining_tool() -> ToolSpec {
strict: false,
defer_loading: None,
parameters: JsonSchema::object(BTreeMap::new(), /*required*/ None, Some(false.into())),
output_schema: None,
output_schema: Some(get_context_remaining_output_schema()),
})
}
fn get_context_remaining_output_schema() -> Value {
json!({
"type": "object",
"properties": {
"tokens_left": {
"anyOf": [
{ "type": "integer" },
{ "type": "null" }
],
"description": "Remaining tokens in the current context window, or null when unavailable."
}
},
"required": ["tokens_left"],
"additionalProperties": false
})
}