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
30 changes: 15 additions & 15 deletions crates/dim-app-server/resources/default-catalog.json

Large diffs are not rendered by default.

26 changes: 25 additions & 1 deletion crates/dim-app-server/src/model_catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,16 @@ pub struct ModelEntry {
pub metadata: Option<ModelMetadata>,
}

impl ModelEntry {
pub(crate) fn codex_context_window_ceiling(&self) -> Option<u64> {
self.metadata
.as_ref()?
.raw
.get("max_context_window")?
.as_u64()
}
}

/// The editable surface excludes model identity, lookup diagnostics and raw
/// provider fields. Resetting an override is a separate provider operation.
#[derive(Clone, Debug, Default, Deserialize)]
Expand Down Expand Up @@ -817,7 +827,21 @@ impl BundledCatalog {
.collect::<Vec<_>>();
for item in overrides {
if let Some(pos) = models.iter().position(|m| m.model_id == item.model_id) {
models[pos] = inherit_limits(item.clone(), &models[pos])
let base = &models[pos];
let mut model = inherit_limits(item.clone(), base);
if provider.provider_id == "openai-codex"
&& let Some(maximum) = base.codex_context_window_ceiling()
{
model
.metadata
.get_or_insert_default()
.raw
.insert("max_context_window".into(), maximum.into());
if let Some(window) = &mut model.capabilities.context_window {
*window = (*window).min(maximum);
}
}
models[pos] = model;
} else {
models.push(item.clone())
}
Expand Down
29 changes: 28 additions & 1 deletion crates/dim-app-server/src/provider/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@
use super::*;
use crate::model_catalog::FieldUpdate;

pub(super) fn validate_context_window(
requested: u64,
maximum: Option<u64>,
) -> Result<(), ProviderError> {
if let Some(maximum) = maximum
&& requested > maximum
{
return Err(ProviderError::InvalidConfig(format!(
"Context window must be at most {maximum} tokens for this model"
)));
}
Ok(())
}

#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PreferencesPatch {
Expand Down Expand Up @@ -433,10 +447,23 @@ impl ProviderService {
.position(|entry| entry.model_id == model_id);
match edit {
Some(edit) if descriptor => {
let current = static_entries(&bundled, &id, record)
let mut current = static_entries(&bundled, &id, record)
.into_iter()
.find(|entry| entry.model_id == model_id)
.ok_or(ProviderError::NotFound)?;
if record.credential_authority == CredentialAuthority::OpenaiCodex {
if let Some(requested) = edit.context_window {
validate_context_window(
requested.get(),
current.codex_context_window_ceiling(),
)?;
} else if let Some(index) = index {
current.capabilities.context_window = record
.model_config_overrides[index]
.capabilities
.context_window;
}
}
let next = bundled.merge_visible_edit(&current, edit);
if let Some(user) = user {
record.user_models[user] = next;
Expand Down
7 changes: 7 additions & 0 deletions crates/dim-app-server/src/provider/startup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,13 @@ impl ProviderService {
.as_mut()
.expect("Provider adopts capabilities");
if let Some(limit) = input.context_window {
if model.provider_id == "openai-codex" {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This now rejects a DIM_MAX_CONTEXT_TOKENS value above the model ceiling, but the startup contract still promises the opposite. docs/design/model-startup.md:30 accepts any positive safe integer and says it may exceed what the server supports, and crates/dim-cli/src/args.rs:264-265 advertises values up to 9007199254740991. A user who sets 900000 for gpt-6.2-sol now fails before the Session exists. Update the startup owner document and the startup help text to state the per-model ceiling and the failure, or move the ceiling statement there and link to the Provider page.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d491746. docs/design/model-startup.md:30 now states the per-model codex ceiling and the failure before Session creation or resume reconfiguration, and crates/dim-cli/src/args.rs:266 states the same failure in the startup help.

let maximum = self
.bundled
.model(&model.provider_id, &model.model_id)
.and_then(|entry| entry.codex_context_window_ceiling());
super::models::validate_context_window(limit, maximum).map_err(failure)?;
}
snapshot.capabilities.context_window = limit;
}
if let Some(limit) = input.max_output_tokens {
Expand Down
175 changes: 174 additions & 1 deletion crates/dim-app-server/tests/managed_oauth_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use dim_app_server::{
OpenAICodexOAuthService,
},
grok_oauth::{GrokOAuthPlugin, GrokOAuthService},
provider::{ModelPreferences, ProviderPlugin, ProviderService},
provider::{ModelPreferences, ProviderCatalog, ProviderError, ProviderPlugin, ProviderService},
};
use futures_util::StreamExt;
use rutis::Ctx;
Expand Down Expand Up @@ -1443,6 +1443,118 @@ async fn managed_provider_selection_http_recovery_and_restart_flow() {
.await
.unwrap();
assert!(updated.info.connection.unwrap().credential_configured);
let window = |catalog: &ProviderCatalog, id| {
let model = catalog.models.iter().find(|model| model.id == id).unwrap();
(
model.capabilities.context_window,
model.metadata.as_ref().unwrap().raw["max_context_window"].as_u64(),
)
};
let catalog = provider
.catalog_for("openai-codex".into(), &cancel)
.await
.unwrap()
.unwrap();
for model in &catalog.models {
let raw = &model.metadata.as_ref().unwrap().raw;
if raw.get("type").and_then(Value::as_str) != Some("chat") {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The loop skips every row whose metadata.raw.type is not exactly chat and asserts no count or full id set. A row that loses type is still treated as conversational, because chat_only_unavailable excludes a model only when the kind is present and differs from chat (crates/dim-app-server/src/provider.rs:1136-1142). If that row also lacks max_context_window, codex_context_window_ceiling returns None (crates/dim-app-server/src/model_catalog.rs:76-83), so edits and DIM_MAX_CONTEXT_TOKENS above the intended ceiling are accepted for a model that remains selectable, while this test still passes. Assert the expected 14 chat rows or list their ids so a lost type fails here instead of shrinking coverage.

continue;
}
assert!(
matches!(
(
model.capabilities.context_window,
raw.get("max_context_window").and_then(Value::as_u64)
),
(Some(default), Some(ceiling)) if default > 0 && ceiling >= default
),
"{} must declare a positive default and a ceiling at least as large",
model.id
);
}
for model_id in ["gpt-6.2-sol", "gpt-6.1-sol", "gpt-6.1-terra"] {
assert_eq!(window(&catalog, model_id), (Some(500_000), Some(872_000)));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This covers three of the fourteen Codex chat rows. Nothing asserts max_context_window on the other ten, and codex_context_window_ceiling returns None when the field is absent or misspelled (crates/dim-app-server/src/model_catalog.rs:75-83), which silently removes both the edit and startup checks for that model. Add a catalog check or test that every openai-codex chat row declares a positive ceiling no smaller than its default window.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d491746. The new loop at crates/dim-app-server/tests/managed_oauth_flow.rs:1458-1474 requires a positive max_context_window at least as large as the default on every row whose raw type is chat, so a missing field now fails instead of being skipped.

}
assert_eq!(window(&catalog, "gpt-5.5"), (Some(272_000), Some(272_000)));
let target = ModelId {
provider_id: "openai-codex".into(),
model_id: "gpt-6.2-sol".into(),
};
let edit_window = |version, tokens| {
provider.update_model_config(
target.provider_id.clone(),
version,
target.model_id.clone(),
Some(serde_json::from_value(json!({"contextWindow": tokens})).unwrap()),
&cancel,
)
};
assert!(matches!(
edit_window(catalog.version, 872_001_u64).await,
Err(ProviderError::InvalidConfig(message)) if message.contains("872000")
));
let edited = edit_window(catalog.version, 872_000_u64).await.unwrap();
assert_eq!(
window(&edited, "gpt-6.2-sol"),
(Some(872_000), Some(872_000))
);
let selection = provider
.configuration(
Some(target.clone()),
None,
ModelPreferences::default(),
&cancel,
)
.await
.unwrap();
assert_eq!(
selection
.capability_snapshot
.unwrap()
.capabilities
.context_window,
872_000
);
let startup = |tokens| {
provider.startup_configuration(
dim_app_server::protocol::ModelSelection {
provider: Some(target.provider_id.clone()),
model_id: Some(target.model_id.clone()),
},
&home,
ModelPreferences::default(),
serde_json::from_value(json!({"contextWindow": tokens, "autoCompactWindow": 400_000}))
.unwrap(),
None,
&cancel,
)
};
assert!(
matches!(startup(872_001_u64).await, Err(error) if error.to_string().contains("872000"))
);
let startup = startup(600_000_u64).await.unwrap();
assert_eq!(
startup
.model
.capability_snapshot
.as_ref()
.unwrap()
.capabilities
.context_window,
600_000
);
assert_eq!(
startup
.model
.metadata
.as_ref()
.unwrap()
.startup
.as_ref()
.unwrap()
.auto_compact_window,
Some(400_000)
);
let old_request = {
let selection = provider
.configuration(
Expand Down Expand Up @@ -1487,6 +1599,16 @@ async fn managed_provider_selection_http_recovery_and_restart_flow() {
assert_eq!(record["credentialAuthority"], "openai_codex");
assert!(record["credential"].is_null());
assert!(!record.to_string().contains("rotated-"));
let legacy_window = 900_000_i64;
assert_eq!(
db.execute(
"UPDATE provider_models SET entry=json_set(entry, '$.capabilities.contextWindow', ?1) \
WHERE provider_id='openai-codex' AND model_id='gpt-6.2-sol' AND source='override'",
[legacy_window],
)
.unwrap(),
1
);
drop(db);
let (restarted, _, _, _) = self::codex(&home, &f.base).await;
let plugins = [
Expand Down Expand Up @@ -1521,6 +1643,57 @@ async fn managed_provider_selection_http_recovery_and_restart_flow() {
.await
.unwrap()
.unwrap();
assert_eq!(
window(&catalog, "gpt-6.2-sol"),
(Some(872_000), Some(872_000))
);
let renamed = provider
.update_model_config(
target.provider_id.clone(),
catalog.version,
target.model_id.clone(),
Some(serde_json::from_value(json!({"displayName": "Renamed Sol"})).unwrap()),
&cancel,
)
.await
.unwrap();
assert_eq!(
renamed
.models
.iter()
.find(|model| model.id == target.model_id)
.unwrap()
.name,
"Renamed Sol"
);
assert_eq!(
window(&renamed, "gpt-6.2-sol"),
(Some(872_000), Some(872_000))
);
let stored_window: i64 = rusqlite::Connection::open(home.join("native.sqlite"))
.unwrap()
.query_row(
"SELECT json_extract(entry, '$.capabilities.contextWindow') FROM provider_models \
WHERE provider_id='openai-codex' AND model_id='gpt-6.2-sol' AND source='override'",
[],
|row| row.get(0),
)
.unwrap();
assert_eq!(stored_window, legacy_window);
let reset = provider
.update_model_config(
target.provider_id,
renamed.version,
target.model_id,
None,
&cancel,
)
.await
.unwrap();
assert_eq!(
window(&reset, "gpt-6.2-sol"),
(Some(500_000), Some(872_000))
);
assert_eq!(
catalog
.models
Expand Down
1 change: 1 addition & 0 deletions crates/dim-cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,7 @@ Model startup:
and it wins over the `provider` setting of the same thing.
DIM_MAX_CONTEXT_TOKENS and DIM_MAX_OUTPUT_TOKENS declare positive capacities
up to 9007199254740991; the request output allowance is derived from them.
For openai-codex, a context window above the model's ceiling fails startup.
--autocompact overrides DIM_AUTO_COMPACT_WINDOW: auto or a positive count,
optionally suffixed k/m (1000/1000000). This is not the model capacity.
Effort, autocompact and capacity startup controls require the product Provider
Expand Down
16 changes: 16 additions & 0 deletions docs/design/appserver/provider-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,22 @@ already records:
| Bundled catalog | `metadataSource` naming the matched bundled provider: an entry declares a limit only where its `metadata.raw` does, and the bundle drops every other limit when it is loaded; that provider's `contextWindowOverride` and `contextWindowFallback` metadata stay declarations | The models the lookup matches, or every model of the provider |
| User | The same `capabilityOverrideFields` field on the descriptor override or user model: `models.edit` writes it for each limit it edits, and either legacy importer for an imported value it keeps | The model the override names |

The bundled `openai-codex` chat rows declare a default `contextWindow` and a
read-only `metadata.raw.max_context_window` for user configuration. These are the
nominal token counts from the
[Codex catalog](https://github.com/openai/codex/blob/8653ca9e99b2c805107bde7b7d6f57a634c643d0/codex-rs/models-manager/models.json),
its [older catalog](https://github.com/openai/codex/blob/rust-v0.145.0/codex-rs/models-manager/models.json)
for GPT-5.4 and GPT-5.4 Mini, and the
[published Spark window](https://openai.com/index/introducing-gpt-5-3-codex-spark/).
Dim uses its own input and compaction budgets. For example, GPT-6.2 Sol,
GPT-6.1 Sol and GPT-6.1 Terra default to 500,000 tokens and allow up to 872,000.
Edit `contextWindow` with `dimcode models openai-codex edit gpt-6.2-sol` or
`provider.models.edit`. Reset restores the bundled default. Source adoption
preserves explicit overrides and caps their effective value at the model's
current ceiling. New edits above the ceiling return `provider_invalid_config`.
The [Session startup override](../model-startup.md) is subject to the same
ceiling when setting a new value.

A listing declares a model's reasoning efforts the same way, and the first shape
it states is the model's own list: the `values` of its `reasoning_options` entry
of type `effort`, else the `effort` of each `supported_reasoning_levels` item,
Expand Down
2 changes: 1 addition & 1 deletion docs/design/model-startup.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ contracts; this document does not introduce a second model backend.
| `DIM_API_KEY` | Key sent through the selected protocol's existing default authentication mapping. |
| `DIM_AUTH_TOKEN` | Bearer authentication, independent of the message format. |
| `DIM_CUSTOM_HEADERS` | Additional headers, one `Name: Value` per line. Parse names case-insensitively; reject invalid or repeated names and conflicting generated authentication headers. Split a line at its first colon only. |
| `DIM_MAX_CONTEXT_TOKENS` | Positive safe integer declaring the adopted context capacity, not a promise that the server supports a larger window. |
| `DIM_MAX_CONTEXT_TOKENS` | Positive safe integer declaring the adopted context capacity. For `openai-codex` models with a [declared ceiling](appserver/provider-management.md#35-declared-model-limits), a larger value fails before Session creation or resume reconfiguration. |
| `DIM_MAX_OUTPUT_TOKENS` | Positive safe integer declaring output capacity where the catalog does not declare it. It is a declared fact, so it may equal or exceed the adopted context capacity; the request output allowance is derived from the final declared pair (see [ContextCompaction §5.1](plugins/ContextCompaction.md#51-productcontextmodel)) and always leaves at least half the window as input budget. |
| `--autocompact auto\|TOKENS` / `DIM_AUTO_COMPACT_WINDOW` | Separate compaction window, not model capacity. The explicit flag wins. Accept positive token counts with optional `k`/`m` suffixes; `auto` uses the existing model-derived threshold. Do not impose Claude's vendor-specific 100K minimum or 1M maximum on Dim models. Reserve the existing output allowance. |

Expand Down
13 changes: 13 additions & 0 deletions docs/zh/design/appserver/provider-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,19 @@ Rpc 沿用 service_reloading/service_unavailable 和准入;调用由 owner 追
| 捆绑目录 | `metadataSource` 指向匹配的捆绑 Provider:条目仅在其 `metadata.raw` 声明处才有上限,其余取值在捆绑加载时删除;该 Provider 的 `contextWindowOverride`、`contextWindowFallback` 元数据仍是声明 | 匹配到的模型,或该 Provider 的全部模型 |
| 用户 | 同一 `capabilityOverrideFields` 字段,写在描述覆盖或用户模型上:`models.edit` 为它编辑的每项上限写入,两个旧版导入器为导入时保留的每项值写入 | 覆盖所指的模型 |

内置 `openai-codex` 对话模型按条目声明默认 `contextWindow` 和只读的配置上限
`metadata.raw.max_context_window`。数值采用
[Codex 目录](https://github.com/openai/codex/blob/8653ca9e99b2c805107bde7b7d6f57a634c643d0/codex-rs/models-manager/models.json)
的标称 token 数,GPT-5.4 和 GPT-5.4 Mini 采用
[旧版目录](https://github.com/openai/codex/blob/rust-v0.145.0/codex-rs/models-manager/models.json),
Spark 采用[公开窗口](https://openai.com/index/introducing-gpt-5-3-codex-spark/)。
Dim 根据自己的规则计算输入与压缩预算。例如,GPT-6.2 Sol、GPT-6.1 Sol 和
GPT-6.1 Terra 默认都是 500,000 token,可配置到 872,000。可用
`dimcode models openai-codex edit gpt-6.2-sol` 或 `provider.models.edit`
修改 `contextWindow`,重置后恢复目录默认值。接纳新版目录时保留显式覆盖,其生效值
受当前模型上限约束。新写入的值超出上限会收到 `provider_invalid_config`。
[会话启动覆盖](../../../design/model-startup.md)设置新值时遵守同一上限。

清单以同样的方式声明模型的推理档位,且它声明的第一个形状就是模型自己的列表:先取
`reasoning_options` 中 `type` 为 `effort` 那一项的 `values`,否则取各项
`supported_reasoning_levels` 的 `effort`,最后才是扁平的 `reasoning_levels` 列表。
Expand Down