From 4c0d42c4cb64df3f9bcbdc896eda5374d9d00598 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Wed, 2 Sep 2026 22:00:38 +0800 Subject: [PATCH] feat(agent): keep long sandbox turns from truncating, overflowing, or rewriting files Refuse truncated tool calls, compact-and-retry once on overflow, and let sandbox files be appended, paged, and batch-edited instead of rewritten. Models can set context_window (default 200K) so compaction sizes itself from the real window; agent max_iterations of -1 means unlimited. --- cli/cmd/agent/view.go | 4 +- client/agent_manage.go | 2 +- config/builtin_models.yaml.example | 2 + docs/BUILTIN_MODELS.md | 2 + docs/api/agent.md | 2 +- docs/api/tenant.md | 2 +- docs/docs.go | 2 +- docs/swagger.json | 2 +- docs/swagger.yaml | 2 +- frontend/src/api/agent/index.ts | 2 +- frontend/src/api/model/index.ts | 3 + .../src/assets/img/context-compaction.svg | 5 + frontend/src/components/Input-field.vue | 75 +++- frontend/src/components/ModelDebugDrawer.vue | 11 +- frontend/src/components/ModelEditorDialog.vue | 13 + frontend/src/components/ModelSelector.vue | 94 ++++- .../src/composables/useChatStreamHandler.ts | 24 +- frontend/src/i18n/locales/en-US.ts | 14 +- frontend/src/i18n/locales/ko-KR.ts | 14 +- frontend/src/i18n/locales/ru-RU.ts | 14 +- frontend/src/i18n/locales/zh-CN.ts | 14 +- frontend/src/stores/chatResources.ts | 18 + frontend/src/utils/contextWindow.test.ts | 41 ++ frontend/src/utils/contextWindow.ts | 44 ++ frontend/src/views/agent/AgentEditorModal.vue | 40 +- .../chat/components/AgentStreamDisplay.vue | 60 +++ .../knowledge/KnowledgeBaseEditorModal.vue | 6 + frontend/src/views/settings/ModelSettings.vue | 38 ++ .../views/settings/WeKnoraCloudSettings.vue | 3 + internal/agent/act.go | 138 ++++--- internal/agent/compaction/compaction_test.go | 382 ++++++++++++++++++ internal/agent/compaction/compactor.go | 245 +++++++++++ internal/agent/compaction/cutpoint.go | 118 ++++++ internal/agent/compaction/fileops.go | 181 +++++++++ internal/agent/compaction/fileops_test.go | 90 +++++ internal/agent/compaction/overflow.go | 116 ++++++ internal/agent/compaction/overflow_test.go | 93 +++++ internal/agent/compaction/prepare.go | 145 +++++++ internal/agent/compaction/prompts.go | 82 ++++ internal/agent/compaction/serialize.go | 128 ++++++ internal/agent/compaction/settings.go | 112 +++++ internal/agent/const.go | 50 ++- internal/agent/context_debug.go | 169 ++++++++ internal/agent/engine.go | 171 ++++++-- internal/agent/engine_test.go | 234 +++++++++++ internal/agent/finalize.go | 2 +- internal/agent/memory/consolidator.go | 337 --------------- internal/agent/memory/consolidator_test.go | 374 ----------------- internal/agent/observe.go | 243 ++++++++--- internal/agent/observe_test.go | 177 ++++++-- internal/agent/prompts.go | 41 +- internal/agent/prompts_shell_test.go | 29 +- internal/agent/think.go | 121 +++++- internal/agent/token/compress.go | 107 ----- internal/agent/token/estimator.go | 55 ++- internal/agent/token/estimator_test.go | 297 +++----------- internal/agent/tools/file_mutation_queue.go | 88 ++++ .../agent/tools/file_mutation_queue_test.go | 120 ++++++ internal/agent/tools/json_repair.go | 31 +- internal/agent/tools/sandbox_edit.go | 218 ++++++++-- internal/agent/tools/sandbox_edit_test.go | 157 ++++++- internal/agent/tools/sandbox_read.go | 322 ++++++++++++--- internal/agent/tools/sandbox_read_test.go | 254 +++++++++++- internal/agent/tools/sandbox_write.go | 244 +++++++++-- internal/agent/tools/sandbox_write_test.go | 195 ++++++++- internal/agent/tools/shell_exec.go | 25 +- internal/agent/tools/shell_exec_test.go | 27 ++ internal/agent/tools/skill_file.go | 7 +- internal/agent/tools/skill_file_tree_test.go | 70 ++++ internal/agent/tools/skill_read.go | 101 ++++- internal/application/service/agent_service.go | 17 +- .../application/service/agent_service_test.go | 19 + .../application/service/session_agent_qa.go | 31 +- .../service/tenant_skill_install.go | 4 +- internal/errors/errors.go | 2 +- internal/event/event.go | 4 + internal/event/event_data.go | 19 + internal/handler/dto/model.go | 9 +- .../handler/session/agent_stream_handler.go | 34 ++ internal/models/chat/chat.go | 15 + internal/models/chat/openai_stream.go | 11 +- internal/types/agent.go | 63 ++- internal/types/agent_test.go | 32 +- internal/types/chat.go | 11 + internal/types/custom_agent.go | 7 +- internal/types/custom_agent_test.go | 22 + internal/types/model.go | 9 + website-docs/03-features/06-models.md | 1 + website-docs/03-features/07-agent.md | 38 +- 89 files changed, 5447 insertions(+), 1550 deletions(-) create mode 100644 frontend/src/assets/img/context-compaction.svg create mode 100644 frontend/src/utils/contextWindow.test.ts create mode 100644 frontend/src/utils/contextWindow.ts create mode 100644 internal/agent/compaction/compaction_test.go create mode 100644 internal/agent/compaction/compactor.go create mode 100644 internal/agent/compaction/cutpoint.go create mode 100644 internal/agent/compaction/fileops.go create mode 100644 internal/agent/compaction/fileops_test.go create mode 100644 internal/agent/compaction/overflow.go create mode 100644 internal/agent/compaction/overflow_test.go create mode 100644 internal/agent/compaction/prepare.go create mode 100644 internal/agent/compaction/prompts.go create mode 100644 internal/agent/compaction/serialize.go create mode 100644 internal/agent/compaction/settings.go create mode 100644 internal/agent/context_debug.go delete mode 100644 internal/agent/memory/consolidator.go delete mode 100644 internal/agent/memory/consolidator_test.go delete mode 100644 internal/agent/token/compress.go create mode 100644 internal/agent/tools/file_mutation_queue.go create mode 100644 internal/agent/tools/file_mutation_queue_test.go create mode 100644 internal/agent/tools/skill_file_tree_test.go diff --git a/cli/cmd/agent/view.go b/cli/cmd/agent/view.go index 7edf2c56..c384c0b1 100644 --- a/cli/cmd/agent/view.go +++ b/cli/cmd/agent/view.go @@ -146,7 +146,9 @@ func renderAgent(w io.Writer, a *sdk.Agent) { if c.MaxCompletionTokens != 0 { llm = append(llm, row{"Max completion tokens", fmt.Sprintf("%d", c.MaxCompletionTokens)}) } - if c.MaxIterations != 0 { + if c.MaxIterations < 0 { + llm = append(llm, row{"Max iterations", "unlimited"}) + } else if c.MaxIterations != 0 { llm = append(llm, row{"Max iterations", fmt.Sprintf("%d", c.MaxIterations)}) } if c.AgentMode != "" { diff --git a/client/agent_manage.go b/client/agent_manage.go index 136c045e..e8267935 100644 --- a/client/agent_manage.go +++ b/client/agent_manage.go @@ -83,7 +83,7 @@ type AgentConfig struct { MaxCompletionTokens int `json:"max_completion_tokens"` Thinking *bool `json:"thinking"` CitationEnabled *bool `json:"citation_enabled"` - MaxIterations int `json:"max_iterations"` + MaxIterations int `json:"max_iterations"` // -1 = unlimited LLMCallTimeout int `json:"llm_call_timeout,omitempty"` AllowedTools []string `json:"allowed_tools"` MCPSelectionMode string `json:"mcp_selection_mode"` diff --git a/config/builtin_models.yaml.example b/config/builtin_models.yaml.example index a873a3bc..f0a18a24 100644 --- a/config/builtin_models.yaml.example +++ b/config/builtin_models.yaml.example @@ -39,6 +39,7 @@ builtin_models: [] # base_url: ${LLM_BASE_URL} # api_key: ${LLM_API_KEY} # provider: ${LLM_PROVIDER} # openai | generic | aliyun | moonshot | ... +# context_window: 200000 # optional; omit to use the 200K default # # - id: builtin-embedding-default # type: Embedding @@ -73,3 +74,4 @@ builtin_models: [] # base_url: https://api.openai.com/v1 # api_key: ${OPENAI_API_KEY} # provider: openai +# context_window: 200000 # optional; omit to use the 200K default diff --git a/docs/BUILTIN_MODELS.md b/docs/BUILTIN_MODELS.md index b4fe9bba..3b1eb4d8 100644 --- a/docs/BUILTIN_MODELS.md +++ b/docs/BUILTIN_MODELS.md @@ -45,6 +45,7 @@ builtin_models: base_url: api_key: provider: # openai | generic | moonshot | ... + context_window: # 对话/VLM 上下文窗口(token);省略则默认 200000 embedding_parameters: # 仅 Embedding 类型 dimension: truncate_prompt_tokens: @@ -64,6 +65,7 @@ builtin_models: base_url: https://api.openai.com/v1 api_key: ${OPENAI_API_KEY} provider: openai + context_window: 200000 - id: builtin-openai-embeddings name: text-embedding-3-small diff --git a/docs/api/agent.md b/docs/api/agent.md index 4463a427..a41d46a3 100644 --- a/docs/api/agent.md +++ b/docs/api/agent.md @@ -432,7 +432,7 @@ curl --location 'http://localhost:8080/api/v1/agents/placeholders' \ | 参数 | 类型 | 默认值 | 说明 | |------|------|--------|------| -| `max_iterations` | int | 10 | ReAct 最大迭代次数 | +| `max_iterations` | int | 10 | ReAct 最大迭代次数。`-1` 表示不限制,直到模型自然结束或用户停止;正数上限为 100 | | `allowed_tools` | []string | - | 允许使用的工具列表 | | `mcp_selection_mode` | string | - | MCP 服务选择模式:`all`/`selected`/`none` | | `mcp_services` | []string | - | 选中的 MCP 服务 ID 列表 | diff --git a/docs/api/tenant.md b/docs/api/tenant.md index e8bad665..0a72af54 100644 --- a/docs/api/tenant.md +++ b/docs/api/tenant.md @@ -630,7 +630,7 @@ curl --location --request PUT 'http://localhost:8080/api/v1/tenants/kv/agent-con **约束**: -- `agent-config`: `max_iterations` 取值范围 `(0, 30]`;`temperature` 取值范围 `[0, 2]`。 +- `agent-config`: `max_iterations` 为正整数时上限 100,`-1` 表示不限制;`temperature` 取值范围 `[0, 2]`。 - `web-search-config`: `max_results` 取值范围 `[1, 50]`。 - `conversation-config`: 包含多项阈值校验(如 `keyword_threshold` / `vector_threshold` ∈ `[0, 1]`,`rerank_threshold` ∈ `[-10, 10]`,`temperature` ∈ `[0, 2]`,`max_completion_tokens` ∈ `[1, 100000]` 等)。 - `retrieval-config`: `embedding_top_k` / `rerank_top_k` ∈ `[0, 200]`;阈值范围同上。 diff --git a/docs/docs.go b/docs/docs.go index 6037c0e2..76dd2e98 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -17912,7 +17912,7 @@ const docTemplate = `{ "type": "integer" }, "max_iterations": { - "description": "===== Agent Mode Settings =====\nMaximum iterations for ReAct loop (only for agent type)", + "description": "===== Agent Mode Settings =====\nMaximum ReAct iterations. -1 is unlimited; 0 is unset (default applied).", "type": "integer" }, "mcp_auth_wait_timeout": { diff --git a/docs/swagger.json b/docs/swagger.json index 6d695c8d..fec4cbeb 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -17905,7 +17905,7 @@ "type": "integer" }, "max_iterations": { - "description": "===== Agent Mode Settings =====\nMaximum iterations for ReAct loop (only for agent type)", + "description": "===== Agent Mode Settings =====\nMaximum ReAct iterations. -1 is unlimited; 0 is unset (default applied).", "type": "integer" }, "mcp_auth_wait_timeout": { diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 411b3110..68de7146 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -876,7 +876,7 @@ definitions: max_iterations: description: |- ===== Agent Mode Settings ===== - Maximum iterations for ReAct loop (only for agent type) + Maximum ReAct iterations. -1 is unlimited; 0 is unset (default applied). type: integer mcp_auth_wait_timeout: description: |- diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts index 1ff670b7..8c05a559 100644 --- a/frontend/src/api/agent/index.ts +++ b/frontend/src/api/agent/index.ts @@ -49,7 +49,7 @@ export interface CustomAgentConfig { citation_enabled?: boolean; // 是否在最终回答中输出知识库/网页来源引用(默认开启) // ===== Agent模式设置 ===== - max_iterations?: number; // 最大迭代次数 + max_iterations?: number; // 最大迭代次数;-1 表示不限制 llm_call_timeout?: number; // LLM调用超时时间(秒) allowed_tools?: string[]; // 允许的工具 reflection_enabled?: boolean; // 是否启用反思 diff --git a/frontend/src/api/model/index.ts b/frontend/src/api/model/index.ts index a5f02c2c..4ad93f09 100644 --- a/frontend/src/api/model/index.ts +++ b/frontend/src/api/model/index.ts @@ -31,6 +31,9 @@ export interface ModelConfig { // 会在调用远程模型 API 时附加到每个请求上。Authorization、Content-Type 等保留头会被忽略。 custom_headers?: Record; supports_vision?: boolean; // Whether the model accepts image/multimodal input + // 对话/VLM 的上下文窗口(token)。0 或不填表示使用后端默认 200000。 + context_window?: number; + max_output_tokens?: number; // 后台任务(入库/富化)对该模型的并发上限,按模型 ID 全副本共享。 // 0 或不填表示沿用全局默认(model.max_concurrency);仅对 chat/embedding/vllm 生效。 max_concurrency?: number; diff --git a/frontend/src/assets/img/context-compaction.svg b/frontend/src/assets/img/context-compaction.svg new file mode 100644 index 00000000..c69855c4 --- /dev/null +++ b/frontend/src/assets/img/context-compaction.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index c74fc5a2..1428130b 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -17,6 +17,11 @@ import AgentSelector from './AgentSelector.vue'; import { getCaretCoordinates } from '@/utils/caret'; import { getRootZoom, rectToCssPx, cssViewportSize } from '@/utils/zoom'; import { type ModelConfig } from '@/api/model'; +import { + formatContextWindow, + isDefaultContextWindow, + effectiveContextWindow, +} from '@/utils/contextWindow'; import { type CustomAgent, BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from '@/api/agent'; import { useChatResourcesStore } from '@/stores/chatResources'; import { useEditorResourcesStore } from '@/stores/editorResources'; @@ -1058,6 +1063,27 @@ const modelDisplayName = (model: ModelConfig) => { return displayName || model.name; }; +const contextWindowTitle = (tokens?: number) => { + if (isDefaultContextWindow(tokens)) { + return t('model.editor.contextWindowDefaultHint', { value: formatContextWindow(tokens) }); + } + return t('model.editor.contextWindowTokens', { count: effectiveContextWindow(tokens) }); +}; + +const selectedModelContextLabel = computed(() => { + if (!selectedModel.value) return ''; + return formatContextWindow(selectedModel.value.parameters?.context_window); +}); + +const selectedModelContextIsDefault = computed(() => { + return isDefaultContextWindow(selectedModel.value?.parameters?.context_window); +}); + +const selectedModelContextTitle = computed(() => { + if (!selectedModel.value) return ''; + return contextWindowTitle(selectedModel.value.parameters?.context_window); +}); + const updateModelDropdownPosition = () => { const anchor = modelButtonRef.value; if (!anchor) { @@ -1852,6 +1878,13 @@ watch(() => uiStore.showSettingsModal, (visible, prevVisible) => { } }); +watch(() => route.path, (path, prev) => { + if (prev === '/platform/settings' && path !== '/platform/settings') { + loadWebSearchConfig(true); + loadChatModels(true); + } +}); + watch([selectedKbIds, selectedFileIds], ([kbIds, fileIds]) => { if (!kbIds.length && !fileIds.length) { closeModelSelector(); @@ -2659,6 +2692,12 @@ defineExpose({ {{ selectedModelDisplayName }} + {{ selectedModelContextLabel }} @@ -2690,6 +2729,11 @@ defineExpose({ {{ model.name }} + {{ formatContextWindow(model.parameters?.context_window) }}
{{ $t('input.noModel') }} @@ -3473,6 +3517,18 @@ const getImgSrc = (url: string) => { white-space: nowrap; } +.model-selector-ctx { + flex-shrink: 0; + font-size: 11px; + font-variant-numeric: tabular-nums; + color: var(--td-text-color-placeholder, #999); + font-weight: 400; + + &.is-default { + opacity: 0.85; + } +} + .model-dropdown-arrow { width: 10px; height: 10px; @@ -3577,6 +3633,8 @@ const getImgSrc = (url: string) => { .model-option { display: flex; align-items: center; + justify-content: space-between; + gap: 8px; padding: 6px 8px; cursor: pointer; transition: background 0.12s; @@ -3608,8 +3666,8 @@ const getImgSrc = (url: string) => { display: flex; align-items: center; gap: 8px; - width: 100%; min-width: 0; + flex: 1; } .model-option-icon { @@ -3645,6 +3703,21 @@ const getImgSrc = (url: string) => { flex-shrink: 0; } +.model-option-ctx { + flex-shrink: 0; + font-size: 11px; + font-variant-numeric: tabular-nums; + color: var(--td-text-color-secondary); + background: var(--td-bg-color-secondarycontainer); + padding: 0 6px; + border-radius: 4px; + line-height: 18px; + + &.is-default { + color: var(--td-text-color-placeholder); + } +} + /* Agent 模式选择下拉菜单 */ .agent-mode-selector-overlay { position: fixed; diff --git a/frontend/src/components/ModelDebugDrawer.vue b/frontend/src/components/ModelDebugDrawer.vue index 00fd0c6d..0b562dea 100644 --- a/frontend/src/components/ModelDebugDrawer.vue +++ b/frontend/src/components/ModelDebugDrawer.vue @@ -58,7 +58,12 @@ >
{{ modelLabel(model) }} - {{ vendorLabel(model) }} + + {{ vendorLabel(model) }} + +
@@ -200,6 +205,10 @@ import SettingDrawer from '@/components/settings/SettingDrawer.vue' import { debugModel, type ModelConfig, type ModelDebugResult } from '@/api/model' import { fileSizeVerification } from '@/utils' import { modelSupportsThinking } from '@/utils/thinkingControl' +import { + formatContextWindow, + modelHasContextWindow, +} from '@/utils/contextWindow' const props = defineProps<{ visible: boolean diff --git a/frontend/src/components/ModelEditorDialog.vue b/frontend/src/components/ModelEditorDialog.vue index 94fcb12d..e1a917df 100644 --- a/frontend/src/components/ModelEditorDialog.vue +++ b/frontend/src/components/ModelEditorDialog.vue @@ -343,6 +343,14 @@
+ +
+ + +

{{ $t('model.editor.contextWindowDesc') }}

+
+
@@ -411,6 +419,7 @@ import { resolveThinkingControl, type ThinkingControlValue, } from '@/utils/thinkingControl' +import { DEFAULT_MODEL_CONTEXT_WINDOW } from '@/utils/contextWindow' import SettingDrawer from '@/components/settings/SettingDrawer.vue' import CredentialResource, { type CredentialFieldDef, @@ -437,6 +446,8 @@ interface ModelFormData { interfaceType?: 'ollama' | 'openai' isDefault: boolean supportsVision?: boolean + /** 对话/VLM 上下文窗口(token)。空/0 表示使用默认 200000。 */ + contextWindow?: number /** 后台任务对该模型的并发上限;0/undefined 表示沿用全局默认。仅 chat/embedding/vllm 生效。 */ maxConcurrency?: number /** extra_config.thinking_control — how agent thinking on/off maps to API fields. */ @@ -885,6 +896,7 @@ const formData = ref({ interfaceType: 'ollama', isDefault: false, supportsVision: false, + contextWindow: undefined, maxConcurrency: undefined, thinkingControl: defaultThinkingControl('generic', ''), customHeaders: [], @@ -1126,6 +1138,7 @@ const resetForm = () => { interfaceType: undefined, isDefault: false, supportsVision: false, + contextWindow: undefined, maxConcurrency: undefined, thinkingControl: defaultThinkingControl('generic', ''), customHeaders: [], diff --git a/frontend/src/components/ModelSelector.vue b/frontend/src/components/ModelSelector.vue index 70af4e79..b855f519 100644 --- a/frontend/src/components/ModelSelector.vue +++ b/frontend/src/components/ModelSelector.vue @@ -11,6 +11,16 @@ filterable style="width: 100%;" > + {{ model.name }} {{ $t('model.builtinTag') }} {{ $t('model.defaultTag') }} + {{ formatContextWindow(model.parameters?.context_window) }}
@@ -44,10 +60,17 @@