diff --git a/.env.example b/.env.example index 069f2829..fb0529a9 100644 --- a/.env.example +++ b/.env.example @@ -637,6 +637,10 @@ WEKNORA_SANDBOX_DOCKER_ENABLED=false # 智能体大模型调用默认超时(秒,默认 120;复杂推理调大如 300/600)。 # 注:全局默认;单个智能体在数据库配独立 llm_call_timeout 时以其为准。 # WEKNORA_AGENT_LLM_TIMEOUT=300 +# web_fetch 单页抓取预算(默认 3m)。HTTP 与 chromedp 共用这一预算,不叠加。 +# 支持 Go duration(150s、3m)或纯数字秒(180)。空值、无效值或非正数使用默认值。 +# 工具包装层再多等 5 秒,以便返回工具自己的超时结果。快速回答管道仍为 15s,不使用此项。 +# WEKNORA_WEB_FETCH_TIMEOUT=3m # MCP 工具人工审核等待超时(秒,默认 600;支持 Go duration 如 30s/5m/1h)。 # WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT=600 # MCP 工具人工审批失败时是否放行(true 放行 / 默认 fail-close 拒绝)。 diff --git a/docker-compose.yml b/docker-compose.yml index a9321cea..d79b93d1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -350,6 +350,8 @@ services: - WEKNORA_CHAT_ATTACHMENT_OCR_MAX_PAGES=${WEKNORA_CHAT_ATTACHMENT_OCR_MAX_PAGES:-8} # Agent LLM call timeout - WEKNORA_AGENT_LLM_TIMEOUT=${WEKNORA_AGENT_LLM_TIMEOUT:-} + # web_fetch 单页抓取预算(Go duration 或纯数字秒,默认 3m;HTTP 与 chromedp 共用,不叠加) + - WEKNORA_WEB_FETCH_TIMEOUT=${WEKNORA_WEB_FETCH_TIMEOUT:-} - WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT=${WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT:-} # MCP 工具人工审批失败时是否放行(true 放行 / 默认 fail-close 拒绝) - WEKNORA_AGENT_TOOL_APPROVAL_FAIL_OPEN=${WEKNORA_AGENT_TOOL_APPROVAL_FAIL_OPEN:-} diff --git a/internal/agent/const.go b/internal/agent/const.go index cadbc142..60627a81 100644 --- a/internal/agent/const.go +++ b/internal/agent/const.go @@ -13,6 +13,7 @@ import ( "github.com/Tencent/WeKnora/internal/agent/compaction" "github.com/Tencent/WeKnora/internal/browserskill" + webfetch "github.com/Tencent/WeKnora/internal/infrastructure/web_fetch" "github.com/Tencent/WeKnora/internal/models/api" "github.com/Tencent/WeKnora/internal/types" "github.com/google/uuid" @@ -36,7 +37,7 @@ const ( defaultLLMStallTimeout = 120 * time.Second // defaultToolExecTimeout is the default maximum time for a single tool execution. - // Prevents long-running tools (web_fetch, database_query) from hanging indefinitely. + // Prevents long-running tools (for example database_query) from hanging indefinitely. defaultToolExecTimeout = 60 * time.Second // shellExecToolTimeout is slightly longer than shell_exec's own hard // 600-second command timeout so the tool can return a structured timeout @@ -45,6 +46,10 @@ const ( // tryAgentToolTimeout is above the trial runner's own 4-minute limit so // a slow trial still reports what the agent did before it was stopped. tryAgentToolTimeout = 4*time.Minute + 30*time.Second + // webFetchToolSlack is how much longer the agent wrapper waits than the + // shared page-fetch budget. Same 5s headroom as shell_exec, so web_fetch can + // return its own timeout result instead of being cancelled first. + webFetchToolSlack = 5 * time.Second // maxLLMRetries is the maximum number of retries for transient LLM errors. maxLLMRetries = 2 @@ -99,6 +104,8 @@ func toolExecutionTimeout(toolName string, arguments ...string) time.Duration { return shellExecToolTimeout case "try_agent": return tryAgentToolTimeout + case "web_fetch": + return webfetch.PageFetchTimeout() + webFetchToolSlack } return defaultToolExecTimeout } diff --git a/internal/agent/const_test.go b/internal/agent/const_test.go index de7d2401..75f65a36 100644 --- a/internal/agent/const_test.go +++ b/internal/agent/const_test.go @@ -8,13 +8,33 @@ import ( ) func TestToolExecutionTimeout(t *testing.T) { + // shell_exec and browser human steps keep their longer budgets. assert.Equal(t, 10*time.Minute+5*time.Second, toolExecutionTimeout("shell_exec")) - assert.Equal(t, 60*time.Second, toolExecutionTimeout("web_fetch")) for _, method := range []string{"request_help", "tab_borrow"} { assert.Equal(t, 5*time.Minute+15*time.Second, toolExecutionTimeout("local_browser", `{"method":"`+method+`"}`)) } + // knowledge_search and non-human browser calls stay at 60s. + assert.Equal(t, 60*time.Second, toolExecutionTimeout("knowledge_search")) for _, args := range []string{`{"method":"click"}`, `{"method":"observe"}`, `{`} { assert.Equal(t, 60*time.Second, toolExecutionTimeout("local_browser", args)) } + + t.Run("default budget plus slack", func(t *testing.T) { + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "") + assert.Equal(t, 3*time.Minute+5*time.Second, toolExecutionTimeout("web_fetch")) + }) + t.Run("go duration", func(t *testing.T) { + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "150s") + assert.Greater(t, toolExecutionTimeout("web_fetch"), 2*time.Minute+30*time.Second) + assert.Equal(t, 2*time.Minute+35*time.Second, toolExecutionTimeout("web_fetch")) + }) + t.Run("bare seconds", func(t *testing.T) { + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "180") + assert.Equal(t, 3*time.Minute+5*time.Second, toolExecutionTimeout("web_fetch")) + }) + t.Run("invalid falls back", func(t *testing.T) { + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "nope") + assert.Equal(t, 3*time.Minute+5*time.Second, toolExecutionTimeout("web_fetch")) + }) } diff --git a/internal/agent/tools/web_fetch.go b/internal/agent/tools/web_fetch.go index 4a549dc5..159efd9b 100644 --- a/internal/agent/tools/web_fetch.go +++ b/internal/agent/tools/web_fetch.go @@ -7,7 +7,6 @@ import ( "net/url" "strings" "sync" - "time" "unicode/utf8" webfetch "github.com/Tencent/WeKnora/internal/infrastructure/web_fetch" @@ -16,10 +15,7 @@ import ( "github.com/Tencent/WeKnora/internal/utils" ) -const ( - webPageFetchTimeout = 60 * time.Second - webPageCacheLimit = 8 -) +const webPageCacheLimit = 8 var webFetchTool = BaseTool{ name: ToolWebFetch, @@ -164,7 +160,7 @@ func snapshotWaitTimeoutError(err error) error { // storePage downloads independently of the caller's deadline so a short // content=true timeout cannot cancel a shared fetch for concurrent web_fetch. func (t *WebFetchTool) storePage(ctx context.Context, rawURL string) (webPageSnapshot, error) { - fetchCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), webPageFetchTimeout) + fetchCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), webfetch.PageFetchTimeout()) defer cancel() content, err := t.fetcher.Fetch(fetchCtx, rawURL) if err != nil { diff --git a/internal/agent/tools/web_fetch_test.go b/internal/agent/tools/web_fetch_test.go index 8cbdc257..7d4c2381 100644 --- a/internal/agent/tools/web_fetch_test.go +++ b/internal/agent/tools/web_fetch_test.go @@ -414,3 +414,25 @@ func TestWebFetchOwnerTimeoutDoesNotCancelSharedFetch(t *testing.T) { assert.Equal(t, "owner page body", longResult.Data["results"].([]map[string]interface{})[0]["raw_content"]) assert.Equal(t, 1, fetcher.callCount[rawURL]) } + +type deadlineWebContentFetcher struct { + deadline time.Time + hasDeadline bool +} + +func (f *deadlineWebContentFetcher) Fetch(ctx context.Context, _ string) (string, error) { + f.deadline, f.hasDeadline = ctx.Deadline() + return "page body", nil +} + +func TestStorePageBudgetFollowsWebFetchTimeout(t *testing.T) { + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "150s") + fetcher := &deadlineWebContentFetcher{} + tool := newWebFetchTool(fetcher) + + _, err := tool.storePage(context.Background(), "https://example.com/slow") + + require.NoError(t, err) + require.True(t, fetcher.hasDeadline) + assert.InDelta(t, 150, time.Until(fetcher.deadline).Seconds(), 2) +} diff --git a/internal/infrastructure/web_fetch/fetcher.go b/internal/infrastructure/web_fetch/fetcher.go index e2236422..92f1005b 100644 --- a/internal/infrastructure/web_fetch/fetcher.go +++ b/internal/infrastructure/web_fetch/fetcher.go @@ -12,6 +12,7 @@ import ( "net" "net/http" "net/url" + "os" "strings" "time" "unicode/utf8" @@ -23,12 +24,39 @@ import ( ) const ( - fetchTimeout = 60 * time.Second - pipelineFetchTimeout = 15 * time.Second - maxBodySize = 100 * 1024 - maxAgentBodySize = 2 * 1024 * 1024 + // defaultPageFetchTimeout is the agent web_fetch page budget when + // WEKNORA_WEB_FETCH_TIMEOUT is empty, invalid, or not positive. Three + // minutes covers a slow browser render plus HTTP fallback: a 150s cap is + // still shorter than the 150036ms success reported for this timeout. + defaultPageFetchTimeout = 3 * time.Minute + pipelineFetchTimeout = 15 * time.Second + maxBodySize = 100 * 1024 + maxAgentBodySize = 2 * 1024 * 1024 ) +// PageFetchTimeout is the shared budget for one agent web_fetch page read. +// The HTTP client, the fetch context, and chromedp all use this value. +// Chromedp's deadline is a child of the fetch context, so the budgets do not add. +// +// WEKNORA_WEB_FETCH_TIMEOUT accepts a Go duration (150s, 3m) or a bare positive +// number of seconds (180), the same pattern as WEKNORA_AGENT_LLM_TIMEOUT. +// Empty, invalid, and non-positive values use defaultPageFetchTimeout. +func PageFetchTimeout() time.Duration { + value := strings.TrimSpace(os.Getenv("WEKNORA_WEB_FETCH_TIMEOUT")) + if value == "" { + return defaultPageFetchTimeout + } + timeout, err := time.ParseDuration(value) + if err != nil { + // Bare number of seconds, for example "180". + timeout, err = time.ParseDuration(value + "s") + } + if err != nil || timeout <= 0 { + return defaultPageFetchTimeout + } + return timeout +} + // ErrorCode identifies the stage and class of a fetch failure. type ErrorCode string @@ -116,7 +144,7 @@ type httpFetchResult struct { // NewFetcher creates a production fetcher with DNS and redirect SSRF guards. func NewFetcher() *Fetcher { - f := newFetcher(fetchTimeout, renderWithChromium) + f := newFetcher(PageFetchTimeout(), renderWithChromium) f.markdown = true f.maxBodySize = maxAgentBodySize return f @@ -350,7 +378,9 @@ func renderWithChromium(ctx context.Context, target pinnedTarget) (string, error defer cancelAllocator() browserCtx, cancelBrowser := chromedp.NewContext(allocatorCtx) defer cancelBrowser() - browserCtx, cancelTimeout := context.WithTimeout(browserCtx, fetchTimeout) + // Child of the fetch context: a full PageFetchTimeout here cannot outlive + // the parent budget, so HTTP and chromedp share one deadline instead of stacking. + browserCtx, cancelTimeout := context.WithTimeout(browserCtx, PageFetchTimeout()) defer cancelTimeout() var html string if err := chromedp.Run(browserCtx, diff --git a/internal/infrastructure/web_fetch/fetcher_test.go b/internal/infrastructure/web_fetch/fetcher_test.go index e22d4a85..af84fb12 100644 --- a/internal/infrastructure/web_fetch/fetcher_test.go +++ b/internal/infrastructure/web_fetch/fetcher_test.go @@ -133,7 +133,12 @@ func TestFetcherUsesBrowserFallbackForClientRenderedPage(t *testing.T) { } func TestNewFetcherKeepsAgentCompatibleTimeout(t *testing.T) { - assert.Equal(t, 60*time.Second, NewFetcher().timeout) + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "") + assert.Equal(t, 3*time.Minute, NewFetcher().timeout) + assert.Equal(t, PageFetchTimeout(), NewFetcher().timeout) + + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "150s") + assert.Equal(t, 150*time.Second, NewFetcher().timeout) } func TestNewPipelineFetcherUsesHTTPOnlyAndLegacyTimeout(t *testing.T) { @@ -142,6 +147,33 @@ func TestNewPipelineFetcherUsesHTTPOnlyAndLegacyTimeout(t *testing.T) { assert.Nil(t, fetcher.renderBrowser) } +func TestPipelineFetcherIgnoresWebFetchToolTimeout(t *testing.T) { + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "180") + fetcher := NewPipelineFetcher() + assert.Equal(t, 15*time.Second, fetcher.timeout) + assert.Nil(t, fetcher.renderBrowser) + assert.Equal(t, 180*time.Second, PageFetchTimeout()) +} + +func TestPageFetchTimeout(t *testing.T) { + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "") + assert.Equal(t, 3*time.Minute, PageFetchTimeout()) + + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "150s") + assert.Equal(t, 150*time.Second, PageFetchTimeout()) + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "3m") + assert.Equal(t, 3*time.Minute, PageFetchTimeout()) + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", "180") + assert.Equal(t, 180*time.Second, PageFetchTimeout()) + + for _, raw := range []string{"", "0", "-1", "0s", "-5s", "nope", " "} { + t.Run("fallback_"+raw, func(t *testing.T) { + t.Setenv("WEKNORA_WEB_FETCH_TIMEOUT", raw) + assert.Equal(t, 3*time.Minute, PageFetchTimeout()) + }) + } +} + func TestFetcherReturnsErrorWhenBrowserFallbackFailsOnSPA(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) { _, _ = writer.Write([]byte(`