diff --git a/internal/agent/tools/browserskill.go b/internal/agent/tools/browserskill.go index 5989f41d..8807ab19 100644 --- a/internal/agent/tools/browserskill.go +++ b/internal/agent/tools/browserskill.go @@ -73,11 +73,10 @@ func (t *BrowserSkillTool) Execute(ctx context.Context, args json.RawMessage) (* return nil, err } method := input["method"].(string) - delete(input, "method") if keep, supplied := input["keep_open"].(bool); supplied { t.keepOpen.Store(keep) } - delete(input, "keep_open") + params := browserCallParams(method, input) if method == "request_help" { t.keepOpen.Store(true) } @@ -117,7 +116,7 @@ func (t *BrowserSkillTool) Execute(ctx context.Context, args json.RawMessage) (* return &types.ToolResult{Success: false, Error: t.prepareErr.Error()}, nil } t.used.Store(true) - result, err := t.manager.Call(ctx, t.scope, t.session, method, input) + result, err := t.manager.Call(ctx, t.scope, t.session, method, params) if err != nil { t.failed.Store(true) return browserToolFailure(method, err), nil diff --git a/internal/agent/tools/browserskill_prompt.go b/internal/agent/tools/browserskill_prompt.go index 0043f72e..c369fe76 100644 --- a/internal/agent/tools/browserskill_prompt.go +++ b/internal/agent/tools/browserskill_prompt.go @@ -22,7 +22,44 @@ func browserDescription(instructions []string) string { // templates or the upstream CLI skill. Uses the paired CLI/extension 0.3.0 // source baseline, remote ownership contract and WeKnora task controls. const browserToolDescription = `Control the user's connected Chrome through local_browser; no shell, installation or CLI -session commands are needed. Arguments are top-level beside method; sessions are server-managed. +session commands are needed. Sessions are server-managed. Pass fields beside method, and only +the fields of that method, for example {"method":"navigate","url":"https://example.com"}. +keep_open is optional on every call. + +Methods: +observe(tab_id?, max_text_chars?, max_depth?, probe_hover?, debug_surfaces?) +snapshot(tab_id?, max_text_chars?, max_depth?) +screenshot(tab_id?, ref?) +navigate(url, tab_id?, wait_until?, timeout_ms?) +navigate_back(tab_id?, wait_until?, timeout_ms?) +navigate_forward(tab_id?, wait_until?, timeout_ms?) +reload(tab_id?, hard?, wait_until?, timeout_ms?) +click(ref | selector, button?, click_count?, modifiers?, tab_id?, timeout_ms?) +fill(ref | selector, value, clear_before?, tab_id?, timeout_ms?) +press(key, ref?, selector?, hold_ms?, modifiers?, tab_id?, timeout_ms?) +hover(ref | selector, settle_ms?, modifiers?, tab_id?, timeout_ms?) +wheel(delta_x?, delta_y?, ref?, selector?, modifiers?, tab_id?, timeout_ms?) +scroll_to(ref | selector, tab_id?, timeout_ms?) +focus(ref | selector, tab_id?, timeout_ms?) +blur(ref?, selector?, tab_id?, timeout_ms?) +select(ref | selector, values, tab_id?, timeout_ms?) +tab_list(scope?) +tab_create(url?, active?, index?) +tab_select(tab_id) +tab_close(tab_id) +tab_borrow(tab_id, confirm?) +tab_return(tab_id) +get_html(tab_id?, ref?, max_bytes?) +evaluate(expression, tab_id?, await_promise?, return_by_value?, timeout_ms?) +console(tab_id?, limit?, max_text_chars?, since?, include_stack?) +network(tab_id?, limit?, max_text_chars?, since?) +wait_for_navigation(tab_id?, wait_until?, timeout_ms?) +wait_ms(duration_ms) +window_resize(width, height) +emulate(off | overrides, tab_id?) +request_help(prompt, tab_id?, title?, targets?, timeout_ms?) +click, fill, hover, scroll_to, focus, and select take exactly one of ref or selector. +press, wheel, and blur take at most one. emulate takes either off or overrides. Workflow: - Use a supplied URL or observed link. If no reliable entry is available, use the search @@ -36,7 +73,7 @@ Workflow: alone is not model-visible evidence. - Prefer refs for iframe/shadow-root targets; selectors search the main document. Use snapshot or get_html for missing structure. Reserve evaluate for a specific gap and return bounded - serializable data. Follow the parameter descriptions and recovery hints in tool results. + serializable data. Follow the method list above and recovery hints in tool results. - Use wheel with delta_y to scroll the viewport; scroll_to brings an observed ref or selector into view. evaluate accepts a JavaScript expression/script; put return inside an IIFE such as (() => { return document.title; })(), never at the top level. diff --git a/internal/agent/tools/browserskill_result_test.go b/internal/agent/tools/browserskill_result_test.go index e2050f3c..8eec3dde 100644 --- a/internal/agent/tools/browserskill_result_test.go +++ b/internal/agent/tools/browserskill_result_test.go @@ -107,13 +107,20 @@ func TestBrowserRPCFailureReachesModelAndAllowsFreshObservation(t *testing.T) { require.True(t, fresh.Success) require.Equal(t, 2, manager.calls) invalid, err := registry.ExecuteTool( - ctx, "local_browser", json.RawMessage(`{"method":"observe","max_text_chars":3000}`), + ctx, "local_browser", json.RawMessage(`{"method":"observe","max_tokens":750}`), ) require.NoError(t, err) require.False(t, invalid.Success) require.Contains(t, invalid.Error, "allowed fields:") - require.Contains(t, invalid.Error, "max_tokens") + require.Contains(t, invalid.Error, "max_text_chars") require.Equal(t, 2, manager.calls, "invalid method fields must fail before dispatch") + capped, err := registry.ExecuteTool( + ctx, "local_browser", json.RawMessage(`{"method":"observe","max_text_chars":3000}`), + ) + require.NoError(t, err) + require.True(t, capped.Success) + require.Equal(t, map[string]any{"max_tokens": 750}, manager.params) + require.Equal(t, 3, manager.calls) } func TestNavigationTimeoutRetainsTask(t *testing.T) { diff --git a/internal/agent/tools/browserskill_schema.go b/internal/agent/tools/browserskill_schema.go index 3933e694..1d416c41 100644 --- a/internal/agent/tools/browserskill_schema.go +++ b/internal/agent/tools/browserskill_schema.go @@ -11,7 +11,8 @@ import ( "github.com/santhosh-tekuri/jsonschema/v6" ) -// Flat argument fields use the paired CLI/extension 0.3.0 source baseline. +// The model sees one text budget, max_text_chars. browserCallParams maps page +// reads onto the extension's max_tokens (about 4 characters per token). // Session identity is server-owned. // Method-specific requirements are also described to the model on each field. const browserToolParameters = `{ @@ -64,11 +65,6 @@ const browserToolParameters = `{ "type": "integer", "minimum": 0.0 }, - "max_tokens": { - "type": "integer", - "minimum": 0.0, - "description": "For observe/snapshot: limit the rendered page content." - }, "probe_hover": { "type": "boolean", "description": "For observe: opt in for hover-only content. Moves the cursor and can take seconds." @@ -218,7 +214,9 @@ const browserToolParameters = `{ }, "max_text_chars": { "type": "integer", - "minimum": 1.0 + "minimum": 1.0, + "description": "Maximum characters of text to return. For observe and snapshot this bounds ` + + `the rendered page; for console and network it bounds each entry." }, "since": { "type": "integer", @@ -354,11 +352,11 @@ type browserArgumentRule struct{ fields, required []string } var browserArgumentRules = map[string]browserArgumentRule{ "screenshot": {fields: []string{"ref", "tab_id"}}, "observe": { - fields: []string{"debug_surfaces", "max_depth", "max_tokens", "probe_hover", "tab_id"}, + fields: []string{"debug_surfaces", "max_depth", "max_text_chars", "probe_hover", "tab_id"}, required: []string{}, }, "snapshot": { - fields: []string{"max_depth", "max_tokens", "tab_id"}, + fields: []string{"max_depth", "max_text_chars", "tab_id"}, required: []string{}, }, "navigate": { @@ -556,3 +554,38 @@ func (t *BrowserSkillTool) ValidateArguments(args json.RawMessage) error { } return nil } + +// browserCallParams copies model arguments into the official tool.* parameter +// names. Page observations budget rendered tokens, so a character cap becomes +// max_tokens at the extension's 4-characters-per-token heuristic. Console and +// network already speak max_text_chars and are passed through. +func browserCallParams(method string, input map[string]any) map[string]any { + out := make(map[string]any, len(input)) + for name, value := range input { + if name == "method" || name == "keep_open" { + continue + } + out[name] = value + } + switch method { + case "observe", "snapshot": + chars, ok := out["max_text_chars"] + if !ok { + break + } + delete(out, "max_text_chars") + out["max_tokens"] = observationTokensFromTextChars(chars) + } + return out +} + +// observationTokensFromTextChars matches the extension heuristic of about four +// characters per rendered token, rounding up so the page cap is not shorter +// than the character budget the model asked for. +func observationTokensFromTextChars(value any) int { + chars := int(toFloat64(value)) + if chars < 1 { + return 1 + } + return (chars + 3) / 4 +} diff --git a/internal/agent/tools/browserskill_schema_test.go b/internal/agent/tools/browserskill_schema_test.go index f71d0741..7ea60ffa 100644 --- a/internal/agent/tools/browserskill_schema_test.go +++ b/internal/agent/tools/browserskill_schema_test.go @@ -2,6 +2,7 @@ package tools import ( "encoding/json" + "strings" "testing" "github.com/Tencent/WeKnora/internal/browserskill" @@ -87,4 +88,74 @@ func TestBrowserFlatArgumentsRejectBeforeDispatch(t *testing.T) { require.NoError(t, tool.ValidateArguments( json.RawMessage(`{"method":"navigate","url":"https://example.com","wait_until":"load"}`), )) + require.NoError(t, tool.ValidateArguments( + json.RawMessage(`{"method":"observe","max_text_chars":3000}`), + )) + require.Error(t, tool.ValidateArguments( + json.RawMessage(`{"method":"observe","max_tokens":750}`), + )) +} + +func TestBrowserDescriptionSignaturesMatchRules(t *testing.T) { + seen := map[string]bool{} + for _, line := range strings.Split(browserToolDescription, "\n") { + line = strings.TrimSpace(line) + name, params, ok := parseBrowserSignature(line) + if !ok { + continue + } + rule, exists := browserArgumentRules[name] + require.True(t, exists, line) + require.False(t, seen[name], "duplicate signature %s", name) + seen[name] = true + require.ElementsMatch(t, rule.fields, params.names) + for _, required := range rule.required { + require.False(t, params.optional[required], "%s required argument %s is marked optional", name, required) + } + } + require.Len(t, seen, len(browserArgumentRules)) +} + +type browserSignatureParams struct { + names []string + optional map[string]bool +} + +func parseBrowserSignature(line string) (string, browserSignatureParams, bool) { + open := strings.IndexByte(line, '(') + space := strings.IndexByte(line, ' ') + if open <= 0 || !strings.HasSuffix(line, ")") || (space >= 0 && space < open) { + return "", browserSignatureParams{}, false + } + name := line[:open] + if _, ok := browserArgumentRules[name]; !ok { + return "", browserSignatureParams{}, false + } + params := browserSignatureParams{optional: map[string]bool{}} + inner := strings.TrimSpace(line[open+1 : len(line)-1]) + if inner == "" { + return name, params, true + } + for _, part := range strings.Split(inner, ",") { + part = strings.TrimSpace(part) + optional := strings.HasSuffix(part, "?") + part = strings.TrimSuffix(part, "?") + for _, field := range strings.Split(part, "|") { + field = strings.TrimSpace(field) + params.names = append(params.names, field) + params.optional[field] = optional + } + } + return name, params, true +} + +func TestBrowserTextCapMapsOntoProtocol(t *testing.T) { + page := browserCallParams("observe", map[string]any{ + "method": "observe", "keep_open": true, "max_text_chars": float64(3000), "tab_id": float64(2), + }) + require.Equal(t, map[string]any{"max_tokens": 750, "tab_id": float64(2)}, page) + require.Equal(t, 1, browserCallParams("snapshot", map[string]any{"max_text_chars": float64(1)})["max_tokens"]) + require.Equal(t, 2, browserCallParams("snapshot", map[string]any{"max_text_chars": float64(5)})["max_tokens"]) + logs := browserCallParams("console", map[string]any{"max_text_chars": float64(3000), "limit": float64(20)}) + require.Equal(t, map[string]any{"max_text_chars": float64(3000), "limit": float64(20)}, logs) }