Merge branch 'correctness/round5': provider stream + file correctness (R7/N11/N12)
This commit is contained in:
commit
8c9bc2963d
13 files changed
+207
-59
No files matched your search
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -164,7 +165,7 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
|||||||
type pendingTC struct {
|
type pendingTC struct {
|
||||||
id string
|
id string
|
||||||
name string
|
name string
|
||||||
inputJSON string // built from input_json_delta events
|
inputJSON strings.Builder // built from input_json_delta events
|
||||||
startInput string // captured from content_block_start (proxy fallback)
|
startInput string // captured from content_block_start (proxy fallback)
|
||||||
}
|
}
|
||||||
var pendingTools []pendingTC
|
var pendingTools []pendingTC
|
||||||
@@ -220,18 +221,21 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
|||||||
}
|
}
|
||||||
case "input_json_delta":
|
case "input_json_delta":
|
||||||
if len(pendingTools) > 0 {
|
if len(pendingTools) > 0 {
|
||||||
pendingTools[len(pendingTools)-1].inputJSON += delta.PartialJSON
|
pendingTools[len(pendingTools)-1].inputJSON.WriteString(delta.PartialJSON)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
case "content_block_stop":
|
case "content_block_stop":
|
||||||
if currentBlockType == "tool_use" && len(pendingTools) > 0 {
|
if currentBlockType == "tool_use" && len(pendingTools) > 0 {
|
||||||
tc := pendingTools[len(pendingTools)-1]
|
// Index in place rather than copying the element: the
|
||||||
|
// pendingTC holds a strings.Builder, which must not be
|
||||||
|
// copied after first write (vet copylock).
|
||||||
|
tc := &pendingTools[len(pendingTools)-1]
|
||||||
// Prefer streamed deltas (canonical Anthropic). Fall
|
// Prefer streamed deltas (canonical Anthropic). Fall
|
||||||
// back to start-time input (proxy emitting full input
|
// back to start-time input (proxy emitting full input
|
||||||
// upfront). Default to "{}" so MCP servers receive a
|
// upfront). Default to "{}" so MCP servers receive a
|
||||||
// valid empty-args envelope rather than null/empty.
|
// valid empty-args envelope rather than null/empty.
|
||||||
inp := tc.inputJSON
|
inp := tc.inputJSON.String()
|
||||||
if inp == "" {
|
if inp == "" {
|
||||||
inp = tc.startInput
|
inp = tc.startInput
|
||||||
}
|
}
|
||||||
@@ -281,7 +285,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
|||||||
// Final event — nothing extra to emit
|
// Final event — nothing extra to emit
|
||||||
|
|
||||||
case "error":
|
case "error":
|
||||||
slog.Error("anthropic stream error", "event", event.Type)
|
// The SDK surfaces error detail via stream.Err() (handled after
|
||||||
|
// the loop); this in-band branch must not be a silent no-op —
|
||||||
|
// emit an EventError so the runtime treats it as a failure.
|
||||||
|
slog.Error("anthropic stream error event", "event", event.Type)
|
||||||
|
events <- llm.ChatEvent{
|
||||||
|
Type: llm.EventError,
|
||||||
|
Error: fmt.Errorf("anthropic stream error event"),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||||
@@ -708,3 +709,11 @@ data: {"type":"message_stop"}
|
|||||||
assert.Equal(t, "end_turn", done.StopReason)
|
assert.Equal(t, "end_turn", done.StopReason)
|
||||||
assert.Empty(t, done.StopCategory)
|
assert.Empty(t, done.StopCategory)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAnthropicInputAccumulation(t *testing.T) {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, part := range []string{`{"a"`, `:1`, `}`} {
|
||||||
|
b.WriteString(part)
|
||||||
|
}
|
||||||
|
require.Equal(t, `{"a":1}`, b.String())
|
||||||
|
}
|
||||||
@@ -182,6 +182,8 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
|||||||
go func() {
|
go func() {
|
||||||
defer close(events)
|
defer close(events)
|
||||||
|
|
||||||
|
var lastUsage *llm.Usage
|
||||||
|
|
||||||
for resp, err := range p.client.Models.GenerateContentStream(ctx, model, contents, config) {
|
for resp, err := range p.client.Models.GenerateContentStream(ctx, model, contents, config) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
|
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
|
||||||
@@ -189,13 +191,9 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
|||||||
}
|
}
|
||||||
|
|
||||||
if resp.UsageMetadata != nil {
|
if resp.UsageMetadata != nil {
|
||||||
events <- llm.ChatEvent{
|
lastUsage = updateUsage(lastUsage,
|
||||||
Type: llm.EventDone,
|
int(resp.UsageMetadata.PromptTokenCount),
|
||||||
Usage: &llm.Usage{
|
int(resp.UsageMetadata.CandidatesTokenCount))
|
||||||
InputTokens: int(resp.UsageMetadata.PromptTokenCount),
|
|
||||||
OutputTokens: int(resp.UsageMetadata.CandidatesTokenCount),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, cand := range resp.Candidates {
|
for _, cand := range resp.Candidates {
|
||||||
@@ -240,12 +238,19 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ensure a Done event is always sent
|
// Ensure a Done event is always sent
|
||||||
events <- llm.ChatEvent{Type: llm.EventDone}
|
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return events, nil
|
return events, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// updateUsage returns a *llm.Usage carrying the latest cumulative counts.
|
||||||
|
// Gemini sends cumulative usage on multiple chunks; we keep only the last and
|
||||||
|
// emit a single EventDone at stream end (mirrors the OpenAI provider's lastUsage).
|
||||||
|
func updateUsage(_ *llm.Usage, prompt, candidates int) *llm.Usage {
|
||||||
|
return &llm.Usage{InputTokens: prompt, OutputTokens: candidates}
|
||||||
|
}
|
||||||
|
|
||||||
// geminiUnsupportedFields are JSON Schema fields Gemini's "OpenAPI 3.0
|
// geminiUnsupportedFields are JSON Schema fields Gemini's "OpenAPI 3.0
|
||||||
// subset" rejects. This is the broadest strip set across the four
|
// subset" rejects. This is the broadest strip set across the four
|
||||||
// providers — most of the cross-provider portability gap shows up here.
|
// providers — most of the cross-provider portability gap shows up here.
|
||||||
|
|||||||
@@ -24,3 +24,12 @@ func TestGeminiResolveSystemPromptEmpty(t *testing.T) {
|
|||||||
got := geminiResolveSystemPrompt(llm.ChatRequest{})
|
got := geminiResolveSystemPrompt(llm.ChatRequest{})
|
||||||
require.Equal(t, "", got)
|
require.Equal(t, "", got)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGeminiUsageBuffer_KeepsLast(t *testing.T) {
|
||||||
|
var last *llm.Usage
|
||||||
|
last = updateUsage(last, 10, 5)
|
||||||
|
last = updateUsage(last, 20, 9) // final cumulative
|
||||||
|
require.NotNil(t, last)
|
||||||
|
require.Equal(t, 20, last.InputTokens)
|
||||||
|
require.Equal(t, 9, last.OutputTokens)
|
||||||
|
}
|
||||||
+38
-19
@@ -271,11 +271,6 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
|||||||
defer stream.Close()
|
defer stream.Close()
|
||||||
|
|
||||||
// Track tool calls being built up across deltas
|
// Track tool calls being built up across deltas
|
||||||
type pendingTC struct {
|
|
||||||
id string
|
|
||||||
name string
|
|
||||||
argsJSON string
|
|
||||||
}
|
|
||||||
toolCalls := make(map[int]*pendingTC)
|
toolCalls := make(map[int]*pendingTC)
|
||||||
|
|
||||||
var lastUsage *llm.Usage
|
var lastUsage *llm.Usage
|
||||||
@@ -337,25 +332,13 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if tc.Function.Arguments != "" {
|
if tc.Function.Arguments != "" {
|
||||||
pending.argsJSON += tc.Function.Arguments
|
pending.args.WriteString(tc.Function.Arguments)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Finish reason
|
// Finish reason
|
||||||
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
|
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
|
||||||
// Emit completed tool calls
|
emitToolCalls(events, toolCalls)
|
||||||
for _, tc := range toolCalls {
|
|
||||||
if tc.name != "" {
|
|
||||||
events <- llm.ChatEvent{
|
|
||||||
Type: llm.EventToolCallDone,
|
|
||||||
ToolCall: &llm.ToolCall{
|
|
||||||
ID: tc.id,
|
|
||||||
Name: tc.name,
|
|
||||||
Input: json.RawMessage(tc.argsJSON),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -366,6 +349,42 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
|||||||
return events, nil
|
return events, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// pendingTC accumulates a single streamed tool call across deltas. The
|
||||||
|
// streamed tool-call index is the map key in toolCalls; the id, name, and
|
||||||
|
// arguments arrive in separate chunks.
|
||||||
|
type pendingTC struct {
|
||||||
|
id string
|
||||||
|
name string
|
||||||
|
args strings.Builder
|
||||||
|
}
|
||||||
|
|
||||||
|
// emitToolCalls sends EventToolCallDone for each completed tool call in
|
||||||
|
// ascending index order. The map key is the streamed tool-call index;
|
||||||
|
// iterating in order keeps the assistant message's tool_use block order
|
||||||
|
// deterministic across turns so the prompt cache stays warm.
|
||||||
|
func emitToolCalls(events chan<- llm.ChatEvent, toolCalls map[int]*pendingTC) {
|
||||||
|
maxIdx := -1
|
||||||
|
for idx := range toolCalls {
|
||||||
|
if idx > maxIdx {
|
||||||
|
maxIdx = idx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for idx := 0; idx <= maxIdx; idx++ {
|
||||||
|
tc, ok := toolCalls[idx]
|
||||||
|
if !ok || tc.name == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
events <- llm.ChatEvent{
|
||||||
|
Type: llm.EventToolCallDone,
|
||||||
|
ToolCall: &llm.ToolCall{
|
||||||
|
ID: tc.id,
|
||||||
|
Name: tc.name,
|
||||||
|
Input: json.RawMessage(tc.args.String()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// openaiUnsupportedFields are JSON Schema fields the OpenAI function-
|
// openaiUnsupportedFields are JSON Schema fields the OpenAI function-
|
||||||
// calling schema rejects. anyOf/oneOf/format are accepted and kept.
|
// calling schema rejects. anyOf/oneOf/format are accepted and kept.
|
||||||
var openaiUnsupportedFields = []string{"$ref", "definitions"}
|
var openaiUnsupportedFields = []string{"$ref", "definitions"}
|
||||||
|
|||||||
@@ -73,3 +73,22 @@ func TestOpenAIChatStreamPartsBeatString(t *testing.T) {
|
|||||||
require.GreaterOrEqual(t, len(captured.Messages), 1)
|
require.GreaterOrEqual(t, len(captured.Messages), 1)
|
||||||
require.Equal(t, "new", captured.Messages[0].Content)
|
require.Equal(t, "new", captured.Messages[0].Content)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEmitToolCalls_OrderedByIndex(t *testing.T) {
|
||||||
|
mk := func(id, name string) *pendingTC {
|
||||||
|
p := &pendingTC{id: id, name: name}
|
||||||
|
p.args.WriteString("{}")
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
toolCalls := map[int]*pendingTC{2: mk("c", "third"), 0: mk("a", "first"), 1: mk("b", "second")}
|
||||||
|
ch := make(chan llm.ChatEvent, 10)
|
||||||
|
emitToolCalls(ch, toolCalls)
|
||||||
|
close(ch)
|
||||||
|
var ids []string
|
||||||
|
for ev := range ch {
|
||||||
|
if ev.Type == llm.EventToolCallDone {
|
||||||
|
ids = append(ids, ev.ToolCall.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require.Equal(t, []string{"a", "b", "c"}, ids, "tool calls must emit in index order")
|
||||||
|
}
|
||||||
+38
-19
@@ -14,6 +14,41 @@ import (
|
|||||||
"github.com/sausheong/harness/llm"
|
"github.com/sausheong/harness/llm"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// pendingTC accumulates a streamed tool call across deltas. args uses
|
||||||
|
// strings.Builder so repeated argument fragments append in O(n) total
|
||||||
|
// (not O(n²) from string concatenation).
|
||||||
|
type pendingTC struct {
|
||||||
|
id string
|
||||||
|
name string
|
||||||
|
args strings.Builder
|
||||||
|
}
|
||||||
|
|
||||||
|
// emitToolCalls sends EventToolCallDone for each completed tool call in
|
||||||
|
// ascending index order so tool_use block order is deterministic across
|
||||||
|
// turns (prompt-cache stability).
|
||||||
|
func emitToolCalls(events chan<- llm.ChatEvent, toolCalls map[int]*pendingTC) {
|
||||||
|
maxIdx := -1
|
||||||
|
for idx := range toolCalls {
|
||||||
|
if idx > maxIdx {
|
||||||
|
maxIdx = idx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for idx := 0; idx <= maxIdx; idx++ {
|
||||||
|
tc, ok := toolCalls[idx]
|
||||||
|
if !ok || tc.name == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
events <- llm.ChatEvent{
|
||||||
|
Type: llm.EventToolCallDone,
|
||||||
|
ToolCall: &llm.ToolCall{
|
||||||
|
ID: tc.id,
|
||||||
|
Name: tc.name,
|
||||||
|
Input: json.RawMessage(tc.args.String()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// QwenProvider implements llm.LLMProvider using the Qwen Chat Completions API.
|
// QwenProvider implements llm.LLMProvider using the Qwen Chat Completions API.
|
||||||
// Qwen uses an OpenAI-compatible API, so we reuse the go-openai client.
|
// Qwen uses an OpenAI-compatible API, so we reuse the go-openai client.
|
||||||
type QwenProvider struct {
|
type QwenProvider struct {
|
||||||
@@ -217,11 +252,6 @@ func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-c
|
|||||||
defer stream.Close()
|
defer stream.Close()
|
||||||
|
|
||||||
// Track tool calls being built up across deltas
|
// Track tool calls being built up across deltas
|
||||||
type pendingTC struct {
|
|
||||||
id string
|
|
||||||
name string
|
|
||||||
argsJSON string
|
|
||||||
}
|
|
||||||
toolCalls := make(map[int]*pendingTC)
|
toolCalls := make(map[int]*pendingTC)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
@@ -271,25 +301,14 @@ func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-c
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if tc.Function.Arguments != "" {
|
if tc.Function.Arguments != "" {
|
||||||
pending.argsJSON += tc.Function.Arguments
|
pending.args.WriteString(tc.Function.Arguments)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Finish reason
|
// Finish reason
|
||||||
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
|
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
|
||||||
// Emit completed tool calls
|
// Emit completed tool calls in index order.
|
||||||
for _, tc := range toolCalls {
|
emitToolCalls(events, toolCalls)
|
||||||
if tc.name != "" {
|
|
||||||
events <- llm.ChatEvent{
|
|
||||||
Type: llm.EventToolCallDone,
|
|
||||||
ToolCall: &llm.ToolCall{
|
|
||||||
ID: tc.id,
|
|
||||||
Name: tc.name,
|
|
||||||
Input: json.RawMessage(tc.argsJSON),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,3 +24,22 @@ func TestQwenResolveSystemPromptEmpty(t *testing.T) {
|
|||||||
got := qwenResolveSystemPrompt(llm.ChatRequest{})
|
got := qwenResolveSystemPrompt(llm.ChatRequest{})
|
||||||
require.Equal(t, "", got)
|
require.Equal(t, "", got)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEmitToolCalls_OrderedByIndex(t *testing.T) {
|
||||||
|
mk := func(id, name string) *pendingTC {
|
||||||
|
p := &pendingTC{id: id, name: name}
|
||||||
|
p.args.WriteString("{}")
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
toolCalls := map[int]*pendingTC{1: mk("b", "second"), 0: mk("a", "first")}
|
||||||
|
ch := make(chan llm.ChatEvent, 10)
|
||||||
|
emitToolCalls(ch, toolCalls)
|
||||||
|
close(ch)
|
||||||
|
var ids []string
|
||||||
|
for ev := range ch {
|
||||||
|
if ev.Type == llm.EventToolCallDone {
|
||||||
|
ids = append(ids, ev.ToolCall.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
require.Equal(t, []string{"a", "b"}, ids)
|
||||||
|
}
|
||||||
@@ -52,7 +52,7 @@ func (t *EditFileTool) Parameters() json.RawMessage {
|
|||||||
// IsConcurrencySafe returns false — edit_file mutates the filesystem.
|
// IsConcurrencySafe returns false — edit_file mutates the filesystem.
|
||||||
func (t *EditFileTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
|
func (t *EditFileTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
|
||||||
|
|
||||||
func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
func (t *EditFileTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||||
var in editFileInput
|
var in editFileInput
|
||||||
if err := json.Unmarshal(input, &in); err != nil {
|
if err := json.Unmarshal(input, &in); err != nil {
|
||||||
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
|
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
|
||||||
@@ -74,6 +74,10 @@ func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return tool.ToolResult{Error: err.Error()}, nil
|
||||||
|
}
|
||||||
|
|
||||||
if msg := checkFileSize(in.Path, int64(maxTextFileSize), "text"); msg != "" {
|
if msg := checkFileSize(in.Path, int64(maxTextFileSize), "text"); msg != "" {
|
||||||
return tool.ToolResult{Error: msg}, nil
|
return tool.ToolResult{Error: msg}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ func detectImageMIMEFromBytes(data []byte, hint string) string {
|
|||||||
// IsConcurrencySafe returns true — read_file is a pure read.
|
// IsConcurrencySafe returns true — read_file is a pure read.
|
||||||
func (t *ReadFileTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
|
func (t *ReadFileTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
|
||||||
|
|
||||||
func (t *ReadFileTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
func (t *ReadFileTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||||
var in readFileInput
|
var in readFileInput
|
||||||
if err := json.Unmarshal(input, &in); err != nil {
|
if err := json.Unmarshal(input, &in); err != nil {
|
||||||
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
|
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
|
||||||
@@ -94,6 +94,10 @@ func (t *ReadFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return tool.ToolResult{Error: err.Error()}, nil
|
||||||
|
}
|
||||||
|
|
||||||
ext := strings.ToLower(filepath.Ext(in.Path))
|
ext := strings.ToLower(filepath.Ext(in.Path))
|
||||||
limit := int64(maxTextFileSize)
|
limit := int64(maxTextFileSize)
|
||||||
kind := "text"
|
kind := "text"
|
||||||
|
|||||||
@@ -58,3 +58,29 @@ func TestEditFile_RejectsOversized(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.Contains(t, res.Error, "too large")
|
require.Contains(t, res.Error, "too large")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestReadFile_HonorsCancelledContext(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
p := filepath.Join(dir, "f.txt")
|
||||||
|
require.NoError(t, os.WriteFile(p, []byte("hello"), 0o600))
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
tool := &ReadFileTool{}
|
||||||
|
in, _ := json.Marshal(map[string]string{"path": p})
|
||||||
|
res, err := tool.Execute(ctx, in)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotEmpty(t, res.Error, "cancelled ctx must short-circuit")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEditFile_HonorsCancelledContext(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
p := filepath.Join(dir, "f.txt")
|
||||||
|
require.NoError(t, os.WriteFile(p, []byte("hello"), 0o600))
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
tool := &EditFileTool{}
|
||||||
|
in, _ := json.Marshal(map[string]string{"path": p, "old_string": "h", "new_string": "H"})
|
||||||
|
res, err := tool.Execute(ctx, in)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotEmpty(t, res.Error, "cancelled ctx must short-circuit")
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"html"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
@@ -271,11 +272,6 @@ func cleanHTMLText(s string) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
result := out.String()
|
result := out.String()
|
||||||
result = strings.ReplaceAll(result, "&", "&")
|
result = html.UnescapeString(result)
|
||||||
result = strings.ReplaceAll(result, "<", "<")
|
|
||||||
result = strings.ReplaceAll(result, ">", ">")
|
|
||||||
result = strings.ReplaceAll(result, """, `"`)
|
|
||||||
result = strings.ReplaceAll(result, "'", "'")
|
|
||||||
result = strings.ReplaceAll(result, " ", " ")
|
|
||||||
return strings.TrimSpace(result)
|
return strings.TrimSpace(result)
|
||||||
}
|
}
|
||||||
@@ -27,3 +27,11 @@ func TestSearxng_BlocksPrivateBaseURL(t *testing.T) {
|
|||||||
_, err := b.Search(testCtx(t), "hello", 3)
|
_, err := b.Search(testCtx(t), "hello", 3)
|
||||||
require.Error(t, err)
|
require.Error(t, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCleanHTMLText_DecodesNumericEntities(t *testing.T) {
|
||||||
|
out := cleanHTMLText("<b>café</b> & t’is done")
|
||||||
|
require.Contains(t, out, "café")
|
||||||
|
require.Contains(t, out, "&", "amp must decode")
|
||||||
|
require.Contains(t, out, "t’is", "numeric entity must decode")
|
||||||
|
require.NotContains(t, out, "&#", "no raw numeric entities remain")
|
||||||
|
}
|
||||||
Reference in new issue
Block a user