diff --git a/active_tools.go b/active_tools.go new file mode 100644 index 0000000..56516dc --- /dev/null +++ b/active_tools.go @@ -0,0 +1,52 @@ +package agent + +// filterToolsByActiveNames reproduces upstream callModel's `activeTools` +// narrowing (packages/agent/src/inner-loop/call-model.ts): +// +// const activeSet = activeTools ? new Set(activeTools) : undefined; +// const activeFilteredTools = activeSet +// ? tools?.filter((t) => isServerTool(t) || activeSet.has(t.function.name)) +// : tools; +// const filteredTools = activeFilteredTools?.length ? activeFilteredTools : undefined; +// +// Semantics: +// - activeTools == nil: no filter (upstream `activeTools` omitted). +// - activeTools non-nil (even empty): only client tools whose ToolName is +// listed survive; an empty slice therefore drops every client tool. +// - Server tools always survive — activeTools is a client-name list; +// tool-set snapshots omit server ids from it. +// - Unknown names in activeTools are silently ignored; duplicates are +// irrelevant. Construction order of tools is preserved. +// - An empty result (filtered to nothing, or tools empty/nil to begin +// with) collapses to nil so the request omits `tools` entirely and the +// engine's tool-execution machinery stays disabled. +// +// The result must replace the tool list everywhere downstream — API +// conversion AND execution registration — so the model can neither see nor +// call a filtered tool. Upstream never errors here. +func filterToolsByActiveNames(tools []Tool, activeTools []string) []Tool { + filtered := tools + if activeTools != nil { + active := make(map[string]struct{}, len(activeTools)) + for _, n := range activeTools { + active[n] = struct{}{} + } + filtered = make([]Tool, 0, len(tools)) + for _, t := range tools { + if t == nil { + continue + } + if IsServerTool(t) { + filtered = append(filtered, t) + continue + } + if _, ok := active[t.ToolName()]; ok { + filtered = append(filtered, t) + } + } + } + if len(filtered) == 0 { + return nil + } + return filtered +} diff --git a/active_tools_test.go b/active_tools_test.go new file mode 100644 index 0000000..7436d4f --- /dev/null +++ b/active_tools_test.go @@ -0,0 +1,74 @@ +package agent + +import ( + "context" + "testing" +) + +// Ports the pure-filter parts of +// packages/agent/tests/unit/call-model-active-tools.test.ts (upstream +// observes the outbound request's `tools`; here the filter's output is the +// list CallModel converts to API tools and registers for execution). +func TestFilterToolsByActiveNames(t *testing.T) { + a, b := makeSetTool("a"), makeSetTool("b") + webSearch := NewServerTool(ServerToolConfig{Name: "web_search", Config: webSearchServerTool()}) + background := MustNewTool(ToolConfig[emptyInput]{ + Name: "background", + Execute: func(context.Context, emptyInput, ToolExecuteContext) (any, error) { return nil, nil }, + }) + + cases := []struct { + name string + tools []Tool + activeTools []string + want []string // nil => expect nil result + }{ + {"sends only active tools", []Tool{a, b}, []string{"a"}, []string{"a"}}, + {"silently ignores unknown names", []Tool{a, b}, []string{"a", "missing"}, []string{"a"}}, + {"nil activeTools sends all tools", []Tool{a, b}, nil, []string{"a", "b"}}, + {"preserves tool order, not activeTools order", []Tool{a, b}, []string{"b", "a"}, []string{"a", "b"}}, + {"duplicate active names are harmless", []Tool{a, b}, []string{"b", "b"}, []string{"b"}}, + {"filtered-out tool is dropped (background/task case)", []Tool{background, a}, []string{"a"}, []string{"a"}}, + {"explicitly empty tools collapses to nil", []Tool{}, nil, nil}, + {"nil tools stays nil", nil, []string{"a"}, nil}, + {"filtering out every tool collapses to nil", []Tool{a, b}, []string{"missing"}, nil}, + {"empty non-nil activeTools drops every client tool", []Tool{a, b}, []string{}, nil}, + {"server tools always pass", []Tool{a, webSearch, b}, []string{"b"}, []string{"server:web_search_2025_08_26", "b"}}, + {"server tools pass even with empty activeTools", []Tool{a, webSearch}, []string{}, []string{"server:web_search_2025_08_26"}}, + {"server tool Name is not matched as a client name", []Tool{webSearch}, []string{"web_search"}, []string{"server:web_search_2025_08_26"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := filterToolsByActiveNames(tc.tools, tc.activeTools) + if tc.want == nil { + if got != nil { + t.Fatalf("got %v, want nil", toolIDs(got)) + } + return + } + eq(t, "tools", toolIDs(got), tc.want) + }) + } +} + +func TestFilterToolsByActiveNamesDoesNotMutateInput(t *testing.T) { + a, b := makeSetTool("a"), makeSetTool("b") + in := []Tool{a, b} + _ = filterToolsByActiveNames(in, []string{"b"}) + eq(t, "input", toolIDs(in), []string{"a", "b"}) +} + +// The documented pairing: a tool-set snapshot's CallModel fields fed back +// through the engine filter produce exactly the snapshot's active tools. +func TestFilterToolsByActiveNamesWithToolSetSnapshot(t *testing.T) { + a, b, c := makeSetTool("a"), makeSetTool("b"), makeSetTool("c") + webSearch := NewServerTool(ServerToolConfig{Config: webSearchServerTool()}) + ts := newSet(t, false, a, webSearch, b, c) + ts = must(ts.Deactivate("b")) + snap := ts.Resolve(none) + + eq(t, "from snapshot tools", toolIDs(filterToolsByActiveNames(snap.CallModel.Tools, snap.CallModel.ActiveTools)), snap.Enabled) + // Passing all tools with the snapshot's ActiveTools gives the same client + // subset (server tools are always kept by the filter). + eq(t, "from all tools", toolIDs(filterToolsByActiveNames(ts.Tools(), snap.CallModel.ActiveTools)), []string{"a", "server:web_search_2025_08_26", "c"}) +} diff --git a/anthropic_compat.go b/anthropic_compat.go index 6e52f8e..fc6b70b 100644 --- a/anthropic_compat.go +++ b/anthropic_compat.go @@ -9,6 +9,12 @@ import ( "github.com/OpenRouterTeam/go-sdk/optionalnullable" ) +// ClaudeMessageInputItem is an input item emitted by FromClaudeMessages +// (upstream ClaudeMessageInputItem): a user/assistant message, a +// function_call, or a function_call_output, expressed as the SDK input-item +// union. +type ClaudeMessageInputItem = components.InputsUnion1 + // ClaudeUsage mirrors the Anthropic Claude message usage shape (distinct from // the OpenRouter SDK usage type). Field names match upstream // stream-transformers.ts convertToClaudeMessage. diff --git a/chat_compat.go b/chat_compat.go index 5d98259..2d4f19c 100644 --- a/chat_compat.go +++ b/chat_compat.go @@ -7,6 +7,12 @@ import ( "github.com/OpenRouterTeam/go-sdk/models/components" ) +// ChatMessageInputItem is an input item emitted by FromChatMessages (upstream +// ChatMessageInputItem): a user/system/assistant/developer message, a +// function_call, or a function_call_output. Go expresses the upstream union as +// the SDK input-item union, so it is directly usable as CallModelInput input. +type ChatMessageInputItem = components.InputsUnion1 + type ChatMessage struct { Role string `json:"role"` Content any `json:"content"` @@ -18,8 +24,10 @@ type ChatMessage struct { // ToChatMessage converts an OpenRouter Responses result into an OpenAI // Chat-style assistant message, carrying id/model/status metadata and any // unsupported content so a round trip through FromChatMessages is lossless. +// Tool calls are carried whatever the response status: this is a format +// conversion, not an execution decision (see ExtractToolCallsFromResponse). func ToChatMessage(resp components.OpenResponsesResult) ChatMessage { - return ChatMessage{Role: "assistant", Content: ExtractTextFromResponse(resp), ToolCalls: ExtractToolCallsFromResponse(resp), Metadata: map[string]any{"id": resp.ID, "model": resp.Model, "status": string(resp.Status), "unsupported_content": ScanUnsupportedContent(resp)}} + return ChatMessage{Role: "assistant", Content: ExtractTextFromResponse(resp), ToolCalls: extractFunctionCalls(resp), Metadata: map[string]any{"id": resp.ID, "model": resp.Model, "status": string(resp.Status), "unsupported_content": ScanUnsupportedContent(resp)}} } // FromChatMessages converts OpenAI Chat-style messages into OpenRouter input @@ -36,11 +44,21 @@ func FromChatMessages(messages []ChatMessage) ([]components.InputsUnion1, error) out = append(out, components.CreateInputsUnion1FunctionCallOutputItem(components.FunctionCallOutputItem{CallID: m.ToolCallID, Output: components.CreateFunctionCallOutputItemOutputUnion2Str(result), Type: components.FunctionCallOutputItemTypeFunctionCallOutputFunctionCallOutput})) continue } - if text, ok := m.Content.(string); ok { - out = append(out, easyMessage(m.Role, components.CreateEasyInputMessageContentUnion2Str(text))) - } else { - out = append(out, easyMessage(m.Role, components.CreateEasyInputMessageContentUnion2Any(m.Content))) + // An assistant message with no content is omitted only when tool calls + // are emitted in its place; a content-less message without tool calls + // still round-trips as an empty message (upstream #11). + if m.Role != "assistant" || !chatContentEmpty(m.Content) || len(m.ToolCalls) == 0 { + if text, ok := m.Content.(string); ok { + out = append(out, easyMessage(m.Role, components.CreateEasyInputMessageContentUnion2Str(text))) + } else if m.Content == nil { + out = append(out, easyMessage(m.Role, components.CreateEasyInputMessageContentUnion2Str(""))) + } else { + out = append(out, easyMessage(m.Role, components.CreateEasyInputMessageContentUnion2Any(m.Content))) + } } + // One function_call item per tool call, after the message. Already + // serialized arguments (RawArgs) are forwarded as-is, never + // re-stringified; only structured Arguments are marshaled. for _, call := range m.ToolCalls { args := call.RawArgs if args == "" && call.Arguments != nil { @@ -50,7 +68,16 @@ func FromChatMessages(messages []ChatMessage) ([]components.InputsUnion1, error) } args = string(b) } - out = append(out, components.CreateInputsUnion1FunctionCallItem(components.FunctionCallItem{ID: callKey(call), CallID: call.CallID, Name: call.Name, Arguments: args, Type: components.FunctionCallItemTypeFunctionCall})) + // A chat tool call carries a single id that serves as both the + // item id and the call_id (upstream sets id = callId = tc.id). + callID, itemID := call.CallID, call.ID + if callID == "" { + callID = itemID + } + if itemID == "" { + itemID = callID + } + out = append(out, components.CreateInputsUnion1FunctionCallItem(components.FunctionCallItem{ID: itemID, CallID: callID, Name: call.Name, Arguments: args, Status: components.ToolCallStatusCompleted.ToPointer(), Type: components.FunctionCallItemTypeFunctionCall})) } } return out, nil @@ -71,3 +98,13 @@ func contentToStringWithError(content any) (string, error) { } return string(b), nil } + +// chatContentEmpty mirrors upstream's `contentToString(content).length === 0` +// check for assistant messages: nil and "" are empty. +func chatContentEmpty(content any) bool { + if content == nil { + return true + } + s, ok := content.(string) + return ok && s == "" +} diff --git a/chat_compat_test.go b/chat_compat_test.go new file mode 100644 index 0000000..503cac9 --- /dev/null +++ b/chat_compat_test.go @@ -0,0 +1,160 @@ +package agent + +import ( + "encoding/json" + "reflect" + "testing" + + openrouter "github.com/OpenRouterTeam/go-sdk" + "github.com/OpenRouterTeam/go-sdk/models/components" + "github.com/OpenRouterTeam/go-sdk/models/operations" +) + +// assertWireJSON compares the wire (JSON) form of got against the JSON literal +// want, independent of key order. Upstream's chat-compat tests assert on the +// emitted object shape, which in Go is the marshaled SDK union. +func assertWireJSON(t *testing.T, got any, want string) { + t.Helper() + b, err := json.Marshal(got) + if err != nil { + t.Fatalf("marshal: %v", err) + } + var g, w any + if err := json.Unmarshal(b, &g); err != nil { + t.Fatalf("unmarshal got: %v", err) + } + if err := json.Unmarshal([]byte(want), &w); err != nil { + t.Fatalf("unmarshal want: %v", err) + } + if !reflect.DeepEqual(g, w) { + t.Fatalf("wire mismatch\n got: %s\nwant: %s", b, want) + } +} + +// Regression tests for upstream issue #11 (assistant tool call conversion). + +func TestFromChatMessagesNullContentToolCallEmitsFunctionCall(t *testing.T) { + items, err := FromChatMessages([]ChatMessage{ + {Role: "user", Content: "What is the weather in Paris?"}, + {Role: "assistant", Content: nil, ToolCalls: []ParsedToolCall{{CallID: "call_123", Name: "get_weather", RawArgs: `{"location":"Paris"}`}}}, + {Role: "tool", Content: "Sunny, 22C", ToolCallID: "call_123"}, + }) + if err != nil { + t.Fatalf("FromChatMessages: %v", err) + } + assertWireJSON(t, items, `[ + {"role":"user","content":"What is the weather in Paris?"}, + {"type":"function_call","call_id":"call_123","id":"call_123","name":"get_weather","arguments":"{\"location\":\"Paris\"}","status":"completed"}, + {"type":"function_call_output","call_id":"call_123","output":"Sunny, 22C"} + ]`) +} + +func TestFromChatMessagesTextAndToolCallsEmitsBothInOrder(t *testing.T) { + items, err := FromChatMessages([]ChatMessage{ + {Role: "assistant", Content: "Let me check the weather for you.", ToolCalls: []ParsedToolCall{{CallID: "call_456", Name: "get_weather", RawArgs: `{"location":"London"}`}}}, + }) + if err != nil { + t.Fatalf("FromChatMessages: %v", err) + } + assertWireJSON(t, items, `[ + {"role":"assistant","content":"Let me check the weather for you."}, + {"type":"function_call","call_id":"call_456","id":"call_456","name":"get_weather","arguments":"{\"location\":\"London\"}","status":"completed"} + ]`) +} + +func TestFromChatMessagesParallelToolCallsEmitOneItemEach(t *testing.T) { + items, err := FromChatMessages([]ChatMessage{ + {Role: "assistant", ToolCalls: []ParsedToolCall{ + {CallID: "call_a", Name: "get_weather", RawArgs: `{"location":"Paris"}`}, + {CallID: "call_b", Name: "get_time", RawArgs: `{"tz":"UTC"}`}, + }}, + }) + if err != nil { + t.Fatalf("FromChatMessages: %v", err) + } + assertWireJSON(t, items, `[ + {"type":"function_call","call_id":"call_a","id":"call_a","name":"get_weather","arguments":"{\"location\":\"Paris\"}","status":"completed"}, + {"type":"function_call","call_id":"call_b","id":"call_b","name":"get_time","arguments":"{\"tz\":\"UTC\"}","status":"completed"} + ]`) +} + +func TestFromChatMessagesDoesNotReStringifyArguments(t *testing.T) { + items, err := FromChatMessages([]ChatMessage{ + {Role: "assistant", ToolCalls: []ParsedToolCall{{CallID: "call_raw", Name: "noop", RawArgs: `{"a":1}`, Arguments: map[string]any{"a": 1}}}}, + }) + if err != nil { + t.Fatalf("FromChatMessages: %v", err) + } + if len(items) != 1 || items[0].FunctionCallItem == nil { + t.Fatalf("expected a single function_call item, got %#v", items) + } + // Would be "\"{\\\"a\\\":1}\"" if the serialized arguments were encoded again. + if got := items[0].FunctionCallItem.Arguments; got != `{"a":1}` { + t.Fatalf("arguments = %q, want %q", got, `{"a":1}`) + } +} + +func TestFromChatMessagesEmptyToolCallsEmitsOnlyMessage(t *testing.T) { + items, err := FromChatMessages([]ChatMessage{ + {Role: "assistant", Content: "No tools needed.", ToolCalls: []ParsedToolCall{}}, + }) + if err != nil { + t.Fatalf("FromChatMessages: %v", err) + } + assertWireJSON(t, items, `[{"role":"assistant","content":"No tools needed."}]`) +} + +// A content-less assistant message without tool calls still round-trips as an +// empty message (upstream keeps it; only tool calls may replace it). +func TestFromChatMessagesEmptyAssistantWithoutToolCallsIsKept(t *testing.T) { + items, err := FromChatMessages([]ChatMessage{{Role: "assistant", Content: nil}, {Role: "assistant", Content: ""}}) + if err != nil { + t.Fatalf("FromChatMessages: %v", err) + } + assertWireJSON(t, items, `[{"role":"assistant","content":""},{"role":"assistant","content":""}]`) +} + +// Regression test for upstream issue #41: the result is directly usable as +// CallModel input (Go: []InputsUnion1 feeds CallModelInput.Input). +func TestFromChatMessagesResultIsCallModelInput(t *testing.T) { + items, err := FromChatMessages([]ChatMessage{ + {Role: "system", Content: "You are helpful."}, + {Role: "user", Content: "Hi"}, + {Role: "assistant", ToolCalls: []ParsedToolCall{{CallID: "call_typed", Name: "get_weather", RawArgs: `{}`}}}, + {Role: "tool", Content: "ok", ToolCallID: "call_typed"}, + }) + if err != nil { + t.Fatalf("FromChatMessages: %v", err) + } + var typed []ChatMessageInputItem = items + resp := components.OpenResponsesResult{ID: "resp_1", Model: "openai/test", Status: components.OpenAIResponsesResponseStatusCompleted, OutputText: openrouter.String("done")} + created := operations.CreateCreateResponsesResponseOpenResponsesResult(resp) + sender := &fakeSender{responses: []*operations.CreateResponsesResponse{&created}} + result, err := CallModel(t.Context(), sender, CallModelInput{Model: "openai/test", Input: typed}) + if err != nil { + t.Fatalf("CallModel: %v", err) + } + if _, err := result.Text(t.Context()); err != nil { + t.Fatalf("Text: %v", err) + } + if len(sender.requests) != 1 || sender.requests[0].Input == nil { + t.Fatalf("expected one request carrying input, got %d", len(sender.requests)) + } + assertWireJSON(t, sender.requests[0].Input.ArrayOfInputsUnion1, `[ + {"role":"system","content":"You are helpful."}, + {"role":"user","content":"Hi"}, + {"type":"function_call","call_id":"call_typed","id":"call_typed","name":"get_weather","arguments":"{}","status":"completed"}, + {"type":"function_call_output","call_id":"call_typed","output":"ok"} + ]`) +} + +// ToChatMessage is a format conversion: it keeps the emitted tool calls even +// for a non-completed response, unlike ExtractToolCallsFromResponse, which +// gates execution on the completed status. +func TestToChatMessageKeepsToolCallsOfIncompleteResponse(t *testing.T) { + call := components.OutputFunctionCallItem{CallID: "c1", Name: "search", Arguments: `{"q":"go"}`} + resp := components.OpenResponsesResult{ID: "r", Status: components.OpenAIResponsesResponseStatusIncomplete, Output: []components.OutputItems{components.CreateOutputItemsFunctionCall(call)}} + if got := ToChatMessage(resp).ToolCalls; len(got) != 1 || got[0].CallID != "c1" { + t.Fatalf("ToChatMessage dropped tool calls: %+v", got) + } +} diff --git a/claude.go b/claude.go index bd6f941..4b79d1f 100644 --- a/claude.go +++ b/claude.go @@ -1,15 +1,132 @@ package agent +import "encoding/json" + +// Claude content block types and non-Claude roles used for Claude-format +// detection (mirrors upstream claude-constants.ts). const ( ClaudeContentBlockTypeText = "text" + ClaudeContentBlockTypeImage = "image" ClaudeContentBlockTypeToolUse = "tool_use" + ClaudeContentBlockTypeToolResult = "tool_result" ClaudeContentBlockTypeThinking = "thinking" ClaudeContentBlockTypeUnsupportedContent = "unsupported_content" NonClaudeMessageRoleDeveloper = "developer" NonClaudeMessageRoleSystem = "system" + NonClaudeMessageRoleTool = "tool" ) type ClaudeContentBlockType string type NonClaudeMessageRole string -func IsClaudeStyleMessages(v any) bool { _, ok := v.([]ClaudeMessage); return ok } +// IsClaudeStyleMessages reports whether v looks like a list of Claude +// messages, using upstream's structural detection (isClaudeStyleMessages): +// +// - v must be a non-empty list; +// - entries that are not objects, have no `role`, or carry a top-level +// `type` (Responses-style items) are skipped; +// - any message with a system/developer/tool role means "not Claude"; +// - otherwise it is Claude-style once some message's content array holds a +// Claude-specific block: `tool_result`, `image` with an object `source`, +// or `tool_use` with a string `id`. +// +// v may be a []ClaudeMessage or any other value (e.g. []any or +// []map[string]any), which is inspected through its JSON encoding; a value +// that cannot be encoded is not Claude-style. For a ClaudeMessage an empty +// Type/ID/Source counts as absent. +func IsClaudeStyleMessages(v any) bool { + switch msgs := v.(type) { + case nil: + return false + case []ClaudeMessage: + return isClaudeStyleTyped(msgs) + } + // Normalize dynamic values (e.g. []any / []map[string]any literals with + // nested Go types) through JSON so the structural checks see plain + // objects and arrays, as upstream does. + b, err := json.Marshal(v) + if err != nil { + return false + } + var decoded any + if json.Unmarshal(b, &decoded) != nil { + return false + } + list, ok := decoded.([]any) + if !ok { + return false + } + return isClaudeStyleDynamic(list) +} + +func isNonClaudeRole(role string) bool { + return role == NonClaudeMessageRoleSystem || role == NonClaudeMessageRoleDeveloper || role == NonClaudeMessageRoleTool +} + +func isClaudeStyleTyped(msgs []ClaudeMessage) bool { + for _, m := range msgs { + if m.Role == "" || m.Type != "" { + continue + } + if isNonClaudeRole(m.Role) { + return false + } + for _, block := range m.Content { + switch block.Type { + case ClaudeContentBlockTypeToolResult: + return true + case ClaudeContentBlockTypeImage: + if block.Source != nil { + return true + } + case ClaudeContentBlockTypeToolUse: + if block.ID != "" { + return true + } + } + } + } + return false +} + +func isClaudeStyleDynamic(msgs []any) bool { + for _, entry := range msgs { + m, ok := entry.(map[string]any) + if !ok { + continue + } + role, hasRole := m["role"] + if !hasRole { + continue + } + if _, hasType := m["type"]; hasType { + continue // Claude messages don't have a top-level "type" + } + if r, ok := role.(string); ok && isNonClaudeRole(r) { + return false + } + content, ok := m["content"].([]any) + if !ok { + continue + } + for _, raw := range content { + block, ok := raw.(map[string]any) + if !ok { + continue + } + switch block["type"] { + case ClaudeContentBlockTypeToolResult: + return true + case ClaudeContentBlockTypeImage: + if _, ok := block["source"].(map[string]any); ok { + return true + } + case ClaudeContentBlockTypeToolUse: + if _, ok := block["id"].(string); ok { + return true + } + } + } + } + return false +} diff --git a/claude_test.go b/claude_test.go new file mode 100644 index 0000000..31c0857 --- /dev/null +++ b/claude_test.go @@ -0,0 +1,70 @@ +package agent + +import "testing" + +// Ports tests/unit/claude-type-guards.test.ts. Inputs are the JSON-shaped +// values upstream feeds isClaudeStyleMessages. +func TestIsClaudeStyleMessages(t *testing.T) { + type obj = map[string]any + type arr = []any + cases := []struct { + name string + input any + want bool + }{ + {"string", "hello", false}, + {"nil", nil, false}, + {"number", 42, false}, + {"single object", obj{"role": "user"}, false}, + {"empty array", arr{}, false}, + {"tool_result block", arr{obj{"role": "user", "content": arr{obj{"type": ClaudeContentBlockTypeToolResult, "tool_use_id": "x", "content": "ok"}}}}, true}, + {"image with source", arr{obj{"role": "user", "content": arr{obj{"type": ClaudeContentBlockTypeImage, "source": obj{"type": "base64", "media_type": "image/png", "data": "abc"}}}}}, true}, + {"image without source", arr{obj{"role": "user", "content": arr{obj{"type": ClaudeContentBlockTypeImage}}}}, false}, + {"image with non-object source", arr{obj{"role": "user", "content": arr{obj{"type": ClaudeContentBlockTypeImage, "source": "base64"}}}}, false}, + {"tool_use with string id", arr{obj{"role": "assistant", "content": arr{obj{"type": ClaudeContentBlockTypeToolUse, "id": "toolu_1", "name": "x", "input": obj{}}}}}, true}, + {"tool_use with non-string id", arr{obj{"role": "assistant", "content": arr{obj{"type": ClaudeContentBlockTypeToolUse, "id": 123}}}}, false}, + {"plain string content", arr{obj{"role": "user", "content": "hello"}, obj{"role": "assistant", "content": "hi there"}}, false}, + {"system role", arr{obj{"role": "system", "content": arr{obj{"type": ClaudeContentBlockTypeToolResult}}}}, false}, + {"developer role", arr{obj{"role": "developer", "content": arr{obj{"type": ClaudeContentBlockTypeToolResult}}}}, false}, + {"tool role", arr{obj{"role": "tool", "content": arr{obj{"type": ClaudeContentBlockTypeImage, "source": obj{}}}}}, false}, + {"skips non-record and role-less entries", arr{"not-a-message", obj{"content": arr{obj{"type": ClaudeContentBlockTypeToolResult}}}, obj{"role": "user", "content": arr{obj{"type": ClaudeContentBlockTypeToolResult}}}}, true}, + {"skips top-level type", arr{obj{"role": "user", "type": "message", "content": arr{obj{"type": ClaudeContentBlockTypeToolResult}}}}, false}, + {"plain text blocks", arr{obj{"role": "user", "content": arr{obj{"type": "text", "text": "hello"}}}}, false}, + {"non-record blocks", arr{obj{"role": "user", "content": arr{"just-a-string", nil, 42}}}, false}, + {"later message detected", arr{obj{"role": "user", "content": "hello"}, obj{"role": "assistant", "content": arr{obj{"type": ClaudeContentBlockTypeToolUse, "id": "toolu_9", "name": "x", "input": obj{}}}}}, true}, + // Go literals with nested typed slices are normalized like JSON. + {"[]map[string]any literal", []map[string]any{{"role": "user", "content": []map[string]any{{"type": "tool_result"}}}}, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := IsClaudeStyleMessages(tc.input); got != tc.want { + t.Fatalf("IsClaudeStyleMessages = %v, want %v", got, tc.want) + } + }) + } +} + +// Typed ClaudeMessage slices get the same structural detection. +func TestIsClaudeStyleMessagesTyped(t *testing.T) { + cases := []struct { + name string + msgs []ClaudeMessage + want bool + }{ + {"empty", []ClaudeMessage{}, false}, + {"plain text", []ClaudeMessage{{Role: "user", Content: []ClaudeContentBlock{{Type: "text", Text: "hi"}}}}, false}, + {"tool_use", []ClaudeMessage{{Role: "assistant", Content: []ClaudeContentBlock{{Type: "tool_use", ID: "toolu_1", Name: "x"}}}}, true}, + {"tool_result", []ClaudeMessage{{Role: "user", Content: []ClaudeContentBlock{{Type: "tool_result", ToolUseID: "toolu_1"}}}}, true}, + {"image without source", []ClaudeMessage{{Role: "user", Content: []ClaudeContentBlock{{Type: "image"}}}}, false}, + {"image with source", []ClaudeMessage{{Role: "user", Content: []ClaudeContentBlock{{Type: "image", Source: &ClaudeImageSource{Type: "url", URL: "u"}}}}}, true}, + {"system role", []ClaudeMessage{{Role: "system", Content: []ClaudeContentBlock{{Type: "tool_result"}}}}, false}, + {"top-level type skipped", []ClaudeMessage{{Type: "message", Role: "assistant", Content: []ClaudeContentBlock{{Type: "tool_use", ID: "t"}}}}, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := IsClaudeStyleMessages(tc.msgs); got != tc.want { + t.Fatalf("IsClaudeStyleMessages = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/hooks_emit.go b/hooks_emit.go index e90ba60..2c30d62 100644 --- a/hooks_emit.go +++ b/hooks_emit.go @@ -138,6 +138,13 @@ func executeHandlerChain(entries []*erasedEntry, initialPayload any, hctx Lifecy for i, entry := range entries { if hctx.Ctx != nil && hctx.Ctx.Err() != nil { + // A hook that can block (PreToolUse, UserPromptSubmit) fails + // closed: the handlers left unrun may include the guard that + // would have blocked, so an aborted chain must not read as an + // approval (upstream #160). + if hasBehavior && behavior.isBlocked != nil { + blocked = true + } break } diff --git a/item_types.go b/item_types.go index 090028b..55f5dd0 100644 --- a/item_types.go +++ b/item_types.go @@ -48,6 +48,18 @@ type UserMessageItem = components.EasyInputMessage type DeveloperMessageItem = components.EasyInputMessage type SystemMessageItem = components.EasyInputMessage type NewUserMessageItem = components.EasyInputMessage + +// NewSystemMessageItem is a new (id-less) system message for input. +type NewSystemMessageItem = components.EasyInputMessage + +// NewAssistantMessageItem is a new (id-less) assistant message for input — +// caller-supplied history such as FromChatMessages / FromClaudeMessages +// output. Distinct from AssistantMessageItem (= OutputMessageItem), which is +// what the model produces. +type NewAssistantMessageItem = components.EasyInputMessage + +// NewDeveloperMessageItem is a new (id-less) developer message for input. +type NewDeveloperMessageItem = components.EasyInputMessage type ErrorItem = components.ErrorEvent type FunctionProgressItem = ToolPreliminaryResultEvent type FunctionResultItem = ToolResultEvent diff --git a/model_result_test.go b/model_result_test.go index bd2e8d2..4e42910 100644 --- a/model_result_test.go +++ b/model_result_test.go @@ -18,10 +18,28 @@ type fakeSender struct { func (f *fakeSender) SendResponse(ctx context.Context, req components.ResponsesRequest, metadata *components.MetadataLevel, opts ...operations.Option) (*operations.CreateResponsesResponse, error) { f.calls++ f.requests = append(f.requests, req) - if f.calls > len(f.responses) { - return f.responses[len(f.responses)-1], nil + res := f.responses[len(f.responses)-1] + if f.calls <= len(f.responses) { + res = f.responses[f.calls-1] } - return f.responses[f.calls-1], nil + return withDefaultCompletedStatus(res), nil +} + +// withDefaultCompletedStatus fills in status "completed" on a non-streaming +// fake response that left it unset. Real Responses traffic always carries a +// status, and only a completed response's function calls are executed +// (upstream #177), so a hand-built fake with an empty status would otherwise +// silently stop exercising the tool loop. Fakes that need a non-completed +// status set it explicitly. +func withDefaultCompletedStatus(res *operations.CreateResponsesResponse) *operations.CreateResponsesResponse { + if res == nil || res.OpenResponsesResult == nil || res.OpenResponsesResult.Status != "" { + return res + } + copied := *res + resp := *res.OpenResponsesResult + resp.Status = components.OpenAIResponsesResponseStatusCompleted + copied.OpenResponsesResult = &resp + return &copied } func TestModelResultConsumesResponseAndReplaysStreams(t *testing.T) { diff --git a/next_turn_params.go b/next_turn_params.go index babb2dd..5cf8231 100644 --- a/next_turn_params.go +++ b/next_turn_params.go @@ -2,34 +2,270 @@ package agent import ( "context" + "encoding/json" + "fmt" "github.com/OpenRouterTeam/go-sdk/models/components" + "github.com/OpenRouterTeam/go-sdk/optionalnullable" ) +// NextTurnParamsContext is the set of request parameters a tool's +// NextTurnParams functions may read and replace for the following turn. +// Mirrors upstream buildNextTurnParamsContext, including ToolChoice (#114): +// a tool can widen `allowed_tools` without touching `tools`, which keeps the +// provider prompt-cache prefix intact. type NextTurnParamsContext struct { - ToolCall ParsedToolCall - Result ToolExecutionResult - Request components.ResponsesRequest + Input []components.InputsUnion1 + ToolChoice *components.OpenAIResponsesToolChoiceUnion + Model string + Models []string + Temperature *float64 + MaxOutputTokens *int64 + TopP *float64 + TopK *int64 + Instructions *string } -type NextTurnParamsFunctions map[string]func(context.Context, NextTurnParamsContext) (any, error) -func BuildNextTurnParamsContext(call ParsedToolCall, result ToolExecutionResult, request components.ResponsesRequest) NextTurnParamsContext { - return NextTurnParamsContext{ToolCall: call, Result: result, Request: request} +// NextTurnParamsFunctions declares per-parameter functions a tool runs after +// one of its calls succeeds. Each receives the decoded input the tool ran on +// and the working context (already reflecting earlier tools' changes), and +// returns the parameter's new value. Unset fields leave the parameter alone. +type NextTurnParamsFunctions[In any] struct { + Input func(context.Context, In, NextTurnParamsContext) ([]components.InputsUnion1, error) + ToolChoice func(context.Context, In, NextTurnParamsContext) (*components.OpenAIResponsesToolChoiceUnion, error) + Model func(context.Context, In, NextTurnParamsContext) (string, error) + Models func(context.Context, In, NextTurnParamsContext) ([]string, error) + Temperature func(context.Context, In, NextTurnParamsContext) (*float64, error) + MaxOutputTokens func(context.Context, In, NextTurnParamsContext) (*int64, error) + TopP func(context.Context, In, NextTurnParamsContext) (*float64, error) + TopK func(context.Context, In, NextTurnParamsContext) (*int64, error) + Instructions func(context.Context, In, NextTurnParamsContext) (*string, error) } -func ExecuteNextTurnParamsFunctions(ctx context.Context, funcs NextTurnParamsFunctions, ntctx NextTurnParamsContext) (map[string]any, error) { - out := map[string]any{} - for k, fn := range funcs { - v, err := fn(ctx, ntctx) + +// NextTurnParamsUpdate is the composed result of every NextTurnParams +// function that ran this round. Set reports which keys were produced (in +// upstream terms, the keys present on the returned partial context). +type NextTurnParamsUpdate struct { + Values NextTurnParamsContext + Set map[string]bool +} + +func (u *NextTurnParamsUpdate) mark(key string) { + if u.Set == nil { + u.Set = map[string]bool{} + } + u.Set[key] = true +} + +// Empty reports whether no parameter was produced. +func (u NextTurnParamsUpdate) Empty() bool { return len(u.Set) == 0 } + +func (f *NextTurnParamsFunctions[In]) apply(ctx context.Context, input In, working *NextTurnParamsContext, update *NextTurnParamsUpdate) error { + // Fixed key order mirrors upstream's documented key list; composition + // means each function sees the values produced before it. + if f.Input != nil { + v, err := f.Input(ctx, input, *working) if err != nil { - return nil, err + return err + } + working.Input, update.Values.Input = v, v + update.mark("input") + } + if f.ToolChoice != nil { + v, err := f.ToolChoice(ctx, input, *working) + if err != nil { + return err + } + working.ToolChoice, update.Values.ToolChoice = v, v + update.mark("toolChoice") + } + if f.Model != nil { + v, err := f.Model(ctx, input, *working) + if err != nil { + return err + } + working.Model, update.Values.Model = v, v + update.mark("model") + } + if f.Models != nil { + v, err := f.Models(ctx, input, *working) + if err != nil { + return err + } + working.Models, update.Values.Models = v, v + update.mark("models") + } + if f.Temperature != nil { + v, err := f.Temperature(ctx, input, *working) + if err != nil { + return err + } + working.Temperature, update.Values.Temperature = v, v + update.mark("temperature") + } + if f.MaxOutputTokens != nil { + v, err := f.MaxOutputTokens(ctx, input, *working) + if err != nil { + return err + } + working.MaxOutputTokens, update.Values.MaxOutputTokens = v, v + update.mark("maxOutputTokens") + } + if f.TopP != nil { + v, err := f.TopP(ctx, input, *working) + if err != nil { + return err + } + working.TopP, update.Values.TopP = v, v + update.mark("topP") + } + if f.TopK != nil { + v, err := f.TopK(ctx, input, *working) + if err != nil { + return err + } + working.TopK, update.Values.TopK = v, v + update.mark("topK") + } + if f.Instructions != nil { + v, err := f.Instructions(ctx, input, *working) + if err != nil { + return err + } + working.Instructions, update.Values.Instructions = v, v + update.mark("instructions") + } + return nil +} + +// ToolWithNextTurnParams is implemented by tools that declare NextTurnParams. +type ToolWithNextTurnParams interface { + Tool + HasNextTurnParams() bool + ApplyNextTurnParams(ctx context.Context, raw json.RawMessage, working *NextTurnParamsContext, update *NextTurnParamsUpdate) error +} + +// BuildNextTurnParamsContext extracts the parameters NextTurnParams functions +// may read from the current request (upstream buildNextTurnParamsContext). +func BuildNextTurnParamsContext(request components.ResponsesRequest) NextTurnParamsContext { + ctx := NextTurnParamsContext{ + Input: requestInputItems(request.Input), + ToolChoice: request.ToolChoice, + Models: append([]string{}, request.Models...), + TopK: request.TopK, + } + if ctx.Input == nil { + ctx.Input = []components.InputsUnion1{} + } + if request.Model != nil { + ctx.Model = *request.Model + } + if v, ok := request.Temperature.GetOrZero(); ok { + ctx.Temperature = &v + } + if v, ok := request.MaxOutputTokens.GetOrZero(); ok { + ctx.MaxOutputTokens = &v + } + if v, ok := request.TopP.GetOrZero(); ok { + ctx.TopP = &v + } + if v, ok := request.Instructions.GetOrZero(); ok { + ctx.Instructions = &v + } + return ctx +} + +// ExecuteNextTurnParamsFunctions runs NextTurnParams for the given calls, +// walking tools in tools order and, per tool, its calls in call order — +// later tools see modifications made by earlier ones (upstream +// executeNextTurnParamsFunctions). Server tools and tools without +// NextTurnParams are skipped. A call whose arguments are not a JSON object +// returns an error, as upstream throws. +func ExecuteNextTurnParamsFunctions(ctx context.Context, calls []ParsedToolCall, tools []Tool, request components.ResponsesRequest) (NextTurnParamsUpdate, error) { + working := BuildNextTurnParamsContext(request) + var update NextTurnParamsUpdate + for _, t := range tools { + nt, ok := t.(ToolWithNextTurnParams) + if !ok || IsServerTool(t) || !nt.HasNextTurnParams() { + continue + } + for _, call := range calls { + if call.Name != t.ToolName() { + continue + } + raw, err := nextTurnParamsArgs(call) + if err != nil { + return NextTurnParamsUpdate{}, err + } + if err := nt.ApplyNextTurnParams(ctx, raw, &working, &update); err != nil { + return NextTurnParamsUpdate{}, err + } } - out[k] = v } - return out, nil + return update, nil } -func ApplyNextTurnParamsToRequest(request components.ResponsesRequest, params map[string]any) components.ResponsesRequest { - if v, ok := params["model"].(string); ok { - request.Model = &v + +func nextTurnParamsArgs(call ParsedToolCall) (json.RawMessage, error) { + var value any = call.Arguments + if call.Arguments == nil && call.RawArgs != "" { + if err := json.Unmarshal([]byte(call.RawArgs), &value); err != nil { + value = call.RawArgs + } + } + if value == nil { + value = map[string]any{} + } + if _, ok := value.(map[string]any); !ok { + return nil, fmt.Errorf("tool call arguments for %s must be an object, got %s", call.Name, describeJSONType(value)) + } + return json.Marshal(value) +} + +// ApplyNextTurnParamsToRequest returns request with every produced parameter +// replaced. A nil pointer value clears the parameter (upstream strips null +// to undefined). +func ApplyNextTurnParamsToRequest(request components.ResponsesRequest, update NextTurnParamsUpdate) components.ResponsesRequest { + v := update.Values + if update.Set["input"] { + items := append([]components.InputsUnion1{}, v.Input...) + request.Input = &components.InputsUnion{ArrayOfInputsUnion1: items, Type: components.InputsUnionTypeArrayOfInputsUnion1} + } + if update.Set["toolChoice"] { + request.ToolChoice = v.ToolChoice + } + if update.Set["model"] { + if v.Model == "" { + request.Model = nil + } else { + model := v.Model + request.Model = &model + } + } + if update.Set["models"] { + request.Models = append([]string(nil), v.Models...) + } + if update.Set["temperature"] { + request.Temperature = optionalFromPtr(v.Temperature) + } + if update.Set["maxOutputTokens"] { + request.MaxOutputTokens = optionalFromPtr(v.MaxOutputTokens) + } + if update.Set["topP"] { + request.TopP = optionalFromPtr(v.TopP) + } + if update.Set["topK"] { + request.TopK = v.TopK + } + if update.Set["instructions"] { + request.Instructions = optionalFromPtr(v.Instructions) } return request } + +func optionalFromPtr[T any](v *T) optionalnullable.OptionalNullable[T] { + if v == nil { + return nil + } + copied := *v + return optionalnullable.From(&copied) +} diff --git a/reusable_stream.go b/reusable_stream.go index c759671..5278629 100644 --- a/reusable_stream.go +++ b/reusable_stream.go @@ -2,168 +2,334 @@ package agent import "sync" +// StreamReplay controls how much history a ReusableStream (and a +// ToolEventBroadcaster) retains for consumers that attach later. It mirrors +// upstream's `StreamReplay` (`'full' | 'active-consumers'`). +type StreamReplay string + +const ( + // StreamReplayFull retains the complete history so delayed and sequential + // consumers always replay every value from the beginning. This is the + // default. + StreamReplayFull StreamReplay = "full" + // StreamReplayActiveConsumers compacts history once every attached + // consumer has advanced past it, bounding memory for long streams. A + // consumer that attaches later starts at the current trim watermark + // instead of replaying from the beginning, and once every consumer has + // departed the unread backlog is released. + StreamReplayActiveConsumers StreamReplay = "active-consumers" +) + +// normalize maps the zero value (and any unrecognized policy) to the +// upstream default, StreamReplayFull. +func (p StreamReplay) normalize() StreamReplay { + if p == StreamReplayActiveConsumers { + return StreamReplayActiveConsumers + } + return StreamReplayFull +} + +// bufferCompactionMinHead mirrors upstream BUFFER_COMPACTION_MIN_HEAD: the +// consumed prefix of the retained buffer is physically reallocated away once +// it is at least this long and makes up at least half of the buffer. +const bufferCompactionMinHead = 1024 + // ReusableStream is a fan-out broadcast of a sequence of values that supports -// multiple concurrent consumers, each of which sees every value plus the -// terminal error — the Go-idiomatic stand-in for the upstream -// ReusableReadableStream. New subscribers also replay the full history. +// multiple concurrent consumers, each of which sees every retained value plus +// the terminal error — the Go-idiomatic stand-in for the upstream +// ReusableReadableStream. // -// Each subscriber gets its own goroutine and an internal queue, so a slow -// consumer never blocks the producer and the producer never sends on a channel -// that is being closed concurrently (which would panic). +// Under the default StreamReplayFull policy, new subscribers replay the full +// history. Under StreamReplayActiveConsumers, history already consumed by every +// attached subscriber is dropped and new subscribers start at that watermark. +// +// Each subscriber gets its own goroutine that owns its output channel, so a +// slow consumer never blocks the producer and the producer never sends on a +// channel that is being closed concurrently (which would panic). type ReusableStream[T any] struct { - mu sync.Mutex - history []T - subs map[*subscriber[T]]struct{} - done bool - err error + mu sync.Mutex + replay StreamReplay + // buf[head:] are the retained values; buf[head] is at absolute position + // trimOffset. Consumer positions are absolute. + buf []T + head int + trimOffset int + consumers map[*streamConsumer[T]]struct{} + // everSubscribed is set once the first consumer attaches. Before that the + // backlog IS the catch-up history late joiners replay and is never + // dropped. + everSubscribed bool + done bool + err error + // wake is closed (and replaced) on every state change so blocked + // consumers re-check; it is the channel analogue of upstream's + // notifyAllConsumers. + wake chan struct{} } -type subscriber[T any] struct { - mu sync.Mutex - cond *sync.Cond - queue []T - out chan T - closed bool // subscriber unsubscribed/cancelled - flushed bool // stream completed and all queued values drained +// streamConsumer is a pull-based reader with an independent absolute read +// position — the analogue of upstream createConsumer(). Subscribe layers a +// channel on top of it. +type streamConsumer[T any] struct { + r *ReusableStream[T] + pos int // guarded by r.mu + cancelled bool // guarded by r.mu } +// NewReusableStream returns a stream with the default StreamReplayFull policy. func NewReusableStream[T any]() *ReusableStream[T] { - return &ReusableStream[T]{subs: map[*subscriber[T]]struct{}{}} + return NewReusableStreamWithReplay[T](StreamReplayFull) +} + +// NewReusableStreamWithReplay returns a stream using the given replay policy. +// The zero value (or an unrecognized policy) selects StreamReplayFull. +func NewReusableStreamWithReplay[T any](replay StreamReplay) *ReusableStream[T] { + return &ReusableStream[T]{ + replay: replay.normalize(), + consumers: map[*streamConsumer[T]]struct{}{}, + wake: make(chan struct{}), + } +} + +// Replay reports the stream's replay policy. +func (r *ReusableStream[T]) Replay() StreamReplay { return r.replay } + +// notifyLocked wakes every blocked consumer. Caller holds r.mu. +func (r *ReusableStream[T]) notifyLocked() { + close(r.wake) + r.wake = make(chan struct{}) } +// Push appends a value and wakes consumers. Pushes after Complete or Cancel +// are ignored. func (r *ReusableStream[T]) Push(v T) { r.mu.Lock() + defer r.mu.Unlock() if r.done { - r.mu.Unlock() return } - r.history = append(r.history, v) - subs := make([]*subscriber[T], 0, len(r.subs)) - for s := range r.subs { - subs = append(subs, s) - } - r.mu.Unlock() - for _, s := range subs { - s.enqueue(v) - } + r.buf = append(r.buf, v) + r.notifyLocked() } +// Complete marks the stream finished with err (nil for success). Every +// consumer — attached now or later — drains its remaining retained values and +// then observes err. Only the first Complete/Cancel takes effect. func (r *ReusableStream[T]) Complete(err error) { r.mu.Lock() + defer r.mu.Unlock() if r.done { - r.mu.Unlock() return } r.done = true r.err = err - subs := make([]*subscriber[T], 0, len(r.subs)) - for s := range r.subs { - subs = append(subs, s) - } - r.subs = map[*subscriber[T]]struct{}{} - r.mu.Unlock() - for _, s := range subs { - s.finish() - } + r.notifyLocked() } -// Subscribe returns a channel of values plus a cancel/wait function that returns -// the terminal error after the stream completes (or the consumer stops early). -func (r *ReusableStream[T]) Subscribe(buffer int) (<-chan T, func() error) { - if buffer <= 0 { - buffer = 16 - } - s := &subscriber[T]{out: make(chan T, buffer)} - s.cond = sync.NewCond(&s.mu) - +// Cancel terminates the stream and every consumer (mirrors upstream +// cancel()): attached subscribers stop and their channels close without +// delivering further values, subsequent pushes are ignored, and the retained +// backlog is released regardless of replay policy because nobody can read it +// anymore. Subscribers created afterwards end immediately. Err is unchanged. +func (r *ReusableStream[T]) Cancel() { r.mu.Lock() - s.queue = append(s.queue, r.history...) - done := r.done - if !done { - r.subs[s] = struct{}{} + defer r.mu.Unlock() + for c := range r.consumers { + c.cancelled = true } - r.mu.Unlock() + clear(r.consumers) + r.done = true + r.dropUnreadBacklogLocked() + r.notifyLocked() +} - go s.pump() - if done { - s.finish() - } +// newConsumer attaches a pull consumer. Full-replay consumers start at +// position 0; active-consumer replay starts at the current trim watermark. +func (r *ReusableStream[T]) newConsumer() *streamConsumer[T] { + r.mu.Lock() + defer r.mu.Unlock() + c := &streamConsumer[T]{r: r, pos: r.trimOffset} + r.consumers[c] = struct{}{} + r.everSubscribed = true + return c +} - return s.out, func() error { +// next returns the consumer's next value. ok is false once the stream has +// ended (inspect r.Err for the terminal error), the consumer was cancelled, or +// stop was closed while waiting. +func (c *streamConsumer[T]) next(stop <-chan struct{}) (v T, ok bool) { + r := c.r + for { r.mu.Lock() - delete(r.subs, s) - err := r.err + if c.cancelled { + r.mu.Unlock() + return v, false + } + if idx := r.head + c.pos - r.trimOffset; idx < len(r.buf) { + v = r.buf[idx] + c.pos++ + r.trimConsumedLocked() + r.mu.Unlock() + return v, true + } + if r.done { + r.mu.Unlock() + return v, false + } + wake := r.wake r.mu.Unlock() - s.close() - return err + select { + case <-wake: + case <-stop: + return v, false + } } } -func (r *ReusableStream[T]) Snapshot() []T { +// cancel detaches the consumer (mirrors upstream consumer return()/throw()): +// a pending next wakes and reports done, and the consumer no longer pins any +// backlog. Idempotent. +func (c *streamConsumer[T]) cancel() { + r := c.r r.mu.Lock() defer r.mu.Unlock() - return append([]T{}, r.history...) + if c.cancelled { + return + } + c.cancelled = true + if _, ok := r.consumers[c]; ok { + delete(r.consumers, c) + r.trimConsumedLocked() + } + r.notifyLocked() } -func (r *ReusableStream[T]) Err() error { r.mu.Lock(); defer r.mu.Unlock(); return r.err } - -// IsComplete reports whether the source has been fully read into the -// buffer. A fresh consumer created after this point replays the retained -// buffer without waiting on a producer. -func (r *ReusableStream[T]) IsComplete() bool { - r.mu.Lock() - defer r.mu.Unlock() - return r.done +// trimConsumedLocked drops history every attached consumer has read. It is a +// no-op under StreamReplayFull. Caller holds r.mu. +func (r *ReusableStream[T]) trimConsumedLocked() { + if r.replay != StreamReplayActiveConsumers { + return + } + if len(r.consumers) == 0 { + r.dropUnreadBacklogLocked() + return + } + minPos := -1 + for c := range r.consumers { + if minPos < 0 || c.pos < minPos { + minPos = c.pos + } + } + nextHead := r.head + minPos - r.trimOffset + if nextHead <= r.head { + return + } + r.trimOffset = minPos + if nextHead == len(r.buf) { + r.buf = nil + r.head = 0 + return + } + // Zero the consumed slots so their referents can be collected even before + // the backing array is reallocated. + clear(r.buf[r.head:nextHead]) + if nextHead >= bufferCompactionMinHead && nextHead*2 >= len(r.buf) { + r.buf = append([]T(nil), r.buf[nextHead:]...) + r.head = 0 + return + } + r.head = nextHead } -// enqueue appends a value for delivery to this subscriber. -func (s *subscriber[T]) enqueue(v T) { - s.mu.Lock() - if !s.closed && !s.flushed { - s.queue = append(s.queue, v) - s.cond.Signal() +// dropUnreadBacklogLocked releases the retained backlog once no consumer can +// ever read it again. Before the first consumer attaches the backlog is kept +// for late joiners. Caller holds r.mu. +func (r *ReusableStream[T]) dropUnreadBacklogLocked() { + if !r.everSubscribed { + return + } + dropped := len(r.buf) - r.head + if dropped == 0 { + return } - s.mu.Unlock() + r.trimOffset += dropped + r.buf = nil + r.head = 0 } -// finish marks the stream as complete; the pump drains remaining queued values -// then closes the output channel. -func (s *subscriber[T]) finish() { - s.mu.Lock() - s.flushed = true - s.cond.Signal() - s.mu.Unlock() +// Subscribe returns a channel of values plus a cancel/wait function. The +// channel closes after the stream completes and every retained value has been +// delivered, or once the function is called. The function detaches the +// subscriber (releasing any backlog it pinned) and returns the stream's +// terminal error, or nil if the stream has not failed (yet). +// +// Under StreamReplayActiveConsumers, values handed to the subscriber's +// buffered channel count as consumed by it: the buffer is read-ahead. +func (r *ReusableStream[T]) Subscribe(buffer int) (<-chan T, func() error) { + if buffer <= 0 { + buffer = 16 + } + c := r.newConsumer() + out := make(chan T, buffer) + stop := make(chan struct{}) + go func() { + defer close(out) + for { + v, ok := c.next(stop) + if !ok { + // Natural end (or stop): detach so a finished subscriber does + // not linger in the consumer set. + c.cancel() + return + } + select { + case out <- v: + case <-stop: + return + } + } + }() + var once sync.Once + return out, func() error { + once.Do(func() { + close(stop) + c.cancel() + }) + return r.Err() + } } -// close stops delivery immediately (consumer unsubscribed/cancelled). -func (s *subscriber[T]) close() { - s.mu.Lock() - s.closed = true - s.cond.Signal() - s.mu.Unlock() +// Snapshot returns the currently retained values: the full history under +// StreamReplayFull, or the not-yet-compacted suffix under +// StreamReplayActiveConsumers. +func (r *ReusableStream[T]) Snapshot() []T { + r.mu.Lock() + defer r.mu.Unlock() + return append([]T{}, r.buf[r.head:]...) } -// pump is the single goroutine that owns the output channel; it is the only -// place that sends on or closes s.out, eliminating send-on-closed races. -func (s *subscriber[T]) pump() { - for { - s.mu.Lock() - for len(s.queue) == 0 && !s.flushed && !s.closed { - s.cond.Wait() - } - if s.closed { - s.mu.Unlock() - close(s.out) - return - } - if len(s.queue) == 0 && s.flushed { - s.mu.Unlock() - close(s.out) - return +// FindLastBuffered scans the retained values from the end and returns the +// last one matching pred (mirrors upstream findLastBuffered). It only sees +// what is still retained. +func (r *ReusableStream[T]) FindLastBuffered(pred func(T) bool) (T, bool) { + r.mu.Lock() + defer r.mu.Unlock() + for i := len(r.buf) - 1; i >= r.head; i-- { + if pred(r.buf[i]) { + return r.buf[i], true } - v := s.queue[0] - s.queue = s.queue[1:] - s.mu.Unlock() - s.out <- v } + var zero T + return zero, false +} + +func (r *ReusableStream[T]) Err() error { r.mu.Lock(); defer r.mu.Unlock(); return r.err } + +// IsComplete reports whether the stream has completed (or been cancelled). A +// fresh consumer created after this point replays the retained buffer without +// waiting on a producer. +func (r *ReusableStream[T]) IsComplete() bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.done } diff --git a/reusable_stream_test.go b/reusable_stream_test.go new file mode 100644 index 0000000..611d8df --- /dev/null +++ b/reusable_stream_test.go @@ -0,0 +1,290 @@ +package agent + +import ( + "errors" + "reflect" + "sync" + "testing" +) + +// Ports tests/unit/reusable-stream.test.ts and +// tests/unit/replay-buffer-compaction.test.ts. Upstream asserts on +// createConsumer() iterators; the pull consumer (newConsumer/next) is their +// exact analogue, while Subscribe-based cases assert the public channel API. + +// drainConsumer reads a pull consumer to the end. +func drainConsumer[T any](c *streamConsumer[T]) []T { + out := []T{} + for { + v, ok := c.next(nil) + if !ok { + return out + } + out = append(out, v) + } +} + +// drainChannel reads a subscription to the end and returns the terminal error. +func drainChannel[T any](ch <-chan T, wait func() error) ([]T, error) { + out := []T{} + for v := range ch { + out = append(out, v) + } + return out, wait() +} + +func mustNext[T comparable](t *testing.T, c *streamConsumer[T], want T) { + t.Helper() + got, ok := c.next(nil) + if !ok || got != want { + t.Fatalf("next = %v, %v; want %v, true", got, ok, want) + } +} + +func streamOf[T any](replay StreamReplay, values ...T) *ReusableStream[T] { + s := NewReusableStreamWithReplay[T](replay) + for _, v := range values { + s.Push(v) + } + s.Complete(nil) + return s +} + +func TestReusableStreamDefaultReplaysFullHistoryToSequentialConsumers(t *testing.T) { + s := NewReusableStream[int]() + if s.Replay() != StreamReplayFull { + t.Fatalf("default replay = %q", s.Replay()) + } + s.Push(1) + s.Push(2) + s.Push(3) + s.Complete(nil) + for i := 0; i < 2; i++ { + got, err := drainChannel(s.Subscribe(1)) + if err != nil || !reflect.DeepEqual(got, []int{1, 2, 3}) { + t.Fatalf("consumer %d = %v, %v; want [1 2 3]", i, got, err) + } + } + if got := s.Snapshot(); !reflect.DeepEqual(got, []int{1, 2, 3}) { + t.Fatalf("full replay must retain history, Snapshot = %v", got) + } +} + +func TestReusableStreamZeroReplayIsFull(t *testing.T) { + if got := NewReusableStreamWithReplay[int]("").Replay(); got != StreamReplayFull { + t.Fatalf("zero replay = %q, want full", got) + } +} + +func TestReusableStreamActiveConsumersStartAtWatermark(t *testing.T) { + s := streamOf(StreamReplayActiveConsumers, 1, 2, 3) + first := s.newConsumer() + mustNext(t, first, 1) + second := s.newConsumer() + if got := drainConsumer(first); !reflect.DeepEqual(got, []int{2, 3}) { + t.Fatalf("first = %v", got) + } + if got := drainConsumer(second); !reflect.DeepEqual(got, []int{2, 3}) { + t.Fatalf("second = %v, want [2 3] (starts at watermark)", got) + } +} + +func TestReusableStreamActiveConsumersRepeatedCompaction(t *testing.T) { + values := make([]int, 2500) + for i := range values { + values[i] = i + } + s := streamOf(StreamReplayActiveConsumers, values...) + c := s.newConsumer() + var got []int + for i := 0; i < 1500; i++ { + v, ok := c.next(nil) + if !ok { + t.Fatalf("ended early at %d", i) + } + got = append(got, v) + } + if n := len(s.Snapshot()); n != 1000 { + t.Fatalf("retained %d values after consuming 1500 of 2500, want 1000", n) + } + got = append(got, drainConsumer(c)...) + if !reflect.DeepEqual(got, values) { + t.Fatalf("consumer lost or reordered values across compaction (len %d)", len(got)) + } + if late := drainConsumer(s.newConsumer()); len(late) != 0 { + t.Fatalf("late consumer replayed %d compacted values", len(late)) + } +} + +func TestReusableStreamActiveBacklogFollowsSlowestConsumer(t *testing.T) { + s := NewReusableStreamWithReplay[int](StreamReplayActiveConsumers) + fast, slow := s.newConsumer(), s.newConsumer() + s.Push(1) + s.Push(2) + mustNext(t, fast, 1) + mustNext(t, fast, 2) + fast.cancel() + mustNext(t, slow, 1) + mustNext(t, slow, 2) + s.Complete(nil) + if _, ok := slow.next(nil); ok { + t.Fatalf("slow consumer should be done") + } +} + +func TestReusableStreamActiveBacklogDroppedWhenEveryConsumerDeparts(t *testing.T) { + s := NewReusableStreamWithReplay[int](StreamReplayActiveConsumers) + only := s.newConsumer() + s.Push(1) + s.Push(2) + mustNext(t, only, 1) + mustNext(t, only, 2) + only.cancel() + if _, ok := s.FindLastBuffered(func(int) bool { return true }); ok { + t.Fatalf("backlog still retained after every consumer departed") + } + s.Push(3) + late := s.newConsumer() + mustNext(t, late, 3) + s.Complete(nil) +} + +func TestReusableStreamActiveBacklogRetainedBeforeFirstConsumer(t *testing.T) { + // Before anyone attaches the backlog is the catch-up history. + s := streamOf(StreamReplayActiveConsumers, 1, 2) + got, err := drainChannel(s.Subscribe(1)) + if err != nil || !reflect.DeepEqual(got, []int{1, 2}) { + t.Fatalf("first subscriber = %v, %v", got, err) + } + // A fully caught-up consumer leaves nothing for later joiners. + if got, _ := drainChannel(s.Subscribe(1)); len(got) != 0 { + t.Fatalf("late subscriber replayed %v under active-consumers", got) + } +} + +func TestReusableStreamConsumerCancelWakesPendingNext(t *testing.T) { + for _, replay := range []StreamReplay{StreamReplayFull, StreamReplayActiveConsumers} { + s := NewReusableStreamWithReplay[int](replay) + c := s.newConsumer() + s.Push(1) + mustNext(t, c, 1) + result := make(chan bool) + go func() { + _, ok := c.next(nil) + result <- ok + }() + c.cancel() + if ok := <-result; ok { + t.Fatalf("%s: pending next after cancel returned a value", replay) + } + s.Complete(nil) + } +} + +func TestReusableStreamCancelSettlesConsumersAndDropsBacklog(t *testing.T) { + s := NewReusableStream[int]() + ch, wait := s.Subscribe(1) + s.Push(1) + s.Push(2) + s.Cancel() + for range ch { + // Whether a buffered value was already handed over depends on + // scheduling; the contract is that the channel closes. + } + if err := wait(); err != nil { + t.Fatalf("cancel is not an error, got %v", err) + } + if _, ok := s.FindLastBuffered(func(int) bool { return true }); ok { + t.Fatalf("Cancel must drop the backlog even under full replay") + } + s.Push(3) + if got, _ := drainChannel(s.Subscribe(1)); len(got) != 0 { + t.Fatalf("fresh subscriber after Cancel got %v", got) + } + if !s.IsComplete() { + t.Fatalf("Cancel must be terminal") + } +} + +// A subscriber that stops reading and cancels must not leave its channel open +// or keep pinning the backlog, even though its pump is blocked on a send. +func TestReusableStreamStalledSubscriberCancelClosesAndReleases(t *testing.T) { + s := NewReusableStreamWithReplay[int](StreamReplayActiveConsumers) + ch, wait := s.Subscribe(1) + for i := 0; i < 10; i++ { + s.Push(i) + } + if got := <-ch; got != 0 { + t.Fatalf("first value = %d", got) + } + if err := wait(); err != nil { + t.Fatal(err) + } + for range ch { + } + if got := s.Snapshot(); len(got) != 0 { + t.Fatalf("cancelled subscriber still pins backlog: %v", got) + } + s.Complete(nil) +} + +func TestReusableStreamFullReplaySurvivesSubscriberCancel(t *testing.T) { + s := NewReusableStream[int]() + ch, wait := s.Subscribe(1) + s.Push(1) + s.Push(2) + <-ch + _ = wait() + s.Complete(nil) + if got, _ := drainChannel(s.Subscribe(1)); !reflect.DeepEqual(got, []int{1, 2}) { + t.Fatalf("late subscriber under full replay = %v", got) + } +} + +func TestReusableStreamErrorReachesEveryConsumer(t *testing.T) { + boom := errors.New("boom") + for _, replay := range []StreamReplay{StreamReplayFull, StreamReplayActiveConsumers} { + s := NewReusableStreamWithReplay[int](replay) + var wg sync.WaitGroup + results := make([][]int, 2) + errs := make([]error, 2) + for i := range results { + ch, wait := s.Subscribe(1) + wg.Add(1) + go func() { + defer wg.Done() + results[i], errs[i] = drainChannel(ch, wait) + }() + } + s.Push(1) + s.Push(2) + s.Complete(boom) + wg.Wait() + for i := range results { + if !errors.Is(errs[i], boom) || !reflect.DeepEqual(results[i], []int{1, 2}) { + t.Fatalf("%s consumer %d = %v, %v", replay, i, results[i], errs[i]) + } + } + late, err := drainChannel(s.Subscribe(1)) + if !errors.Is(err, boom) { + t.Fatalf("%s: late subscriber err = %v", replay, err) + } + want := []int{1, 2} + if replay == StreamReplayActiveConsumers { + want = []int{} + } + if !reflect.DeepEqual(late, want) { + t.Fatalf("%s: late subscriber = %v, want %v", replay, late, want) + } + } +} + +func TestReusableStreamFindLastBuffered(t *testing.T) { + s := streamOf(StreamReplayFull, 1, 2, 3, 4) + if v, ok := s.FindLastBuffered(func(v int) bool { return v%2 == 1 }); !ok || v != 3 { + t.Fatalf("FindLastBuffered = %v, %v; want 3", v, ok) + } + if _, ok := s.FindLastBuffered(func(v int) bool { return v > 10 }); ok { + t.Fatalf("FindLastBuffered matched nothing but reported ok") + } +} diff --git a/stream_transformers.go b/stream_transformers.go index 88ba353..aac3903 100644 --- a/stream_transformers.go +++ b/stream_transformers.go @@ -32,17 +32,58 @@ func ExtractTextFromResponse(resp components.OpenResponsesResult) string { return b.String() } +// isResponseCompleted reports whether the response reached the "completed" +// terminal status, which is what makes its function_call items eligible for +// local tool execution. Non-completed responses (incomplete for +// max_output_tokens or content_filter, failed, cancelled, in_progress, queued, +// or an unknown status) may carry truncated, filtered, or in-flight +// output and must not trigger tool execution. +func isResponseCompleted(resp components.OpenResponsesResult) bool { + return resp.Status == components.OpenAIResponsesResponseStatusCompleted +} + +// ExtractToolCallsFromResponse returns the parsed function calls of a +// completed response. Any response whose status is not "completed" yields no +// tool calls (upstream non-completed-response gating); the response itself, +// including its output items, is left untouched for the caller. func ExtractToolCallsFromResponse(resp components.OpenResponsesResult) []ParsedToolCall { + if !isResponseCompleted(resp) { + return nil + } + return extractFunctionCalls(resp) +} + +// ResponseHasToolCalls reports whether a response carries function calls the +// tool loop should execute. Only a response with status "completed" is +// eligible, even when a non-completed response's output contains +// function_call items. +func ResponseHasToolCalls(resp components.OpenResponsesResult) bool { + if !isResponseCompleted(resp) { + return false + } + for _, item := range resp.Output { + if item.OutputFunctionCallItem != nil { + return true + } + } + return false +} + +// extractFunctionCalls parses every function_call output item regardless of +// response status. Format conversions (ToChatMessage) use it because they +// describe what the model emitted rather than deciding execution. +func extractFunctionCalls(resp components.OpenResponsesResult) []ParsedToolCall { var calls []ParsedToolCall for _, item := range resp.Output { if item.OutputFunctionCallItem == nil { continue } fc := item.OutputFunctionCallItem - raw, args, err := ParseToolArguments(fc.Arguments) - if err != nil { - continue - } + // Invalid JSON arguments are kept (Arguments holds the raw string), + // mirroring upstream: the call still runs through the executor, which + // reports the parse failure to the model as an error output, so every + // function_call in history keeps a paired function_call_output. + raw, args, _ := ParseToolArguments(fc.Arguments) id := fc.CallID if id == "" && fc.ID != nil { id = *fc.ID diff --git a/tool.go b/tool.go index 76f9154..3d24d9c 100644 --- a/tool.go +++ b/tool.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "reflect" openrouter "github.com/OpenRouterTeam/go-sdk" @@ -14,12 +15,26 @@ import ( var ErrReservedToolName = errors.New("tool name 'shared' is reserved") +// ErrWireInputSchemaNotManual is returned by NewTool when WireInputSchema is +// set on a tool that executes locally. Upstream only accepts +// `wireInputSchema` on manual (`execute: false`) tools (it is a type error +// elsewhere); MCP-wrapped tools supply it through MarkMcpWithOptions instead. +var ErrWireInputSchemaNotManual = errors.New("wireInputSchema is only supported on manual tools (no Execute/Generate/OnToolCalled)") + type ToolConfig[In any] struct { - Name string - Description string - InputSchema map[string]any - OutputSchema map[string]any - EventSchema map[string]any + Name string + Description string + InputSchema map[string]any + OutputSchema map[string]any + EventSchema map[string]any + // WireInputSchema is a caller-owned JSON Schema serialized to the model + // verbatim (sanitized of `~`-prefixed keys, never mutated) instead of the + // schema derived from In / InputSchema, which still validates the call. + // Manual tools only (upstream #118). + WireInputSchema map[string]any + // Strict is forwarded as the function tool's `strict` flag. nil sends + // `strict: null` (provider default), matching upstream #99. + Strict *bool Execute func(context.Context, In, ToolExecuteContext) (any, error) Generate func(context.Context, In, ToolExecuteContext, func(any) error) (any, error) Manual bool @@ -27,6 +42,17 @@ type ToolConfig[In any] struct { Approval ToolApprovalCheck OnToolCalled func(context.Context, In, ToolExecuteContext) (any, bool, error) OnResponseReceived func(context.Context, any, ToolExecuteContext) (any, error) + // ToModelOutput maps a successful execution's output to model-facing + // content. It receives the decoded input (the same value Execute got) + // and runs on every result path, including the approval-resume path + // (upstream #155). A nil result (or one whose Type is not "content") + // sends the JSON-encoded output unchanged. + ToModelOutput func(context.Context, ToModelOutputParams[In]) (*ToModelOutputResult, error) + // NextTurnParams lets a successful call change request parameters for + // the next turn (upstream nextTurnParams, incl. ToolChoice from #114). + // Only calls whose tool body ran and returned without error contribute, + // and they receive the input the tool actually ran on (upstream #153). + NextTurnParams *NextTurnParamsFunctions[In] } type TypedTool[In any] struct { @@ -42,6 +68,9 @@ func NewTool[In any](config ToolConfig[In]) (*TypedTool[In], error) { return nil, errors.New("tool name is required") } t := &TypedTool[In]{config: config} + if config.WireInputSchema != nil && t.ToolType() != ToolTypeManual { + return nil, ErrWireInputSchemaNotManual + } if config.InputSchema != nil { t.schema = copyMap(config.InputSchema) } else { @@ -97,29 +126,125 @@ func (t *TypedTool[In]) HandleResponseReceived(ctx context.Context, output any, } func (t *TypedTool[In]) ToAPITool() components.ResponsesRequestToolUnion { + return functionAPITool(t.config.Name, t.config.Description, t.config.Strict, t.WireInputSchema(), t.InputSchema()) +} + +// WireInputSchema returns the caller-owned schema serialized to the model in +// place of InputSchema, sanitized and copied, or nil when none was supplied. +func (t *TypedTool[In]) WireInputSchema() map[string]any { + if t.config.WireInputSchema == nil { + return nil + } + return SanitizeSchema(t.config.WireInputSchema) +} + +// Strict reports the tool's configured `strict` flag (nil = unset). +func (t *TypedTool[In]) Strict() *bool { return t.config.Strict } + +// functionAPITool builds the wire function-tool definition shared by +// TypedTool and MCP-branded tools: `strict` passes through (nil -> null, +// upstream #99) and a wire schema, when present, replaces the derived one. +func functionAPITool(name, description string, strict *bool, wire, derived map[string]any) components.ResponsesRequestToolUnion { + params := derived + if wire != nil { + params = wire + } fn := components.ResponsesRequestToolFunction{ - Name: t.config.Name, - Parameters: t.InputSchema(), + Name: name, + Parameters: params, Type: components.ResponsesRequestTypeFunction, } - if t.config.Description != "" { - fn.Description = optionalnullable.From(openrouter.String(t.config.Description)) + if description != "" { + fn.Description = optionalnullable.From(openrouter.String(description)) + } + if strict != nil { + v := *strict + fn.Strict = optionalnullable.From(&v) + } else { + fn.Strict = optionalnullable.From[bool](nil) } - strict := true - fn.Strict = optionalnullable.From(&strict) return components.CreateResponsesRequestToolUnionFunction(fn) } -func (t *TypedTool[In]) Execute(ctx context.Context, raw json.RawMessage, execCtx ToolExecuteContext) (ToolExecutionResult, error) { +// decodeInput decodes raw arguments into In and validates them against the +// tool schema — the same parse Execute performs before running the body. +func (t *TypedTool[In]) decodeInput(raw json.RawMessage) (In, error) { var input In if len(raw) == 0 || string(raw) == "null" { raw = []byte("{}") } if err := json.Unmarshal(raw, &input); err != nil { - return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Error: err}, nil + return input, err } if err := ValidateAgainstSchema(raw, t.schema); err != nil { - return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Error: err}, nil + return input, err + } + return input, nil +} + +// ParseToolInput decodes raw call arguments the way Execute will and returns +// them re-encoded as a JSON object, so lifecycle hooks and approval checks +// inspect the same normalized value the tool body receives (upstream #179 / +// #94). ok is false when the arguments do not decode or validate, or do not +// form an object; callers then fall back to the raw arguments. +func (t *TypedTool[In]) ParseToolInput(raw json.RawMessage) (map[string]any, bool) { + input, err := t.decodeInput(raw) + if err != nil { + return nil, false + } + b, err := json.Marshal(input) + if err != nil { + return nil, false + } + var out map[string]any + if err := json.Unmarshal(b, &out); err != nil || out == nil { + return nil, false + } + return out, true +} + +// MapModelOutput applies the configured ToModelOutput mapper to a successful +// execution's output. ok is false when the tool has no mapper or the mapper +// did not return content; the caller then sends the output unchanged. +func (t *TypedTool[In]) MapModelOutput(ctx context.Context, raw json.RawMessage, output any) ([]ToolOutputContentItem, bool, error) { + if t.config.ToModelOutput == nil { + return nil, false, nil + } + input, err := t.decodeInput(raw) + if err != nil { + return nil, false, fmt.Errorf("toModelOutput input for %q: %w", t.config.Name, err) + } + res, err := t.config.ToModelOutput(ctx, ToModelOutputParams[In]{Output: output, Input: input}) + if err != nil { + return nil, false, err + } + if res == nil || (res.Type != "" && res.Type != ToModelOutputTypeContent) { + return nil, false, nil + } + return res.Value, true, nil +} + +// ApplyNextTurnParams runs this tool's NextTurnParams functions for one +// successful call, composing into working (later tools see earlier +// changes) and recording each produced key in update. +func (t *TypedTool[In]) ApplyNextTurnParams(ctx context.Context, raw json.RawMessage, working *NextTurnParamsContext, update *NextTurnParamsUpdate) error { + if t.config.NextTurnParams == nil { + return nil + } + input, err := t.decodeInput(raw) + if err != nil { + return fmt.Errorf("nextTurnParams input for %q: %w", t.config.Name, err) + } + return t.config.NextTurnParams.apply(ctx, input, working, update) +} + +// HasNextTurnParams reports whether the tool declares NextTurnParams. +func (t *TypedTool[In]) HasNextTurnParams() bool { return t.config.NextTurnParams != nil } + +func (t *TypedTool[In]) Execute(ctx context.Context, raw json.RawMessage, execCtx ToolExecuteContext) (ToolExecutionResult, error) { + input, err := t.decodeInput(raw) + if err != nil { + return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Error: err, InputInvalid: true}, nil } if t.config.OnToolCalled != nil { out, proceed, err := t.config.OnToolCalled(ctx, input, execCtx) @@ -135,24 +260,25 @@ func (t *TypedTool[In]) Execute(ctx context.Context, raw json.RawMessage, execCt return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Output: out}, nil } if t.config.Generate != nil { - var events []any + // Yields are broadcast live through execCtx.Emit and never + // accumulated on the result (upstream 1.0.0 / #110): a long-running + // generator no longer grows an unbounded preliminary-results slice. out, err := t.config.Generate(ctx, input, execCtx, func(v any) error { if err := validateAny(v, t.config.EventSchema); err != nil { return err } - events = append(events, v) if execCtx.Emit != nil { execCtx.Emit(v) } return nil }) if err != nil { - return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Events: events, Error: err}, nil + return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Error: err}, nil } if err := t.validateOutput(out); err != nil { - return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Output: out, Events: events, Error: err}, nil + return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Output: out, Error: err}, nil } - return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Output: out, Events: events}, nil + return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Output: out}, nil } if t.config.Execute == nil { return ToolExecutionResult{CallID: execCtx.ToolCall.CallID, Name: t.config.Name, Error: ErrManualTool}, nil diff --git a/tool_event_broadcaster.go b/tool_event_broadcaster.go index fa19121..3c7e225 100644 --- a/tool_event_broadcaster.go +++ b/tool_event_broadcaster.go @@ -1,12 +1,25 @@ package agent +// ToolEventBroadcaster is a push-based fan-out of tool stream events to +// multiple concurrent consumers (the analogue of upstream +// ToolEventBroadcaster). Full replay is the default; StreamReplayActiveConsumers +// compacts events once every attached consumer has read them. type ToolEventBroadcaster struct { stream *ReusableStream[ToolStreamEvent] } +// NewToolEventBroadcaster returns a broadcaster with the default +// StreamReplayFull policy. func NewToolEventBroadcaster() *ToolEventBroadcaster { - return &ToolEventBroadcaster{stream: NewReusableStream[ToolStreamEvent]()} + return NewToolEventBroadcasterWithReplay(StreamReplayFull) } + +// NewToolEventBroadcasterWithReplay returns a broadcaster using the given +// replay policy (the zero value selects StreamReplayFull). +func NewToolEventBroadcasterWithReplay(replay StreamReplay) *ToolEventBroadcaster { + return &ToolEventBroadcaster{stream: NewReusableStreamWithReplay[ToolStreamEvent](replay)} +} + func (b *ToolEventBroadcaster) Push(event ToolStreamEvent) { b.stream.Push(event) } func (b *ToolEventBroadcaster) Complete() { b.stream.Complete(nil) } func (b *ToolEventBroadcaster) Error(err error) { b.stream.Complete(err) } @@ -14,3 +27,6 @@ func (b *ToolEventBroadcaster) Subscribe() (<-chan ToolStreamEvent, func() error return b.stream.Subscribe(32) } func (b *ToolEventBroadcaster) Snapshot() []ToolStreamEvent { return b.stream.Snapshot() } + +// Replay reports the broadcaster's replay policy. +func (b *ToolEventBroadcaster) Replay() StreamReplay { return b.stream.Replay() } diff --git a/tool_event_broadcaster_test.go b/tool_event_broadcaster_test.go new file mode 100644 index 0000000..ba11acc --- /dev/null +++ b/tool_event_broadcaster_test.go @@ -0,0 +1,231 @@ +package agent + +import ( + "errors" + "reflect" + "sync" + "testing" +) + +// Ports tests/unit/tool-event-broadcaster.test.ts. + +func ev(n int) ToolStreamEvent { return ToolStreamEvent{Type: "tool.preliminary_result", Turn: n} } + +func turns(events []ToolStreamEvent) []int { + out := []int{} + for _, e := range events { + out = append(out, e.Turn) + } + return out +} + +func TestToolEventBroadcasterRetainsFullReplayByDefault(t *testing.T) { + b := NewToolEventBroadcaster() + if b.Replay() != StreamReplayFull { + t.Fatalf("default replay = %q", b.Replay()) + } + ch, wait := b.Subscribe() + b.Push(ev(1)) + b.Complete() + if got, err := drainChannel(ch, wait); err != nil || !reflect.DeepEqual(turns(got), []int{1}) { + t.Fatalf("first = %v, %v", turns(got), err) + } + if got, err := drainChannel(b.Subscribe()); err != nil || !reflect.DeepEqual(turns(got), []int{1}) { + t.Fatalf("second = %v, %v", turns(got), err) + } +} + +func TestToolEventBroadcasterCompactsActiveConsumerHistory(t *testing.T) { + b := NewToolEventBroadcasterWithReplay(StreamReplayActiveConsumers) + first := b.stream.newConsumer() + b.Push(ev(1)) + b.Push(ev(2)) + b.Complete() + mustNext(t, first, ev(1)) + second := b.stream.newConsumer() + if got := turns(drainConsumer(first)); !reflect.DeepEqual(got, []int{2}) { + t.Fatalf("first = %v", got) + } + if got := turns(drainConsumer(second)); !reflect.DeepEqual(got, []int{2}) { + t.Fatalf("second = %v, want [2]", got) + } +} + +func TestToolEventBroadcasterSingleConsumer(t *testing.T) { + b := NewToolEventBroadcaster() + ch, wait := b.Subscribe() + b.Push(ev(1)) + b.Push(ev(2)) + b.Push(ev(3)) + b.Complete() + if got, err := drainChannel(ch, wait); err != nil || !reflect.DeepEqual(turns(got), []int{1, 2, 3}) { + t.Fatalf("got %v, %v", turns(got), err) + } + + empty := NewToolEventBroadcaster() + ch, wait = empty.Subscribe() + empty.Complete() + if got, err := drainChannel(ch, wait); err != nil || len(got) != 0 { + t.Fatalf("empty stream = %v, %v", got, err) + } +} + +func TestToolEventBroadcasterConsumerCancellation(t *testing.T) { + b := NewToolEventBroadcaster() + ch, wait := b.Subscribe() + b.Push(ev(1)) + b.Push(ev(2)) + if got := <-ch; got.Turn != 1 { + t.Fatalf("first = %d", got.Turn) + } + if err := wait(); err != nil { + t.Fatal(err) + } + // The channel must close after cancellation (at most the read-ahead value + // is still buffered), never hang. + for range ch { + } +} + +func TestToolEventBroadcasterMultipleConsumersAndPositions(t *testing.T) { + b := NewToolEventBroadcaster() + c1 := b.stream.newConsumer() + b.Push(ev(1)) + b.Push(ev(2)) + mustNext(t, c1, ev(1)) + c2 := b.stream.newConsumer() + b.Push(ev(3)) + b.Complete() + var wg sync.WaitGroup + var r1, r2 []ToolStreamEvent + wg.Add(2) + go func() { defer wg.Done(); r1 = drainConsumer(c1) }() + go func() { defer wg.Done(); r2 = drainConsumer(c2) }() + wg.Wait() + if !reflect.DeepEqual(turns(r1), []int{2, 3}) { + t.Fatalf("consumer 1 continues from its position, got %v", turns(r1)) + } + if !reflect.DeepEqual(turns(r2), []int{1, 2, 3}) { + t.Fatalf("consumer 2 replays from position 0, got %v", turns(r2)) + } +} + +func TestToolEventBroadcasterWaitsForEvents(t *testing.T) { + b := NewToolEventBroadcaster() + ch, wait := b.Subscribe() + done := make(chan []ToolStreamEvent) + go func() { + got, _ := drainChannel(ch, wait) + done <- got + }() + for i := 0; i < 10; i++ { + b.Push(ev(i)) + } + b.Complete() + if got := turns(<-done); !reflect.DeepEqual(got, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) { + t.Fatalf("got %v", got) + } +} + +func TestToolEventBroadcasterPropagatesErrors(t *testing.T) { + b := NewToolEventBroadcaster() + ch, wait := b.Subscribe() + b.Push(ev(1)) + b.Error(errors.New("Test error")) + got, err := drainChannel(ch, wait) + if !reflect.DeepEqual(turns(got), []int{1}) || err == nil || err.Error() != "Test error" { + t.Fatalf("got %v, %v", turns(got), err) + } + + // A consumer already waiting when the error lands. + waiting := NewToolEventBroadcasterWithReplay(StreamReplayActiveConsumers) + c := waiting.stream.newConsumer() + result := make(chan bool) + go func() { + _, ok := c.next(nil) + result <- ok + }() + waiting.Error(errors.New("Async error")) + if ok := <-result; ok { + t.Fatalf("waiting consumer received a value") + } + if err := waiting.stream.Err(); err == nil || err.Error() != "Async error" { + t.Fatalf("err = %v", err) + } +} + +func TestToolEventBroadcasterIgnoresPushAfterComplete(t *testing.T) { + b := NewToolEventBroadcaster() + ch, wait := b.Subscribe() + b.Push(ev(1)) + b.Complete() + b.Push(ev(2)) + if got, _ := drainChannel(ch, wait); !reflect.DeepEqual(turns(got), []int{1}) { + t.Fatalf("got %v", turns(got)) + } +} + +func TestToolEventBroadcasterCompletionWithRemainingEvents(t *testing.T) { + b := NewToolEventBroadcaster() + c := b.stream.newConsumer() + b.Push(ev(1)) + mustNext(t, c, ev(1)) + b.Push(ev(2)) + b.Push(ev(3)) + b.Complete() + mustNext(t, c, ev(2)) + mustNext(t, c, ev(3)) + if _, ok := c.next(nil); ok { + t.Fatalf("expected done after remaining events") + } +} + +func TestToolEventBroadcasterLifecycleCompaction(t *testing.T) { + t.Run("drops backlog once every consumer departs", func(t *testing.T) { + b := NewToolEventBroadcasterWithReplay(StreamReplayActiveConsumers) + only := b.stream.newConsumer() + b.Push(ev(1)) + b.Push(ev(2)) + mustNext(t, only, ev(1)) + mustNext(t, only, ev(2)) + only.cancel() + b.Push(ev(3)) + b.Complete() + if got, _ := drainChannel(b.Subscribe()); !reflect.DeepEqual(turns(got), []int{3}) { + t.Fatalf("late = %v, want [3]", turns(got)) + } + }) + t.Run("backlog survives while one consumer remains", func(t *testing.T) { + b := NewToolEventBroadcasterWithReplay(StreamReplayActiveConsumers) + fast, slow := b.stream.newConsumer(), b.stream.newConsumer() + b.Push(ev(1)) + b.Push(ev(2)) + mustNext(t, fast, ev(1)) + mustNext(t, fast, ev(2)) + fast.cancel() + mustNext(t, slow, ev(1)) + mustNext(t, slow, ev(2)) + b.Complete() + if _, ok := slow.next(nil); ok { + t.Fatalf("slow should be done") + } + if got := b.Snapshot(); len(got) != 0 { + t.Fatalf("fully consumed history still retained: %v", turns(got)) + } + }) + t.Run("cancel wakes a pending next", func(t *testing.T) { + b := NewToolEventBroadcasterWithReplay(StreamReplayActiveConsumers) + c := b.stream.newConsumer() + b.Push(ev(1)) + mustNext(t, c, ev(1)) + result := make(chan bool) + go func() { + _, ok := c.next(nil) + result <- ok + }() + c.cancel() + if <-result { + t.Fatalf("pending next returned a value after cancel") + } + }) +} diff --git a/tool_set.go b/tool_set.go new file mode 100644 index 0000000..c55730e --- /dev/null +++ b/tool_set.go @@ -0,0 +1,702 @@ +// Tool sets: declarative activate / deactivate / activateWhen / +// deactivateWhen for tools, with state- and context-aware predicates, named +// situations, and exhaustive resolved snapshots. +// +// Port of upstream `@openrouter/agent/tool-set` (packages/agent/src/lib/ +// tool-set.ts and tool-set-types.ts), which is itself adapted from +// ai-tool-set v1.0.0 (https://github.com/zirkelc/ai-tool-set/tree/v1.0.0): +// +// MIT License +// +// Copyright (c) 2024 Chris +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package agent + +import ( + "encoding/json" + "errors" + "fmt" + "sort" + "sync" +) + +// Tool-set errors. Every error returned by the tool-set API wraps one of +// these sentinels so callers can match with errors.Is; the message text +// mirrors upstream's thrown Error messages (lower-cased per Go convention). +var ( + // ErrToolSetDuplicateID: two tools in one set resolve to the same id + // (upstream `Duplicate tool ID: ""`). + ErrToolSetDuplicateID = errors.New("duplicate tool ID") + // ErrToolSetUnknownTool: a directive or situation named an id the set + // does not contain (upstream `Unknown tool: ""`). + ErrToolSetUnknownTool = errors.New("unknown tool") + // ErrToolSetUnknownSituation: ResolveSituation was called with a name + // that DefineSituations never registered (upstream + // `Unknown situation: ""`). + ErrToolSetUnknownSituation = errors.New("unknown situation") + // ErrToolSetMissingPredicate: ActivateWhen/DeactivateWhen was called by + // name with a nil predicate. + ErrToolSetMissingPredicate = errors.New("activateWhen/deactivateWhen requires a predicate when called with a name") + // ErrToolSetSituationDuplicate: a situation lists the same tool more + // than once across enabled/disabled/conditional. + ErrToolSetSituationDuplicate = errors.New("situation lists tool more than once") + // ErrToolSetInvalidConditionalRule: a situation conditional rule has no + // predicate or an unknown mode. + ErrToolSetInvalidConditionalRule = errors.New("conditional rule must be a function or { mode, predicate } object") + // ErrToolSetNilTool: the tools list contains a nil Tool. + ErrToolSetNilTool = errors.New("tool set: nil tool") + // ErrServerToolEmptyID mirrors upstream serverTool's + // `Server tool ID must not be empty`. + ErrServerToolEmptyID = errors.New("server tool ID must not be empty") +) + +// ActivationInput is what every activation predicate receives (upstream +// `ActivationInput` = `{ state?: ConversationState; context?: TShared }`). +// A nil State / zero-valued Context corresponds to upstream's omitted field; +// use a pointer or map type for TShared when "absent" must be distinguishable. +type ActivationInput[TShared any] struct { + State *ConversationState + Context TShared +} + +// ActivationPredicate decides whether a conditional tool is active (upstream +// `ActivationPredicate`). +type ActivationPredicate[TShared any] func(ActivationInput[TShared]) bool + +// ActivationMode selects how a situation conditional rule is interpreted. +type ActivationMode string + +const ( + // ActivationModeActivateWhen: inactive until the predicate returns true. + ActivationModeActivateWhen ActivationMode = "activateWhen" + // ActivationModeDeactivateWhen: active until the predicate returns true. + ActivationModeDeactivateWhen ActivationMode = "deactivateWhen" +) + +// SituationConditionalRule is one conditional entry of a situation (upstream +// `SituationConditionalRule` = predicate | { mode?, predicate }). An empty +// Mode defaults to ActivationModeActivateWhen. +type SituationConditionalRule[TShared any] struct { + Mode ActivationMode + Predicate ActivationPredicate[TShared] +} + +// SituationActivateWhen is the Go spelling of upstream's bare-function +// conditional rule shorthand (default mode activateWhen). +func SituationActivateWhen[TShared any](p ActivationPredicate[TShared]) *SituationConditionalRule[TShared] { + return &SituationConditionalRule[TShared]{Mode: ActivationModeActivateWhen, Predicate: p} +} + +// SituationDeactivateWhen builds a `{ mode: 'deactivateWhen', predicate }` rule. +func SituationDeactivateWhen[TShared any](p ActivationPredicate[TShared]) *SituationConditionalRule[TShared] { + return &SituationConditionalRule[TShared]{Mode: ActivationModeDeactivateWhen, Predicate: p} +} + +// SituationConfig is a declarative overlay for one named situation (upstream +// `SituationConfig`). Ids not listed keep the base tool-set partition. A nil +// Conditional value is ignored, like upstream's `undefined` entries. +type SituationConfig[TShared any] struct { + Enabled []string + Disabled []string + Conditional map[string]*SituationConditionalRule[TShared] +} + +// StatusReason explains why a tool resolved the way it did. +type StatusReason string + +const ( + StatusReasonDefault StatusReason = "default" + StatusReasonActivate StatusReason = "activate" + StatusReasonDeactivate StatusReason = "deactivate" + StatusReasonActivateWhen StatusReason = "activateWhen" + StatusReasonDeactivateWhen StatusReason = "deactivateWhen" + StatusReasonSituation StatusReason = "situation" +) + +// StatusDirective is the last applicable directive for a tool. +type StatusDirective string + +const ( + DirectiveActivate StatusDirective = "activate" + DirectiveDeactivate StatusDirective = "deactivate" + DirectiveActivateWhen StatusDirective = "activateWhen" + DirectiveDeactivateWhen StatusDirective = "deactivateWhen" +) + +// ToolStatusEntry is one row of the exhaustive StatusByTool map (upstream +// `ToolStatusEntry`). Directive is empty when the tool is still at its +// construction default; Predicate is true when the final state depended on +// evaluating a runtime predicate (upstream omits the key otherwise). +type ToolStatusEntry struct { + Enabled bool `json:"enabled"` + Reason StatusReason `json:"reason"` + Directive StatusDirective `json:"directive,omitempty"` + Predicate bool `json:"predicate,omitempty"` +} + +// ToolSetCallModelInput holds exactly the two fields meant to reach CallModel +// (upstream snapshot `.callModel`). Copy them into CallModelInput.Tools and +// CallModelInput.ActiveTools. +type ToolSetCallModelInput struct { + Tools []Tool + ActiveTools []string +} + +// ResolvedToolSnapshot is what Resolve / ResolveSituation / InferTools return +// (upstream `ResolvedToolSnapshot`). Slices are always non-nil — in +// particular ActiveTools is an empty (non-nil) slice when no client tool is +// active, which CallModel must treat as "filter every client tool out", +// not "no filter". +type ResolvedToolSnapshot struct { + // Active tools only (client + server), construction order preserved. + Tools []Tool + // Active client tool names only (CallModel ActiveTools wire format). + // Server tool ids are omitted. + ActiveTools []string + // Spread-safe CallModel input; snapshot metadata intentionally excluded. + CallModel ToolSetCallModelInput + // Ids that resolved active (client + server), construction order. + Enabled []string + // Ids that resolved inactive (client + server), construction order. + Disabled []string + // Exhaustive id -> status; every id of the set is present. + StatusByTool map[string]ToolStatusEntry +} + +// ToolSetConfig configures CreateToolSet (upstream `{ tools, mutable? }`). +type ToolSetConfig struct { + Tools []Tool + // Mutable makes mutators update the receiver in place and return it. + // Default false: every mutator returns a new, independent *ToolSet. + Mutable bool +} + +type activationKind int + +const ( + activationStatic activationKind = iota + activationActivateWhen + activationDeactivateWhen +) + +type activationSource int + +const ( + sourceDirective activationSource = iota // activate/deactivate/activateWhen/deactivateWhen + sourceSituation +) + +type activationEntry[TShared any] struct { + kind activationKind + active bool // static only + predicate ActivationPredicate[TShared] + source activationSource +} + +type situationConditional[TShared any] struct { + id string + kind activationKind + predicate ActivationPredicate[TShared] +} + +type situationRuntime[TShared any] struct { + enabled []string + disabled []string + conditional []situationConditional[TShared] +} + +type indexedTools struct { + orderedTools []Tool + orderedIDs []string + toolByID map[string]Tool +} + +// ToolSet is an immutable-by-default set of tools with per-tool activation +// directives and optional named situations (upstream `ToolSet`). Upstream's +// compile-time partition tracking (P / Sit generics) has no Go equivalent; +// the runtime snapshot is exact. Safe for concurrent use. +type ToolSet[TShared any] struct { + index *indexedTools + mutable bool + + mu sync.RWMutex + activation map[string]activationEntry[TShared] + situations map[string]situationRuntime[TShared] +} + +// serverToolIdentity is implemented by server tools that carry an explicit +// tool-set id (see NewServerToolWithID). +type serverToolIdentity interface { + ServerToolID() string +} + +type serverToolWithID struct { + Tool + id string +} + +func (s serverToolWithID) ServerToolID() string { return s.id } + +// NewServerToolWithID is NewServerTool plus upstream's +// `serverTool(config, { id })` option: it overrides the tool-set id (default +// `server:`), e.g. when two server tools of the same type need +// distinct activation ids. An empty id is rejected with ErrServerToolEmptyID. +func NewServerToolWithID(config ServerToolConfig, id string) (Tool, error) { + if id == "" { + return nil, ErrServerToolEmptyID + } + return serverToolWithID{Tool: NewServerTool(config), id: id}, nil +} + +// ToolSetID returns the id a tool set addresses tool by (upstream internal +// `toolId`): the function name (ToolName) for client tools; for server tools +// an explicit id when present (NewServerToolWithID or any server Tool +// implementing `ServerToolID() string`), otherwise `server:`, +// e.g. "server:web_search_2025_08_26". ServerToolConfig.Name is not used. +func ToolSetID(t Tool) string { + if t == nil { + return "" + } + if !IsServerTool(t) { + return t.ToolName() + } + if ider, ok := t.(serverToolIdentity); ok { + if id := ider.ServerToolID(); id != "" { + return id + } + } + return "server:" + serverToolType(t) +} + +// serverToolType returns the wire `type` of a server tool's API union. +func serverToolType(t Tool) string { + api := t.ToAPITool() + if api.Type != "" { + return string(api.Type) + } + // Hand-built unions may omit the discriminator; read it off the wire shape. + b, err := json.Marshal(api) + if err != nil { + return "" + } + var probe struct { + Type string `json:"type"` + } + if json.Unmarshal(b, &probe) != nil { + return "" + } + return probe.Type +} + +func indexTools(tools []Tool) (*indexedTools, error) { + idx := &indexedTools{ + orderedTools: append([]Tool(nil), tools...), + orderedIDs: make([]string, 0, len(tools)), + toolByID: make(map[string]Tool, len(tools)), + } + for i, t := range tools { + if t == nil { + return nil, fmt.Errorf("%w at index %d", ErrToolSetNilTool, i) + } + id := ToolSetID(t) + if _, dup := idx.toolByID[id]; dup { + return nil, fmt.Errorf("%w: %q", ErrToolSetDuplicateID, id) + } + idx.toolByID[id] = t + idx.orderedIDs = append(idx.orderedIDs, id) + } + return idx, nil +} + +// CreateToolSet constructs a ToolSet (upstream `createToolSet`). Every tool +// starts active. Returns ErrToolSetDuplicateID when two tools share an id. +// TShared is the predicate context type (upstream's `TShared` generic, +// default `Record` ≈ map[string]any). +func CreateToolSet[TShared any](config ToolSetConfig) (*ToolSet[TShared], error) { + idx, err := indexTools(config.Tools) + if err != nil { + return nil, err + } + return &ToolSet[TShared]{ + index: idx, + mutable: config.Mutable, + activation: map[string]activationEntry[TShared]{}, + situations: map[string]situationRuntime[TShared]{}, + }, nil +} + +// Tools returns every tool in construction order, regardless of activation. +func (s *ToolSet[TShared]) Tools() []Tool { + return append([]Tool(nil), s.index.orderedTools...) +} + +// Mutable reports whether mutators modify this instance in place. +func (s *ToolSet[TShared]) Mutable() bool { return s.mutable } + +func (s *ToolSet[TShared]) assertKnown(id string) error { + if _, ok := s.index.toolByID[id]; !ok { + return fmt.Errorf("%w: %q", ErrToolSetUnknownTool, id) + } + return nil +} + +func (s *ToolSet[TShared]) withPartitionMutation(mutate func(map[string]activationEntry[TShared])) *ToolSet[TShared] { + if s.mutable { + s.mu.Lock() + mutate(s.activation) + s.mu.Unlock() + return s + } + s.mu.RLock() + next := cloneMap(s.activation) + situations := s.situations // immutable instances never mutate this map + s.mu.RUnlock() + mutate(next) + return &ToolSet[TShared]{index: s.index, mutable: false, activation: next, situations: situations} +} + +func cloneMap[K comparable, V any](m map[K]V) map[K]V { + out := make(map[K]V, len(m)) + for k, v := range m { + out[k] = v + } + return out +} + +// Activate statically turns the named tools on (upstream `activate`). Every +// name is validated before anything is applied; an unknown name returns +// ErrToolSetUnknownTool and leaves the receiver untouched. +func (s *ToolSet[TShared]) Activate(names ...string) (*ToolSet[TShared], error) { + return s.setStatic(names, true) +} + +// Deactivate statically turns the named tools off (upstream `deactivate`). +func (s *ToolSet[TShared]) Deactivate(names ...string) (*ToolSet[TShared], error) { + return s.setStatic(names, false) +} + +func (s *ToolSet[TShared]) setStatic(names []string, active bool) (*ToolSet[TShared], error) { + for _, n := range names { + if err := s.assertKnown(n); err != nil { + return nil, err + } + } + return s.withPartitionMutation(func(a map[string]activationEntry[TShared]) { + for _, n := range names { + a[n] = activationEntry[TShared]{kind: activationStatic, active: active, source: sourceDirective} + } + }), nil +} + +// ActivateWhen makes a tool inactive unless predicate returns true +// (upstream `activateWhen(name, predicate)`). +func (s *ToolSet[TShared]) ActivateWhen(name string, predicate ActivationPredicate[TShared]) (*ToolSet[TShared], error) { + return s.setConditionalByName(name, predicate, activationActivateWhen) +} + +// ActivateWhenMap is upstream's `activateWhen({ name: predicate, ... })` +// overload. Nil predicates are skipped; every remaining name is validated +// before anything is applied. +func (s *ToolSet[TShared]) ActivateWhenMap(predicates map[string]ActivationPredicate[TShared]) (*ToolSet[TShared], error) { + return s.setConditionalMap(predicates, activationActivateWhen) +} + +// DeactivateWhen makes a tool active unless predicate returns true +// (upstream `deactivateWhen(name, predicate)`). +func (s *ToolSet[TShared]) DeactivateWhen(name string, predicate ActivationPredicate[TShared]) (*ToolSet[TShared], error) { + return s.setConditionalByName(name, predicate, activationDeactivateWhen) +} + +// DeactivateWhenMap is upstream's `deactivateWhen({ name: predicate, ... })`. +func (s *ToolSet[TShared]) DeactivateWhenMap(predicates map[string]ActivationPredicate[TShared]) (*ToolSet[TShared], error) { + return s.setConditionalMap(predicates, activationDeactivateWhen) +} + +type namedPredicate[TShared any] struct { + name string + predicate ActivationPredicate[TShared] +} + +func (s *ToolSet[TShared]) setConditionalByName(name string, predicate ActivationPredicate[TShared], kind activationKind) (*ToolSet[TShared], error) { + // Upstream checks the predicate before the name. + if predicate == nil { + return nil, ErrToolSetMissingPredicate + } + if err := s.assertKnown(name); err != nil { + return nil, err + } + return s.applyConditional([]namedPredicate[TShared]{{name, predicate}}, kind), nil +} + +func (s *ToolSet[TShared]) setConditionalMap(predicates map[string]ActivationPredicate[TShared], kind activationKind) (*ToolSet[TShared], error) { + entries := make([]namedPredicate[TShared], 0, len(predicates)) + for _, name := range sortedKeys(predicates) { + if p := predicates[name]; p != nil { + entries = append(entries, namedPredicate[TShared]{name, p}) + } + } + for _, e := range entries { + if err := s.assertKnown(e.name); err != nil { + return nil, err + } + } + return s.applyConditional(entries, kind), nil +} + +func (s *ToolSet[TShared]) applyConditional(entries []namedPredicate[TShared], kind activationKind) *ToolSet[TShared] { + return s.withPartitionMutation(func(a map[string]activationEntry[TShared]) { + for _, e := range entries { + a[e.name] = activationEntry[TShared]{kind: kind, predicate: e.predicate, source: sourceDirective} + } + }) +} + +func sortedKeys[V any](m map[string]V) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +// DefineSituations registers named declarative situations (upstream +// `defineSituations`). Each situation overlays the base partition; ids it +// does not mention keep the base directives. Replaces any previously defined +// situations. Validation (unknown ids, an id listed more than once across +// enabled/disabled/conditional, malformed conditional rules) happens here; +// on error the receiver is untouched. Go maps are unordered, so situations +// and conditional ids are validated in sorted key order. +func (s *ToolSet[TShared]) DefineSituations(situations map[string]SituationConfig[TShared]) (*ToolSet[TShared], error) { + next := make(map[string]situationRuntime[TShared], len(situations)) + + for _, name := range sortedKeys(situations) { + cfg := situations[name] + condIDs := make([]string, 0, len(cfg.Conditional)) + for _, id := range sortedKeys(cfg.Conditional) { + if cfg.Conditional[id] != nil { + condIDs = append(condIDs, id) + } + } + + seen := map[string]struct{}{} + record := func(id string) error { + if err := s.assertKnown(id); err != nil { + return err + } + if _, dup := seen[id]; dup { + return fmt.Errorf("situation %q lists tool %q more than once (across enabled/disabled/conditional): %w", name, id, ErrToolSetSituationDuplicate) + } + seen[id] = struct{}{} + return nil + } + for _, id := range cfg.Enabled { + if err := record(id); err != nil { + return nil, err + } + } + for _, id := range cfg.Disabled { + if err := record(id); err != nil { + return nil, err + } + } + for _, id := range condIDs { + if err := record(id); err != nil { + return nil, err + } + } + + rt := situationRuntime[TShared]{ + enabled: append([]string{}, cfg.Enabled...), + disabled: append([]string{}, cfg.Disabled...), + } + for _, id := range condIDs { + rule := cfg.Conditional[id] + var kind activationKind + switch rule.Mode { + case "", ActivationModeActivateWhen: + kind = activationActivateWhen + case ActivationModeDeactivateWhen: + kind = activationDeactivateWhen + default: + return nil, invalidRuleErr(name, id) + } + if rule.Predicate == nil { + return nil, invalidRuleErr(name, id) + } + rt.conditional = append(rt.conditional, situationConditional[TShared]{id: id, kind: kind, predicate: rule.Predicate}) + } + next[name] = rt + } + + if s.mutable { + s.mu.Lock() + s.situations = next + s.mu.Unlock() + return s, nil + } + s.mu.RLock() + activation := cloneMap(s.activation) + s.mu.RUnlock() + return &ToolSet[TShared]{index: s.index, mutable: false, activation: activation, situations: next}, nil +} + +func invalidRuleErr(situation, id string) error { + return fmt.Errorf("situation %q: conditional rule for tool %q must be a function or { mode, predicate } object: %w", situation, id, ErrToolSetInvalidConditionalRule) +} + +// Resolve evaluates the base partition (no situation overlay) against input +// (upstream `resolve(input?)`; pass the zero ActivationInput for none). +// Predicates run synchronously, in construction order of their tools. +// +// Like upstream, each tool's directive is read from the live activation +// state just before it is evaluated, so a predicate that mutates a mutable +// set affects tools evaluated after it within the same Resolve. The lock is +// never held while a predicate runs. +func (s *ToolSet[TShared]) Resolve(input ActivationInput[TShared]) ResolvedToolSnapshot { + return s.resolveWith(func(id string) (activationEntry[TShared], bool) { + s.mu.RLock() + defer s.mu.RUnlock() + e, ok := s.activation[id] + return e, ok + }, input) +} + +// InferTools is upstream's back-compat alias of Resolve. Only the Tools and +// ActiveTools fields (or .CallModel) are meant to reach CallModel. +func (s *ToolSet[TShared]) InferTools(input ActivationInput[TShared]) ResolvedToolSnapshot { + return s.Resolve(input) +} + +// ResolveSituation resolves a previously defined situation overlaid on the +// base partition (upstream `resolveSituation(name, input?)`). Returns +// ErrToolSetUnknownSituation for an unregistered name. +func (s *ToolSet[TShared]) ResolveSituation(name string, input ActivationInput[TShared]) (ResolvedToolSnapshot, error) { + s.mu.RLock() + situation, ok := s.situations[name] + activation := cloneMap(s.activation) + s.mu.RUnlock() + if !ok { + return ResolvedToolSnapshot{}, fmt.Errorf("%w: %q", ErrToolSetUnknownSituation, name) + } + for _, id := range situation.enabled { + activation[id] = activationEntry[TShared]{kind: activationStatic, active: true, source: sourceSituation} + } + for _, id := range situation.disabled { + activation[id] = activationEntry[TShared]{kind: activationStatic, active: false, source: sourceSituation} + } + for _, c := range situation.conditional { + activation[c.id] = activationEntry[TShared]{kind: c.kind, predicate: c.predicate, source: sourceSituation} + } + return s.resolveWith(func(id string) (activationEntry[TShared], bool) { + e, ok := activation[id] + return e, ok + }, input), nil +} + +func (s *ToolSet[TShared]) resolveWith(lookup func(string) (activationEntry[TShared], bool), input ActivationInput[TShared]) ResolvedToolSnapshot { + snap := ResolvedToolSnapshot{ + Tools: []Tool{}, + ActiveTools: []string{}, + Enabled: []string{}, + Disabled: []string{}, + StatusByTool: make(map[string]ToolStatusEntry, len(s.index.orderedIDs)), + } + for _, id := range s.index.orderedIDs { + t := s.index.toolByID[id] + entry, has := lookup(id) + active := evaluateActivation(entry, has, input) + snap.StatusByTool[id] = toStatusEntry(active, entry, has) + if active { + snap.Tools = append(snap.Tools, t) + snap.Enabled = append(snap.Enabled, id) + if !IsServerTool(t) { + snap.ActiveTools = append(snap.ActiveTools, id) + } + } else { + snap.Disabled = append(snap.Disabled, id) + } + } + snap.CallModel = ToolSetCallModelInput{ + Tools: append([]Tool{}, snap.Tools...), + ActiveTools: append([]string{}, snap.ActiveTools...), + } + return snap +} + +func evaluateActivation[TShared any](entry activationEntry[TShared], has bool, input ActivationInput[TShared]) bool { + if !has { + return true + } + switch entry.kind { + case activationStatic: + return entry.active + case activationActivateWhen: + return entry.predicate(input) + default: + return !entry.predicate(input) + } +} + +func toStatusEntry[TShared any](active bool, entry activationEntry[TShared], has bool) ToolStatusEntry { + if !has { + return ToolStatusEntry{Enabled: active, Reason: StatusReasonDefault} + } + if entry.kind == activationStatic { + directive := DirectiveDeactivate + if entry.active { + directive = DirectiveActivate + } + reason := StatusReason(directive) + if entry.source == sourceSituation { + reason = StatusReasonSituation + } + return ToolStatusEntry{Enabled: active, Reason: reason, Directive: directive} + } + directive := DirectiveActivateWhen + if entry.kind == activationDeactivateWhen { + directive = DirectiveDeactivateWhen + } + reason := StatusReason(directive) + if entry.source == sourceSituation { + reason = StatusReasonSituation + } + return ToolStatusEntry{Enabled: active, Reason: reason, Directive: directive, Predicate: true} +} + +// Clone copies state into a fresh, independent instance with the same +// mutability (upstream `clone()`). +func (s *ToolSet[TShared]) Clone() *ToolSet[TShared] { + return s.CloneWithMutable(s.mutable) +} + +// CloneWithMutable copies state into a fresh, independent instance with the +// given mutability (upstream `clone({ mutable })`). +func (s *ToolSet[TShared]) CloneWithMutable(mutable bool) *ToolSet[TShared] { + s.mu.RLock() + defer s.mu.RUnlock() + return &ToolSet[TShared]{ + index: s.index, + mutable: mutable, + activation: cloneMap(s.activation), + situations: cloneMap(s.situations), + } +} diff --git a/tool_set_test.go b/tool_set_test.go new file mode 100644 index 0000000..c79c2b9 --- /dev/null +++ b/tool_set_test.go @@ -0,0 +1,738 @@ +package agent + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "sort" + "strings" + "sync" + "testing" + + "github.com/OpenRouterTeam/go-sdk/models/components" +) + +// Ports packages/agent/tests/unit/tool-set.test.ts. Type-level +// (expectTypeOf) assertions have no Go equivalent; their runtime halves are +// ported. + +type emptyInput struct{} + +func makeSetTool(name string) Tool { + return MustNewTool(ToolConfig[emptyInput]{ + Name: name, + Description: name + " tool", + Execute: func(context.Context, emptyInput, ToolExecuteContext) (any, error) { + return map[string]any{"name": name}, nil + }, + }) +} + +var ( + tsA = makeSetTool("a") + tsB = makeSetTool("b") + tsC = makeSetTool("c") +) + +type ctxMap = map[string]any + +func newSet(t *testing.T, mutable bool, tools ...Tool) *ToolSet[ctxMap] { + t.Helper() + ts, err := CreateToolSet[ctxMap](ToolSetConfig{Tools: tools, Mutable: mutable}) + if err != nil { + t.Fatalf("CreateToolSet: %v", err) + } + return ts +} + +// must unwraps (v, err) for chaining; an unexpected error panics, which +// fails the calling test with the error text. +func must[T any](v T, err error) T { + if err != nil { + panic("unexpected error: " + err.Error()) + } + return v +} + +func toolIDs(tools []Tool) []string { + out := make([]string, 0, len(tools)) + for _, tl := range tools { + out = append(out, ToolSetID(tl)) + } + return out +} + +func eq(t *testing.T, label string, got, want any) { + t.Helper() + if !reflect.DeepEqual(got, want) { + t.Fatalf("%s = %#v, want %#v", label, got, want) + } +} + +func wantErr(t *testing.T, err, sentinel error, substr string) { + t.Helper() + if err == nil { + t.Fatalf("expected error matching %q, got nil", substr) + } + if !errors.Is(err, sentinel) { + t.Fatalf("error %v does not wrap %v", err, sentinel) + } + if !strings.Contains(err.Error(), substr) { + t.Fatalf("error %q does not contain %q", err.Error(), substr) + } +} + +func datetimeServerTool() components.ResponsesRequestToolUnion { + return components.CreateResponsesRequestToolUnionOpenrouterDatetime( + components.DatetimeServerTool{Type: components.DatetimeServerToolTypeOpenrouterDatetime}, + ) +} + +var none = ActivationInput[ctxMap]{} + +// ─── createToolSet ────────────────────────────────────────────────────────── + +func TestToolSetPreservesToolOrder(t *testing.T) { + ts := newSet(t, false, tsA, tsB, tsC) + eq(t, "Tools", toolIDs(ts.Tools()), []string{"a", "b", "c"}) +} + +func TestToolSetRejectsDuplicateNames(t *testing.T) { + _, err := CreateToolSet[ctxMap](ToolSetConfig{Tools: []Tool{tsA, makeSetTool("a")}}) + wantErr(t, err, ErrToolSetDuplicateID, `duplicate tool ID: "a"`) +} + +func TestToolSetRejectsNilTool(t *testing.T) { + _, err := CreateToolSet[ctxMap](ToolSetConfig{Tools: []Tool{tsA, nil}}) + wantErr(t, err, ErrToolSetNilTool, "index 1") +} + +func TestToolSetEmpty(t *testing.T) { + ts := newSet(t, false) + eq(t, "Tools", len(ts.Tools()), 0) + snap := ts.Resolve(none) + eq(t, "tools", snap.Tools, []Tool{}) + eq(t, "activeTools", snap.ActiveTools, []string{}) + eq(t, "enabled", snap.Enabled, []string{}) + eq(t, "disabled", snap.Disabled, []string{}) + eq(t, "statusByTool", snap.StatusByTool, map[string]ToolStatusEntry{}) +} + +func TestToolSetDefaultsAllActive(t *testing.T) { + snap := newSet(t, false, tsA, tsB).Resolve(none) + eq(t, "tools", snap.Tools, []Tool{tsA, tsB}) + eq(t, "activeTools", snap.ActiveTools, []string{"a", "b"}) + eq(t, "enabled", snap.Enabled, []string{"a", "b"}) + eq(t, "disabled", snap.Disabled, []string{}) + eq(t, "statusByTool", snap.StatusByTool, map[string]ToolStatusEntry{ + "a": {Enabled: true, Reason: StatusReasonDefault}, + "b": {Enabled: true, Reason: StatusReasonDefault}, + }) +} + +// ─── activate / deactivate ────────────────────────────────────────────────── + +func TestToolSetActivateDeactivate(t *testing.T) { + ts := must(newSet(t, false, tsA, tsB, tsC).Deactivate("b")) + eq(t, "activeTools", ts.Resolve(none).ActiveTools, []string{"a", "c"}) + eq(t, "disabled", ts.Resolve(none).Disabled, []string{"b"}) + + ts2 := must(must(newSet(t, false, tsA, tsB, tsC).Deactivate("a", "b")).Activate("b")) + eq(t, "activeTools", ts2.Resolve(none).ActiveTools, []string{"b", "c"}) +} + +func TestToolSetUnknownNames(t *testing.T) { + ts := newSet(t, false, tsA) + _, err := ts.Activate("missing") + wantErr(t, err, ErrToolSetUnknownTool, `unknown tool: "missing"`) + _, err = ts.Deactivate("a", "missing") + wantErr(t, err, ErrToolSetUnknownTool, `unknown tool: "missing"`) + // Validation precedes mutation: nothing applied. + eq(t, "activeTools", ts.Resolve(none).ActiveTools, []string{"a"}) + + mut := newSet(t, true, tsA, tsB) + if _, err := mut.Deactivate("a", "missing"); err == nil { + t.Fatal("expected error") + } + eq(t, "mutable untouched", mut.Resolve(none).ActiveTools, []string{"a", "b"}) +} + +// ─── activateWhen / deactivateWhen ────────────────────────────────────────── + +func TestToolSetActivateWhen(t *testing.T) { + ts := must(newSet(t, false, tsA, tsB).ActivateWhen("a", func(in ActivationInput[ctxMap]) bool { + return in.Context["enabled"] == true + })) + eq(t, "no ctx", ts.Resolve(none).ActiveTools, []string{"b"}) + eq(t, "ctx", ts.Resolve(ActivationInput[ctxMap]{Context: ctxMap{"enabled": true}}).ActiveTools, []string{"a", "b"}) + + m := must(newSet(t, false, tsA, tsB).ActivateWhenMap(map[string]ActivationPredicate[ctxMap]{ + "a": func(ActivationInput[ctxMap]) bool { return true }, + "b": func(ActivationInput[ctxMap]) bool { return false }, + })) + eq(t, "map", m.Resolve(none).ActiveTools, []string{"a"}) +} + +func TestToolSetActivateWhenMapValidatesBeforeApplying(t *testing.T) { + ts := newSet(t, false, tsA, tsB) + _, err := ts.ActivateWhenMap(map[string]ActivationPredicate[ctxMap]{ + "a": func(ActivationInput[ctxMap]) bool { return true }, + "nope": func(ActivationInput[ctxMap]) bool { return true }, + }) + wantErr(t, err, ErrToolSetUnknownTool, `unknown tool: "nope"`) + eq(t, "original", ts.Resolve(none).ActiveTools, []string{"a", "b"}) +} + +func TestToolSetConditionalPredicateValidation(t *testing.T) { + ts := newSet(t, false, tsA) + _, err := ts.ActivateWhen("a", nil) + wantErr(t, err, ErrToolSetMissingPredicate, "requires a predicate") + // Predicate is checked before the name, as upstream. + _, err = ts.DeactivateWhen("missing", nil) + wantErr(t, err, ErrToolSetMissingPredicate, "requires a predicate") + // Nil map entries are skipped (upstream filters non-functions), even for + // unknown names. + got := must(ts.DeactivateWhenMap(map[string]ActivationPredicate[ctxMap]{"missing": nil})) + eq(t, "skip nil", got.Resolve(none).ActiveTools, []string{"a"}) +} + +func TestToolSetDeactivateWhen(t *testing.T) { + ts := must(newSet(t, false, tsA, tsB).DeactivateWhen("a", func(ActivationInput[ctxMap]) bool { return true })) + eq(t, "activeTools", ts.Resolve(none).ActiveTools, []string{"b"}) + + m := must(newSet(t, false, tsA, tsB).DeactivateWhenMap(map[string]ActivationPredicate[ctxMap]{ + "a": func(ActivationInput[ctxMap]) bool { return true }, + "b": func(ActivationInput[ctxMap]) bool { return false }, + })) + eq(t, "map", m.Resolve(none).ActiveTools, []string{"b"}) +} + +func TestToolSetLastCallWins(t *testing.T) { + yes := func(ActivationInput[ctxMap]) bool { return true } + ts := must(must(newSet(t, false, tsA, tsB).Activate("a")).DeactivateWhen("a", yes)) + eq(t, "activate then deactivateWhen", ts.Resolve(none).ActiveTools, []string{"b"}) + + ts2 := must(must(newSet(t, false, tsA, tsB).DeactivateWhen("a", yes)).Activate("a")) + eq(t, "deactivateWhen then activate", ts2.Resolve(none).ActiveTools, []string{"a", "b"}) +} + +// ─── immutability vs mutability / clone ───────────────────────────────────── + +func TestToolSetImmutableByDefault(t *testing.T) { + base := newSet(t, false, tsA, tsB) + next := must(base.Deactivate("a")) + if next == base { + t.Fatal("immutable mutator returned the receiver") + } + eq(t, "base", base.Resolve(none).ActiveTools, []string{"a", "b"}) + eq(t, "next", next.Resolve(none).ActiveTools, []string{"b"}) + + // Each immutable step is a distinct instance. + step := must(next.ActivateWhen("a", func(ActivationInput[ctxMap]) bool { return true })) + if step == next { + t.Fatal("ActivateWhen on immutable set returned the receiver") + } +} + +func TestToolSetMutableInPlace(t *testing.T) { + base := newSet(t, true, tsA, tsB, tsC) + next := must(base.Deactivate("a")) + if next != base { + t.Fatal("mutable mutator must return the receiver") + } + eq(t, "base", base.Resolve(none).ActiveTools, []string{"b", "c"}) + + // Every alias observes every mutation. + if r := must(base.Activate("a")); r != base { + t.Fatal("Activate: not receiver") + } + if r := must(base.Deactivate("b")); r != base { + t.Fatal("Deactivate: not receiver") + } + if r := must(base.ActivateWhen("c", func(ActivationInput[ctxMap]) bool { return true })); r != base { + t.Fatal("ActivateWhen: not receiver") + } + if r := must(base.DeactivateWhen("c", func(ActivationInput[ctxMap]) bool { return false })); r != base { + t.Fatal("DeactivateWhen: not receiver") + } + eq(t, "aliases", base.Resolve(none).ActiveTools, []string{"a", "c"}) +} + +func TestToolSetClone(t *testing.T) { + immutable := must(newSet(t, false, tsA, tsB).Deactivate("a")) + mutableCopy := immutable.CloneWithMutable(true) + if !mutableCopy.Mutable() { + t.Fatal("clone should be mutable") + } + must(mutableCopy.Activate("a")) + eq(t, "mutable copy", mutableCopy.Resolve(none).ActiveTools, []string{"a", "b"}) + eq(t, "original", immutable.Resolve(none).ActiveTools, []string{"b"}) + + // Mode inherited when not overridden. + mut := newSet(t, true, tsA) + clone := mut.Clone() + if after := must(clone.Deactivate("a")); after != clone { + t.Fatal("clone of mutable set should be mutable") + } + eq(t, "source untouched", mut.Resolve(none).ActiveTools, []string{"a"}) + + // clone()/CloneWithMutable(false) of an immutable keeps state & mode. + for _, c := range []*ToolSet[ctxMap]{immutable.Clone(), immutable.CloneWithMutable(false)} { + if c.Mutable() { + t.Fatal("clone should stay immutable") + } + eq(t, "clone state", c.Resolve(none).ActiveTools, []string{"b"}) + } +} + +// ─── resolve / inferTools input shapes ────────────────────────────────────── + +func TestToolSetResolveEmptyInput(t *testing.T) { + ts := must(newSet(t, false, tsA).ActivateWhen("a", func(in ActivationInput[ctxMap]) bool { + return in.State == nil && in.Context == nil + })) + eq(t, "zero input", ts.Resolve(ActivationInput[ctxMap]{}).ActiveTools, []string{"a"}) +} + +func TestToolSetPassesStateAndContextToPredicate(t *testing.T) { + var seen []ActivationInput[ctxMap] + ts := must(newSet(t, false, tsA).ActivateWhen("a", func(in ActivationInput[ctxMap]) bool { + seen = append(seen, in) + return true + })) + state := &ConversationState{ID: "conv_test", Status: "complete", + Messages: []components.InputsUnion1{}} + ts.Resolve(ActivationInput[ctxMap]{State: state, Context: ctxMap{"foo": "bar"}}) + if len(seen) != 1 { + t.Fatalf("predicate called %d times, want 1", len(seen)) + } + if seen[0].State != state { + t.Fatal("predicate did not receive the state") + } + eq(t, "context", seen[0].Context, ctxMap{"foo": "bar"}) +} + +func TestToolSetInferToolsAliasesResolve(t *testing.T) { + ts := must(newSet(t, false, tsA, tsB).Deactivate("a")) + eq(t, "InferTools", ts.InferTools(none), ts.Resolve(none)) +} + +// ─── exhaustive statusByTool ──────────────────────────────────────────────── + +func TestToolSetStatusByTool(t *testing.T) { + ts := must(must(newSet(t, false, tsA, tsB, tsC).Deactivate("b")). + ActivateWhen("c", func(ActivationInput[ctxMap]) bool { return true })) + snap := ts.Resolve(none) + eq(t, "statusByTool", snap.StatusByTool, map[string]ToolStatusEntry{ + "a": {Enabled: true, Reason: StatusReasonDefault}, + "b": {Enabled: false, Reason: StatusReasonDeactivate, Directive: DirectiveDeactivate}, + "c": {Enabled: true, Reason: StatusReasonActivateWhen, Directive: DirectiveActivateWhen, Predicate: true}, + }) + eq(t, "enabled", snap.Enabled, []string{"a", "c"}) + eq(t, "disabled", snap.Disabled, []string{"b"}) + + // JSON shape matches upstream's (absent directive/predicate keys). + b, err := json.Marshal(snap.StatusByTool["a"]) + if err != nil { + t.Fatal(err) + } + eq(t, "json", string(b), `{"enabled":true,"reason":"default"}`) + b, _ = json.Marshal(snap.StatusByTool["c"]) + eq(t, "json", string(b), `{"enabled":true,"reason":"activateWhen","directive":"activateWhen","predicate":true}`) +} + +func TestToolSetPrototypeSensitiveIDs(t *testing.T) { + proto := makeSetTool("__proto__") + ctor := makeSetTool("constructor") + prototype := makeSetTool("prototype") + ts := must(newSet(t, false, tsA, proto, ctor, prototype, tsB).Deactivate("constructor")) + snap := ts.Resolve(none) + keys := make([]string, 0) + for k := range snap.StatusByTool { + keys = append(keys, k) + } + sort.Strings(keys) + eq(t, "keys", keys, []string{"__proto__", "a", "b", "constructor", "prototype"}) + eq(t, "constructor", snap.StatusByTool["constructor"], ToolStatusEntry{Enabled: false, Reason: StatusReasonDeactivate, Directive: DirectiveDeactivate}) + eq(t, "__proto__", snap.StatusByTool["__proto__"], ToolStatusEntry{Enabled: true, Reason: StatusReasonDefault}) + eq(t, "enabled", snap.Enabled, []string{"a", "__proto__", "prototype", "b"}) + eq(t, "disabled", snap.Disabled, []string{"constructor"}) + eq(t, "tools", snap.Tools, []Tool{tsA, proto, prototype, tsB}) + eq(t, "activeTools", snap.ActiveTools, []string{"a", "__proto__", "prototype", "b"}) + + ts2 := must(newSet(t, false, proto, ctor, prototype).Activate("__proto__")) + ts2 = must(ts2.Deactivate("prototype")) + ts2 = must(ts2.ActivateWhen("constructor", func(ActivationInput[ctxMap]) bool { return false })) + s2 := ts2.Resolve(none) + eq(t, "status", s2.StatusByTool, map[string]ToolStatusEntry{ + "__proto__": {Enabled: true, Reason: StatusReasonActivate, Directive: DirectiveActivate}, + "constructor": {Enabled: false, Reason: StatusReasonActivateWhen, Directive: DirectiveActivateWhen, Predicate: true}, + "prototype": {Enabled: false, Reason: StatusReasonDeactivate, Directive: DirectiveDeactivate}, + }) + eq(t, "enabled", s2.Enabled, []string{"__proto__"}) + eq(t, "disabled", s2.Disabled, []string{"constructor", "prototype"}) +} + +func TestToolSetConditionalFalseLandsInDisabled(t *testing.T) { + ts := must(must(newSet(t, false, tsA, tsB).Deactivate("b")). + ActivateWhen("a", func(ActivationInput[ctxMap]) bool { return false })) + eq(t, "disabled", ts.Resolve(none).Disabled, []string{"a", "b"}) +} + +func TestToolSetStaticPartitionTools(t *testing.T) { + snap := must(newSet(t, false, tsA, tsB, tsC).Deactivate("b")).Resolve(none) + eq(t, "tools", snap.Tools, []Tool{tsA, tsC}) + eq(t, "activeTools", snap.ActiveTools, []string{"a", "c"}) +} + +// ─── server tools ─────────────────────────────────────────────────────────── + +func TestToolSetServerToolIDs(t *testing.T) { + webSearch := NewServerTool(ServerToolConfig{Name: "web_search", Config: webSearchServerTool()}) + datetime := NewServerTool(ServerToolConfig{Config: datetimeServerTool()}) + publicSearch := must(NewServerToolWithID(ServerToolConfig{Config: webSearchServerTool()}, "server:public_search")) + + eq(t, "webSearch id", ToolSetID(webSearch), "server:web_search_2025_08_26") + eq(t, "datetime id", ToolSetID(datetime), "server:openrouter:datetime") + eq(t, "publicSearch id", ToolSetID(publicSearch), "server:public_search") + eq(t, "client id", ToolSetID(tsA), "a") + + // The ID wrapper is still a server tool with the unmodified wire config. + if !IsServerTool(publicSearch) || publicSearch.ToAPITool().WebSearchServerTool == nil { + t.Fatal("NewServerToolWithID must preserve the server tool shape") + } + _, err := NewServerToolWithID(ServerToolConfig{Config: webSearchServerTool()}, "") + wantErr(t, err, ErrServerToolEmptyID, "must not be empty") +} + +func TestToolSetServerTools(t *testing.T) { + webSearch := NewServerTool(ServerToolConfig{Name: "web_search", Config: webSearchServerTool()}) + datetime := NewServerTool(ServerToolConfig{Config: datetimeServerTool()}) + const wsID = "server:web_search_2025_08_26" + + t.Run("preserves construction order", func(t *testing.T) { + ts := newSet(t, false, tsA, webSearch, tsB, datetime) + eq(t, "Tools", ts.Tools(), []Tool{tsA, webSearch, tsB, datetime}) + }) + + t.Run("active server tools in tools/enabled/status but not activeTools", func(t *testing.T) { + snap := must(newSet(t, false, tsA, webSearch, tsB).Deactivate("a")).Resolve(none) + eq(t, "tools", snap.Tools, []Tool{webSearch, tsB}) + eq(t, "activeTools", snap.ActiveTools, []string{"b"}) + eq(t, "enabled", snap.Enabled, []string{wsID, "b"}) + eq(t, "status", snap.StatusByTool[wsID], ToolStatusEntry{Enabled: true, Reason: StatusReasonDefault}) + }) + + t.Run("deactivate by stable id", func(t *testing.T) { + snap := must(newSet(t, false, tsA, webSearch, tsB).Deactivate(wsID)).Resolve(none) + eq(t, "tools", snap.Tools, []Tool{tsA, tsB}) + eq(t, "enabled", snap.Enabled, []string{"a", "b"}) + eq(t, "disabled", snap.Disabled, []string{wsID}) + eq(t, "status", snap.StatusByTool[wsID], ToolStatusEntry{Enabled: false, Reason: StatusReasonDeactivate, Directive: DirectiveDeactivate}) + }) + + t.Run("override ids and duplicate rejection", func(t *testing.T) { + publicSearch := must(NewServerToolWithID(ServerToolConfig{Config: webSearchServerTool()}, "server:public_search")) + eq(t, "enabled", newSet(t, false, tsA, publicSearch).Resolve(none).Enabled, []string{"a", "server:public_search"}) + + _, err := CreateToolSet[ctxMap](ToolSetConfig{Tools: []Tool{ + webSearch, NewServerTool(ServerToolConfig{Config: webSearchServerTool()}), + }}) + wantErr(t, err, ErrToolSetDuplicateID, `duplicate tool ID: "server:web_search_2025_08_26"`) + }) + + t.Run("raw type strings and ServerToolConfig.Name are not ids", func(t *testing.T) { + ts := newSet(t, false, tsA, webSearch) + _, err := ts.Activate("web_search_2025_08_26") + wantErr(t, err, ErrToolSetUnknownTool, "unknown tool") + _, err = ts.Activate("web_search") + wantErr(t, err, ErrToolSetUnknownTool, "unknown tool") + }) + + t.Run("hand-written server tool without an id", func(t *testing.T) { + handWritten := struct{ Tool }{NewServerTool(ServerToolConfig{Config: webSearchServerTool()})} + snap := must(newSet(t, false, tsA, handWritten).Deactivate(wsID)).Resolve(none) + eq(t, "enabled", snap.Enabled, []string{"a"}) + eq(t, "disabled", snap.Disabled, []string{wsID}) + eq(t, "status", snap.StatusByTool[wsID], ToolStatusEntry{Enabled: false, Reason: StatusReasonDeactivate, Directive: DirectiveDeactivate}) + eq(t, "tools", snap.Tools, []Tool{tsA}) + }) + + t.Run("union without discriminator falls back to wire type", func(t *testing.T) { + raw := components.ResponsesRequestToolUnion{WebSearchServerTool: &components.WebSearchServerTool{ + Type: components.WebSearchServerToolTypeWebSearch20250826, + }} + eq(t, "id", ToolSetID(NewServerTool(ServerToolConfig{Config: raw})), wsID) + }) + + t.Run("custom id: real id accepted, synthesized default rejected", func(t *testing.T) { + erased := must(NewServerToolWithID(ServerToolConfig{Config: webSearchServerTool()}, "server:public_search")) + snap := must(newSet(t, false, tsA, erased).Deactivate("server:public_search")).Resolve(none) + eq(t, "enabled", snap.Enabled, []string{"a"}) + eq(t, "disabled", snap.Disabled, []string{"server:public_search"}) + + _, err := newSet(t, false, tsA, erased).Deactivate(wsID) + wantErr(t, err, ErrToolSetUnknownTool, "unknown tool") + }) +} + +// ─── defineSituations / resolveSituation ──────────────────────────────────── + +func TestToolSetSituationsStaticOverlay(t *testing.T) { + ts := must(must(newSet(t, false, tsA, tsB, tsC).Deactivate("c")).DefineSituations(map[string]SituationConfig[ctxMap]{ + "guest": {Enabled: []string{"a"}, Disabled: []string{"b", "c"}}, + "full": {Enabled: []string{"a", "b", "c"}}, + })) + guest := must(ts.ResolveSituation("guest", none)) + eq(t, "tools", guest.Tools, []Tool{tsA}) + eq(t, "activeTools", guest.ActiveTools, []string{"a"}) + eq(t, "enabled", guest.Enabled, []string{"a"}) + eq(t, "disabled", guest.Disabled, []string{"b", "c"}) + eq(t, "status", guest.StatusByTool, map[string]ToolStatusEntry{ + "a": {Enabled: true, Reason: StatusReasonSituation, Directive: DirectiveActivate}, + "b": {Enabled: false, Reason: StatusReasonSituation, Directive: DirectiveDeactivate}, + "c": {Enabled: false, Reason: StatusReasonSituation, Directive: DirectiveDeactivate}, + }) + full := must(ts.ResolveSituation("full", none)) + eq(t, "full", full.Tools, []Tool{tsA, tsB, tsC}) + + // The base partition is unaffected by situations. + eq(t, "base", ts.Resolve(none).Enabled, []string{"a", "b"}) +} + +func TestToolSetSituationConditionalRules(t *testing.T) { + ts := must(newSet(t, false, tsA, tsB, tsC).DefineSituations(map[string]SituationConfig[ctxMap]{ + "authed": { + Enabled: []string{"a"}, + Disabled: []string{"b"}, + Conditional: map[string]*SituationConditionalRule[ctxMap]{ + "c": SituationActivateWhen(func(in ActivationInput[ctxMap]) bool { return in.Context["admin"] == true }), + }, + }, + })) + denied := must(ts.ResolveSituation("authed", ActivationInput[ctxMap]{Context: ctxMap{"admin": false}})) + eq(t, "tools", denied.Tools, []Tool{tsA}) + eq(t, "enabled", denied.Enabled, []string{"a"}) + eq(t, "disabled", denied.Disabled, []string{"b", "c"}) + eq(t, "status c", denied.StatusByTool["c"], ToolStatusEntry{Enabled: false, Reason: StatusReasonSituation, Directive: DirectiveActivateWhen, Predicate: true}) + + allowed := must(ts.ResolveSituation("authed", ActivationInput[ctxMap]{Context: ctxMap{"admin": true}})) + eq(t, "tools", allowed.Tools, []Tool{tsA, tsC}) + eq(t, "enabled", allowed.Enabled, []string{"a", "c"}) + + // Bare rule with empty Mode defaults to activateWhen. + bare := must(newSet(t, false, tsA).DefineSituations(map[string]SituationConfig[ctxMap]{ + "s": {Conditional: map[string]*SituationConditionalRule[ctxMap]{ + "a": {Predicate: func(ActivationInput[ctxMap]) bool { return false }}, + }}, + })) + eq(t, "bare default mode", must(bare.ResolveSituation("s", none)).Disabled, []string{"a"}) +} + +func TestToolSetSituationDeactivateWhen(t *testing.T) { + ts := must(newSet(t, false, tsA).DefineSituations(map[string]SituationConfig[ctxMap]{ + "guarded": {Conditional: map[string]*SituationConditionalRule[ctxMap]{ + "a": {Mode: ActivationModeDeactivateWhen, Predicate: func(in ActivationInput[ctxMap]) bool { return in.Context["blocked"] == true }}, + }}, + })) + eq(t, "enabled", must(ts.ResolveSituation("guarded", none)).Enabled, []string{"a"}) + blocked := must(ts.ResolveSituation("guarded", ActivationInput[ctxMap]{Context: ctxMap{"blocked": true}})) + eq(t, "disabled", blocked.Disabled, []string{"a"}) + eq(t, "status", blocked.StatusByTool["a"], ToolStatusEntry{Enabled: false, Reason: StatusReasonSituation, Directive: DirectiveDeactivateWhen, Predicate: true}) + + viaHelper := must(newSet(t, false, tsA).DefineSituations(map[string]SituationConfig[ctxMap]{ + "g": {Conditional: map[string]*SituationConditionalRule[ctxMap]{ + "a": SituationDeactivateWhen(func(ActivationInput[ctxMap]) bool { return true }), + }}, + })) + eq(t, "helper", must(viaHelper.ResolveSituation("g", none)).Disabled, []string{"a"}) +} + +func TestToolSetSituationValidation(t *testing.T) { + base := newSet(t, false, tsA, tsB) + yes := func(ActivationInput[ctxMap]) bool { return true } + cases := []struct { + name string + cfg SituationConfig[ctxMap] + sentinel error + substr string + }{ + {"unknown id", SituationConfig[ctxMap]{Enabled: []string{"nope"}}, ErrToolSetUnknownTool, `unknown tool: "nope"`}, + {"enabled+disabled", SituationConfig[ctxMap]{Enabled: []string{"a"}, Disabled: []string{"a"}}, ErrToolSetSituationDuplicate, `lists tool "a" more than once`}, + {"enabled+conditional", SituationConfig[ctxMap]{Enabled: []string{"a"}, Conditional: map[string]*SituationConditionalRule[ctxMap]{"a": SituationActivateWhen(yes)}}, ErrToolSetSituationDuplicate, `lists tool "a" more than once`}, + {"repeated within enabled", SituationConfig[ctxMap]{Enabled: []string{"b", "b"}}, ErrToolSetSituationDuplicate, `lists tool "b" more than once`}, + {"unknown conditional id", SituationConfig[ctxMap]{Conditional: map[string]*SituationConditionalRule[ctxMap]{"nope": SituationActivateWhen(yes)}}, ErrToolSetUnknownTool, `unknown tool: "nope"`}, + {"missing predicate", SituationConfig[ctxMap]{Conditional: map[string]*SituationConditionalRule[ctxMap]{"a": {Mode: ActivationModeActivateWhen}}}, ErrToolSetInvalidConditionalRule, `situation "checkout": conditional rule for tool "a" must be a function or { mode, predicate } object`}, + {"invalid mode", SituationConfig[ctxMap]{Conditional: map[string]*SituationConditionalRule[ctxMap]{"a": {Mode: "sometimes", Predicate: yes}}}, ErrToolSetInvalidConditionalRule, `situation "checkout": conditional rule for tool "a"`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + _, err := base.DefineSituations(map[string]SituationConfig[ctxMap]{"checkout": tc.cfg}) + wantErr(t, err, tc.sentinel, tc.substr) + }) + } +} + +func TestToolSetSituationIgnoresNilConditionalEntries(t *testing.T) { + ts := must(newSet(t, false, tsA, tsB).DefineSituations(map[string]SituationConfig[ctxMap]{ + "optional": {Conditional: map[string]*SituationConditionalRule[ctxMap]{ + "a": nil, + "b": SituationActivateWhen(func(ActivationInput[ctxMap]) bool { return false }), + }}, + })) + eq(t, "activeTools", must(ts.ResolveSituation("optional", none)).ActiveTools, []string{"a"}) + + // A nil entry does not count toward duplicate detection either. + _, err := newSet(t, false, tsA).DefineSituations(map[string]SituationConfig[ctxMap]{ + "s": {Enabled: []string{"a"}, Conditional: map[string]*SituationConditionalRule[ctxMap]{"a": nil}}, + }) + if err != nil { + t.Fatalf("nil conditional entry should be ignored: %v", err) + } +} + +func TestToolSetUnknownSituation(t *testing.T) { + ts := must(newSet(t, false, tsA).DefineSituations(map[string]SituationConfig[ctxMap]{ + "guest": {Enabled: []string{"a"}}, + })) + _, err := ts.ResolveSituation("missing", none) + wantErr(t, err, ErrToolSetUnknownSituation, `unknown situation: "missing"`) +} + +func TestToolSetSituationLeavesUnmentionedIDsOnBase(t *testing.T) { + ts := must(must(newSet(t, false, tsA, tsB, tsC).Deactivate("c")).DefineSituations(map[string]SituationConfig[ctxMap]{ + "onlyB": {Disabled: []string{"b"}}, + })) + snap := must(ts.ResolveSituation("onlyB", none)) + eq(t, "enabled", snap.Enabled, []string{"a"}) + eq(t, "disabled", snap.Disabled, []string{"b", "c"}) + eq(t, "status c", snap.StatusByTool["c"], ToolStatusEntry{Enabled: false, Reason: StatusReasonDeactivate, Directive: DirectiveDeactivate}) +} + +func TestToolSetDefineSituationsReplacesAndRespectsMutability(t *testing.T) { + base := must(newSet(t, false, tsA).DefineSituations(map[string]SituationConfig[ctxMap]{"one": {}})) + next := must(base.DefineSituations(map[string]SituationConfig[ctxMap]{"two": {}})) + if next == base { + t.Fatal("immutable DefineSituations returned receiver") + } + if _, err := next.ResolveSituation("one", none); !errors.Is(err, ErrToolSetUnknownSituation) { + t.Fatalf("situations must be replaced, got %v", err) + } + if _, err := base.ResolveSituation("one", none); err != nil { + t.Fatalf("original situations must be untouched: %v", err) + } + // Directives made after DefineSituations keep the situations. + after := must(next.Deactivate("a")) + if _, err := after.ResolveSituation("two", none); err != nil { + t.Fatalf("situations lost across mutation: %v", err) + } + + mut := newSet(t, true, tsA) + if r := must(mut.DefineSituations(map[string]SituationConfig[ctxMap]{"x": {Disabled: []string{"a"}}})); r != mut { + t.Fatal("mutable DefineSituations must return receiver") + } + eq(t, "mutable", must(mut.ResolveSituation("x", none)).Disabled, []string{"a"}) + // A clone gets an independent situation registry. + clone := mut.Clone() + must(mut.DefineSituations(map[string]SituationConfig[ctxMap]{})) + if _, err := clone.ResolveSituation("x", none); err != nil { + t.Fatalf("clone situations should be independent: %v", err) + } +} + +// ─── TShared generic ──────────────────────────────────────────────────────── + +type appContext struct { + IsAuthenticated bool + UserID string +} + +func TestToolSetTypedSharedContext(t *testing.T) { + ts, err := CreateToolSet[*appContext](ToolSetConfig{Tools: []Tool{tsA}}) + if err != nil { + t.Fatal(err) + } + ts = must(ts.ActivateWhen("a", func(in ActivationInput[*appContext]) bool { + if in.Context == nil { + return false + } + return in.Context.IsAuthenticated + })) + eq(t, "authed", ts.Resolve(ActivationInput[*appContext]{Context: &appContext{IsAuthenticated: true, UserID: "u1"}}).ActiveTools, []string{"a"}) + eq(t, "anon", ts.Resolve(ActivationInput[*appContext]{Context: &appContext{UserID: "u1"}}).ActiveTools, []string{}) + eq(t, "absent", ts.Resolve(ActivationInput[*appContext]{}).ActiveTools, []string{}) +} + +// ─── callModel-oriented shape ─────────────────────────────────────────────── + +func TestToolSetCallModelShape(t *testing.T) { + snap := must(newSet(t, false, tsA, tsB, tsC).Deactivate("b")).Resolve(none) + eq(t, "callModel.tools", snap.CallModel.Tools, []Tool{tsA, tsC}) + eq(t, "callModel.activeTools", snap.CallModel.ActiveTools, []string{"a", "c"}) + + // The snapshot's CallModel field does not alias the top-level slices. + snap.CallModel.ActiveTools[0] = "mutated" + eq(t, "top-level untouched", snap.ActiveTools, []string{"a", "c"}) +} + +// When every client tool is deactivated, ActiveTools must be an empty +// non-nil slice: CallModel treats nil as "no filter" but empty as "filter +// every client tool out" — the latter is what upstream's [] means. +func TestToolSetAllClientToolsDeactivatedStillFilters(t *testing.T) { + webSearch := NewServerTool(ServerToolConfig{Config: webSearchServerTool()}) + snap := must(newSet(t, false, tsA, webSearch, tsB).Deactivate("a", "b")).Resolve(none) + if snap.CallModel.ActiveTools == nil { + t.Fatal("ActiveTools must be non-nil when all client tools are off") + } + // Feeding the full tool list plus the snapshot's ActiveTools through the + // engine filter yields exactly the snapshot's active tools. + eq(t, "filtered", filterToolsByActiveNames([]Tool{tsA, webSearch, tsB}, snap.CallModel.ActiveTools), []Tool{webSearch}) + + snapAllOff := must(newSet(t, false, tsA, tsB).Deactivate("a", "b")).Resolve(none) + if got := filterToolsByActiveNames(snapAllOff.CallModel.Tools, snapAllOff.CallModel.ActiveTools); got != nil { + t.Fatalf("fully deactivated set must collapse to nil tools, got %v", got) + } +} + +// ─── concurrency ──────────────────────────────────────────────────────────── + +func TestToolSetMutableConcurrentUse(t *testing.T) { + ts := newSet(t, true, tsA, tsB, tsC) + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(3) + go func() { + defer wg.Done() + _, _ = ts.Deactivate("a") + }() + go func() { + defer wg.Done() + _, _ = ts.Activate("a") + _, _ = ts.DefineSituations(map[string]SituationConfig[ctxMap]{"s": {Disabled: []string{"b"}}}) + }() + go func() { + defer wg.Done() + snap := ts.Resolve(none) + if len(snap.StatusByTool) != 3 { + t.Errorf("statusByTool not exhaustive: %v", snap.StatusByTool) + } + _ = ts.Clone().Resolve(none) + }() + } + wg.Wait() + enabled := ts.Resolve(none).Enabled + eq(t, "b,c active", enabled[len(enabled)-2:], []string{"b", "c"}) +} + +// A predicate may mutate a mutable set it belongs to without deadlocking. +// As upstream (which reads the live activation map per tool), the mutation +// is visible to tools evaluated later in the same Resolve. +func TestToolSetPredicateMayMutateMutableSet(t *testing.T) { + ts := newSet(t, true, tsA, tsB) + must(ts.ActivateWhen("a", func(ActivationInput[ctxMap]) bool { + _, _ = ts.Deactivate("b") + return true + })) + eq(t, "enabled", ts.Resolve(none).Enabled, []string{"a"}) +} diff --git a/tool_test.go b/tool_test.go index 32233e7..426cfad 100644 --- a/tool_test.go +++ b/tool_test.go @@ -55,8 +55,10 @@ func TestToolExecutionValidationAndGeneratorEvents(t *testing.T) { if err != nil { t.Fatal(err) } - if len(result.Events) != 1 || len(live) != 1 { - t.Fatalf("generator events should be emitted live and recorded") + // Yields are broadcast live only; the terminal result no longer carries + // the yield history (upstream 1.0.0 dropped preliminaryResults). + if len(live) != 1 { + t.Fatalf("generator events should be emitted live, got %d", len(live)) } if !IsGeneratorTool(generator) || !IsRegularExecuteTool(regular) || IsManualTool(regular) { t.Fatalf("tool guards misclassified tools") diff --git a/tool_types.go b/tool_types.go index b17ebd0..5c1189c 100644 --- a/tool_types.go +++ b/tool_types.go @@ -19,8 +19,29 @@ const ( ) type ToolApprovalCheck func(context.Context, ParsedToolCall, TurnContext) (bool, error) -type ToModelOutputFunction func(any) (any, error) -type ToModelOutputResult struct{ Output any } + +// ToModelOutputTypeContent is the only ToModelOutputResult type upstream +// defines: the value replaces the tool output sent to the model. +const ToModelOutputTypeContent = "content" + +// ToModelOutputParams is what a ToolConfig.ToModelOutput mapper receives: +// the successful execution output and the decoded input the tool ran on. +type ToModelOutputParams[In any] struct { + Output any + Input In +} + +// ToModelOutputResult is a mapper's model-facing replacement output. Type +// should be ToModelOutputTypeContent ("" is accepted as shorthand); Value is +// sent as the function_call_output content array. +type ToModelOutputResult struct { + Type string + Value []ToolOutputContentItem +} + +// ToModelOutputFunction is the untyped mapper signature (input decoded as a +// JSON object) for tools that are not built with NewTool. +type ToModelOutputFunction func(context.Context, ToModelOutputParams[map[string]any]) (*ToModelOutputResult, error) type Tool interface { ToolName() string @@ -127,6 +148,11 @@ type ParsedToolCall struct { Name string Arguments any RawArgs string + // PreToolUseApplied marks a persisted pending call whose PreToolUse hook + // already ran (and whose Arguments are the hook's effective input), so a + // resume does not apply the hook a second time. Additive: legacy state + // without the marker re-runs PreToolUse on resume (upstream #94). + PreToolUseApplied bool `json:",omitempty"` } type TypedToolCall = ParsedToolCall @@ -140,7 +166,9 @@ type ToolExecutionResult struct { Source ToolSource Output any Error error - Events []any + // InputInvalid reports that the call never reached the tool body + // because its arguments failed to decode or validate. + InputInvalid bool } type ToolExecutionResultUnion = ToolExecutionResult @@ -222,6 +250,13 @@ type ConversationState struct { Status ConversationStatus CreatedAt int64 UpdatedAt int64 + // ConsumedForcedToolChoiceKey records that a forced caller ToolChoice + // (required, a specific tool, or allowed_tools mode=required) already + // produced a tool call in this logical run, so follow-up turns — + // including ones resumed after an approval/HITL/client-tool pause — send + // the relaxed choice instead (upstream DEV-785 / #100). Cleared when the + // run completes. Additive within version 1. + ConsumedForcedToolChoiceKey *string `json:",omitempty"` } type StateAccessor interface { diff --git a/turn_context.go b/turn_context.go index 6cb67fb..e27b4d9 100644 --- a/turn_context.go +++ b/turn_context.go @@ -1,14 +1,65 @@ package agent -import "github.com/OpenRouterTeam/go-sdk/models/components" +import ( + "encoding/json" + + openrouter "github.com/OpenRouterTeam/go-sdk" + "github.com/OpenRouterTeam/go-sdk/models/components" + "github.com/OpenRouterTeam/go-sdk/optionalnullable" +) func BuildTurnContext(call *components.OutputFunctionCallItem, turns int, req *components.ResponsesRequest) TurnContext { return TurnContext{ToolCall: call, NumberOfTurns: turns, TurnRequest: req} } +// NormalizeInputToArray converts a Responses input into an input-item slice +// (mirrors upstream normalizeInputToArray): a string input — including the +// empty string — becomes a single user message; an array input is returned as +// a copy of its items. func NormalizeInputToArray(input components.InputsUnion) []components.InputsUnion1 { - if input.Type == components.InputsUnionTypeArrayOfInputsUnion1 { - return append([]components.InputsUnion1{}, input.ArrayOfInputsUnion1...) + if input.Str != nil { + msg := components.EasyInputMessage{ + Role: components.CreateEasyInputMessageRoleUnionEasyInputMessageRoleUser(components.EasyInputMessageRoleUserUser), + Content: optionalnullable.From(openrouter.Pointer(components.CreateEasyInputMessageContentUnion2Str(*input.Str))), + } + return []components.InputsUnion1{components.CreateInputsUnion1EasyInputMessage(msg)} + } + return append([]components.InputsUnion1{}, input.ArrayOfInputsUnion1...) +} + +// IsInputItem reports whether value is shaped like a single item of a +// Responses input array: a JSON object carrying a string item `type` or a +// string message `role` (mirrors upstream isInputItem). Typed SDK values are +// inspected through their JSON encoding; values that do not encode to an +// object are not input items. +func IsInputItem(value any) bool { + var obj map[string]any + switch v := value.(type) { + case nil: + return false + case map[string]any: + obj = v + default: + b, err := json.Marshal(value) + if err != nil || json.Unmarshal(b, &obj) != nil { + return false + } } - return []components.InputsUnion1{} + if obj == nil { + return false + } + if _, ok := obj["type"].(string); ok { + return true + } + _, ok := obj["role"].(string) + return ok +} + +// OutputToInputItems converts response output items into input items for the +// next request (mirrors upstream outputToInputItems). Output items are fed back +// as input on the next turn; the SDK types the two directions separately, so +// each item is re-decoded through its wire form. It returns an error rather +// than dropping an item that cannot be converted. +func OutputToInputItems(output ...components.OutputItems) ([]components.InputsUnion1, error) { + return responseInputItemsWithError(components.OpenResponsesResult{Output: output}) } diff --git a/turn_context_test.go b/turn_context_test.go new file mode 100644 index 0000000..e1bc55b --- /dev/null +++ b/turn_context_test.go @@ -0,0 +1,175 @@ +package agent + +import ( + "context" + "encoding/json" + "testing" + + openrouter "github.com/OpenRouterTeam/go-sdk" + "github.com/OpenRouterTeam/go-sdk/models/components" + "github.com/OpenRouterTeam/go-sdk/models/operations" +) + +// Ports tests/unit/turn-context.test.ts. + +func TestBuildTurnContextCarriesFields(t *testing.T) { + minimal := BuildTurnContext(nil, 0, nil) + if minimal.NumberOfTurns != 0 || minimal.ToolCall != nil || minimal.TurnRequest != nil { + t.Fatalf("minimal context = %+v", minimal) + } + call := &components.OutputFunctionCallItem{CallID: "call_2", Name: "browse", Arguments: "{}"} + req := &components.ResponsesRequest{Model: openrouter.String("openai/gpt-4")} + both := BuildTurnContext(call, 3, req) + if both.NumberOfTurns != 3 || both.ToolCall != call || both.TurnRequest != req { + t.Fatalf("context = %+v", both) + } +} + +func TestNormalizeInputToArrayStringBecomesUserMessage(t *testing.T) { + assertWireJSON(t, NormalizeInputToArray(components.CreateInputsUnionStr("Hello!")), `[{"role":"user","content":"Hello!"}]`) + // The empty string is still a message, not "no input". + assertWireJSON(t, NormalizeInputToArray(components.CreateInputsUnionStr("")), `[{"role":"user","content":""}]`) +} + +func TestNormalizeInputToArrayPassesArrayThrough(t *testing.T) { + items, err := FromChatMessages([]ChatMessage{{Role: "user", Content: "hi"}, {Role: "assistant", Content: "hello"}}) + if err != nil { + t.Fatal(err) + } + got := NormalizeInputToArray(components.CreateInputsUnionArrayOfInputsUnion1(items)) + assertWireJSON(t, got, `[{"role":"user","content":"hi"},{"role":"assistant","content":"hello"}]`) +} + +func TestIsInputItem(t *testing.T) { + cases := []struct { + name string + value any + want bool + }{ + {"nil", nil, false}, + {"string", "hi", false}, + {"number", 1, false}, + {"array", []any{map[string]any{"type": "message"}}, false}, + {"empty object", map[string]any{}, false}, + {"typed item", map[string]any{"type": "function_call"}, true}, + {"role message", map[string]any{"role": "user", "content": "hi"}, true}, + {"non-string type and role", map[string]any{"type": 1, "role": false}, false}, + {"SDK output item", components.CreateOutputItemsFunctionCall(components.OutputFunctionCallItem{CallID: "c", Name: "n", Arguments: "{}"}), true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := IsInputItem(tc.value); got != tc.want { + t.Fatalf("IsInputItem = %v, want %v", got, tc.want) + } + }) + } +} + +func TestOutputToInputItemsFeedsOutputBackAsInput(t *testing.T) { + msg := components.OutputMessageItem{ID: "msg_1", Role: components.OutputMessageItemRoleAssistant, Content: []components.OutputMessageItemContent{components.CreateOutputMessageItemContentOutputText(components.ResponseOutputText{Text: "hello"})}} + fc := components.OutputFunctionCallItem{ID: openrouter.String("fc_1"), CallID: "call_1", Name: "search", Arguments: `{"q":"go"}`} + items, err := OutputToInputItems(components.CreateOutputItemsMessage(msg), components.CreateOutputItemsFunctionCall(fc)) + if err != nil { + t.Fatalf("OutputToInputItems: %v", err) + } + if len(items) != 2 { + t.Fatalf("expected 2 input items, got %d", len(items)) + } + wire := func(v any) map[string]any { + b, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + var m map[string]any + if err := json.Unmarshal(b, &m); err != nil { + t.Fatal(err) + } + return m + } + if m := wire(items[0]); m["role"] != "assistant" || m["content"] != "hello" { + t.Fatalf("message not converted to input: %v", m) + } + if m := wire(items[1]); m["type"] != "function_call" || m["call_id"] != "call_1" || m["name"] != "search" || m["arguments"] != `{"q":"go"}` { + t.Fatalf("function call not converted to input: %v", m) + } + for _, it := range items { + if !IsInputItem(it) { + t.Fatalf("converted item is not an input item: %#v", it) + } + } + empty, err := OutputToInputItems() + if err != nil || len(empty) != 0 { + t.Fatalf("empty output = %v, %v", empty, err) + } +} + +// Ports the extractor cases of tests/unit/non-completed-response-tool-calls.test.ts. +func TestToolCallExtractorsGateOnCompletedStatus(t *testing.T) { + call := components.OutputFunctionCallItem{CallID: "call_1", Name: "run_shell", Arguments: `{"command":"echo hi"}`} + withStatus := func(s components.OpenAIResponsesResponseStatus) components.OpenResponsesResult { + return components.OpenResponsesResult{ID: "r", Status: s, Output: []components.OutputItems{components.CreateOutputItemsFunctionCall(call)}} + } + nonCompleted := []components.OpenAIResponsesResponseStatus{ + components.OpenAIResponsesResponseStatusIncomplete, + components.OpenAIResponsesResponseStatusFailed, + components.OpenAIResponsesResponseStatusCancelled, + components.OpenAIResponsesResponseStatusInProgress, + components.OpenAIResponsesResponseStatusQueued, + components.OpenAIResponsesResponseStatus("some_future_status"), + } + for _, s := range nonCompleted { + resp := withStatus(s) + if ResponseHasToolCalls(resp) { + t.Fatalf("ResponseHasToolCalls(%q) = true, want false", s) + } + if got := ExtractToolCallsFromResponse(resp); len(got) != 0 { + t.Fatalf("ExtractToolCallsFromResponse(%q) = %+v, want none", s, got) + } + } + completed := withStatus(components.OpenAIResponsesResponseStatusCompleted) + if !ResponseHasToolCalls(completed) { + t.Fatalf("ResponseHasToolCalls(completed) = false") + } + got := ExtractToolCallsFromResponse(completed) + if len(got) != 1 || got[0].CallID != "call_1" || got[0].Name != "run_shell" { + t.Fatalf("ExtractToolCallsFromResponse(completed) = %+v", got) + } + if args, ok := got[0].Arguments.(map[string]any); !ok || args["command"] != "echo hi" { + t.Fatalf("arguments = %#v", got[0].Arguments) + } + if ResponseHasToolCalls(components.OpenResponsesResult{Status: components.OpenAIResponsesResponseStatusCompleted}) { + t.Fatalf("ResponseHasToolCalls without function calls = true") + } +} + +// callModel refuses to execute tools on an initial non-completed response: the +// caller still receives the response, and ToolCalls is empty. +func TestCallModelDoesNotExecuteToolsFromIncompleteResponse(t *testing.T) { + executed := 0 + tool := MustNewTool(ToolConfig[sampleInput]{ + Name: "search", + Execute: func(ctx context.Context, in sampleInput, tc ToolExecuteContext) (any, error) { + executed++ + return "ok", nil + }, + }) + call := components.OutputFunctionCallItem{CallID: "call_1", Name: "search", Arguments: `{"query":"go"}`} + resp := components.OpenResponsesResult{ID: "resp_inc", Model: "openai/test", Status: components.OpenAIResponsesResponseStatusIncomplete, Output: []components.OutputItems{components.CreateOutputItemsFunctionCall(call)}} + created := operations.CreateCreateResponsesResponseOpenResponsesResult(resp) + sender := &fakeSender{responses: []*operations.CreateResponsesResponse{&created}} + result, err := CallModel(t.Context(), sender, CallModelInput{Model: "openai/test", Input: "Run it.", Tools: []Tool{tool}}) + if err != nil { + t.Fatal(err) + } + got, err := result.Response(t.Context()) + if err != nil { + t.Fatalf("Response: %v", err) + } + if got.Status != components.OpenAIResponsesResponseStatusIncomplete { + t.Fatalf("status = %q", got.Status) + } + calls, _ := result.ToolCalls(t.Context()) + if executed != 0 || sender.calls != 1 || len(calls) != 0 { + t.Fatalf("executed=%d requests=%d toolCalls=%d; want 0/1/0", executed, sender.calls, len(calls)) + } +}