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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 38 additions & 9 deletions crates/agent/src/claude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,8 @@ struct ClaudeLaunchOptions {
fast_mode: bool,
ultracode: bool,
auto_compact_window: Option<u64>,
/// The window is the bare slug's own, so `auto_compact_window` adds nothing.
/// The window is the bare slug's own and below its largest, so
/// `auto_compact_window` adds nothing.
native_window: bool,
}

Expand Down Expand Up @@ -728,13 +729,20 @@ impl ClaudeLaunchOptions {
let suffix = entry.map_or("", |entry| entry.context_window_suffix(window));
format!("{base}{suffix}")
});
// Anything below the model's largest window is enforced through
// `autoCompactWindow`: some bare slugs (e.g. Opus 5.5) already run at
// 1M, so a smaller selection must be told to compact early.
let largest = entry
.and_then(CatalogModel::largest_context_window)
.unwrap_or(window);
let auto_compact_window = (window < largest).then_some(window);
// A size the person chose is enforced through `autoCompactWindow`,
// the model's largest too: Claude Code's own `auto` (2.1.334)
// compacts a 1M model near 400k unless told otherwise. With no size
// chosen, a default below the largest is still enforced, because some
// bare slugs (e.g. Opus 5.5) run at more than that default. A model
// without window data is sent none.
let largest = entry.and_then(CatalogModel::largest_context_window);
let chosen = selections
.iter()
.find(|selection| selection.id == crate::context_window::OPTION_ID)
.and_then(|selection| crate::context_window::parse_tokens(&selection.value))
.is_some();
let auto_compact_window =
largest.and_then(|largest| (chosen || window < largest).then_some(window));

// `--settings` object: only supported/true keys are emitted.
let fast_supported = spec.is_some_and(|spec| has_boolean_option(spec, "fastMode"));
Expand All @@ -759,7 +767,11 @@ impl ClaudeLaunchOptions {
fast_mode,
ultracode,
auto_compact_window,
native_window: entry.and_then(CatalogModel::default_context_window) == Some(window),
// Claude Code's `auto` lowers the window the slug opens only to a
// smaller size (2.1.334: 400k for 1M models), so a default below
// the model's largest is taken to run at exactly its own.
native_window: largest.is_some_and(|largest| window < largest)
&& entry.and_then(CatalogModel::default_context_window) == Some(window),
}
}

