From ebc8425f38774861cf2062803f7fef916090128f Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:24:10 +0800 Subject: [PATCH] perf(pi): reduce DeepSeek input overhead with automatic economy profile --- config.example.yaml | 2 +- docs/en-US/configuration.md | 2 +- docs/en-US/token-usage-monitoring.md | 2 + docs/zh-CN/configuration.md | 13 ++- docs/zh-CN/token-usage-monitoring.md | 2 + internal/agentruntime/types.go | 25 ++--- internal/config/config.go | 4 +- internal/config/context_profile.go | 35 ++++++- internal/config/context_profile_test.go | 50 ++++++++++ internal/handler/config.go | 7 +- internal/multiagent/pi_integration_test.go | 110 +++++++++++++++++++++ internal/multiagent/pi_model.go | 2 +- internal/multiagent/pi_runner.go | 11 ++- internal/tooloutput/economy_test.go | 38 +++++++ internal/tooloutput/spill.go | 26 +++++ runtime/pi/src/tool-output.ts | 13 +++ runtime/pi/src/worker.ts | 41 +++++--- runtime/pi/test/tool-output.test.mjs | 11 +++ runtime/pi/test/worker.test.mjs | 33 +++++++ web/static/i18n/en-US.json | 6 +- web/static/i18n/ru-RU.json | 6 +- web/static/i18n/zh-CN.json | 6 +- web/static/js/settings.js | 2 +- web/templates/index.html | 6 +- 24 files changed, 404 insertions(+), 49 deletions(-) create mode 100644 internal/tooloutput/economy_test.go create mode 100644 runtime/pi/src/tool-output.ts create mode 100644 runtime/pi/test/tool-output.test.mjs diff --git a/config.example.yaml b/config.example.yaml index 9f850233..bbf8b767 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -126,7 +126,7 @@ ai: # 独立审计身份如需请求头,请在 hitl.audit_model.headers 中单独配置。 # 空 headers 与未配置等价;所有自定义头值在设置接口中均按敏感值脱敏。 context_window: 262144 # 模型原生上下文窗口(token);0/省略=未知。检测到窗口后,预算会被自动收紧 - context_profile: auto # auto=通用;local=本地模型档位(32K-256K),会收紧压缩/工具输出/常驻工具,token 估算留 10% 保守余量 + context_profile: auto # auto=DeepSeek 自动节省输入;economy=显式启用;custom=按运行时配置;local=本地模型预算档位 # Pi 路径模型推理:DeepSeek/OpenAI 为 thinking / reasoning_effort;Claude 4.6+ 为 adaptive + output_config.effort(仅显式配置 effort 时下发);3.7 为 enabled+budget_tokens:10000(文档示例),effort 不映射,自定义预算用 extra_request_fields reasoning: mode: on # auto | on | off;off:OpenAI/Claude 不附加推理字段,DeepSeek 发送 thinking.type=disabled(其默认开启思考) diff --git a/docs/en-US/configuration.md b/docs/en-US/configuration.md index 99c7f62c..0c910f32 100644 --- a/docs/en-US/configuration.md +++ b/docs/en-US/configuration.md @@ -73,7 +73,7 @@ ai: | `max_total_tokens` | Shared context budget for compression, attack-chain generation, multi-agent summaries, and similar paths. When `context_window` is known, it is clamped to the window minus the output reserve. | | `max_completion_tokens` | Per-response output cap; default is used when empty, and it is clamped to half of the known/assumed window. | | `context_window` | Native model context window in tokens. When set, the runtime clamps `max_total_tokens` to it; 0/omitted means unknown. | -| `context_profile` | `auto` (default) or `local`. `local` targets 32K–256K local models: the budget is 60% of the window (capped at 128K), while summary reserve, tool-output truncation/clearing, user-message and ledger caps are tightened, and `tool_search` with a small always-visible tool set is enabled. It only tightens numeric middleware settings and enables tool_search/reduction where needed. | +| `context_profile` | `auto` (default) enables input savings for the official DeepSeek endpoint or an explicit DeepSeek reasoning profile. Select `economy` to enable savings on another channel, `custom` to use runtime settings, or `local` to tighten context budgets and tool overhead for 32K–256K local models. | | `reasoning` | Default reasoning fields for the channel. Gateway support varies; try `mode: off` first when a provider rejects requests. | ### Local Model Context (32K–256K) diff --git a/docs/en-US/token-usage-monitoring.md b/docs/en-US/token-usage-monitoring.md index 654c11ed..279418bb 100644 --- a/docs/en-US/token-usage-monitoring.md +++ b/docs/en-US/token-usage-monitoring.md @@ -13,3 +13,5 @@ Streaming updates carry deltas; complete messages are committed at message end. In the channel’s reasoning settings, use `off` for simple Q&A and format conversions or pair `auto` with `low` to keep reasoning on at a lower effort. The official API defaults to `high` when effort is unspecified and maps `medium` to `high`. The channel sends its per-request output limit as `max_tokens`, shared by reasoning and the visible answer. Compare output tokens, reasoning tokens and the cache hit rate for the same tasks at different effort levels. [DeepSeek Thinking Mode](https://api-docs.deepseek.com/guides/thinking_mode/) · [Chat Completions](https://api-docs.deepseek.com/api/create-chat-completion/) The official API automatically caches reusable request prefixes. Pi orders MCP tool definitions by name so the same catalog introduces fewer prefix changes across requests. The provider reports the actual cache hits. [DeepSeek Context Caching](https://api-docs.deepseek.com/guides/kv_cache/) + +The default `auto` context profile enables input savings for the official DeepSeek endpoint and explicit `deepseek` / `deepseek_compat` reasoning profiles. At 16 tools, native discovery keeps six catalog entries plus core tools and explicit always-visible tools available. Other builtins load on demand. With authorized file access, results over 8,000 bytes become head/tail previews backed by the full output. Tighter configured limits take precedence. Valid JSON tool results lose formatting whitespace, including when replaying older sessions. Strings and numeric lexemes retain their original text. Select `custom` to use the configured runtime settings. Compare complete tasks, including discovery/readback calls and evidence quality, to measure actual savings. diff --git a/docs/zh-CN/configuration.md b/docs/zh-CN/configuration.md index 79e778d2..d28a97ba 100644 --- a/docs/zh-CN/configuration.md +++ b/docs/zh-CN/configuration.md @@ -74,7 +74,7 @@ ai: | `max_total_tokens` | 上下文压缩、攻击链构建、多代理摘要等共用的总预算。已知 `context_window` 时会收紧到“窗口 − 输出预留”。 | | `max_completion_tokens` | 单次模型输出上限;未填时使用默认值,并会被压到已知/假定窗口的一半以内。 | | `context_window` | 模型原生上下文窗口(token)。填写后运行时会按窗口收紧 `max_total_tokens`;0/省略表示未知。 | -| `context_profile` | `auto`(默认)或 `local`。`local` 面向 32K–256K 本地模型:预算折到窗口的 60%(上限 128K),收紧摘要预留、工具输出截断/清理、用户消息与账本上限,并启用 `tool_search` 与精简常驻工具。数值参数只收紧、不放大,同时按需启用 tool_search/reduction。 | +| `context_profile` | `auto`(默认)为官方 DeepSeek 地址或显式 DeepSeek 推理线路启用节省输入;其他通道可选 `economy` 启用。`custom` 使用运行时配置。`local` 面向 32K–256K 本地模型,收紧上下文预算与工具开销。 | | `reasoning` | 该通道的默认推理扩展字段。不同网关支持差异较大,异常时先尝试 `mode: off`。 | ### 按提供商和模型关闭推理 @@ -88,6 +88,17 @@ ai: GPT-5.6 和 GPT-6 Sol/Luna 在 Chat Completions 中使用函数工具时,应明确选择“关闭”;不指定强度会采用模型默认推理,不等同于关闭。工具与推理不兼容时会提示关闭推理,不会静默改写用户选择的强度。GPT-6.1 Sol 和 GPT-6 Astra 不支持 `none`,工具调用必须使用 Responses;当前 Chat Completions 后端会明确提示该限制,需要选择兼容模型。仅把 `base_url` 改成 Responses URL 不能完成协议适配。详见 [OpenAI 官方推理说明](https://developers.openai.com/api/docs/guides/reasoning)。 `allow_client_reasoning: false` 时忽略对话或请求的推理覆盖,按通道设置执行。 + +### DeepSeek 输入优化 + +升级后,`auto` 在 `api.deepseek.com` 或推理线路为 `deepseek` / `deepseek_compat` 的通道启用以下规则。第三方通道可显式选择 `economy`。 + +- 工具数达到 16 时使用 Pi 原生 `tool_search`,默认常驻前 6 个工具和会话、执行控制、读取文件等核心工具。配置的 `tool_search_always_visible_tools` 继续作为常驻清单,其他内置工具按需发现和调用。 +- 有本地文件读取权限时,超过 8,000 字节的工具结果保存全文并返回首尾预览,模型可用 `read_file` 按行读取中间证据。更小的已配置阈值优先,落盘失败时返回完整内容。 +- 发送给模型的 JSON 工具回包精简格式空白,保留字符串、数字原文和字段顺序。已有会话中的 JSON 工具回包也会在请求时精简,原始会话记录保留完整文本。 + +输出上限和推理强度由通道与对话设置决定。工具检索和分段回读会增加必要调用,收益随工具目录和任务变化。可在「上下文优化档位」选 `custom`,按已有运行时参数控制工具发现与结果缩减。 + ### 本地模型(32K–256K)上下文要点 本地模型的有效上下文通常明显小于标称窗口,且不同后端的“模型上限”和“运行时窗口”可能不一致。建议: diff --git a/docs/zh-CN/token-usage-monitoring.md b/docs/zh-CN/token-usage-monitoring.md index 37ff0802..0bc5900e 100644 --- a/docs/zh-CN/token-usage-monitoring.md +++ b/docs/zh-CN/token-usage-monitoring.md @@ -24,3 +24,5 @@ 在 AI 通道的推理设置中,可用 `off` 处理简单问答和格式转换,或用 `auto` 配合 `low` 保留低强度推理。官方接口未指定强度时默认使用 `high`,`medium` 也映射到 `high`。通道的「单次输出上限」通过 `max_tokens` 发送,推理和正文共用额度。对照面板里的输出、推理 Token 和缓存命中率,可比较相同任务在不同强度下的用量。[DeepSeek 推理模式](https://api-docs.deepseek.com/guides/thinking_mode/) · [Chat Completions](https://api-docs.deepseek.com/api/create-chat-completion/) 官方接口自动缓存可复用的请求前缀。Pi 按名称固定 MCP 工具定义的顺序,以减少相同工具目录在请求之间的前缀变化。缓存命中以供应商返回的用量为准。[DeepSeek 上下文缓存](https://api-docs.deepseek.com/guides/kv_cache/) + +默认 `auto` 上下文档位会为官方 DeepSeek 地址及显式 DeepSeek 线路启用按需工具发现、JSON 回包精简与可回读的大结果预览。具体阈值和 `custom` 选项见[配置说明](configuration.md#deepseek-输入优化)。验证节省效果时,对照完整任务的输入、输出、缓存命中和调用次数,并检查任务产物与证据完整性。 diff --git a/internal/agentruntime/types.go b/internal/agentruntime/types.go index 4989d289..54022c4a 100644 --- a/internal/agentruntime/types.go +++ b/internal/agentruntime/types.go @@ -9,18 +9,19 @@ import ( const ProtocolVersion = 1 type Model struct { - Provider string `json:"provider"` - API string `json:"api,omitempty"` - ID string `json:"id"` - BaseURL string `json:"baseUrl"` - APIKey string `json:"apiKey"` - Headers map[string]string `json:"headers,omitempty"` - ContextWindow int `json:"contextWindow"` - MaxTokens int `json:"maxTokens"` - Thinking string `json:"thinking,omitempty"` - ExtraFields map[string]any `json:"extraFields,omitempty"` - Compat map[string]any `json:"compat,omitempty"` - InputBudget int `json:"inputBudget,omitempty"` + Provider string `json:"provider"` + API string `json:"api,omitempty"` + ID string `json:"id"` + BaseURL string `json:"baseUrl"` + APIKey string `json:"apiKey"` + Headers map[string]string `json:"headers,omitempty"` + ContextWindow int `json:"contextWindow"` + MaxTokens int `json:"maxTokens"` + Thinking string `json:"thinking,omitempty"` + ExtraFields map[string]any `json:"extraFields,omitempty"` + Compat map[string]any `json:"compat,omitempty"` + InputBudget int `json:"inputBudget,omitempty"` + CompactToolJSON bool `json:"compactToolJSON,omitempty"` } type Tool struct { diff --git a/internal/config/config.go b/internal/config/config.go index 2530c59b..15ae7eb9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -731,7 +731,7 @@ type OpenAIConfig struct { Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"` // ContextWindow 是模型原生上下文窗口(token);0 表示未知。用于校验/压缩 max_total_tokens。 ContextWindow int `yaml:"context_window,omitempty" json:"context_window,omitempty"` - // ContextProfile 选择上下文预算档位:""/"auto" 通用;"local" 针对 32K-256K 本地模型收紧预算。 + // ContextProfile selects auto (DeepSeek input savings), economy, custom or local. ContextProfile string `yaml:"context_profile,omitempty" json:"context_profile,omitempty"` // Reasoning 控制 Agent ChatModel 的 thinking / reasoning_effort / output_config 等(Agent 单/多代理路径生效)。 Reasoning OpenAIReasoningConfig `yaml:"reasoning,omitempty" json:"reasoning,omitempty"` @@ -1678,7 +1678,7 @@ func ValidateContextSettings(prefix string, window int, profile string) error { } if raw := strings.TrimSpace(profile); raw != "" && !strings.EqualFold(raw, "auto") && NormalizeContextProfile(raw) == "" { - return fmt.Errorf("%s.context_profile 只支持 auto 或 local", prefix) + return fmt.Errorf("%s.context_profile 只支持 auto、economy、custom 或 local", prefix) } return nil } diff --git a/internal/config/context_profile.go b/internal/config/context_profile.go index a719b558..4f5fe9af 100644 --- a/internal/config/context_profile.go +++ b/internal/config/context_profile.go @@ -23,14 +23,28 @@ const ( ContextWarningMaxCompletionClamped = "max_completion_tokens_clamped" ) -// NormalizeContextProfile 只接受 auto(空)与 local;未知值按 auto 处理,避免配置拼写错误放大预算。 +// NormalizeContextProfile returns an explicit profile, or empty for auto. func NormalizeContextProfile(raw string) string { - if strings.EqualFold(strings.TrimSpace(raw), "local") { - return "local" + switch profile := strings.ToLower(strings.TrimSpace(raw)); profile { + case "local", "economy", "custom": + return profile } return "" } +// IsEconomyContextProfile enables input savings for DeepSeek by default. An +// explicit custom/local profile takes precedence, including on older channels. +func (c OpenAIConfig) IsEconomyContextProfile() bool { + switch NormalizeContextProfile(c.ContextProfile) { + case "economy": + return true + case "custom", "local": + return false + } + profile := c.Reasoning.ProfileEffective() + return c.IsDeepSeekOfficialEndpoint() || profile == "deepseek" || profile == "deepseek_compat" +} + func (c OpenAIConfig) IsLocalContextProfile() bool { return NormalizeContextProfile(c.ContextProfile) == "local" } @@ -148,9 +162,20 @@ func (c *Config) WithEffectiveContextBudget() *Config { return &out } -// EffectiveRuntimeForChannel 在 local 档位下只收紧参数,不放大用户已经设得更小的值。 -// 档位是显式 opt-in;希望完全自定义时使用 auto。 +// EffectiveRuntimeForChannel applies input-saving or local-model limits to a +// runtime copy. Explicit custom profiles use the configured runtime settings. func EffectiveRuntimeForChannel(mw AgentTuningConfig, oa OpenAIConfig) AgentTuningConfig { + if oa.IsEconomyContextProfile() { + out := mw + out.ToolSearchEnable = true + out.ToolSearchMinTools = tightenInt(mw.ToolSearchMinTools, 16) + out.ToolSearchAlwaysVisible = tightenInt(mw.ToolSearchAlwaysVisible, 6) + includeBuiltins := false + out.ToolSearchIncludeBuiltins = &includeBuiltins + out.ReductionEnable = true + out.ReductionMaxLengthForTrunc = tightenInt(mw.ReductionMaxLengthForTruncEffective(), 8000) + return out + } if !oa.IsLocalContextProfile() { return mw } diff --git a/internal/config/context_profile_test.go b/internal/config/context_profile_test.go index 99f63587..37b6655c 100644 --- a/internal/config/context_profile_test.go +++ b/internal/config/context_profile_test.go @@ -306,6 +306,56 @@ func TestEffectiveAgentMiddlewareForChannelAutoUnchanged(t *testing.T) { } } +func TestEconomyContextProfileSelectionAndLimits(t *testing.T) { + for _, tc := range []struct { + name string + oa OpenAIConfig + want bool + }{ + {"official default", OpenAIConfig{BaseURL: "https://api.deepseek.com/v1"}, true}, + {"gateway explicit profile", OpenAIConfig{Reasoning: OpenAIReasoningConfig{Profile: "deepseek_compat"}}, true}, + {"model name alone", OpenAIConfig{Model: "deepseek-flash", BaseURL: "https://gateway.example/v1"}, false}, + {"lookalike host", OpenAIConfig{BaseURL: "https://api.deepseek.com.example/v1"}, false}, + {"custom opt out", OpenAIConfig{BaseURL: "https://api.deepseek.com", ContextProfile: "custom"}, false}, + {"local opt in", OpenAIConfig{BaseURL: "https://api.deepseek.com", ContextProfile: "local"}, false}, + {"economy opt in", OpenAIConfig{ContextProfile: " ECONOMY "}, true}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := tc.oa.IsEconomyContextProfile(); got != tc.want { + t.Fatalf("economy=%v, want %v", got, tc.want) + } + }) + } + includeBuiltins := true + mw := AgentTuningConfig{ToolSearchMinTools: 20, ToolSearchAlwaysVisible: 12, ToolSearchIncludeBuiltins: &includeBuiltins, + ToolSearchAlwaysVisibleTools: []string{"record_vulnerability"}, ReductionMaxLengthForTrunc: 12000} + oa := OpenAIConfig{BaseURL: "https://api.deepseek.com/v1", MaxTotalTokens: 120000, MaxCompletionTokens: 32768, + Reasoning: OpenAIReasoningConfig{Mode: "on", Effort: "high"}} + out := EffectiveRuntimeForChannel(mw, oa) + if !out.ToolSearchEnable || out.ToolSearchMinTools != 16 || out.ToolSearchAlwaysVisible != 6 || out.ToolSearchIncludeBuiltinsEffective() || !out.ReductionEnable || out.ReductionMaxLengthForTrunc != 8000 { + t.Fatalf("unexpected economy runtime: %+v", out) + } + if !reflect.DeepEqual(out.ToolSearchAlwaysVisibleTools, mw.ToolSearchAlwaysVisibleTools) || !*mw.ToolSearchIncludeBuiltins || mw.ToolSearchEnable { + t.Fatal("explicit visible tools or original config modified") + } + if again := EffectiveRuntimeForChannel(out, oa); !reflect.DeepEqual(out, again) { + t.Fatal("economy profile is not idempotent") + } + out.ToolSearchMinTools, out.ToolSearchAlwaysVisible, out.ReductionMaxLengthForTrunc = 4, 2, 2048 + if again := EffectiveRuntimeForChannel(out, oa); !reflect.DeepEqual(out, again) { + t.Fatal("economy profile loosened tighter limits") + } + for _, profile := range []string{"auto", "economy", "custom", "local"} { + if err := ValidateContextSettings("channel", 0, profile); err != nil { + t.Fatal(err) + } + } + oa.ContextProfile = "custom" + if got := EffectiveRuntimeForChannel(mw, oa); !reflect.DeepEqual(got, mw) { + t.Fatal("custom profile did not preserve runtime settings") + } +} + func TestWithEffectiveContextBudgetIsIdempotent(t *testing.T) { t.Parallel() cfg := &Config{ diff --git a/internal/handler/config.go b/internal/handler/config.go index 97daf326..2e33bbc6 100644 --- a/internal/handler/config.go +++ b/internal/handler/config.go @@ -352,6 +352,11 @@ func (h *ConfigHandler) GetConfig(c *gin.Context) { if load, err := agents.LoadMarkdownAgentsDir(agentsDir); err == nil { subAgentCount = len(agents.MergeYAMLAndMarkdown(h.config.MultiAgent.SubAgents, load.SubAgents)) } + effectiveRuntime := config.EffectiveRuntimeForChannel(h.config.MultiAgent.Runtime, h.config.OpenAI) + builtinAlwaysVisible := builtin.GetAllBuiltinTools() + if !effectiveRuntime.ToolSearchIncludeBuiltinsEffective() { + builtinAlwaysVisible = []string{builtin.ToolGetToolExecution, builtin.ToolWaitToolExecution, builtin.ToolCancelToolExecution} + } multiPub := config.MultiAgentPublic{ Enabled: h.config.MultiAgent.Enabled, RobotDefaultAgentMode: config.NormalizeRobotAgentMode(h.config.MultiAgent), @@ -366,7 +371,7 @@ func (h *ConfigHandler) GetConfig(c *gin.Context) { ToolSearchAlwaysVisibleTools: append([]string(nil), h.config.MultiAgent.Runtime.ToolSearchAlwaysVisibleTools...), ToolSearchAlwaysVisibleEffectiveTools: mergeToolNameLists( h.config.MultiAgent.Runtime.ToolSearchAlwaysVisibleTools, - builtin.GetAllBuiltinTools(), + builtinAlwaysVisible, ), } diff --git a/internal/multiagent/pi_integration_test.go b/internal/multiagent/pi_integration_test.go index 5b060745..dea237fc 100644 --- a/internal/multiagent/pi_integration_test.go +++ b/internal/multiagent/pi_integration_test.go @@ -9,6 +9,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "slices" "strings" "sync" @@ -17,9 +18,11 @@ import ( "time" "cyberstrike-ai/internal/agent" + "cyberstrike-ai/internal/authctx" "cyberstrike-ai/internal/config" "cyberstrike-ai/internal/database" "cyberstrike-ai/internal/mcp" + "cyberstrike-ai/internal/mcp/builtin" "go.uber.org/zap" ) @@ -244,6 +247,113 @@ func TestPiDeepSeekOutputBudgetAndUsage(t *testing.T) { } } +func TestPiDeepSeekEconomyDiscoversToolsAndReadsFullEvidence(t *testing.T) { + full := strings.Repeat("fixture output line with details\n", 150) + "MIDDLE_EVIDENCE\n" + strings.Repeat("trailing output line with details\n", 150) + "end" + var baselineBytes, optimizedBytes int + for _, profile := range []string{"custom", "auto"} { + t.Run(profile, func(t *testing.T) { + cfg := piTestConfig(t) + cfg.OpenAI.Reasoning.Profile = "deepseek" + cfg.OpenAI.ContextProfile = profile + cfg.MultiAgent.Skills.Disable = false + cfg.MultiAgent.Runtime.ToolSearchEnable = true + cfg.MultiAgent.Runtime.ReductionRootDir = t.TempDir() + var calls int + var originalPath string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + var body struct { + Tools json.RawMessage `json:"tools"` + Messages []struct { + Role string + Content any + } `json:"messages"` + } + if err := json.NewDecoder(req.Body).Decode(&body); err != nil { + t.Error(err) + return + } + calls++ + if profile == "custom" { + baselineBytes = len(body.Tools) + piReply(w, "", "", nil, "baseline") + return + } + switch calls { + case 1: + optimizedBytes = len(body.Tools) + if strings.Contains(string(body.Tools), `"name":"record_vulnerability"`) { + t.Error("unused builtin schema was exposed before discovery") + } + piReply(w, "tool_search", "discover", map[string]any{"query": "record_vulnerability", "limit": 1}, "") + case 2: + if !strings.Contains(string(body.Tools), `"name":"record_vulnerability"`) { + t.Error("discovered tool is unavailable") + } + if !strings.Contains(string(body.Tools), `"name":"read_file"`) { + t.Error("read_file was lost during tool discovery") + } + piReply(w, "record_vulnerability", "record", map[string]any{"text": "fixture"}, "") + case 3: + preview, _ := body.Messages[len(body.Messages)-1].Content.(string) + match := regexp.MustCompile(`Full output saved to: ([^\n]+)`).FindStringSubmatch(preview) + if len(match) != 2 || len(preview) > 8000 || strings.Contains(preview, "MIDDLE_EVIDENCE") { + t.Errorf("expected recoverable preview, got %d bytes", len(preview)) + piReply(w, "", "", nil, "failed preview") + return + } + originalPath = match[1] + t.Logf("tool result bytes: full=%d preview=%d", len(full)+1, len(preview)) + piReply(w, "read_file", "read", map[string]any{"path": originalPath, "offset": 151, "limit": 1}, "") + case 4: + if got := body.Messages[len(body.Messages)-1].Content; got != "MIDDLE_EVIDENCE" { + t.Errorf("evidence readback=%q", got) + } + piReply(w, "", "", nil, "verified middle evidence") + default: + t.Error("unexpected retry") + piReply(w, "", "", nil, "unexpected") + } + })) + defer server.Close() + cfg.OpenAI.BaseURL = server.URL + "/v1" + srv := mcp.NewServer(zap.NewNop()) + srv.ConfigureToolResultSpillRoot(t.TempDir()) + srv.SetToolAuthorizer(func(context.Context, string, map[string]interface{}) error { return nil }) + var executed int + for _, name := range builtin.GetAllBuiltinTools() { + srv.RegisterTool(mcp.Tool{Name: name, Description: "Fixture operation " + name, + InputSchema: piToolSchema(map[string]any{"text": map[string]any{"type": "string", "description": "Fixture evidence text"}}, "text")}, + func(context.Context, map[string]interface{}) (*mcp.ToolResult, error) { + executed++ + return &mcp.ToolResult{Content: []mcp.Content{{Type: "text", Text: full}}}, nil + }) + } + ag := agent.NewAgent(&cfg.OpenAI, &cfg.Agent, srv, nil, zap.NewNop(), 8) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + ctx = authctx.WithPrincipal(ctx, authctx.NewPrincipal("fixture", "fixture", "all", map[string]bool{"agent:local-execute": true})) + res, err := RunSingleAgent(ctx, cfg, &cfg.MultiAgent, ag, nil, zap.NewNop(), "economy-fixture", "", "Read the evidence", nil, nil, nil, nil, "") + if err != nil || res == nil || res.RuntimeStatus != "completed" { + t.Fatalf("result=%+v error=%v", res, err) + } + if profile == "auto" { + if calls != 4 || executed != 1 || res.Response != "verified middle evidence" { + t.Fatalf("calls=%d executed=%d result=%+v", calls, executed, res) + } + b, err := os.ReadFile(originalPath) + // The host adds a newline after each MCP text block. + if err != nil || string(b) != full+"\n" { + t.Fatalf("full evidence changed: err=%v got=%d want=%d", err, len(b), len(full)+1) + } + } + }) + } + if optimizedBytes >= baselineBytes/2 { + t.Errorf("tool schema savings too small: custom=%d auto=%d", baselineBytes, optimizedBytes) + } + t.Logf("first-request tool schema bytes: custom=%d auto=%d", baselineBytes, optimizedBytes) +} + func TestPiBackgroundGenerationReturnsProposalWithoutExecutingTools(t *testing.T) { for _, provider := range []string{"openai", "claude"} { t.Run(provider, func(t *testing.T) { diff --git a/internal/multiagent/pi_model.go b/internal/multiagent/pi_model.go index f4f4b675..7b73d53c 100644 --- a/internal/multiagent/pi_model.go +++ b/internal/multiagent/pi_model.go @@ -50,5 +50,5 @@ func piModelConfig(oa config.OpenAIConfig, intent *reasoning.ClientIntent, conve compat["requiresReasoningContentOnAssistantMessages"] = true compat["maxTokensField"] = "max_tokens" } - return agentruntime.Model{Provider: provider, API: api, ID: oa.Model, BaseURL: base, APIKey: oa.APIKey, Headers: headers, ContextWindow: window, InputBudget: budget, MaxTokens: oa.MaxCompletionTokensEffective(), Thinking: thinking, ExtraFields: extra, Compat: compat} + return agentruntime.Model{Provider: provider, API: api, ID: oa.Model, BaseURL: base, APIKey: oa.APIKey, Headers: headers, ContextWindow: window, InputBudget: budget, MaxTokens: oa.MaxCompletionTokensEffective(), Thinking: thinking, ExtraFields: extra, Compat: compat, CompactToolJSON: oa.IsEconomyContextProfile()} } diff --git a/internal/multiagent/pi_runner.go b/internal/multiagent/pi_runner.go index ffc1fafd..3e0b5330 100644 --- a/internal/multiagent/pi_runner.go +++ b/internal/multiagent/pi_runner.go @@ -406,7 +406,16 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { result.IsError = true } if r.cfg.MultiAgent.Runtime.ReductionEnable { - result.Content = tooloutput.BoundWithSpill(result.Content, r.cfg.MultiAgent.Runtime.ReductionMaxLengthForTruncEffective(), tooloutput.SpillOpts{RootDir: r.cfg.MultiAgent.Runtime.ReductionRootDir, ConversationID: r.conversationID, ExecutionID: result.ExecutionID}) + limit := r.cfg.MultiAgent.Runtime.ReductionMaxLengthForTruncEffective() + opts := tooloutput.SpillOpts{RootDir: r.cfg.MultiAgent.Runtime.ReductionRootDir, ConversationID: r.conversationID, ExecutionID: result.ExecutionID} + if oa.IsEconomyContextProfile() { + // Automatic previews require an authorized way to read the full evidence. + if localNames["read_file"] { + result.Content = tooloutput.ReduceForModel(result.Content, limit, opts) + } + } else { + result.Content = tooloutput.BoundWithSpill(result.Content, limit, opts) + } } progress("tool_result", result.Content, map[string]any{"toolName": call.Name, "toolCallId": call.ID, "executionId": result.ExecutionID, "result": result.Content, "success": !result.IsError, "isError": result.IsError, "agentFacing": true}) return result, err diff --git a/internal/tooloutput/economy_test.go b/internal/tooloutput/economy_test.go new file mode 100644 index 00000000..72d8a057 --- /dev/null +++ b/internal/tooloutput/economy_test.go @@ -0,0 +1,38 @@ +package tooloutput + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestReduceForModelRetainsEvidence(t *testing.T) { + jsonText := "{\n \"id\": 9007199254740993,\n \"value\": \"keep spaces\\n\",\n \"id\": 2\n}" + if got := ReduceForModel(jsonText, 8000, SpillOpts{}); got != `{"id":9007199254740993,"value":"keep spaces\n","id":2}` { + t.Fatalf("JSON value or numeric precision changed: %s", got) + } + full := strings.Repeat("first line\n", 1000) + "middle evidence\n" + strings.Repeat("last line\n", 1000) + root := t.TempDir() + opts := SpillOpts{RootDir: root, ConversationID: "fixture", ExecutionID: "result"} + preview := ReduceForModel(full, 8000, opts) + if len(preview) >= len(full) || len(preview) > 8000 || !strings.Contains(preview, "read_file") { + t.Fatalf("invalid preview: %d bytes", len(preview)) + } + b, err := os.ReadFile(filepath.Join(SessionRoot(root, "", "fixture"), "trunc", "result")) + if err != nil || string(b) != full { + t.Fatalf("original evidence lost: %v", err) + } + ReduceForModel(preview, 1024, opts) + b, err = os.ReadFile(filepath.Join(SessionRoot(root, "", "fixture"), "trunc", "result")) + if err != nil || string(b) != full { + t.Fatal("reducing an existing preview overwrote full evidence") + } + blocked := filepath.Join(root, "file") + if err := os.WriteFile(blocked, []byte("file"), 0600); err != nil { + t.Fatal(err) + } + if got := ReduceForModel(full, 8000, SpillOpts{RootDir: blocked}); got != full { + t.Fatal("failed spill lost evidence") + } +} diff --git a/internal/tooloutput/spill.go b/internal/tooloutput/spill.go index 1352e219..e5f0ca72 100644 --- a/internal/tooloutput/spill.go +++ b/internal/tooloutput/spill.go @@ -4,6 +4,8 @@ package tooloutput import ( + "bytes" + "encoding/json" "fmt" "os" "path/filepath" @@ -14,6 +16,30 @@ import ( "github.com/google/uuid" ) +// ReduceForModel first removes JSON formatting whitespace. If the result still +// exceeds the limit, retain the exact original evidence and return a preview. +// A failed spill keeps the content available to the model. +func ReduceForModel(full string, maxBytes int, opts SpillOpts) string { + // The MCP storage guard may already have saved this execution under the + // same path. Spilling its notice again would overwrite the original file. + if strings.HasPrefix(strings.TrimSpace(full), "") { + return full + } + compact := full + var buf bytes.Buffer + if json.Compact(&buf, []byte(full)) == nil { + compact = buf.String() + } + if maxBytes <= 0 || len(compact) <= maxBytes { + return compact + } + path, err := WriteTruncFile(opts, full) + if err != nil { + return compact + } + return FormatPersistedOutput(full, path, maxBytes) +} + const ( defaultRootDir = "tmp/reduction" readFileHint = "read_file" diff --git a/runtime/pi/src/tool-output.ts b/runtime/pi/src/tool-output.ts new file mode 100644 index 00000000..b4f47ca2 --- /dev/null +++ b/runtime/pi/src/tool-output.ts @@ -0,0 +1,13 @@ +// Compact only valid JSON containers. Retain the original numeric lexemes, +// key order, duplicate keys and string escapes instead of reserializing parsed +// values. Stored session messages and evidence keep their original text. +export function compactToolJSON(text: string): string { + const start = text.trimStart()[0]; + if (start !== "{" && start !== "[") return text; + try { + JSON.parse(text); + } catch { + return text; + } + return text.replace(/"(?:[^"\\]|\\.)*"|\s+/g, part => part.startsWith('"') ? part : ""); +} diff --git a/runtime/pi/src/worker.ts b/runtime/pi/src/worker.ts index 777f140f..732fabe6 100644 --- a/runtime/pi/src/worker.ts +++ b/runtime/pi/src/worker.ts @@ -9,6 +9,7 @@ import { } from "@earendil-works/pi-coding-agent"; import { PROTOCOL_VERSION, RecordReader, send } from "./protocol.js"; import { installModelFetchPolicy } from "./network.js"; +import { compactToolJSON } from "./tool-output.js"; installModelFetchPolicy(); @@ -18,6 +19,7 @@ interface ModelConfig { contextWindow: number; maxTokens: number; thinking?: string; extraFields?: Record; compat?: Record; inputBudget?: number; + compactToolJSON?: boolean; } interface RunRequest { generateOnly?: boolean; @@ -208,20 +210,29 @@ async function run(req: RunRequest): Promise { modelConfigs.set(provider, config); } const streamSimple = runtime.streamSimple.bind(runtime); - runtime.streamSimple = (m, context, options) => streamSimple(m, - m.api === "openai-completions" ? { ...context, messages: pairToolResults(context.messages) } : context, { - ...options, - transport: "sse", - onPayload: async (original, currentModel) => { - const transformed = (await options?.onPayload?.(original, currentModel)) ?? original; - if (!transformed || typeof transformed !== "object") return transformed; - const payload = { ...transformed, ...modelConfigs.get(currentModel.provider)?.extraFields } as Record; - for (const key of ["model", "messages", "tools", "stream"]) { - if (key in transformed) payload[key] = (transformed as Record)[key]; - } - return payload; - }, - }); + runtime.streamSimple = (m, context, options) => { + let messages = context.messages; + if (modelConfigs.get(m.provider)?.compactToolJSON) { + messages = messages.map(message => message.role === "toolResult" ? { + ...message, + content: message.content.map(block => block.type === "text" ? { ...block, text: compactToolJSON(block.text) } : block), + } : message); + } + if (m.api === "openai-completions") messages = pairToolResults(messages); + return streamSimple(m, { ...context, messages }, { + ...options, + transport: "sse", + onPayload: async (original, currentModel) => { + const transformed = (await options?.onPayload?.(original, currentModel)) ?? original; + if (!transformed || typeof transformed !== "object") return transformed; + const payload = { ...transformed, ...modelConfigs.get(currentModel.provider)?.extraFields } as Record; + for (const key of ["model", "messages", "tools", "stream"]) { + if (key in transformed) payload[key] = (transformed as Record)[key]; + } + return payload; + }, + }); + }; let model = physical[0]; if (physical.length > 1) { runtime.registerVirtualModel({ provider: "cyberstrike-router", id: "auto", name: "CyberStrikeAI channels", @@ -255,7 +266,7 @@ async function run(req: RunRequest): Promise { if (manager.getEntryCount() === 0) importHistory(manager, req.history ?? [], req.model); repairInterruptedCalls(manager); const searchEnabled = req.toolSearch === true && names.length >= (req.toolSearchMinTools || 20) && !names.includes("tool_search"); - const always = new Set(["task", "exit", "transfer_to_agent", "write_todos", "TaskCreate", "TaskUpdate", "TaskGet", "TaskList", "skill", "read_file", "execute", "wait_tool_execution", "get_tool_execution", ...(req.alwaysVisibleTools ?? [])]); + const always = new Set(["task", "exit", "transfer_to_agent", "write_todos", "TaskCreate", "TaskUpdate", "TaskGet", "TaskList", "skill", "read_file", "execute", "wait_tool_execution", "get_tool_execution", "cancel_tool_execution", ...(req.alwaysVisibleTools ?? [])]); const loader = resources(req.systemPrompt + (searchEnabled ? "\nDiscover additional task tools with tool_search. Search results enable matching tools for subsequent calls." : "")); if (searchEnabled) { const extensions = new DefaultResourceLoader({ cwd: scratch, agentDir: scratch, settingsManager: SettingsManager.inMemory(), diff --git a/runtime/pi/test/tool-output.test.mjs b/runtime/pi/test/tool-output.test.mjs new file mode 100644 index 00000000..3ab44585 --- /dev/null +++ b/runtime/pi/test/tool-output.test.mjs @@ -0,0 +1,11 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { compactToolJSON } from "../dist/tool-output.js"; + +test("tool JSON compaction preserves evidence, numeric lexemes and duplicate keys", () => { + const input = '{\n "id": 9007199254740993, "id": 2, "small": 1e-99,\n "text": "a b\\n\\t\\\"quoted\\\"", "nested": [ 1, 2 ]\n}'; + assert.equal(compactToolJSON(input), '{"id":9007199254740993,"id":2,"small":1e-99,"text":"a b\\n\\t\\\"quoted\\\"","nested":[1,2]}'); + for (const text of ['{ broken json }', ' ordinary text\n', '"a string"', '[output] partial', '']) { + assert.equal(compactToolJSON(text), text); + } +}); diff --git a/runtime/pi/test/worker.test.mjs b/runtime/pi/test/worker.test.mjs index 68f78ad4..10f256ee 100644 --- a/runtime/pi/test/worker.test.mjs +++ b/runtime/pi/test/worker.test.mjs @@ -286,6 +286,39 @@ test("native tool search loads a deferred host tool without exposing the full ca assert.equal(hostCalls, 1); }); +test("economy compacts persisted tool JSON while preserving reasoning and original session evidence", { timeout: 30000 }, async t => { + const raw = '{\n "id": 9007199254740993,\n "evidence": "keep spaces\\n"\n}'; + const fixture = await startFixture(t, (_, res, count) => { + if (count === 1) sse(res, { role: "assistant", reasoning_content: "inspect fixture", tool_calls: [{ index: 0, id: "inspect", type: "function", function: { name: "echo", arguments: '{"text":"fixture"}' } }] }, "tool_calls"); + else sse(res, { role: "assistant", content: "evidence inspected" }, "stop"); + }); + const dir = await mkdtemp(join(tmpdir(), "csai-pi-economy-")); + t.after(() => rm(dir, { recursive: true, force: true })); + const req = request(fixture.url, dir); + req.tools.push(...Array.from({ length: 30 }, (_, i) => ({ name: "old_unused_" + i, description: "Unused fixture operation", parameters: { type: "object", properties: {} } }))); + req.model.thinking = "high"; + req.model.compat = { thinkingFormat: "deepseek", requiresReasoningContentOnAssistantMessages: true }; + req.model.extraFields = { thinking: { type: "enabled" }, reasoning_effort: "high" }; + const first = await invoke(t, req, (r, send) => { + if (r.type === "tool_call") send({ type: "tool_result", id: r.call.id, result: { content: raw } }); + }); + assert.equal(first.result.status, "completed", first.result.error); + assert.equal(fixture.requests[1].messages.find(m => m.role === "tool").content, raw); + + req.model.compactToolJSON = true; + const resumed = await invoke(t, { ...req, toolSearch: true, alwaysVisibleTools: ["echo"], runId: "economy-resume", message: "Continue" }); + assert.equal(resumed.result.status, "completed", resumed.result.error); + const body = fixture.requests[2]; + assert.equal(fixture.requests[0].tools.length, 31); + assert.deepEqual(body.tools.map(t => t.function.name).sort(), ["echo", "tool_search"]); + assert.equal(body.messages.find(m => m.role === "tool").content, '{"id":9007199254740993,"evidence":"keep spaces\\n"}'); + assert.ok(body.messages.some(m => m.reasoning_content === "inspect fixture")); + assert.equal(body.reasoning_effort, "high"); + assert.equal(resumed.result.history.find(m => m.role === "tool").content, raw); + const entries = (await readFile(first.result.sessionFile, "utf8")).trim().split("\n").map(line => JSON.parse(line)); + assert.ok(entries.some(e => e.message?.role === "toolResult" && e.message.content.some(b => b.text === raw))); +}); + test("provider custom credentials never cross a redirect origin", { timeout: 30000 }, async t => { let targetCalls = 0; const target = createServer((_, res) => { targetCalls++; res.end("unexpected"); }); diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index 33698944..7b0d950c 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -3097,9 +3097,11 @@ "contextWindowPlaceholder": "131072", "contextWindowHint": "Native model window used to validate and clamp the budget. For local models, match the server num_ctx/ctx-size.", "contextProfile": "Context Optimization Profile", - "contextProfileAuto": "General (default)", + "contextProfileAuto": "Auto (input savings for DeepSeek)", + "contextProfileEconomy": "Save input tokens", + "contextProfileCustom": "Custom (use runtime settings)", "contextProfileLocal": "Local model (32K-256K optimized)", - "contextProfileHint": "The local profile tightens compaction triggers, tool-output limits, and always-visible tools. It only tightens existing settings.", + "contextProfileHint": "Input savings load tools on demand, compact JSON results and preview large results with access to the full output. The local profile also tightens context budgets.", "detectContext": "Auto-detect", "detectContextFillRequired": "Fill in Base URL and model first", "detectedContext": "Detected {tokens} tokens", diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index 09fe5223..b063eb8d 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -3110,9 +3110,11 @@ "contextWindowPlaceholder": "131072", "contextWindowHint": "Собственное окно модели для проверки и ограничения бюджета. Для локальных моделей укажите серверный num_ctx/ctx-size.", "contextProfile": "Профиль оптимизации контекста", - "contextProfileAuto": "Общий (по умолчанию)", + "contextProfileAuto": "Авто (экономия для DeepSeek)", + "contextProfileEconomy": "Экономия входных токенов", + "contextProfileCustom": "Свой профиль (настройки среды)", "contextProfileLocal": "Локальная модель (32K-256K)", - "contextProfileHint": "Локальный профиль ужесточает пороги сжатия, лимиты вывода инструментов и число постоянных инструментов. Он только уменьшает существующие значения.", + "contextProfileHint": "Экономия загружает инструменты по запросу, уплотняет JSON и показывает превью больших результатов с доступом к полному выводу. Локальный профиль также ограничивает контекст.", "detectContext": "Автоопределение", "detectContextFillRequired": "Сначала заполните Base URL и модель", "detectedContext": "Обнаружено {tokens} токенов", diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index 92aa44ed..f2e38aa3 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -3085,9 +3085,11 @@ "contextWindowPlaceholder": "131072", "contextWindowHint": "模型原生窗口;用于校验并收紧预算。本地模型请按服务端 num_ctx/ctx-size 填写。", "contextProfile": "上下文优化档位", - "contextProfileAuto": "通用(默认)", + "contextProfileAuto": "自动(DeepSeek 启用节省)", + "contextProfileEconomy": "节省输入", + "contextProfileCustom": "自定义(使用运行时配置)", "contextProfileLocal": "本地模型(32K-256K 优化)", - "contextProfileHint": "本地档位会收紧压缩触发、工具输出阈值和常驻工具数;只收紧不放大已有配置。", + "contextProfileHint": "节省输入按需加载工具、精简 JSON 回包,并为大结果提供可回读的预览。本地档位同时收紧上下文预算。", "detectContext": "自动检测", "detectContextFillRequired": "请先填写 Base URL 和模型", "detectedContext": "检测到 {tokens} tokens", diff --git a/web/static/js/settings.js b/web/static/js/settings.js index 98a7fd0c..70b7c29e 100644 --- a/web/static/js/settings.js +++ b/web/static/js/settings.js @@ -2700,7 +2700,7 @@ function writeAIChannelToMainForm(id) { const contextWindowEl = document.getElementById('openai-context-window'); if (contextWindowEl) contextWindowEl.value = ch.context_window || ''; const contextProfileEl = document.getElementById('openai-context-profile'); - if (contextProfileEl) contextProfileEl.value = ['auto', 'local'].includes(String(ch.context_profile || '').toLowerCase()) ? String(ch.context_profile).toLowerCase() : 'auto'; + if (contextProfileEl) contextProfileEl.value = ['auto', 'economy', 'custom', 'local'].includes(String(ch.context_profile || '').toLowerCase()) ? String(ch.context_profile).toLowerCase() : 'auto'; const r = ch.reasoning || {}; const modeEl = document.getElementById('openai-reasoning-mode'); if (modeEl) { diff --git a/web/templates/index.html b/web/templates/index.html index c3f98f9a..75c4ea5d 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -3788,10 +3788,12 @@
- 本地档位会收紧压缩触发、工具输出阈值和常驻工具数;只收紧不放大已有配置。 + 节省输入按需加载工具、精简 JSON 回包,并为大结果提供可回读的预览。本地档位同时收紧上下文预算。