Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions internal/assistant/anthropic.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (

"github.com/omarluq/librecode/internal/database"
"github.com/omarluq/librecode/internal/model"
"github.com/omarluq/librecode/internal/tool"
)

func (client *HTTPCompletionClient) completeAnthropic(
Expand Down Expand Up @@ -76,6 +75,7 @@ func executeAnthropicToolCalls(
) []ToolEvent {
_, events := executeToolCalls(
ctx,
request.ToolRegistry,
request.CWD,
calls,
request.OnEvent,
Expand Down Expand Up @@ -406,13 +406,13 @@ func anthropicMessages(messages []database.MessageEntity) []map[string]any {
}

func anthropicTools(request *CompletionRequest) []map[string]any {
definitions := tool.AllDefinitions()
definitions := requestToolDefinitions(request)
tools := make([]map[string]any, 0, len(definitions))
for _, definition := range definitions {
tools = append(tools, map[string]any{
jsonToolNameKey: anthropicProviderToolName(string(definition.Name), usesAnthropicOAuth(request)),
jsonDescriptionKey: definition.Description,
jsonInputSchemaKey: toolParameterSchema(definition.Name),
jsonInputSchemaKey: toolParameterSchema(&definition),
"eager_input_streaming": true,
})
}
Expand Down
1 change: 1 addition & 0 deletions internal/assistant/anthropic_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ func testCompletionRequestAuth(args ...string) *CompletionRequest {
OnEvent: nil,
OnToolCall: nil,
OnToolResult: nil,
ToolRegistry: nil,
SessionID: "",
SystemPrompt: "",
ThinkingLevel: "",
Expand Down
2 changes: 2 additions & 0 deletions internal/assistant/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"github.com/omarluq/librecode/internal/database"
"github.com/omarluq/librecode/internal/model"
"github.com/omarluq/librecode/internal/tool"
)

const (
Expand Down Expand Up @@ -84,6 +85,7 @@ type CompletionRequest struct {
OnEvent func(StreamEvent) `json:"-"`
OnToolCall func(context.Context, ToolCallEvent) `json:"-"`
OnToolResult func(context.Context, *ToolEvent) `json:"-"`
ToolRegistry *tool.Registry `json:"-"`
SessionID string `json:"session_id"`
SystemPrompt string `json:"system_prompt"`
ThinkingLevel string `json:"thinking_level"`
Expand Down
3 changes: 2 additions & 1 deletion internal/assistant/openai_chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ func executeOpenAIChatToolCalls(
) []ToolEvent {
_, events := executeToolCalls(
ctx,
request.ToolRegistry,
request.CWD,
calls,
request.OnEvent,
Expand Down Expand Up @@ -116,7 +117,7 @@ func openAIChatPayload(request *CompletionRequest, messages []map[string]any) ma
"messages": messages,
"stream": false,
"temperature": 0.2,
"tools": openAIChatTools(),
"tools": openAIChatTools(request),
jsonToolChoiceKey: "auto",
}
if request.Model.Reasoning && request.ThinkingLevel != "" && request.ThinkingLevel != thinkingOff {
Expand Down
3 changes: 2 additions & 1 deletion internal/assistant/openai_responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ func (client *HTTPCompletionClient) completeResponsesLoop(
input = append(input, statelessResponseOutputItems(providerResult.OutputItems)...)
outputs, events := executeToolCalls(
ctx,
request.ToolRegistry,
request.CWD,
providerResult.ToolCalls,
request.OnEvent,
Expand All @@ -73,7 +74,7 @@ func (client *HTTPCompletionClient) completeResponsesLoop(

func responsesPayload(request *CompletionRequest, input []any, stream bool) map[string]any {
payload := responsesBasePayload(request, input, stream)
payload["tools"] = responseTools()
payload["tools"] = responseTools(request)
payload[jsonToolChoiceKey] = "auto"
payload["parallel_tool_calls"] = true

Expand Down
7 changes: 7 additions & 0 deletions internal/assistant/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -621,13 +621,18 @@
return nil, err
}
runtime.emitUsage(ctx, onEvent, contextResult.Usage)
registry, err := newToolRegistry(cwd, runtime.extensions)
if err != nil {
return nil, err
}
request := runtime.modelCompletionRequest(
&selectedModel,
auth,
contextResult.Messages,
sessionID,
contextResult.SystemPrompt,
cwd,
registry,
onEvent,
)
result, err := runtime.completeWithRetry(ctx, request, onRetry)
Expand All @@ -645,19 +650,21 @@
}, nil
}

func (runtime *Runtime) modelCompletionRequest(

Check warning on line 653 in internal/assistant/runtime.go

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

This function has 8 parameters, which is greater than the 7 authorized.

See more on https://sonarcloud.io/project/issues?id=omarluq_librecode&issues=AZ5SKr1UavhadsG2HoLK&open=AZ5SKr1UavhadsG2HoLK&pullRequest=43
selectedModel *model.Model,
auth model.RequestAuth,
messages []database.MessageEntity,
sessionID string,
systemPrompt string,
cwd string,
registry *tool.Registry,
onEvent func(StreamEvent),
) *CompletionRequest {
return &CompletionRequest{
OnEvent: onEvent,
OnToolCall: runtime.emitToolCall,
OnToolResult: runtime.emitToolResult,
ToolRegistry: registry,
SessionID: sessionID,
SystemPrompt: systemPrompt,
ThinkingLevel: runtime.cfg.Assistant.ThinkingLevel,
Expand Down
5 changes: 4 additions & 1 deletion internal/assistant/tool_loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,16 @@ func validateToolCalls(calls []toolCall) error {

func executeToolCalls(
ctx context.Context,
registry *tool.Registry,
cwd string,
calls []toolCall,
onEvent func(StreamEvent),
onToolCall func(context.Context, ToolCallEvent),
onToolResult func(context.Context, *ToolEvent),
) ([]any, []ToolEvent) {
registry := tool.NewRegistry(cwd)
if registry == nil {
registry = tool.NewRegistry(cwd)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
outputs := make([]any, 0, len(calls))
events := make([]ToolEvent, 0, len(calls))
for _, call := range calls {
Expand Down
12 changes: 12 additions & 0 deletions internal/assistant/tool_loop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,21 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/omarluq/librecode/internal/tool"
)

const testCallID = "call-1"

func newToolRegistryForTest(t *testing.T) *tool.Registry {
t.Helper()

registry, err := newToolRegistry(t.TempDir(), nil)
require.NoError(t, err)

return registry
}

func TestValidateToolCallsRejectsMissingFields(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -45,6 +56,7 @@ func TestExecuteToolCallsInvokesCallbacksAndStreamsEvents(t *testing.T) {
toolResults := []ToolEvent{}
outputs, events := executeToolCalls(
context.Background(),
newToolRegistryForTest(t),
t.TempDir(),
[]toolCall{{
Arguments: map[string]any{jsonPathKey: "missing.txt"},
Expand Down
52 changes: 52 additions & 0 deletions internal/assistant/tool_registry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package assistant

import (
"reflect"

"github.com/samber/oops"

"github.com/omarluq/librecode/internal/extension"
"github.com/omarluq/librecode/internal/tool"
)

var nilableToolProviderKinds = map[reflect.Kind]struct{}{
reflect.Chan: {},
reflect.Func: {},
reflect.Interface: {},
reflect.Map: {},
reflect.Pointer: {},
reflect.Slice: {},
}

type toolProvider interface {
Tools() []extension.Tool
tool.ExtensionToolRunner
}

func newToolRegistry(cwd string, provider toolProvider) (*tool.Registry, error) {
registry := tool.NewRegistry(cwd)
if isNilToolProvider(provider) {
return registry, nil
}
if err := registry.RegisterExtensions(provider, provider.Tools()); err != nil {
return nil, oops.In("assistant").Code("register_extension_tools").Wrapf(err, "register extension tools")
}

return registry, nil
}

func isNilToolProvider(provider toolProvider) bool {
if provider == nil {
return true
}
value := reflect.ValueOf(provider)
if !value.IsValid() {
return true
}

if _, ok := nilableToolProviderKinds[value.Kind()]; !ok {
return false
}

return value.IsNil()
}
70 changes: 70 additions & 0 deletions internal/assistant/tool_registry_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package assistant

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/omarluq/librecode/internal/extension"
"github.com/omarluq/librecode/internal/tool"
)

type nilToolProvider struct{}

func (*nilToolProvider) Tools() []extension.Tool {
panic("typed nil provider Tools called")
}

func (*nilToolProvider) ExecuteTool(context.Context, string, map[string]any) (extension.ToolResult, error) {
panic("typed nil provider ExecuteTool called")
}

func TestNewToolRegistryHandlesNilProviders(t *testing.T) {
t.Parallel()

tests := []struct {
provider toolProvider
name string
}{
{name: "nil interface", provider: nil},
{name: "typed nil", provider: (*nilToolProvider)(nil)},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()

registry, err := newToolRegistry(t.TempDir(), tt.provider)

require.NoError(t, err)
assert.NotNil(t, registry)
assert.Equal(t, len(tool.AllDefinitions()), len(registry.Definitions()))
})
}
}

func TestExecuteToolCallsUsesFallbackRegistryCWD(t *testing.T) {
t.Parallel()

cwd := t.TempDir()
_, events := executeToolCalls(
context.Background(),
nil,
cwd,
[]toolCall{{
Arguments: map[string]any{jsonCommandKey: "pwd"},
ID: testCallID,
Name: jsonBashToolName,
ArgumentsJSON: `{"command":"pwd"}`,
TextFallback: false,
}},
nil,
nil,
nil,
)

require.Len(t, events, 1)
assert.Contains(t, events[0].Result, cwd)
}
Loading
Loading