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:40 UTC

(maka) 02/02: feat(runtime): derive automatic compaction thresholds from model limits

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