Expand Down Expand Up @@ -2147,6 +2159,12 @@ pub(crate) struct Mapper {
pending_settings: Option<PendingSettings>,
/// The `get_settings` read awaiting its answer.
pending_settings_read: Option<String>,
/// The `get_context_usage` read awaiting its answer.
pending_window_read: Option<String>,
/// The window Claude Code compacts against, as `get_context_usage` last
/// said: its `auto` or `/autocompact` size, which the model's own
/// `contextWindow` in `modelUsage` does not show.
compact_window: Option<u64>,
/// The skills init named: a pushed command list does not say which of
/// its commands are skills.
skills: Vec<String>,
Expand Down Expand Up @@ -2224,6 +2242,8 @@ impl Mapper {
applied_settings: ClaudeLaunchOptions::default(),
pending_settings: None,
pending_settings_read: None,
pending_window_read: None,
compact_window: None,
skills: Vec::new(),
reported_model: None,
reported_fast_mode: None,
Expand Down Expand Up @@ -2677,6 +2697,11 @@ impl Mapper {
.as_u64()
})
.or(usage.context_window);
// The window the CLI compacts against is at most the model's.
usage.context_window = match (self.compact_window, usage.context_window) {
(Some(compact), Some(model)) => Some(compact.min(model)),
(compact, model) => compact.or(model),
};
usage.turn_processed_tokens = processed;
// The timeline owns lifetime accumulation, including restored history.
usage.total_processed_tokens = None;
Expand Down Expand Up @@ -2725,6 +2750,10 @@ impl Mapper {
status,
usage,
});
// The turn may have moved the window: its first request enrolls the
// session in `auto`, and a size or model chosen since takes effect.
let read = self.window_read_request();
self.outgoing.push(read);
events
}
}
Expand Down
4 changes: 4 additions & 0 deletions crates/agent/src/claude/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ impl Mapper {
.into_iter()
.collect();
}
if self.pending_window_read.as_deref() == Some(request_id) {
self.pending_window_read = None;
return self.on_window_read(response);
}
if self.pending_settings_read.as_deref() == Some(request_id) {
self.pending_settings_read = None;
return self.on_settings_read(response);
Expand Down
26 changes: 26 additions & 0 deletions crates/agent/src/claude/requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,32 @@ impl Mapper {
message
}

/// `get_context_usage`, whose `maxTokens` is the window the session
/// compacts against (2.1.334): `autoWindow` once the session is on
/// `auto`, a size from settings, or the model's own.
pub(super) fn window_read_request(&mut self) -> Value {
let message = self.control_request(json!({ "subtype": "get_context_usage" }));
self.pending_window_read = message["request_id"].as_str().map(str::to_owned);
message
}

pub(super) fn on_window_read(&mut self, response: &Value) -> Vec<AgentEvent> {
let Some(window) = response
.pointer("/response/maxTokens")
.and_then(Value::as_u64)
.filter(|_| response.get("subtype").and_then(Value::as_str) == Some("success"))
else {
log::debug!("claude: get_context_usage gave no window: {response}");
return Vec::new();
};
self.compact_window = Some(window);
if self.latest_usage.context_window == Some(window) {
return Vec::new();
}
self.latest_usage.context_window = Some(window);
vec![AgentEvent::TokenUsage(self.latest_usage)]
}

pub(super) fn on_settings_read(&mut self, response: &Value) -> Vec<AgentEvent> {
let applied = response
.pointer("/response/applied")
Expand Down
54 changes: 49 additions & 5 deletions crates/agent/src/claude/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1092,13 +1092,17 @@ fn context_window_launch_semantics() {
};
let auto_compact = |launch: &ClaudeLaunchOptions| settings(launch)["autoCompactWindow"].clone();

// Default window of a 1M-default profile: the bare slug already runs
// at 1M, so no suffix is sent (and none is needed for `1m` either).
for value in [None, Some(json!("1m"))] {
// A 1M-default profile with no size chosen, or `auto`, sends no window:
// Claude Code runs at its own (2.1.334 compacts near 400k). Choosing 1M
// sends it, as the bare slug already opens 1M without a suffix.
for value in [None, Some(json!("auto"))] {
let launch = resolve("test-wide", value);
assert_eq!(launch.model_id.as_deref(), Some("test-wide"));
assert!(launch.settings_json.is_none());
}
let launch = resolve("test-wide", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("test-wide"));
assert_eq!(auto_compact(&launch), json!(1_000_000));
assert_eq!(catalog.resolved_context_window("test-wide", &[]), 1_000_000);
// A suffixed id still resolves to the same model.
assert_eq!(
Expand All @@ -1122,7 +1126,7 @@ fn context_window_launch_semantics() {
}
let launch = resolve("test-narrow", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("test-narrow[1m]"));
assert!(launch.settings_json.is_none());
assert_eq!(auto_compact(&launch), json!(1_000_000));
let launch = resolve("test-narrow", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("test-narrow[1m]"));
assert_eq!(auto_compact(&launch), json!(500_000));
Expand All @@ -1132,9 +1136,14 @@ fn context_window_launch_semantics() {
catalog.resolved_context_window("test-fixed", &[]),
1_000_000
);
for value in [None, Some(json!("auto"))] {
let launch = resolve("test-fixed", value);
assert_eq!(launch.model_id.as_deref(), Some("test-fixed"));
assert!(launch.settings_json.is_none());
}
let launch = resolve("test-fixed", Some(json!("1m")));
assert_eq!(launch.model_id.as_deref(), Some("test-fixed"));
assert!(launch.settings_json.is_none());
assert_eq!(auto_compact(&launch), json!(1_000_000));
let launch = resolve("test-fixed", Some(json!(500_000)));
assert_eq!(launch.model_id.as_deref(), Some("test-fixed"));
assert_eq!(auto_compact(&launch), json!(500_000));
Expand Down Expand Up @@ -3039,6 +3048,41 @@ fn result_maps_to_turn_completed_with_usage() {
));
}

/// The meter's window is the one Claude Code compacts against, not the
/// model's: on `auto` a 1M model reports `contextWindow` 1000000 in
/// `modelUsage` while `get_context_usage` gives `maxTokens` 400000 and
/// compacts at 367k. Shapes recorded from Claude Code 2.1.334 on Opus 5.5.
#[test]
fn the_window_is_the_one_claude_code_compacts_against() {
let result = r#"{"type":"result","subtype":"success","is_error":false,"usage":{"input_tokens":2,"cache_read_input_tokens":11952,"cache_creation_input_tokens":11829,"output_tokens":5},"modelUsage":{"claude-opus-5-5":{"contextWindow":1000000,"canonicalModel":"claude-opus-5-5"}}}"#;
let window = |events: &[AgentEvent]| {
events.iter().find_map(|event| match event {
AgentEvent::TurnCompleted { usage, .. } => usage.and_then(|usage| usage.context_window),
AgentEvent::TokenUsage(usage) => usage.context_window,
_ => None,
})
};
let mut m = Mapper::new();
m.start_turn();
assert_eq!(window(&feed(&mut m, result)), Some(1_000_000));
let [read] = m.take_outgoing().try_into().expect("one read");
assert_eq!(read["request"], json!({ "subtype": "get_context_usage" }));
let answer = |read: &Value| {
format!(
r#"{{"type":"control_response","response":{{"subtype":"success","request_id":"{}","response":{{"model":"claude-opus-5-5","maxTokens":400000,"rawMaxTokens":400000,"autoWindow":400000,"autoCompactThreshold":367000,"isAutoCompactEnabled":true,"totalTokens":23783}}}}}}"#,
read["request_id"].as_str().unwrap()
)
};
assert_eq!(window(&feed(&mut m, &answer(&read))), Some(400_000));

// The next turn reports the CLI's window from the start, and an
// unchanged answer adds nothing.
m.start_turn();
assert_eq!(window(&feed(&mut m, result)), Some(400_000));
let [read] = m.take_outgoing().try_into().expect("one read");
assert!(feed(&mut m, &answer(&read)).is_empty());
}

#[test]
fn interrupted_result_status() {
let mut idle = Mapper::new();
Expand Down
112 changes: 96 additions & 16 deletions crates/agent/src/claude_manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,11 +224,13 @@ impl CatalogModel {
})
}

/// Tokens of the default context window selection.
/// Tokens of the window the bare slug opens with no selection.
pub(crate) fn default_context_window(&self) -> Option<u64> {
self.runtime.fixed_context_window_tokens.or_else(|| {
let default = self.default_select("contextWindow")?;
self.runtime.context_window_tokens.get(default).copied()
match self.default_select("contextWindow")? {
AUTO_WINDOW => self.largest_context_window(),
default => self.runtime.context_window_tokens.get(default).copied(),
}
})
}

Expand Down Expand Up @@ -364,6 +366,55 @@ fn descriptor(option: &Value, skipped: &mut Vec<String>) -> Option<OptionDescrip
/// settings schema of Claude Code 2.1.322.
const AUTO_COMPACT_MINIMUM: u64 = 100_000;

/// The `contextWindow` preset that sends Claude Code no window, so the CLI
/// runs at its own: since 2.1.334 its `auto` setting, which compacts a 1M
/// model near 400k, or the size `/autocompact` saved.
pub(crate) const AUTO_WINDOW: &str = "auto";

/// Make [`AUTO_WINDOW`] the default of a selector whose default sends no
/// window, which is one whose default is the model's largest: naming that
/// size as the default would claim a window the CLI may not run at.
fn offer_auto_window(options: &mut [OptionDescriptor], runtime: &ClaudeCodeProfile) {
let Some(OptionDescriptor::Select {
options,
default_value,
..
}) = options.iter_mut().find(|option| {
matches!(option, OptionDescriptor::Select { id, .. } if id == crate::context_window::OPTION_ID)
})
else {
return;
};
let tokens = |value: &str| {
runtime
.fixed_context_window_tokens
.or_else(|| runtime.context_window_tokens.get(value).copied())
};
let largest = runtime
.fixed_context_window_tokens
.or_else(|| runtime.context_window_tokens.values().copied().max());
let default = default_value.as_deref().and_then(tokens);
if default.is_none() || default != largest {
return;
}
options.insert(
0,
SelectOption {
value: AUTO_WINDOW.into(),
label: "Auto".into(),
description: Some(
"Claude Code's own window: its auto setting, or the size /autocompact saved".into(),
),
unavailable: None,
speed: None,
summary: None,
approval: None,
apply: None,
},
);
*default_value = Some(AUTO_WINDOW.into());
}

/// A `contextWindow` selector whose only preset is the model's fixed window.
fn fixed_context_window_descriptor(tokens: u64) -> OptionDescriptor {
let label = crate::context_window::format(tokens);
Expand Down Expand Up @@ -452,6 +503,7 @@ fn catalog_model(
{
options.push(fixed_context_window_descriptor(tokens));
}
offer_auto_window(&mut options, &runtime);
Ok(CatalogModel {
spec: ModelSpec {
is_default: defaults.get("chat").and_then(Value::as_str) == Some(slug.as_str()),
Expand Down Expand Up @@ -1013,6 +1065,19 @@ mod tests {
id: "contextWindow".into(),
label: "Context Window".into(),
options: vec![
SelectOption {
value: AUTO_WINDOW.into(),
label: "Auto".into(),
description: Some(
"Claude Code's own window: its auto setting, or the size /autocompact saved"
.into(),
),
unavailable: None,
speed: None,
summary: None,
approval: None,
apply: None,
},
SelectOption {
value: "200k".into(),
label: "200k".into(),
Expand All @@ -1034,7 +1099,7 @@ mod tests {
apply: None,
},
],
default_value: Some("1m".into()),
default_value: Some(AUTO_WINDOW.into()),
role: crate::OptionRole::ContextWindow,
apply: crate::ApplyTiming::Live,
recommended: None,
Expand All @@ -1057,23 +1122,38 @@ mod tests {
permissive: None,
}
);
// A fixed window still gets a selector, defaulting to that window.
// A fixed window still gets a selector, defaulting to the CLI's own.
assert_eq!(
catalog.model("test-fixed").unwrap().spec.options[2],
OptionDescriptor::Select {
id: "contextWindow".into(),
label: "Context Window".into(),
options: vec![SelectOption {
value: "1m".into(),
label: "1M".into(),
description: None,
unavailable: None,
speed: None,
summary: None,
approval: None,
apply: None,
}],
default_value: Some("1m".into()),
options: vec![
SelectOption {
value: AUTO_WINDOW.into(),
label: "Auto".into(),
description: Some(
"Claude Code's own window: its auto setting, or the size /autocompact saved"
.into(),
),
unavailable: None,
speed: None,
summary: None,
approval: None,
apply: None,
},
SelectOption {
value: "1m".into(),
label: "1M".into(),
description: None,
unavailable: None,
speed: None,
summary: None,
approval: None,
apply: None,
},
],
default_value: Some(AUTO_WINDOW.into()),
role: crate::OptionRole::ContextWindow,
apply: crate::ApplyTiming::Live,
recommended: None,
Expand Down
Loading
Loading