You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/25 05:27:38 UTC
(maka) branch feat/runtime-host-rust updated (6a81910587 -> 2d3231c18d)
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a change to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
from 6a81910587 Merge branch 'feat/runtime-host-rust' of https://github.com/apache/maka into feat/runtime-host-rust
new 33b9fde599 fix(rust): harden catalog decoding and stream ownership
new 2d3231c18d feat(runtime): derive automatic compaction thresholds from model limits
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
crates/acp/src/content.rs | 15 +--
crates/agent/src/auto_context.rs | 17 ++-
crates/agent/tests/integration/auto_context.rs | 8 +-
crates/agent/tests/integration/context_overflow.rs | 2 +-
crates/agent/tests/integration/dynamic_tools.rs | 2 +-
.../agent/tests/integration/handoff_compaction.rs | 2 +-
crates/agent/tests/integration/pruning.rs | 2 +-
crates/cli/src/args.rs | 8 --
crates/cli/tests/integration/tui.rs | 4 +
crates/cli/tests/integration/tui/projects.rs | 14 +-
crates/config/src/model_catalog.rs | 3 +-
crates/config/src/model_catalog/entry.rs | 85 +-----------
crates/config/src/projection.rs | 4 +-
crates/config/tests/catalog_projection.rs | 2 +-
crates/external-agent/src/driver/v2.rs | 19 ---
crates/external-agent/src/plugin/terminal.rs | 2 +-
crates/external-agent/src/setup.rs | 21 +--
crates/protocol/src/configuration_pages.rs | 141 ++------------------
crates/protocol/tests/configuration_pages.rs | 44 ++++++-
.../runtime-host/src/execution/provider/context.rs | 60 ++++++++-
crates/runtime-host/tests/external_agents.rs | 20 ++-
.../runtime-host/tests/integration/auto_context.rs | 5 +-
.../tests/integration/client_write/workflow.rs | 3 +-
.../tests/integration/large_outputs/workflow.rs | 13 +-
crates/runtime/src/configuration.rs | 2 +
crates/runtime/src/configuration/model_catalog.rs | 142 +++++++++++++++++++++
crates/runtime/src/configuration/model_info.rs | 3 +
crates/runtime/src/configuration/model_override.rs | 5 +
crates/runtime/src/configuration/validation.rs | 73 +++++------
crates/runtime/src/context.rs | 7 +-
crates/tui/src/pages/chat/render.rs | 2 +-
.../pages/manage/enabled_models/profile/view.rs | 4 +-
crates/tui/src/theme.rs | 7 +-
crates/tui/src/view.rs | 8 +-
crates/tui/src/view/form.rs | 4 +-
crates/tui/src/view/session.rs | 6 +-
crates/tui/src/view/tone.rs | 36 +-----
docs/rust-runtime.md | 65 +++++++++-
docs/rust-runtime.zh-CN.md | 52 +++++++-
tests/fixtures/client-auto-context-fixture.mjs | 2 +-
tests/fixtures/client-auto-context-workflow.mjs | 6 +-
41 files changed, 507 insertions(+), 413 deletions(-)
create mode 100644 crates/runtime/src/configuration/model_catalog.rs
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 01/02: fix(rust): harden catalog decoding and stream ownership
Posted by wy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
commit 33b9fde5995b48640c35ebc70402705b1f35beee
Author: Wang <m4...@gmail.com>
AuthorDate: Fri Sep 25 13:25:33 2026 +0800
fix(rust): harden catalog decoding and stream ownership
Share typed catalog validation so supported model overrides survive decoding. Isolate nested setup cancellation and require confirmed cleanup. Remove redundant tests and color forwarding wrappers, and fix fixture readiness and notification consumption.
Generated-by: Codex
---
crates/acp/src/content.rs | 15 +--
crates/cli/src/args.rs | 8 --
crates/cli/tests/integration/tui.rs | 4 +
crates/cli/tests/integration/tui/projects.rs | 14 +-
crates/config/src/model_catalog.rs | 3 +-
crates/config/src/model_catalog/entry.rs | 85 +-----------
crates/config/src/projection.rs | 4 +-
crates/config/tests/catalog_projection.rs | 2 +-
crates/external-agent/src/driver/v2.rs | 19 ---
crates/external-agent/src/plugin/terminal.rs | 2 +-
crates/external-agent/src/setup.rs | 21 +--
crates/protocol/src/configuration_pages.rs | 141 ++------------------
crates/protocol/tests/configuration_pages.rs | 44 ++++++-
crates/runtime-host/tests/external_agents.rs | 20 ++-
.../tests/integration/client_write/workflow.rs | 3 +-
.../tests/integration/large_outputs/workflow.rs | 13 +-
crates/runtime/src/configuration.rs | 2 +
crates/runtime/src/configuration/model_catalog.rs | 142 +++++++++++++++++++++
crates/runtime/src/configuration/validation.rs | 73 +++++------
crates/tui/src/pages/chat/render.rs | 2 +-
.../pages/manage/enabled_models/profile/view.rs | 4 +-
crates/tui/src/theme.rs | 7 +-
crates/tui/src/view.rs | 8 +-
crates/tui/src/view/form.rs | 4 +-
crates/tui/src/view/session.rs | 6 +-
crates/tui/src/view/tone.rs | 36 +-----
26 files changed, 302 insertions(+), 380 deletions(-)
diff --git a/crates/acp/src/content.rs b/crates/acp/src/content.rs
index db5d5b7e0d..466c8b6aa1 100644
--- a/crates/acp/src/content.rs
+++ b/crates/acp/src/content.rs
@@ -246,11 +246,15 @@ mod tests {
serde_json::from_value(value).unwrap()
}
#[test]
- fn text_and_remote_links_are_explicit_context() {
- let (content, files) = validate(vec!["hello".into(), block(serde_json::json!({"type":"resource_link", "uri":"https://example.com/doc", "name":"guide"}))]).unwrap();
+ fn text_links_and_embedded_resources_preserve_explicit_context() {
+ let (content, files) = validate(vec![
+ "hello".into(),
+ block(serde_json::json!({"type":"resource_link", "uri":"https://example.com/doc", "name":"guide"})),
+ block(serde_json::json!({"type":"resource", "resource":{"uri":"memory://context", "text":"actual content"}})),
+ ]).unwrap();
assert_eq!(
content.text,
- "hello\n\nResource: guide\nhttps://example.com/doc"
+ "hello\n\nResource: guide\nhttps://example.com/doc\n\nResource: memory://context\nactual content"
);
assert!(files.is_empty());
}
@@ -269,9 +273,4 @@ mod tests {
assert!(validate(vec![link; 9]).is_err());
assert!(validate(vec![block(serde_json::json!({"type":"resource_link", "uri":"file:///tmp/a?query", "name":"file"}))]).is_err());
}
- #[test]
- fn embedded_text_keeps_uri_and_content() {
- let (content, _) = validate(vec![block(serde_json::json!({"type":"resource", "resource":{"uri":"memory://context", "text":"actual content"}}))]).unwrap();
- assert!(content.text.contains("memory://context\nactual content"));
- }
}
diff --git a/crates/cli/src/args.rs b/crates/cli/src/args.rs
index bd692e12d3..49235444d7 100644
--- a/crates/cli/src/args.rs
+++ b/crates/cli/src/args.rs
@@ -366,12 +366,4 @@ mod tests {
Some(Command::Tui(Tui {profile: Some(profile), ..})) if profile == "second")
);
}
-
- #[test]
- fn help_keeps_tui_and_existing_commands_discoverable() {
- let help = Cli::command().render_long_help().to_string();
- for command in ["tui", "host", "code", "inspect", "sandbox"] {
- assert!(help.contains(command));
- }
- }
}
diff --git a/crates/cli/tests/integration/tui.rs b/crates/cli/tests/integration/tui.rs
index 27d4f81bee..42cc5055dd 100644
--- a/crates/cli/tests/integration/tui.rs
+++ b/crates/cli/tests/integration/tui.rs
@@ -331,6 +331,10 @@ fn real_host_catalog_subscription_and_remote_updates_reach_clients() {
Some(directory.path()),
);
tui.wait_for(&first[0].name);
+ // Plugin pages pin below the list and change its viewport when they arrive.
+ for page in ["WorkHub", "Scheduled tasks", "Recall"] {
+ tui.wait_for(page);
+ }
// The sidebar keeps loading older sessions at the end of its list.
tui.wheel_at(&first[0].name, true, 12);
tui.wait_for("Load more…");
diff --git a/crates/cli/tests/integration/tui/projects.rs b/crates/cli/tests/integration/tui/projects.rs
index 3413bdada2..5ae118bfde 100644
--- a/crates/cli/tests/integration/tui/projects.rs
+++ b/crates/cli/tests/integration/tui/projects.rs
@@ -143,7 +143,6 @@ fn project_catalog_notifications_and_creation_use_host_project_identity() {
tui.wait_until(|text| text.contains("Renamed project") && !text.contains("Archived"));
tui.click_text("ⓘ");
tui.wait_for("Preferred Host directory");
- tui.wait_for(project_path.to_str().unwrap());
runtime
.block_on(client.request(
Operation::ProjectCatalogMutate,
@@ -151,9 +150,7 @@ fn project_catalog_notifications_and_creation_use_host_project_identity() {
))
.unwrap();
tui.wait_until(|text| {
- text.contains("Observed project")
- && text.contains("Preferred Host directory")
- && text.contains(project_path.to_str().unwrap())
+ text.contains("Observed project") && text.contains("Preferred Host directory")
});
runtime
.block_on(client.request(
@@ -357,15 +354,6 @@ fn project_catalog_notifications_and_creation_use_host_project_identity() {
tui.click_text("Project locations");
tui.wait_for("Preferred Host directory");
// The location dialog wraps long paths; canonical identity is checked above.
- tui.wait_for(
- browse_target
- .parent()
- .unwrap()
- .canonicalize()
- .unwrap()
- .to_str()
- .unwrap(),
- );
tui.wait_for("目标");
tui.send(b"\x1b");
tui.wait_until(|text| !text.contains("Preferred Host directory") && text.contains("TUI 项目"));
diff --git a/crates/config/src/model_catalog.rs b/crates/config/src/model_catalog.rs
index f80496f719..c7f47237ee 100644
--- a/crates/config/src/model_catalog.rs
+++ b/crates/config/src/model_catalog.rs
@@ -20,9 +20,8 @@
use crate::Result;
mod entry;
mod limits;
-pub use entry::ModelCatalogEntry;
pub(crate) use limits::validate_overrides;
-use maka_runtime::configuration::{ConnectionCatalogEntry, ModelInfo};
+use maka_runtime::configuration::{ConnectionCatalogEntry, ModelCatalogEntry, ModelInfo};
use std::collections::HashSet;
/// Project persisted provider facts and explicit user declarations without resolving plugins.
diff --git a/crates/config/src/model_catalog/entry.rs b/crates/config/src/model_catalog/entry.rs
index 6869ab60eb..516f5cf35e 100644
--- a/crates/config/src/model_catalog/entry.rs
+++ b/crates/config/src/model_catalog/entry.rs
@@ -18,90 +18,9 @@
*/
use super::wire_limit;
-use crate::{ConfigError, Result};
-use maka_runtime::{
- configuration::{ConnectionCatalogEntry, ModelInfo, ModelModality, validation},
- execution::ThinkingLevel,
+use maka_runtime::configuration::{
+ ConnectionCatalogEntry, ModelCatalogEntry, ModelInfo, ModelModality,
};
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase", deny_unknown_fields)]
-pub struct ModelCatalogEntry {
- /// Effective facts for execution; the catalog's metadata remains the wire authority.
- #[serde(skip)]
- pub capabilities: maka_runtime::configuration::ModelCapabilities,
- pub id: String,
- pub can_use_as_chat_default: bool,
- pub is_default: bool,
- pub supports_vision: bool,
- pub thinking_levels: Vec<ThinkingLevel>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub default_thinking_level: Option<ThinkingLevel>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub default_supports_vision: Option<bool>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub default_context_window: Option<u64>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub default_input_limit: Option<u64>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub input_limit: Option<u64>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub compaction_threshold: Option<u64>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub display_name: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub description: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub context_window: Option<u64>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub knowledge_cutoff: Option<String>,
-}
-
-impl ModelCatalogEntry {
- pub fn new(id: impl Into<String>) -> Self {
- Self {
- id: id.into(),
- can_use_as_chat_default: true,
- ..Self::default()
- }
- }
-
- pub(crate) fn validate(&self) -> Result<()> {
- validation::text(&self.id, 512, true).map_err(ConfigError::Invalid)?;
- for (value, max) in [
- (self.display_name.as_deref(), 512),
- (self.description.as_deref(), 2048),
- (self.knowledge_cutoff.as_deref(), 2048),
- ] {
- if let Some(value) = value {
- validation::text(value, max, false).map_err(ConfigError::Invalid)?;
- }
- }
- for value in [self.context_window, self.input_limit]
- .into_iter()
- .flatten()
- {
- validation::revision(value, true).map_err(ConfigError::Invalid)?;
- }
- for (index, level) in self.thinking_levels.iter().enumerate() {
- if self.thinking_levels[..index].contains(level) {
- return Err(ConfigError::Invalid(
- "duplicate catalog thinking level".into(),
- ));
- }
- }
- if self
- .default_thinking_level
- .is_some_and(|level| !self.thinking_levels.contains(&level))
- {
- return Err(ConfigError::Invalid(
- "unsupported default thinking level".into(),
- ));
- }
- Ok(())
- }
-}
pub(super) fn resolve(
row: &ConnectionCatalogEntry,
diff --git a/crates/config/src/projection.rs b/crates/config/src/projection.rs
index 690b9c7008..cbe6b3d036 100644
--- a/crates/config/src/projection.rs
+++ b/crates/config/src/projection.rs
@@ -20,8 +20,6 @@ use crate::{ConfigError, Result};
use maka_runtime::configuration::*;
use serde_json::{Value, json};
-pub use crate::model_catalog::ModelCatalogEntry;
-
/// Produces a 128-item / 128 KiB wire page; the cursor identifies
/// the next item, and only belongs to the revision that produced it.
pub fn project(
@@ -47,7 +45,7 @@ pub fn project(
.map(|target| target.model_id.as_str());
let entries = resolve(row, default)?;
for entry in &entries {
- entry.validate()?;
+ entry.validate().map_err(ConfigError::Invalid)?;
}
let mut header = json!({"kind":"connection", "connectionIndex":connection_index,
"connectionId":row.connection_id,"revision":row.revision,"slug":row.slug,
diff --git a/crates/config/tests/catalog_projection.rs b/crates/config/tests/catalog_projection.rs
index 56b6a32017..107a520f63 100644
--- a/crates/config/tests/catalog_projection.rs
+++ b/crates/config/tests/catalog_projection.rs
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
-use maka_config::{Result, model_catalog::ModelCatalogEntry, projection::project};
+use maka_config::{Result, projection::project};
use maka_runtime::configuration::*;
use maka_runtime::execution::ThinkingLevel;
use serde_json::json;
diff --git a/crates/external-agent/src/driver/v2.rs b/crates/external-agent/src/driver/v2.rs
index 90ce9f06b1..98eefbfc61 100644
--- a/crates/external-agent/src/driver/v2.rs
+++ b/crates/external-agent/src/driver/v2.rs
@@ -257,22 +257,3 @@ impl Driver<'_> {
Ok(())
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- #[test]
- fn config_values_use_v2_discriminated_config_id_wire_shape() {
- let input = acp::SetSessionConfigOptionRequest::new(
- "s",
- "model",
- acp::SessionConfigOptionValue::Id {
- value: "choice".into(),
- },
- );
- let value = serde_json::to_value(input).unwrap();
- assert_eq!(value["configId"], "model");
- assert_eq!(value["type"], "id");
- assert_eq!(value["value"], "choice");
- }
-}
diff --git a/crates/external-agent/src/plugin/terminal.rs b/crates/external-agent/src/plugin/terminal.rs
index 137c26a683..ae414c0dba 100644
--- a/crates/external-agent/src/plugin/terminal.rs
+++ b/crates/external-agent/src/plugin/terminal.rs
@@ -122,7 +122,7 @@ impl Agents {
})
.await;
stream.cancel();
- let _ = stream.close().await;
+ stream.close().await?;
answer.map_err(|_| Error::Provider("The agent did not answer in time".into()))?
}
}
diff --git a/crates/external-agent/src/setup.rs b/crates/external-agent/src/setup.rs
index 38146bcde4..cae125bd26 100644
--- a/crates/external-agent/src/setup.rs
+++ b/crates/external-agent/src/setup.rs
@@ -93,8 +93,10 @@ impl remote::StreamProvider for Provider {
{
return Err(Error::Invalid("Invalid authentication method".into()));
}
- // Views captured this same request token; cancel also withdraws pending consent.
- let cancellation = caller.cancellation.clone();
+ // This stream owns only its work. The authorized scope below settles
+ // pending consent/processes; closing a nested stream must not cancel
+ // the Remote method that is consuming its result.
+ let cancellation = caller.cancellation.child_token();
let worker_cancel = cancellation.clone();
let (send, receive) = mpsc::channel(8);
let done = context
@@ -345,18 +347,3 @@ async fn emit(send: &mpsc::Sender<Result<Value, Error>>, event: Value) -> Result
fn provider(error: impl std::fmt::Display) -> Error {
Error::Provider(error.to_string())
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn setup_actions_require_explicit_authentication_method() {
- let mut input = json!({"agentId":"agent", "operationId":Uuid::nil(), "kind":"check"});
- assert!(serde_json::from_value::<Input>(input.clone()).is_ok());
- input["kind"] = json!("authenticate");
- assert!(serde_json::from_value::<Input>(input.clone()).is_err());
- input["methodId"] = json!("offered-method");
- assert!(serde_json::from_value::<Input>(input).is_ok());
- }
-}
diff --git a/crates/protocol/src/configuration_pages.rs b/crates/protocol/src/configuration_pages.rs
index 3d240c54a1..a89c8659c4 100644
--- a/crates/protocol/src/configuration_pages.rs
+++ b/crates/protocol/src/configuration_pages.rs
@@ -16,11 +16,12 @@
* specific language governing permissions and limitations
* under the License.
*/
-//! Epoch 141 catalog output boundary, independent of the catalog producer.
+//! Catalog output boundary using the shared public configuration types.
use crate::codec::{count, exact, record, shaped, string};
use crate::{ProtocolError, Result};
-use maka_runtime::configuration::{ConnectionCatalogEntry, ConnectionTarget, validation as v};
-use maka_runtime::execution::ThinkingLevel;
+use maka_runtime::configuration::{
+ ConnectionCatalogEntry, ConnectionTarget, ModelCatalogEntry, ModelOverride, validation as v,
+};
use serde_json::{Value, json};
// Stored inventory + independent overrides + enabled IDs + fallback + default.
@@ -133,7 +134,6 @@ pub fn decode_catalog_query_result(value: &Value) -> Result<Value> {
fn decode_item(value: &Value) -> Result<Value> {
let o = record(value, "catalog item")?;
- let mut output = value.clone();
match value["kind"].as_str().unwrap_or("") {
"connection" => return header(value),
"enabled_model_id" => {
@@ -150,137 +150,18 @@ fn decode_item(value: &Value) -> Result<Value> {
&["kind", "connectionIndex", "itemIndex", "entry"],
&["modelOverride"],
)?;
- model_entry(&value["entry"])?;
+ let entry: ModelCatalogEntry =
+ serde_json::from_value(value["entry"].clone()).map_err(|_| invalid())?;
+ domain(entry.validate())?;
if let Some(profile) = o.get("modelOverride") {
- output["modelOverride"] = model_override(profile)?;
+ let profile: ModelOverride =
+ serde_json::from_value(profile.clone()).map_err(|_| invalid())?;
+ domain(v::model_override(&entry.id, &profile))?;
}
}
_ => return Err(invalid()),
}
- Ok(output)
-}
-
-fn model_entry(value: &Value) -> Result<()> {
- let o = record(value, "model catalog entry")?;
- shaped(
- o,
- &[
- "id",
- "canUseAsChatDefault",
- "isDefault",
- "supportsVision",
- "thinkingLevels",
- ],
- &[
- "displayName",
- "description",
- "contextWindow",
- "inputLimit",
- "compactionThreshold",
- "defaultContextWindow",
- "defaultInputLimit",
- "defaultSupportsVision",
- "knowledgeCutoff",
- ],
- )?;
- let mut shared = json!({"id":value["id"]});
- for field in [
- "displayName",
- "description",
- "contextWindow",
- "inputLimit",
- "knowledgeCutoff",
- ] {
- if let Some(v) = o.get(field) {
- shared[field] = v.clone();
- }
- }
- domain(v::connection_model(&shared))?;
- for field in ["canUseAsChatDefault", "isDefault", "supportsVision"] {
- if !value[field].is_boolean() {
- return Err(invalid());
- }
- }
- if o.get("defaultSupportsVision")
- .is_some_and(|v| !v.is_boolean())
- {
- return Err(invalid());
- }
- for field in [
- "compactionThreshold",
- "defaultContextWindow",
- "defaultInputLimit",
- ] {
- if let Some(value) = o.get(field)
- && count(value, field)? == 0
- {
- return Err(invalid());
- }
- }
- let levels = value["thinkingLevels"].as_array().ok_or_else(invalid)?;
- let mut seen = std::collections::BTreeSet::new();
- for level in levels {
- let level = level.as_str().ok_or_else(invalid)?;
- if serde_json::from_value::<ThinkingLevel>(json!(level)).is_err() || !seen.insert(level) {
- return Err(invalid());
- }
- }
- Ok(())
-}
-
-fn model_override(value: &Value) -> Result<Value> {
- record(value, "model override")?;
- let mut result = json!({});
- if let Some(levels) = value["thinkingLevels"].as_array() {
- let selected: Vec<ThinkingLevel> = levels
- .iter()
- .filter_map(|level| serde_json::from_value(level.clone()).ok())
- .collect();
- let levels: Vec<_> = ThinkingLevel::ALL
- .into_iter()
- .filter(|level| selected.contains(level))
- .collect();
- if !levels.is_empty() {
- result["thinkingLevels"] = json!(levels);
- }
- }
- for field in ["vision", "codeMode", "applyPatch"] {
- if value[field].is_boolean() {
- result[field] = value[field].clone();
- }
- }
- for field in [
- "contextWindow",
- "inputLimit",
- "compactionThreshold",
- "maxOutputTokens",
- ] {
- if let Ok(n) = count(&value[field], field)
- && n > 0
- {
- result[field] = json!(n);
- }
- }
- for field in ["displayName", "description", "knowledgeCutoff"] {
- if value[field].is_string() {
- result[field] = value[field].clone();
- }
- }
- for field in ["capabilities", "modalities"] {
- if value[field].is_object() {
- result[field] = value[field].clone();
- }
- }
- if matches!(
- value["apiProtocol"].as_str(),
- Some("openai-chat" | "openai-responses" | "anthropic-messages")
- ) {
- result["apiProtocol"] = value["apiProtocol"].clone();
- }
- if value["serviceTier"] == "fast" {
- result["serviceTier"] = json!("fast");
- }
- Ok(result)
+ Ok(value.clone())
}
fn header(value: &Value) -> Result<Value> {
diff --git a/crates/protocol/tests/configuration_pages.rs b/crates/protocol/tests/configuration_pages.rs
index 019e4bcb82..ef94585b01 100644
--- a/crates/protocol/tests/configuration_pages.rs
+++ b/crates/protocol/tests/configuration_pages.rs
@@ -34,11 +34,11 @@ fn mixed_page() -> Value {
{"kind":"model","connectionIndex":0,"itemIndex":0,
"model":{"id":"model","contextWindow":128000,"capabilities":{"chat":true}}},
{"kind":"catalog_entry","connectionIndex":0,"itemIndex":0,
- "modelOverride":{"thinkingLevels":["low","high"],"vision":false},
+ "modelOverride":{"adapter":"external.responses","defaultThinkingLevel":"high","thinkingLevels":["low","high"],"vision":false},
"entry":{"id":"model","displayName":"Model","description":"A model",
"contextWindow":128000,"knowledgeCutoff":"2025-01","canUseAsChatDefault":true,
"isDefault":false,"supportsVision":false,"thinkingLevels":["off","low","high"],
- "defaultSupportsVision":false}}
+ "defaultSupportsVision":false,"defaultThinkingLevel":"high"}}
]})
}
@@ -127,10 +127,13 @@ fn strict_public_shapes_reject_nulls_private_fields_and_invalid_models() {
json!(["contextWindow"]),
),
("/items/3/entry", "apiProtocol", json!("openai-chat")),
+ ("/items/3/entry", "capabilities", json!({"chat":true})),
("/items/3/entry", "thinkingLevels", json!(["low", "low"])),
("/items/3/entry", "thinkingLevels", json!(["unknown"])),
("/items/3/entry", "thinkingLevels", Value::Null),
("/items/3/entry", "supportsVision", json!(1)),
+ ("/items/3/entry", "defaultThinkingLevel", json!("medium")),
+ ("/items/3/entry", "defaultThinkingLevel", Value::Null),
] {
let mut value = page.clone();
value.pointer_mut(pointer).unwrap()[key] = bad;
@@ -139,6 +142,19 @@ fn strict_public_shapes_reject_nulls_private_fields_and_invalid_models() {
"{pointer}/{key}"
);
}
+ for field in [
+ "contextWindow",
+ "inputLimit",
+ "compactionThreshold",
+ "defaultContextWindow",
+ "defaultInputLimit",
+ ] {
+ for bad in [Value::Null, json!(0), json!(9007199254740992_u64)] {
+ let mut value = page.clone();
+ value["items"][3]["entry"][field] = bad;
+ assert!(decode_catalog_query_result(&value).is_err(), "{field}");
+ }
+ }
}
#[test]
@@ -184,15 +200,13 @@ fn pages_enforce_bounds_and_forward_progress_without_requiring_whole_connections
}
#[test]
-fn model_override_sanitization_matches_source_and_empty_overlay_is_omitted() {
+fn model_overrides_are_preserved_or_rejected_and_empty_overlay_is_omitted() {
let mut page = mixed_page();
- page["items"][3]["modelOverride"] = json!({"thinkingLevels":["high","off","low","low"],
- "vision":null,"contextWindow":-1,"serviceTier":"fast","unknown":true});
page["items"][0]["requestBodyOverlay"] = json!({});
let result = decode_catalog_query_result(&page).unwrap();
assert_eq!(
result["items"][3]["modelOverride"],
- json!({"thinkingLevels":["off","low","high"],"serviceTier":"fast"})
+ page["items"][3]["modelOverride"]
);
assert!(result["items"][0].get("requestBodyOverlay").is_none());
page["items"][3]["modelOverride"] = json!({"thinkingLevels":["off"]});
@@ -205,6 +219,24 @@ fn model_override_sanitization_matches_source_and_empty_overlay_is_omitted() {
decode_catalog_query_result(&page).unwrap()["items"][3]["modelOverride"],
json!({})
);
+ for profile in [
+ json!({"thinkingLevels":["low","low"]}),
+ json!({"thinkingLevels":["unknown"]}),
+ json!({"thinkingLevels":[]}),
+ json!({"vision":null}),
+ json!({"adapter":""}),
+ json!({"adapter":"unsafe\nname"}),
+ json!({"defaultThinkingLevel":"unknown"}),
+ json!({"contextWindow":-1}),
+ json!({"inputLimit":0}),
+ json!({"maxOutputTokens":9007199254740992_u64}),
+ json!({"capabilities":{"chat":"yes"}}),
+ json!({"modalities":{"input":["text"],"output":["unknown"]}}),
+ json!({"unknown":true}),
+ ] {
+ page["items"][3]["modelOverride"] = profile;
+ assert!(decode_catalog_query_result(&page).is_err());
+ }
}
#[test]
diff --git a/crates/runtime-host/tests/external_agents.rs b/crates/runtime-host/tests/external_agents.rs
index 2c38e8691b..e6c5451dad 100644
--- a/crates/runtime-host/tests/external_agents.rs
+++ b/crates/runtime-host/tests/external_agents.rs
@@ -766,11 +766,29 @@ async fn acp_setup_stream_authenticates_filters_urls_and_closes_cancelled_proces
success(running.peer.rpc("plugin.remote", json!({"kind":"close","document":document,"stream":stream})).await);
process_closed(&mut process).await;
}
+ // The terminal action consumes the setup stream inside a live Remote
+ // method. Closing that child must not cancel the containing action.
+ let terminal = json!({"packageId":"acceptance.acp-package","method":"terminal"});
+ let terminal_target = success(running.peer.rpc("plugin.remote",
+ json!({"kind":"bind","binding":terminal})).await)["target"].clone();
+ let view = success(running.peer.rpc("plugin.remote", json!({
+ "kind":"call","binding":terminal,"target":terminal_target,"document":document,
+ "input":{"kind":"read","route":{"agent":"test.acp"},"locale":"en"}
+ })).await)["value"]["view"].clone();
+ let checked = success(running.peer.rpc("plugin.remote", json!({
+ "kind":"call","binding":terminal,"target":terminal_target,"document":document,
+ "input":{"kind":"submit","route":{"agent":"test.acp"},"revision":view["revision"],
+ "action":"check","fields":{},"locale":"en"}
+ })).await)["value"].clone();
+ assert_eq!(checked["kind"], "applied", "{checked}");
+ assert!(checked["route"]["checked"].as_str().is_some_and(|text| !text.is_empty()));
+ let mut process = fixture.process().await;
+ process_closed(&mut process).await;
success(running.peer.rpc("plugin.remote", json!({"kind":"close_document","document":document})).await);
running.close().await;
let records = fixture.records();
let versions = records.iter().filter(|row| row["method"] == "initialize").map(|row| row["params"]["protocolVersion"].clone()).collect::<Vec<_>>();
- assert_eq!(versions, if protocol != 2 { [json!(2), json!(1)].into_iter().cycle().take(8).collect::<Vec<_>>() } else { vec![json!(2); 4] });
+ assert_eq!(versions, if protocol != 2 { [json!(2), json!(1)].into_iter().cycle().take(10).collect::<Vec<_>>() } else { vec![json!(2); 5] });
assert_eq!(records.iter().filter(|row| row["method"] == "spawn").count(), versions.len());
assert_eq!(records.iter().filter(|row| row["method"] == if protocol != 2 { "authenticate" } else { "auth/login" }).count(), 3);
assert!(!records.iter().any(|row| row["method"] == "session/new" || row["method"] == "session/prompt"));
diff --git a/crates/runtime-host/tests/integration/client_write/workflow.rs b/crates/runtime-host/tests/integration/client_write/workflow.rs
index 622f1ddbc3..5b81a62339 100644
--- a/crates/runtime-host/tests/integration/client_write/workflow.rs
+++ b/crates/runtime-host/tests/integration/client_write/workflow.rs
@@ -52,7 +52,8 @@ pub(super) async fn run(fixture: &ClientFixture, reopened: bool) -> (Vec<Value>,
Host::open_with_global_instructions(fixture.owner(), Some(fixture.workspace.join(".maka")))
.await
.unwrap();
- let (peer, hello) = Peer::handshake(host.clone(), "write-identity").await;
+ let (mut peer, hello) = Peer::handshake(host.clone(), "write-identity").await;
+ peer.wait_for_plugins().await;
peer.close().await;
#[cfg(unix)]
let endpoint = fixture.workspace.parent().unwrap().join("h.sock");
diff --git a/crates/runtime-host/tests/integration/large_outputs/workflow.rs b/crates/runtime-host/tests/integration/large_outputs/workflow.rs
index 4f8f7c98eb..589bd91855 100644
--- a/crates/runtime-host/tests/integration/large_outputs/workflow.rs
+++ b/crates/runtime-host/tests/integration/large_outputs/workflow.rs
@@ -130,7 +130,18 @@ pub(super) async fn verify(
.unwrap();
live = Some(open.subscription_id);
}
- let terminal = support::completed(client, &turn).await;
+ // This is an active subscriber. Drain live frames while polling the
+ // Turn so the bounded client queue does not fail as a slow consumer.
+ let terminal = {
+ let completed = support::completed(client, &turn);
+ tokio::pin!(completed);
+ loop {
+ tokio::select! {
+ result = &mut completed => break result,
+ notice = native.notices.recv() => assert!(notice.is_some(), "client disconnected during the Turn"),
+ }
+ }
+ };
if case == "control" {
capacity(client, &session, live.as_deref()).await;
let basis = client
diff --git a/crates/runtime/src/configuration.rs b/crates/runtime/src/configuration.rs
index bc6b1a3caf..4ddf12e99f 100644
--- a/crates/runtime/src/configuration.rs
+++ b/crates/runtime/src/configuration.rs
@@ -24,8 +24,10 @@ pub mod headers;
pub mod onboarding;
pub use catalog_wire::*;
pub use effects::*;
+mod model_catalog;
mod model_info;
mod model_override;
+pub use model_catalog::ModelCatalogEntry;
pub use model_info::{ModelCapabilities, ModelInfo};
mod model_validation;
pub mod policy;
diff --git a/crates/runtime/src/configuration/model_catalog.rs b/crates/runtime/src/configuration/model_catalog.rs
new file mode 100644
index 0000000000..dc3737276d
--- /dev/null
+++ b/crates/runtime/src/configuration/model_catalog.rs
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::{ModelCapabilities, present, validation};
+use crate::execution::ThinkingLevel;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct ModelCatalogEntry {
+ /// Effective facts for execution; the catalog's metadata remains the wire authority.
+ #[serde(skip)]
+ pub capabilities: ModelCapabilities,
+ pub id: String,
+ pub can_use_as_chat_default: bool,
+ pub is_default: bool,
+ pub supports_vision: bool,
+ pub thinking_levels: Vec<ThinkingLevel>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub default_thinking_level: Option<ThinkingLevel>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub default_supports_vision: Option<bool>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub default_context_window: Option<u64>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub default_input_limit: Option<u64>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub input_limit: Option<u64>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub compaction_threshold: Option<u64>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub display_name: Option<String>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub description: Option<String>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub context_window: Option<u64>,
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "present"
+ )]
+ pub knowledge_cutoff: Option<String>,
+}
+
+impl ModelCatalogEntry {
+ pub fn new(id: impl Into<String>) -> Self {
+ Self {
+ id: id.into(),
+ can_use_as_chat_default: true,
+ ..Self::default()
+ }
+ }
+
+ pub fn validate(&self) -> validation::ValidationResult {
+ validation::text(&self.id, 512, true)?;
+ for (value, max) in [
+ (self.display_name.as_deref(), 512),
+ (self.description.as_deref(), 2048),
+ (self.knowledge_cutoff.as_deref(), 2048),
+ ] {
+ if let Some(value) = value {
+ validation::text(value, max, false)?;
+ }
+ }
+ for value in [
+ self.context_window,
+ self.input_limit,
+ self.compaction_threshold,
+ self.default_context_window,
+ self.default_input_limit,
+ ]
+ .into_iter()
+ .flatten()
+ {
+ validation::revision(value, true)?;
+ }
+ for (index, level) in self.thinking_levels.iter().enumerate() {
+ if self.thinking_levels[..index].contains(level) {
+ return Err("duplicate catalog thinking level".into());
+ }
+ }
+ if self
+ .default_thinking_level
+ .is_some_and(|level| !self.thinking_levels.contains(&level))
+ {
+ return Err("unsupported default thinking level".into());
+ }
+ Ok(())
+ }
+}
diff --git a/crates/runtime/src/configuration/validation.rs b/crates/runtime/src/configuration/validation.rs
index f927381d9a..ed8200a4a8 100644
--- a/crates/runtime/src/configuration/validation.rs
+++ b/crates/runtime/src/configuration/validation.rs
@@ -112,47 +112,44 @@ pub fn profiles(values: &BTreeMap<String, ModelOverride>) -> ValidationResult {
return Err("too many model overrides".into());
}
for (id, p) in values {
- text(id, 512, true)?;
- if let Some(adapter) = &p.adapter {
- text(adapter, 256, true)?;
- if adapter.chars().any(char::is_control) {
- return Err("invalid model adapter name".into());
- }
- }
- if let Some(levels) = &p.thinking_levels
- && (levels.is_empty()
- || levels
- .iter()
- .enumerate()
- .any(|(index, level)| levels[..index].contains(level)))
- {
- return Err("invalid relay thinking levels".into());
+ model_override(id, p)?;
+ }
+ Ok(())
+}
+
+pub fn model_override(id: &str, p: &ModelOverride) -> ValidationResult {
+ text(id, 512, true)?;
+ if let Some(adapter) = &p.adapter {
+ text(adapter, 256, true)?;
+ if adapter.chars().any(char::is_control) {
+ return Err("invalid model adapter name".into());
}
- for n in [
- p.context_window,
- p.input_limit,
- p.compaction_threshold,
- p.max_output_tokens,
- ]
+ }
+ if let Some(levels) = &p.thinking_levels
+ && (levels.is_empty()
+ || levels
+ .iter()
+ .enumerate()
+ .any(|(index, level)| levels[..index].contains(level)))
+ {
+ return Err("invalid relay thinking levels".into());
+ }
+ for n in [
+ p.context_window,
+ p.input_limit,
+ p.compaction_threshold,
+ p.max_output_tokens,
+ ]
+ .into_iter()
+ .flatten()
+ {
+ revision(n, true)?;
+ }
+ for value in [&p.display_name, &p.description, &p.knowledge_cutoff]
.into_iter()
.flatten()
- {
- revision(n, true)?;
- }
- for value in [&p.display_name, &p.description].into_iter().flatten() {
- text(value, 2048, false)?;
- }
- let mut facts = serde_json::json!({"id":id});
- if let Some(value) = &p.knowledge_cutoff {
- facts["knowledgeCutoff"] = serde_json::json!(value);
- }
- if let Some(value) = &p.capabilities {
- facts["capabilities"] = serde_json::to_value(value).map_err(|e| e.to_string())?;
- }
- if let Some(value) = &p.modalities {
- facts["modalities"] = serde_json::to_value(value).map_err(|e| e.to_string())?;
- }
- connection_model(&facts)?;
+ {
+ text(value, 2048, false)?;
}
Ok(())
}
diff --git a/crates/tui/src/pages/chat/render.rs b/crates/tui/src/pages/chat/render.rs
index b9d11c52c9..2d36e00d92 100644
--- a/crates/tui/src/pages/chat/render.rs
+++ b/crates/tui/src/pages/chat/render.rs
@@ -1008,7 +1008,7 @@ impl Transcript {
Kind::Thinking | Kind::Steps => {
let mut line = line;
for span in &mut line.spans {
- span.style.fg = Some(crate::view::tone::thinking(self.colors));
+ span.style.fg = Some(self.colors.thinking);
span.style = span.style.remove_modifier(Modifier::BOLD);
}
line
diff --git a/crates/tui/src/pages/manage/enabled_models/profile/view.rs b/crates/tui/src/pages/manage/enabled_models/profile/view.rs
index 7347a73b99..81135d6dbe 100644
--- a/crates/tui/src/pages/manage/enabled_models/profile/view.rs
+++ b/crates/tui/src/pages/manage/enabled_models/profile/view.rs
@@ -23,7 +23,7 @@ use crate::{
app::{Action, App},
pages::manage::Dialog,
ui::{Node, On, Role, Sheet, Size, Tone},
- view::{safe, tone},
+ view::safe,
};
use crossterm::event::{Event, KeyCode, KeyEventKind, KeyModifiers, MouseButton, MouseEventKind};
use ratatui::{
@@ -282,7 +282,7 @@ pub(in crate::pages::manage::enabled_models) fn draw(frame: &mut Frame<'_>, app:
frame.buffer_mut().set_style(label, colors.base());
frame.render_widget(
Paragraph::new(labels[index].as_str()).style(Style::default().fg(if here {
- tone::accent(colors)
+ colors.accent
} else {
colors.muted
})),
diff --git a/crates/tui/src/theme.rs b/crates/tui/src/theme.rs
index 41d086fb2d..d763cfdf32 100644
--- a/crates/tui/src/theme.rs
+++ b/crates/tui/src/theme.rs
@@ -314,15 +314,18 @@ mod tests {
(a.max(b) + 0.05) / (a.min(b) + 0.05)
}
#[test]
- fn shipped_rgb_palettes_keep_body_status_syntax_and_selection_readable() {
+ fn shipped_palettes_keep_text_readable_and_motion_appropriate() {
let mut choice = Choice::default();
for expected in [Choice::Maka, Choice::Dusk, Choice::Paper, Choice::Terminal] {
assert_eq!(choice, expected);
choice = choice.next();
+ let c = expected.colors();
if expected == Choice::Terminal {
+ assert_eq!(c.breath(true, Some(0.0)), c.breath(true, Some(1.0)));
continue;
}
- let c = expected.colors();
+ assert_ne!(c.breath(true, Some(0.0)), c.breath(true, Some(1.0)));
+ assert_eq!(c.breath(true, Some(1.0)), c.accent);
for color in [
c.foreground,
c.muted,
diff --git a/crates/tui/src/view.rs b/crates/tui/src/view.rs
index 1cab35d725..aad5f1bc00 100644
--- a/crates/tui/src/view.rs
+++ b/crates/tui/src/view.rs
@@ -169,7 +169,7 @@ pub fn draw(frame: &mut Frame<'_>, app: &mut App) {
let color = if activity == activity::Activity::Waiting {
app.theme.colors().warning
} else {
- tone::accent(app.theme.colors())
+ app.theme.colors().accent
};
Line::from(vec![
ratatui::text::Span::styled(face, Style::default().fg(color)),
@@ -797,12 +797,12 @@ fn control(
.fg(app.theme.colors().subtle)
.add_modifier(Modifier::DIM)
} else if focused || app.hover.as_ref() == Some(&action) {
- tone::selection(app.theme.colors()).fg(if destructive {
+ app.theme.colors().focused().fg(if destructive {
app.theme.colors().error
} else if caution {
app.theme.colors().warning
} else {
- tone::accent(app.theme.colors())
+ app.theme.colors().accent
})
} else if destructive {
Style::default().fg(app.theme.colors().error)
@@ -812,7 +812,7 @@ fn control(
action,
Action::SendMessage | Action::SteerMessage | Action::StopTurn(_)
) {
- Style::default().fg(tone::accent(app.theme.colors()))
+ Style::default().fg(app.theme.colors().accent)
} else {
Style::default().fg(app.theme.colors().muted)
};
diff --git a/crates/tui/src/view/form.rs b/crates/tui/src/view/form.rs
index 333bc6cc35..a2cc139e33 100644
--- a/crates/tui/src/view/form.rs
+++ b/crates/tui/src/view/form.rs
@@ -20,7 +20,7 @@
//! Labelled text rows of a form sheet. Each whole row is one kernel slot,
//! so a form's rows share a focus group and the arrows walk them; the
//! label and the editor are painted here, over the drawn sheet.
-use crate::{editor::Editor, theme::Palette, view::tone};
+use crate::{editor::Editor, theme::Palette};
use ratatui::{Frame, layout::Rect, style::Style, widgets::Paragraph};
/// The label column for labels this wide, on a terminal this wide.
@@ -52,7 +52,7 @@ pub(crate) fn draw(
frame.buffer_mut().set_style(label, colors.base());
frame.render_widget(
Paragraph::new(row.label).style(Style::default().fg(if row.focused {
- tone::accent(colors)
+ colors.accent
} else {
colors.muted
})),
diff --git a/crates/tui/src/view/session.rs b/crates/tui/src/view/session.rs
index de7830c711..bb144bf8d0 100644
--- a/crates/tui/src/view/session.rs
+++ b/crates/tui/src/view/session.rs
@@ -236,7 +236,7 @@ pub(super) fn draw(frame: &mut Frame<'_>, app: &mut App, area: Rect, id: &str) {
BorderType::Rounded
})
.padding(Padding::new(4, control_width, 0, 0))
- .border_style(Style::default().fg(tone::border(app.theme.colors(), focused, breath)));
+ .border_style(Style::default().fg(app.theme.colors().breath(focused, breath)));
let mut input = border.inner(parts[3]);
frame.render_widget(border, parts[3]);
frame.render_widget(Paragraph::new(metadata), metadata_area);
@@ -496,7 +496,7 @@ mod tests {
assert_eq!(button, " ■ ");
assert_eq!(
terminal.backend().buffer()[(area.x, area.y - 1)].fg,
- tone::border(app.theme.colors(), true, Some(0.45))
+ app.theme.colors().breath(true, Some(0.45))
);
assert!(!app.drafts["chat"].contains(Position::new(area.x, area.y)));
assert_eq!(
@@ -593,7 +593,7 @@ mod tests {
.unwrap();
assert_ne!(
terminal.backend().buffer()[(send.area.x, send.area.y - 1)].fg,
- tone::border(app.theme.colors(), true, Some(0.45))
+ app.theme.colors().breath(true, Some(0.45))
);
app.chat.snapshot = Some(snapshot.clone());
app.chat
diff --git a/crates/tui/src/view/tone.rs b/crates/tui/src/view/tone.rs
index 8de6be4edc..1ce89baac8 100644
--- a/crates/tui/src/view/tone.rs
+++ b/crates/tui/src/view/tone.rs
@@ -17,18 +17,9 @@
* under the License.
*/
-//! Shared semantic colors; no process-global theme or terminal-cell recoloring.
+//! Stable session identity hues from the selected palette.
use crate::theme::Palette;
-use ratatui::style::{Color, Style};
-pub fn accent(colors: Palette) -> Color {
- colors.accent
-}
-pub fn thinking(colors: Palette) -> Color {
- colors.thinking
-}
-pub fn selection(colors: Palette) -> Style {
- colors.focused()
-}
+use ratatui::style::Color;
/// Stable identity hue index for a session ID (FNV-1a), never its position.
pub fn session_hue(id: &str) -> u8 {
let hash = id.bytes().fold(0xcbf29ce484222325_u64, |h, b| {
@@ -50,26 +41,3 @@ pub fn hue(index: u8, colors: Palette) -> Color {
];
variants[usize::from(index) % variants.len()]
}
-pub fn border(colors: Palette, focused: bool, breath: Option<f32>) -> Color {
- colors.breath(focused, breath)
-}
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::theme::Choice;
- #[test]
- fn working_border_has_visible_blue_breath_without_flashing_or_changing_terminal_palette() {
- let palette = Choice::Maka.colors();
- let Color::Rgb(r, g, b) = border(palette, true, Some(0.0)) else {
- panic!("RGB");
- };
- assert!(b > g && g > r && b >= 100);
- assert_eq!(border(palette, true, Some(1.0)), palette.accent);
- assert!(253 - b >= 100);
- let terminal = Choice::Terminal.colors();
- assert_eq!(
- border(terminal, true, Some(0.0)),
- border(terminal, true, Some(1.0))
- );
- }
-}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
(maka) 02/02: feat(runtime): derive automatic compaction thresholds from model limits
Posted by wy...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
commit 2d3231c18d6820568ed6e8b62d7f29ec8ed298f3
Author: Wang <m4...@gmail.com>
AuthorDate: Fri Sep 25 13:25:47 2026 +0800
feat(runtime): derive automatic compaction thresholds from model limits
Reserve maximum output within the total context window, respect the provider input ceiling, and retain five percent headroom. Use manual thresholds literally and preserve unknown limits and overflow recovery. Document the token budgets in English and Chinese and cover automatic compaction across restart.
Generated-by: Codex
---
crates/agent/src/auto_context.rs | 17 +++---
crates/agent/tests/integration/auto_context.rs | 8 +--
crates/agent/tests/integration/context_overflow.rs | 2 +-
crates/agent/tests/integration/dynamic_tools.rs | 2 +-
.../agent/tests/integration/handoff_compaction.rs | 2 +-
crates/agent/tests/integration/pruning.rs | 2 +-
.../runtime-host/src/execution/provider/context.rs | 60 ++++++++++++++++++--
.../runtime-host/tests/integration/auto_context.rs | 5 +-
crates/runtime/src/configuration/model_info.rs | 3 +
crates/runtime/src/configuration/model_override.rs | 5 ++
crates/runtime/src/context.rs | 7 ++-
docs/rust-runtime.md | 65 +++++++++++++++++++++-
docs/rust-runtime.zh-CN.md | 52 ++++++++++++++++-
tests/fixtures/client-auto-context-fixture.mjs | 2 +-
tests/fixtures/client-auto-context-workflow.mjs | 6 +-
15 files changed, 205 insertions(+), 33 deletions(-)
diff --git a/crates/agent/src/auto_context.rs b/crates/agent/src/auto_context.rs
index ab5bc2d963..19d96dc18e 100644
--- a/crates/agent/src/auto_context.rs
+++ b/crates/agent/src/auto_context.rs
@@ -131,10 +131,9 @@ fn threshold(input: Option<u64>, output: Option<u64>, window: u64) -> bool {
return false;
};
let output = output.unwrap_or(0);
- input
- .saturating_add(output)
- .saturating_add(output.saturating_mul(2).min(8000))
- >= window
+ // Host has already reserved maximum output and input-growth headroom when
+ // deriving this threshold. A manual threshold is used literally as well.
+ input.saturating_add(output) >= window
}
pub(super) async fn attempt(
@@ -212,14 +211,14 @@ mod tests {
assert_eq!(cap_output(4096, 200_000, 199_999, 0), 4096);
}
#[test]
- fn actual_usage_threshold_preserves_unknown_and_caps_reply_reserve() {
+ fn actual_usage_threshold_preserves_unknown_without_reserving_output_twice() {
assert!(!threshold(None, Some(5000), 1));
assert!(!threshold(Some(0), Some(5000), 1));
assert!(threshold(Some(100), None, 100));
assert!(!threshold(Some(100), None, 101));
- assert!(threshold(Some(100), Some(20), 160));
- assert!(!threshold(Some(100), Some(20), 161));
- assert!(threshold(Some(100), Some(5000), 13100));
- assert!(!threshold(Some(100), Some(5000), 13101));
+ assert!(threshold(Some(100), Some(20), 120));
+ assert!(!threshold(Some(100), Some(20), 121));
+ assert!(threshold(Some(100), Some(5000), 5100));
+ assert!(!threshold(Some(100), Some(5000), 5101));
}
}
diff --git a/crates/agent/tests/integration/auto_context.rs b/crates/agent/tests/integration/auto_context.rs
index d803f01ff3..04f420e50d 100644
--- a/crates/agent/tests/integration/auto_context.rs
+++ b/crates/agent/tests/integration/auto_context.rs
@@ -42,11 +42,11 @@ fn context(window: Option<u64>) -> Option<ModelRequestContext> {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn declaration_and_matching_latest_main_route_are_required_for_preturn() {
+async fn resolved_threshold_and_matching_latest_main_route_are_required_for_preturn() {
for (declared, matching, expected) in [
(None, true, false),
- (Some(170), false, false),
- (Some(170), true, true),
+ (Some(70), false, false),
+ (Some(70), true, true),
] {
let directory = tempfile::tempdir().unwrap();
let log = Arc::new(
@@ -186,7 +186,7 @@ async fn midturn_waits_for_all_code_mode_results_and_replays_exact_image_anchor_
together: Arc::new(Barrier::new(2)),
});
let mut input = code_mode::input(&base, "first", effects.clone());
- input.context = context(Some(13));
+ input.context = context(Some(7));
input.supports_vision = true;
input.configuration.model = fixture::input(&base, "unused", false).configuration.model;
if let RunWork::Message { message, .. } = &mut input.work {
diff --git a/crates/agent/tests/integration/context_overflow.rs b/crates/agent/tests/integration/context_overflow.rs
index f4fef8c706..0fab425957 100644
--- a/crates/agent/tests/integration/context_overflow.rs
+++ b/crates/agent/tests/integration/context_overflow.rs
@@ -192,7 +192,7 @@ async fn proactive_failure_spends_the_same_budget_as_overflow_recovery() {
next.context = Some(ModelRequestContext {
provider_id: "openai".into(),
context_window: Some(170),
- declared_window: Some(170),
+ declared_window: Some(70),
model_context_window: None,
});
if let RunWork::Message { max_steps, .. } = &mut next.work {
diff --git a/crates/agent/tests/integration/dynamic_tools.rs b/crates/agent/tests/integration/dynamic_tools.rs
index 9478142083..a7608fbc1d 100644
--- a/crates/agent/tests/integration/dynamic_tools.rs
+++ b/crates/agent/tests/integration/dynamic_tools.rs
@@ -148,7 +148,7 @@ async fn search_activates_next_step_and_only_committed_compaction_unloads_direct
}]).unwrap().with_discovery();
let mut input = fixture::input(&base, "discovery", false);
input.configuration.tool_mode = mode;
- input.context = Some(ModelRequestContext { provider_id:"openai".into(), context_window:Some(220), declared_window:Some(220), model_context_window:None });
+ input.context = Some(ModelRequestContext { provider_id:"openai".into(), context_window:Some(220), declared_window:Some(210), model_context_window:None });
input.work = RunWork::Message { allow_prior_unknown:false, source_messages:Vec::new(), message:"Use echo".into(), tools:catalog, max_steps:3 };
let engine = fixture::engine(log.clone());
engine.run(input, CancellationToken::new()).await.unwrap();
diff --git a/crates/agent/tests/integration/handoff_compaction.rs b/crates/agent/tests/integration/handoff_compaction.rs
index 8053b1cb18..f27ed18442 100644
--- a/crates/agent/tests/integration/handoff_compaction.rs
+++ b/crates/agent/tests/integration/handoff_compaction.rs
@@ -91,7 +91,7 @@ async fn handoff_preserves_conversation_replay_and_compacts_before_its_physical_
connection_id: "connection".into(), connection_slug: "fixture".into(), model: "test".into(),
});
first.context = Some(ModelRequestContext {
- provider_id: "openai".into(), context_window: Some(10), declared_window: Some(10),
+ provider_id: "openai".into(), context_window: Some(10), declared_window: Some(7),
model_context_window: None,
});
let configuration = first.configuration.clone();
diff --git a/crates/agent/tests/integration/pruning.rs b/crates/agent/tests/integration/pruning.rs
index d9e3d79a40..4b66c673ab 100644
--- a/crates/agent/tests/integration/pruning.rs
+++ b/crates/agent/tests/integration/pruning.rs
@@ -167,7 +167,7 @@ async fn settled_results_are_pruned_before_context_limits_and_survive_failed_sum
provider_id: "openai".into(),
context_window: Some(220),
model_context_window: None,
- declared_window: spent.then_some(220),
+ declared_window: spent.then_some(210),
});
input.work = RunWork::Message {
allow_prior_unknown: false,
diff --git a/crates/runtime-host/src/execution/provider/context.rs b/crates/runtime-host/src/execution/provider/context.rs
index 567a35c623..26b96783d4 100644
--- a/crates/runtime-host/src/execution/provider/context.rs
+++ b/crates/runtime-host/src/execution/provider/context.rs
@@ -31,6 +31,26 @@ pub(super) fn resolve(
{
return Err(unavailable("Model input limit exceeds its context window"));
}
+ let declaration = connection
+ .model_overrides
+ .as_ref()
+ .and_then(|values| values.get(&model.id));
+ let output = match (
+ declaration.and_then(|value| value.max_output_tokens),
+ model.max_output_tokens,
+ ) {
+ (Some(requested), Some(capacity)) => Some(requested.min(capacity)),
+ (requested, capacity) => requested.or(capacity),
+ };
+ // Reserve the entire output budget, respect any independent input ceiling,
+ // then leave 5% for input growth since the last measured request.
+ let automatic = model
+ .context_window
+ .zip(output)
+ .and_then(|(window, output)| window.checked_sub(output))
+ .map(|budget| model.input_limit.map_or(budget, |limit| budget.min(limit)))
+ .map(|budget| budget - budget.div_ceil(20))
+ .filter(|threshold| *threshold > 0);
Ok(ModelRequestContext {
provider_id: connection.provider.name.clone(),
context_window: model
@@ -39,11 +59,9 @@ pub(super) fn resolve(
.chain(model.input_limit)
.min(),
model_context_window: model.context_window,
- declared_window: connection
- .model_overrides
- .as_ref()
- .and_then(|values| values.get(&model.id))
- .and_then(|value| value.compaction_threshold),
+ declared_window: declaration
+ .and_then(|value| value.compaction_threshold)
+ .or(automatic),
})
}
@@ -53,7 +71,7 @@ mod tests {
use serde_json::json;
#[test]
- fn full_window_input_budget_and_compaction_policy_remain_independent() {
+ fn compaction_reserves_output_and_headroom_unless_manually_overridden() {
let mut connection: ConnectionCatalogEntry = serde_json::from_value(json!({
"connectionId":"connection","revision":1,"slug":"fixture","name":"Fixture",
"provider":{"packageId":"fixture","entryId":"fixture","scope":"profile","name":"model"},
@@ -73,5 +91,35 @@ mod tests {
context.model_context_window, None,
"input-only limits cannot become full capacity"
);
+ connection.models[0].context_window = Some(1_000_000);
+ for (input, maximum, requested, manual, expected) in [
+ (None, Some(128_000), None, None, Some(828_400)),
+ (Some(800_000), Some(128_000), None, None, Some(760_000)),
+ (None, Some(128_000), Some(64_000), None, Some(889_200)),
+ (None, Some(128_000), Some(256_000), None, Some(828_400)),
+ (None, None, Some(128_000), None, Some(828_400)),
+ (None, None, None, None, None),
+ (None, Some(1_000_000), None, None, None),
+ (None, None, None, Some(700_000), Some(700_000)),
+ ] {
+ let model = &mut connection.models[0];
+ model.input_limit = input;
+ model.max_output_tokens = maximum;
+ let profile = connection
+ .model_overrides
+ .as_mut()
+ .unwrap()
+ .get_mut("custom")
+ .unwrap();
+ profile.max_output_tokens = requested;
+ profile.compaction_threshold = manual;
+ assert_eq!(
+ resolve(&connection, &connection.models[0])
+ .unwrap()
+ .declared_window,
+ expected,
+ "input={input:?}, output={maximum:?}, requested={requested:?}, manual={manual:?}"
+ );
+ }
}
}
diff --git a/crates/runtime-host/tests/integration/auto_context.rs b/crates/runtime-host/tests/integration/auto_context.rs
index 56ce44a462..f584a8b50d 100644
--- a/crates/runtime-host/tests/integration/auto_context.rs
+++ b/crates/runtime-host/tests/integration/auto_context.rs
@@ -120,8 +120,9 @@ async fn original_client_keeps_auto_summary_private_and_reopens_anchor_without_r
);
let context = main.context.unwrap();
assert_eq!(context.provider_id, "openai");
- assert_eq!(context.context_window, Some(10000));
- assert_eq!(context.declared_window, Some(120));
+ assert_eq!(context.context_window, Some(1_000_000));
+ assert_eq!(context.model_context_window, Some(1_000_000));
+ assert_eq!(context.declared_window, Some(828_400));
let facts = serde_json::to_value(&prefix.events).unwrap();
if let Some(original) = &original {
let original: &Vec<serde_json::Value> = original;
diff --git a/crates/runtime/src/configuration/model_info.rs b/crates/runtime/src/configuration/model_info.rs
index 04e20581ba..ce4a782551 100644
--- a/crates/runtime/src/configuration/model_info.rs
+++ b/crates/runtime/src/configuration/model_info.rs
@@ -48,18 +48,21 @@ pub struct ModelInfo {
skip_serializing_if = "Option::is_none",
deserialize_with = "present"
)]
+ /// Total model capacity for input plus generated output, before any reply reserve.
pub context_window: Option<u64>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "present"
)]
+ /// Independent provider input ceiling; not context_window minus max_output_tokens.
pub input_limit: Option<u64>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "present"
)]
+ /// Provider output ceiling; also the default output reserve for auto-compaction.
pub max_output_tokens: Option<u64>,
/// Choices reported by the provider plugin.
#[serde(
diff --git a/crates/runtime/src/configuration/model_override.rs b/crates/runtime/src/configuration/model_override.rs
index 6a1cd076f3..dde89812c2 100644
--- a/crates/runtime/src/configuration/model_override.rs
+++ b/crates/runtime/src/configuration/model_override.rs
@@ -86,24 +86,29 @@ pub struct ModelOverride {
skip_serializing_if = "Option::is_none",
deserialize_with = "present"
)]
+ /// Override total input-plus-output capacity, without subtracting a reply budget.
pub context_window: Option<u64>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "present"
)]
+ /// Optional override of the automatic compaction threshold, in retained tokens.
+ /// By default Host reserves maximum output, then leaves 5% input-growth headroom.
pub compaction_threshold: Option<u64>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "present"
)]
+ /// Independent input ceiling; also caps the default compaction input budget.
pub input_limit: Option<u64>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "present"
)]
+ /// Requested per-step output budget, subject to provider and remaining-capacity caps.
pub max_output_tokens: Option<u64>,
#[serde(
default,
diff --git a/crates/runtime/src/context.rs b/crates/runtime/src/context.rs
index d5b1b7ad8c..c31fc2868e 100644
--- a/crates/runtime/src/context.rs
+++ b/crates/runtime/src/context.rs
@@ -42,13 +42,18 @@ pub const MAX_HISTORY_BYTES: usize = 8 * 1024 * 1024;
#[serde(deny_unknown_fields)]
pub struct ModelRequestContext {
pub provider_id: String,
- /// Historical field: effective input budget, not the model's total capacity.
+ /// Effective input ceiling: the smaller known contextWindow/inputLimit value.
+ /// Unlike ModelInfo::context_window, this may be input-only. No output budget
+ /// is subtracted here; this value is not the proactive compaction threshold.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context_window: Option<u64>,
/// Full selected-model capacity. Unknown legacy values must not be inferred
/// from context_window, which may be an independent input-only limit.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model_context_window: Option<u64>,
+ /// Resolved proactive threshold: explicit compactionThreshold, otherwise 95% of
+ /// the smaller of (total capacity - output reserve) and any input-only limit.
+ /// None means no usable threshold; overflow recovery remains available.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub declared_window: Option<u64>,
}
diff --git a/docs/rust-runtime.md b/docs/rust-runtime.md
index f882495701..9fa057a45a 100644
--- a/docs/rust-runtime.md
+++ b/docs/rust-runtime.md
@@ -431,8 +431,9 @@ user/project content paths stay separate from private journals.
and unfinished response fragments. Unknown effects block admission; repeating
the same admitted request returns its original Turn, including after restart.
- Typed model inventory flows from discovery through storage and catalog projection;
- connection-owned overrides remain separate. Capacity,
- proactive compaction threshold and per-request output budget are independent.
+ connection-owned overrides remain separate. Proactive compaction reserves maximum
+ output and input-growth headroom within the total capacity;
+ see [Context windows and compaction](#context-windows-and-compaction).
- Tool dispatch commits before effects; outcomes commit afterward. An uncertain
outcome is not permission to repeat an effect. Cancellation drains admitted work.
- Permission-only grants can widen during execution. New tool calls capture the
@@ -504,6 +505,66 @@ user/project content paths stay separate from private journals.
A real provider finish releases the stream without waiting for transport EOF;
synthetic finishes from truncated streams are not successful completions.
+## Context windows and compaction
+
+Model configuration uses `contextWindow` for the **total input-plus-output capacity**.
+Enter the full model window and the desired `maxOutputTokens`; a separate
+`compactionThreshold` is optional. The default trigger reserves the full maximum
+output and leaves 5% of the remaining input space for growth:
+
+```text
+output reserve = requested maxOutputTokens, capped by the provider's output ceiling
+ (use the provider ceiling when no request override is set)
+input budget = min(contextWindow - output reserve, provider inputLimit if known)
+auto threshold = floor(input budget × 95%)
+threshold = explicit compactionThreshold, otherwise auto threshold
+```
+
+For a **1,000,000-token window and 128,000-token maximum output**, with no smaller
+input limit, the default threshold is **828,400 tokens**. The 43,600-token margin
+before the 872,000-token input budget accommodates growth between requests.
+If the provider also limits input to 800,000 tokens, the default becomes 760,000.
+These are decimal token counts. A manual threshold replaces the default trigger;
+it does not change provider capacity or reserve output a second time.
+
+The internal names distinguish frozen request facts from model configuration:
+
+| Quantity | Meaning |
+| --- | --- |
+| `ModelInfo.context_window` / configuration `contextWindow` | Total model capacity, including output; an explicit model override replaces the reported value. |
+| `inputLimit` | Independent provider input ceiling, if known; it is not another required auto-compaction setting. |
+| `ModelRequestContext.context_window` | Internal input ceiling before the output reserve: the smaller known value of `contextWindow` and `inputLimit`, or the sole known value. |
+| `ModelRequestContext.model_context_window` | Full model capacity. An input-only limit cannot supply this value. Context diagnostics expose this as `contextWindow`. |
+| Model / override `maxOutputTokens` | Provider output ceiling / requested per-step output budget. They supply the output reserve above; provider policy still resolves the actual request limit. |
+| `ModelRequestContext.declared_window` | Resolved compaction threshold, either explicit or automatic, frozen for the request. |
+
+Before a main model step, the runtime compares the previous completed main
+request's actual **input tokens + output tokens** with the resolved threshold.
+Input usage must be positive; missing output usage counts as zero.
+The usage must belong to the same connection, model and current checkpoint.
+Compaction waits for a safe execution boundary. It does not add a second
+recent-reply reserve on top of the default 5% margin.
+
+If total capacity or the output reserve is unknown, or reserving output leaves
+insufficient input space, no default threshold is guessed. An explicit threshold
+can still be used. Missing usable usage also prevents a proactive trigger.
+The 5% margin is a heuristic: new messages or tool results may exceed it because
+the complete next prompt is not locally tokenized. A provider context-overflow
+rejection before observable output therefore retains bounded compaction recovery;
+an output-length finish alone does not prove context overflow. The context
+meter's estimates are display-only.
+
+Per-request output capping remains a separate fallback. With a selected request
+budget `M`, full window `C` and matching usage `R`, it limits output to the remaining
+window minus 8,000 tokens for new input and any fixed Anthropic thinking budget,
+with a floor of `min(M, 8000)`. It neither changes configured capacity nor guarantees
+that the next prompt fits. The first main request after compaction is capped at
+8,000 tokens (or a smaller selected budget).
+
+See [Host threshold resolution](../crates/runtime-host/src/execution/provider/context.rs),
+[usage and output checks](../crates/agent/src/auto_context.rs), and
+[compaction admission/recovery](../crates/agent/src/steps.rs).
+
## Web
The `maka.web` plugin publishes WebFetch and WebSearch. Settings → Web search
diff --git a/docs/rust-runtime.zh-CN.md b/docs/rust-runtime.zh-CN.md
index 550cc1ae71..65b5591c01 100644
--- a/docs/rust-runtime.zh-CN.md
+++ b/docs/rust-runtime.zh-CN.md
@@ -306,7 +306,7 @@ Host 不可连接不代表进程已停止。`host logs --root-id <rootId>` 返
- 手动 resume 先只读检查已封口的源,再原子开启续跑。模型只回放选定谱系,不混入后来的旁支或
未完成的响应片段。未知副作用阻止准入;重复已接受的请求返回原 Turn,重启后仍然如此。
- 类型化模型列表贯通发现、存储和目录投影,连接自有声明单独保存;
- 容量、主动压缩阈值与单次回复预算互相独立。
+ 主动压缩从总容量中预留最大输出和输入增长余量,详见[上下文窗口与压缩](#上下文窗口与压缩)。
- 工具先提交派发,再执行副作用,最后提交结果。结果未知不代表可以重做;取消必须等待
已准入工作收尾。
- 执行中可单独扩大权限,新工具调用捕获已提交的边界;收紧权限须等待执行静止及原生
@@ -355,6 +355,56 @@ Host 不可连接不代表进程已停止。`host logs --root-id <rootId>` 返
模型活动刷新 120 秒空闲预算,持续输出不受两分钟总时限限制;用户取消仍关闭请求并等待收尾。
真实 provider finish 到达后释放流,不等待传输 EOF;残缺流合成的 finish 不算成功完成。
+## 上下文窗口与压缩
+
+模型配置中的 `contextWindow` 是**输入与输出共享的总容量**。填写完整模型窗口和希望
+使用的 `maxOutputTokens` 即可;`compactionThreshold` 是可选覆盖项。默认触发线先
+预留完整最大输出,再从剩余输入空间留出 5% 的增长余量:
+
+```text
+输出预留 = 请求的 maxOutputTokens,受提供商输出上限约束
+ (未显式设置时使用提供商输出上限)
+输入预算 = min(contextWindow − 输出预留, 提供商 inputLimit(若已知))
+自动阈值 = floor(输入预算 × 95%)
+最终阈值 = 显式 compactionThreshold,否则使用自动阈值
+```
+
+例如,**总窗口 1,000,000 token,最大输出 128,000 token**,没有更小的输入上限时,
+默认在 **828,400 token** 触发。它比 872,000 token 的输入预算提前 43,600 token,
+用于容纳请求间增长。若提供商另有限制输入最多 800,000 token,则默认阈值为 760,000。
+这里使用十进制 token 数。手动阈值替换默认触发线,不改变提供商容量,也不再次扣除输出。
+
+内部字段区分模型配置和每次请求冻结的事实:
+
+| 数值 | 含义 |
+| --- | --- |
+| `ModelInfo.context_window`/配置 `contextWindow` | 模型总容量,包含输出;显式模型覆盖替换提供商报告值。 |
+| `inputLimit` | 独立的提供商输入上限(若已知),不是自动压缩必填的第三个设置。 |
+| `ModelRequestContext.context_window` | 内部扣除输出前的输入上限:`contextWindow` 与 `inputLimit` 都已知时取较小值,仅一个已知时取该值。 |
+| `ModelRequestContext.model_context_window` | 完整模型窗口,不能从仅有的输入上限推断;上下文诊断以 `contextWindow` 返回它。 |
+| 模型/覆盖配置 `maxOutputTokens` | 提供商输出上限/请求的单步输出预算,为上述公式提供输出预留;实际请求限制仍由提供商策略决定。 |
+| `ModelRequestContext.declared_window` | 解析并冻结到该请求的最终压缩阈值,可以来自手动配置或自动计算。 |
+
+每次主模型步骤之前,runtime 比较上一已完成主请求的**实际输入 token + 实际输出 token**
+与最终阈值,输入用量须为正,缺失输出用量按零计算。用量必须属于同一连接、模型和当前
+checkpoint,压缩还须满足安全执行边界。
+默认已有 5% 余量,不再叠加根据上一次回复大小计算的第二份余量。
+
+总容量或输出预留未知、或者预留输出后没有足够输入空间时,不猜测默认阈值,仍可使用
+显式阈值。没有可用的实际用量时也不主动触发。5% 余量是启发式保护:新消息或工具结果
+可能超过它,因为 runtime 不会在本地对完整的下一次提示词做 token 计数。因此仍保留
+提供商在产生可观察输出前明确报告上下文溢出时的有界压缩恢复;仅以输出长度结束不能
+证明上下文溢出。界面上下文用量的估算只用于展示。
+
+单次输出限制保留为另一层保护:已知请求预算 `M`、完整窗口 `C` 和匹配实际用量 `R`
+时,按剩余窗口减去 8,000 token 的新输入余量、以及 Anthropic 固定 thinking 预算
+(若有)收紧输出,并保留 `min(M, 8000)` 的输出下限。这不会改变配置容量,也不保证
+下一次提示词一定放得下。压缩后第一次主请求最多输出 8,000 token,已选预算更小时取更小值。
+
+实现见 [Host 阈值解析](../crates/runtime-host/src/execution/provider/context.rs)、
+[用量与输出检查](../crates/agent/src/auto_context.rs)和
+[压缩准入/恢复](../crates/agent/src/steps.rs)。
+
## Web
`maka.web` 插件发布 WebFetch 与 WebSearch。设置 → 联网搜索选择模型原生搜索或 Tavily,
diff --git a/tests/fixtures/client-auto-context-fixture.mjs b/tests/fixtures/client-auto-context-fixture.mjs
index bee44b1e22..f720f3957f 100644
--- a/tests/fixtures/client-auto-context-fixture.mjs
+++ b/tests/fixtures/client-auto-context-fixture.mjs
@@ -130,7 +130,7 @@ export async function autoContextFixture(port = 0, reopened = false) {
? ''
: frame({ content: 'automatic context complete' });
const [prompt, completion, cached] = isRead
- ? [90, 10, 7]
+ ? [828390, 10, 7]
: isSummary
? [999, 200, 99]
: reopened
diff --git a/tests/fixtures/client-auto-context-workflow.mjs b/tests/fixtures/client-auto-context-workflow.mjs
index f364be8c13..ff7874384c 100644
--- a/tests/fixtures/client-auto-context-workflow.mjs
+++ b/tests/fixtures/client-auto-context-workflow.mjs
@@ -101,7 +101,7 @@ function diagnostics(value, inputTokens, cacheReadInputTokens, since) {
completedAt: value.completedAt,
inputTokens,
cacheReadInputTokens,
- contextWindow: 10000,
+ contextWindow: 1000000,
});
}
function readResult(stored) {
@@ -153,7 +153,7 @@ export async function verifyAutoContext(connection, workspace, reopened) {
apiKey: 'auto-context-fixture',
enabledModelIds: ['fixture-model'],
modelOverrides: {
- 'fixture-model': { vision: false, contextWindow: 10000, compactionThreshold: 120 },
+ 'fixture-model': { vision: false, contextWindow: 1000000, maxOutputTokens: 128000 },
},
});
const basis = created.connection;
@@ -181,7 +181,7 @@ export async function verifyAutoContext(connection, workspace, reopened) {
await request('turn.start', saved.turn);
await model.waitFor('summary');
const firstDiagnostics = await query();
- diagnostics(firstDiagnostics, 90, 7, since);
+ diagnostics(firstDiagnostics, 828390, 7, since);
const settledRows = await rows(connection, saved.sessionId);
readResult(settledRows);
await request('session.read_marker.set', {
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org