From e40733145f807686b73d550439ae972c68e6d16e Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 12:40:57 +0800 Subject: [PATCH 1/7] fix(openai): emit tool calls in index order for prompt-cache determinism (R7a) --- providers/openai/openai.go | 55 ++++++++++++++++++++++----------- providers/openai/openai_test.go | 18 +++++++++++ 2 files changed, 55 insertions(+), 18 deletions(-) diff --git a/providers/openai/openai.go b/providers/openai/openai.go index e75bd93..da0188b 100644 --- a/providers/openai/openai.go +++ b/providers/openai/openai.go @@ -271,11 +271,6 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (< defer stream.Close() // Track tool calls being built up across deltas - type pendingTC struct { - id string - name string - argsJSON string - } toolCalls := make(map[int]*pendingTC) var lastUsage *llm.Usage @@ -343,19 +338,7 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (< // Finish reason if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop { - // Emit completed tool calls - 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), - }, - } - } - } + emitToolCalls(events, toolCalls) } } } @@ -366,6 +349,42 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (< 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 + argsJSON string +} + +// 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.argsJSON), + }, + } + } +} + // openaiUnsupportedFields are JSON Schema fields the OpenAI function- // calling schema rejects. anyOf/oneOf/format are accepted and kept. var openaiUnsupportedFields = []string{"$ref", "definitions"} diff --git a/providers/openai/openai_test.go b/providers/openai/openai_test.go index b8aecef..667a522 100644 --- a/providers/openai/openai_test.go +++ b/providers/openai/openai_test.go @@ -73,3 +73,21 @@ func TestOpenAIChatStreamPartsBeatString(t *testing.T) { require.GreaterOrEqual(t, len(captured.Messages), 1) require.Equal(t, "new", captured.Messages[0].Content) } + +func TestEmitToolCalls_OrderedByIndex(t *testing.T) { + toolCalls := map[int]*pendingTC{ + 2: {id: "c", name: "third", argsJSON: "{}"}, + 0: {id: "a", name: "first", argsJSON: "{}"}, + 1: {id: "b", name: "second", argsJSON: "{}"}, + } + 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") +} From 79a69e5dceb4d0df7a8e27ca3563c839756c8050 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 12:42:41 +0800 Subject: [PATCH 2/7] fix(qwen): index-order tool emit + strings.Builder accumulation (R7a/R7c) --- providers/qwen/qwen.go | 57 ++++++++++++++++++++++++------------- providers/qwen/qwen_test.go | 19 +++++++++++++ 2 files changed, 57 insertions(+), 19 deletions(-) diff --git a/providers/qwen/qwen.go b/providers/qwen/qwen.go index 2505a20..70eca44 100644 --- a/providers/qwen/qwen.go +++ b/providers/qwen/qwen.go @@ -14,6 +14,41 @@ import ( "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. // Qwen uses an OpenAI-compatible API, so we reuse the go-openai client. type QwenProvider struct { @@ -217,11 +252,6 @@ func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-c defer stream.Close() // Track tool calls being built up across deltas - type pendingTC struct { - id string - name string - argsJSON string - } toolCalls := make(map[int]*pendingTC) for { @@ -271,25 +301,14 @@ func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-c } } if tc.Function.Arguments != "" { - pending.argsJSON += tc.Function.Arguments + pending.args.WriteString(tc.Function.Arguments) } } // Finish reason if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop { - // Emit completed tool calls - 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), - }, - } - } - } + // Emit completed tool calls in index order. + emitToolCalls(events, toolCalls) } } } diff --git a/providers/qwen/qwen_test.go b/providers/qwen/qwen_test.go index 8cd897a..051a526 100644 --- a/providers/qwen/qwen_test.go +++ b/providers/qwen/qwen_test.go @@ -24,3 +24,22 @@ func TestQwenResolveSystemPromptEmpty(t *testing.T) { got := qwenResolveSystemPrompt(llm.ChatRequest{}) 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) +} From 385cd26e4ba857d5d5ad64255c02c7c15d20e353 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 12:44:06 +0800 Subject: [PATCH 3/7] fix(openai): strings.Builder for tool-arg accumulation (R7c) --- providers/openai/openai.go | 10 +++++----- providers/openai/openai_test.go | 9 +++++---- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/providers/openai/openai.go b/providers/openai/openai.go index da0188b..17b632a 100644 --- a/providers/openai/openai.go +++ b/providers/openai/openai.go @@ -332,7 +332,7 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (< } } if tc.Function.Arguments != "" { - pending.argsJSON += tc.Function.Arguments + pending.args.WriteString(tc.Function.Arguments) } } @@ -353,9 +353,9 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (< // 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 - argsJSON string + id string + name string + args strings.Builder } // emitToolCalls sends EventToolCallDone for each completed tool call in @@ -379,7 +379,7 @@ func emitToolCalls(events chan<- llm.ChatEvent, toolCalls map[int]*pendingTC) { ToolCall: &llm.ToolCall{ ID: tc.id, Name: tc.name, - Input: json.RawMessage(tc.argsJSON), + Input: json.RawMessage(tc.args.String()), }, } } diff --git a/providers/openai/openai_test.go b/providers/openai/openai_test.go index 667a522..7940c77 100644 --- a/providers/openai/openai_test.go +++ b/providers/openai/openai_test.go @@ -75,11 +75,12 @@ func TestOpenAIChatStreamPartsBeatString(t *testing.T) { } func TestEmitToolCalls_OrderedByIndex(t *testing.T) { - toolCalls := map[int]*pendingTC{ - 2: {id: "c", name: "third", argsJSON: "{}"}, - 0: {id: "a", name: "first", argsJSON: "{}"}, - 1: {id: "b", name: "second", argsJSON: "{}"}, + 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) From d0cd0989a9266255ed40f5826bbce5289050700d Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 12:45:56 +0800 Subject: [PATCH 4/7] fix(gemini): emit a single EventDone with final usage (R7b) --- providers/gemini/gemini.go | 21 +++++++++++++-------- providers/gemini/gemini_test.go | 9 +++++++++ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/providers/gemini/gemini.go b/providers/gemini/gemini.go index 24df532..ddd786c 100644 --- a/providers/gemini/gemini.go +++ b/providers/gemini/gemini.go @@ -182,6 +182,8 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (< go func() { defer close(events) + var lastUsage *llm.Usage + for resp, err := range p.client.Models.GenerateContentStream(ctx, model, contents, config) { if err != nil { 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 { - events <- llm.ChatEvent{ - Type: llm.EventDone, - Usage: &llm.Usage{ - InputTokens: int(resp.UsageMetadata.PromptTokenCount), - OutputTokens: int(resp.UsageMetadata.CandidatesTokenCount), - }, - } + lastUsage = updateUsage(lastUsage, + int(resp.UsageMetadata.PromptTokenCount), + int(resp.UsageMetadata.CandidatesTokenCount)) } 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 - events <- llm.ChatEvent{Type: llm.EventDone} + events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage} }() 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 // subset" rejects. This is the broadest strip set across the four // providers — most of the cross-provider portability gap shows up here. diff --git a/providers/gemini/gemini_test.go b/providers/gemini/gemini_test.go index 7bf4098..28310d6 100644 --- a/providers/gemini/gemini_test.go +++ b/providers/gemini/gemini_test.go @@ -24,3 +24,12 @@ func TestGeminiResolveSystemPromptEmpty(t *testing.T) { got := geminiResolveSystemPrompt(llm.ChatRequest{}) 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) +} From 373e44b9c74787cce9be6ba68f587e161bd6a451 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 12:48:10 +0800 Subject: [PATCH 5/7] fix(anthropic): surface in-band stream error + Builder accumulation (R7c) --- providers/anthropic/anthropic.go | 23 +++++++++++++++++------ providers/anthropic/anthropic_test.go | 9 +++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/providers/anthropic/anthropic.go b/providers/anthropic/anthropic.go index 07b8cb9..0604505 100644 --- a/providers/anthropic/anthropic.go +++ b/providers/anthropic/anthropic.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "encoding/json" + "fmt" "log/slog" "strings" @@ -164,8 +165,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest) type pendingTC struct { id string name string - inputJSON string // built from input_json_delta events - startInput string // captured from content_block_start (proxy fallback) + inputJSON strings.Builder // built from input_json_delta events + startInput string // captured from content_block_start (proxy fallback) } var pendingTools []pendingTC var currentBlockType string @@ -220,18 +221,21 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest) } case "input_json_delta": if len(pendingTools) > 0 { - pendingTools[len(pendingTools)-1].inputJSON += delta.PartialJSON + pendingTools[len(pendingTools)-1].inputJSON.WriteString(delta.PartialJSON) } } case "content_block_stop": 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 // back to start-time input (proxy emitting full input // upfront). Default to "{}" so MCP servers receive a // valid empty-args envelope rather than null/empty. - inp := tc.inputJSON + inp := tc.inputJSON.String() if inp == "" { inp = tc.startInput } @@ -281,7 +285,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest) // Final event — nothing extra to emit 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"), + } } } diff --git a/providers/anthropic/anthropic_test.go b/providers/anthropic/anthropic_test.go index 681e6a4..70e6cad 100644 --- a/providers/anthropic/anthropic_test.go +++ b/providers/anthropic/anthropic_test.go @@ -6,6 +6,7 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "strings" "testing" anthropic "github.com/anthropics/anthropic-sdk-go" @@ -708,3 +709,11 @@ data: {"type":"message_stop"} assert.Equal(t, "end_turn", done.StopReason) 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()) +} From e133f97e1ec65fb98876f470397a33b8edc859ed Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 12:50:07 +0800 Subject: [PATCH 6/7] fix(web): decode all HTML entities via html.UnescapeString (N11) --- tools/web/websearch.go | 8 ++------ tools/web/websearch_test.go | 8 ++++++++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/tools/web/websearch.go b/tools/web/websearch.go index f08dee6..f9e0a91 100644 --- a/tools/web/websearch.go +++ b/tools/web/websearch.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "html" "io" "net/http" "net/url" @@ -271,11 +272,6 @@ func cleanHTMLText(s string) string { } } result := out.String() - result = strings.ReplaceAll(result, "&", "&") - result = strings.ReplaceAll(result, "<", "<") - result = strings.ReplaceAll(result, ">", ">") - result = strings.ReplaceAll(result, """, `"`) - result = strings.ReplaceAll(result, "'", "'") - result = strings.ReplaceAll(result, " ", " ") + result = html.UnescapeString(result) return strings.TrimSpace(result) } diff --git a/tools/web/websearch_test.go b/tools/web/websearch_test.go index 5f34ee1..e901204 100644 --- a/tools/web/websearch_test.go +++ b/tools/web/websearch_test.go @@ -27,3 +27,11 @@ func TestSearxng_BlocksPrivateBaseURL(t *testing.T) { _, err := b.Search(testCtx(t), "hello", 3) require.Error(t, err) } + +func TestCleanHTMLText_DecodesNumericEntities(t *testing.T) { + out := cleanHTMLText("café & 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") +} From 1752cbf2fb549af93608091282bf1830ac753847 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 12:51:30 +0800 Subject: [PATCH 7/7] fix(file): honor ctx cancellation in read_file/edit_file (N12) --- tools/file/editfile.go | 6 +++++- tools/file/readfile.go | 6 +++++- tools/file/readfile_test.go | 26 ++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/tools/file/editfile.go b/tools/file/editfile.go index 54e43e1..1f5c39a 100644 --- a/tools/file/editfile.go +++ b/tools/file/editfile.go @@ -52,7 +52,7 @@ func (t *EditFileTool) Parameters() json.RawMessage { // IsConcurrencySafe returns false — edit_file mutates the filesystem. 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 if err := json.Unmarshal(input, &in); 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 != "" { return tool.ToolResult{Error: msg}, nil } diff --git a/tools/file/readfile.go b/tools/file/readfile.go index 703c1b1..3e9096a 100644 --- a/tools/file/readfile.go +++ b/tools/file/readfile.go @@ -72,7 +72,7 @@ func detectImageMIMEFromBytes(data []byte, hint string) string { // IsConcurrencySafe returns true — read_file is a pure read. 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 if err := json.Unmarshal(input, &in); 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)) limit := int64(maxTextFileSize) kind := "text" diff --git a/tools/file/readfile_test.go b/tools/file/readfile_test.go index 744123a..78bdc8c 100644 --- a/tools/file/readfile_test.go +++ b/tools/file/readfile_test.go @@ -58,3 +58,29 @@ func TestEditFile_RejectsOversized(t *testing.T) { require.NoError(t, err) 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") +}