Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
986c233d39 | ||
|
|
8e92125fb6 | ||
|
|
eb4fa67976 | ||
|
|
445614757b | ||
|
|
c7846eeab9 | ||
|
|
0300af6717 | ||
|
|
152d8b972e | ||
|
|
d3c74e5681 | ||
|
|
d1c63cac56 | ||
|
|
ef3a1d4927 | ||
|
|
2f97b1cf78 | ||
|
|
69f58903eb | ||
|
|
1ec0f9cac3 | ||
|
|
2630d88245 | ||
|
|
a797d446f8 | ||
|
|
ac724d18e1 | ||
|
|
7f0c3fd23d | ||
|
|
a5f21d3a2c | ||
|
|
34435736c5 | ||
|
|
3da8fe8ed3 | ||
|
|
9292731d79 | ||
|
|
04f02c56d6 | ||
|
|
3eb9596ee6 | ||
|
|
275636ed20 | ||
|
|
754721bc30 | ||
|
|
22f4329f44 | ||
|
|
8c9bc2963d | ||
|
|
1752cbf2fb | ||
|
|
e133f97e1e | ||
|
|
373e44b9c7 | ||
|
|
d0cd0989a9 | ||
|
|
385cd26e4b | ||
|
|
79a69e5dce | ||
|
|
e40733145f | ||
|
|
b85ffeac69 | ||
|
|
d6db565d7c | ||
|
|
fb5103fb87 | ||
|
|
01b55a1446 | ||
|
|
7d85074509 | ||
|
|
d7777f7c89 | ||
|
|
1e00916a82 | ||
|
|
083122a81f | ||
|
|
5d5dcd1902 | ||
|
|
34ebfc5e95 | ||
|
|
e1fd4dc689 | ||
|
|
25b2e9163f | ||
|
|
c710ea5a94 | ||
|
|
671c10e89a | ||
|
|
1da0584530 | ||
|
|
7151562d99 | ||
|
|
86ad622144 | ||
|
|
7052a66e38 | ||
|
|
de23ad986a | ||
|
|
27fecf4588 | ||
|
|
87f77c76ba | ||
|
|
7ae944f0eb | ||
|
|
c4750347e6 | ||
|
|
7fa3e75ad1 | ||
|
|
d5e8abf492 | ||
|
|
3064a0da14 | ||
|
|
cf47b2fca8 | ||
|
|
6f0040f606 | ||
|
|
0341628068 | ||
|
|
5d6326981e | ||
|
|
b7cbfc584c | ||
|
|
8f8d75cd06 | ||
|
|
fe71e7b36d | ||
|
|
f35070594f | ||
|
|
67178e018a | ||
|
|
ecdf97ca79 | ||
|
|
b7f4cfcf4a | ||
|
|
35896d215a | ||
|
|
1c6a05c0d8 | ||
|
|
e5c9b5dbb5 | ||
|
|
65021e1fe2 |
No files matched your search
@@ -4,6 +4,7 @@
|
||||
!/developer.md
|
||||
!/examples/*/kb/
|
||||
!/examples/*/kb/*.md
|
||||
/docs/
|
||||
|
||||
# Other prose/document formats
|
||||
*.txt
|
||||
|
||||
@@ -5,7 +5,7 @@ streaming agent loop, tool registry, session storage, compaction, and
|
||||
token budgeting needed to run a multi-provider agent in production. BYO
|
||||
concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins.
|
||||
|
||||
> **Status: v0.1.0.** First tagged release. The `runtime` API
|
||||
> **Status: v0.3.6.** Latest tagged release. The `runtime` API
|
||||
> surface may still shift in the v0.x line — pin your version.
|
||||
|
||||
## Why Harness
|
||||
@@ -229,6 +229,9 @@ them via `LoopConfig`:
|
||||
|
||||
`LoopConfig` field values win over env vars when set. Set the field
|
||||
to its zero value (or omit it) to fall back to env, then to defaults.
|
||||
`RuntimeDeps.AgentLoop` supplies shared process defaults;
|
||||
non-zero fields and non-nil hooks in `AgentSpec.Loop` override those
|
||||
defaults for that agent.
|
||||
|
||||
Everything else (provider API keys, model selection, workspace path,
|
||||
skill paths, etc.) is your config's responsibility — harness reads
|
||||
@@ -373,12 +376,12 @@ a real failure.
|
||||
|
||||
## Status
|
||||
|
||||
`v0.1.0` is the first tagged release. The v0.x line follows Go
|
||||
`v0.3.6` is the latest tagged release. The v0.x line follows Go
|
||||
module semver: minor bumps may break API, patch bumps are bug-fix
|
||||
only. Pin your dependency:
|
||||
|
||||
```bash
|
||||
go get github.com/sausheong/harness@v0.1.0
|
||||
go get github.com/sausheong/harness@v0.3.6
|
||||
```
|
||||
|
||||
Likely sources of v0.x churn before a v1.0.0:
|
||||
|
||||
@@ -82,6 +82,8 @@ func main() {
|
||||
}
|
||||
defer rt.Close() // no-op here (no MCP), but idiomatic
|
||||
|
||||
_ = llm.ReasoningOff // keep llm import live for clarity in the demo
|
||||
|
||||
// 5. REPL loop.
|
||||
in := bufio.NewScanner(os.Stdin)
|
||||
fmt.Println("harness demo — type a message, blank line to exit")
|
||||
@@ -115,5 +117,4 @@ func main() {
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = llm.ReasoningOff // keep llm import live for clarity in the demo
|
||||
}
|
||||
@@ -93,6 +93,11 @@ func stripCacheKey(tools []ToolDef, fields []string) string {
|
||||
h.Write([]byte(t.Name))
|
||||
h.Write([]byte("\x02"))
|
||||
h.Write(t.Parameters)
|
||||
if t.CacheControl != nil {
|
||||
h.Write([]byte(t.CacheControl.Type))
|
||||
h.Write([]byte("\x04"))
|
||||
h.Write([]byte(t.CacheControl.TTL))
|
||||
}
|
||||
h.Write([]byte("\x03"))
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
@@ -104,6 +109,12 @@ func cloneToolDefs(in []ToolDef) []ToolDef {
|
||||
}
|
||||
out := make([]ToolDef, len(in))
|
||||
copy(out, in)
|
||||
for i := range out {
|
||||
if in[i].CacheControl != nil {
|
||||
cache := *in[i].CacheControl
|
||||
out[i].CacheControl = &cache
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
@@ -118,3 +118,16 @@ func TestStripFieldsMalformedSchema(t *testing.T) {
|
||||
assert.Equal(t, bad, out)
|
||||
assert.Empty(t, diags)
|
||||
}
|
||||
|
||||
func TestStripCacheKeyIncludesCacheControl(t *testing.T) {
|
||||
base := ToolDef{Name: "lookup", Parameters: json.RawMessage(`{"type":"object"}`)}
|
||||
fiveMinutes := base
|
||||
fiveMinutes.CacheControl = &CacheControl{Type: "ephemeral", TTL: "5m"}
|
||||
oneHour := base
|
||||
oneHour.CacheControl = &CacheControl{Type: "ephemeral", TTL: "1h"}
|
||||
assert.NotEqual(t, stripCacheKey([]ToolDef{fiveMinutes}, nil), stripCacheKey([]ToolDef{oneHour}, nil))
|
||||
|
||||
cloned := cloneToolDefs([]ToolDef{oneHour})
|
||||
cloned[0].CacheControl.TTL = "5m"
|
||||
assert.Equal(t, "1h", oneHour.CacheControl.TTL, "cached normalization results must not alias cache metadata")
|
||||
}
|
||||
+110
-22
@@ -17,6 +17,9 @@ const (
|
||||
EventToolCallDone
|
||||
EventDone
|
||||
EventError
|
||||
// EventThinkingBlock is emitted when the model returns an extended-thinking
|
||||
// block. The runtime must echo these back in subsequent turns verbatim.
|
||||
EventThinkingBlock
|
||||
)
|
||||
|
||||
// ImageContent holds image data for multimodal messages.
|
||||
@@ -26,13 +29,26 @@ type ImageContent struct {
|
||||
}
|
||||
|
||||
// Message represents a conversation message.
|
||||
// ThinkingBlock holds an opaque thinking/reasoning block returned by models
|
||||
// that support extended thinking (e.g. Anthropic with thinking enabled,
|
||||
// DeepSeek-v4-pro). The Signature field is the provider-supplied integrity
|
||||
// token that must be echoed back verbatim in subsequent turns.
|
||||
type ThinkingBlock struct {
|
||||
Thinking string `json:"thinking"`
|
||||
Signature string `json:"signature,omitempty"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
Role string `json:"role"` // "user", "assistant", "system"
|
||||
Content string `json:"content,omitempty"`
|
||||
Images []ImageContent `json:"-"` // image attachments (not serialized)
|
||||
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"` // for tool results
|
||||
IsError bool `json:"is_error,omitempty"` // for tool results
|
||||
Role string `json:"role"` // "user", "assistant", "system"
|
||||
Content string `json:"content,omitempty"`
|
||||
Images []ImageContent `json:"-"` // image attachments (not serialized)
|
||||
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"` // for tool results
|
||||
IsError bool `json:"is_error,omitempty"` // for tool results
|
||||
ThinkingBlocks []ThinkingBlock `json:"thinking_blocks,omitempty"` // echoed back for thinking-mode models
|
||||
// CacheControl requests a cache breakpoint on the final cacheable block of
|
||||
// this logical message. Nil means no explicit breakpoint.
|
||||
CacheControl *CacheControl `json:"cache_control,omitempty"`
|
||||
}
|
||||
|
||||
// ToolCall represents a tool invocation requested by the LLM.
|
||||
@@ -44,9 +60,17 @@ type ToolCall struct {
|
||||
|
||||
// ToolDef defines a tool for the LLM.
|
||||
type ToolDef struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters json.RawMessage `json:"parameters"` // JSON Schema
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters json.RawMessage `json:"parameters"` // JSON Schema
|
||||
CacheControl *CacheControl `json:"cache_control,omitempty"`
|
||||
}
|
||||
|
||||
// CacheControl is provider-neutral prompt-cache metadata. Type is currently
|
||||
// "ephemeral"; TTL is empty/"5m" or "1h".
|
||||
type CacheControl struct {
|
||||
Type string `json:"type"`
|
||||
TTL string `json:"ttl,omitempty"`
|
||||
}
|
||||
|
||||
// Diagnostic describes a single normalization or clamping event emitted
|
||||
@@ -66,7 +90,8 @@ type SystemPromptPart struct {
|
||||
Text string
|
||||
// Cache requests that the prefix up to and including this part be cached.
|
||||
// Anthropic-only; ignored elsewhere.
|
||||
Cache bool
|
||||
Cache bool
|
||||
CacheControl *CacheControl
|
||||
}
|
||||
|
||||
// ReasoningMode is the unified reasoning/thinking knob across providers.
|
||||
@@ -83,6 +108,31 @@ const (
|
||||
ReasoningHigh ReasoningMode = "high"
|
||||
)
|
||||
|
||||
// NativeReasoningConfig preserves an inbound provider reasoning request when
|
||||
// Harness is used as a protocol proxy. A nil config means the client omitted
|
||||
// the provider's reasoning controls; this is deliberately different from an
|
||||
// explicit disabled config because some models think by default.
|
||||
//
|
||||
// Type is "adaptive", "enabled", or "disabled". BudgetTokens applies to
|
||||
// enabled thinking and Effort is one of "low", "medium", "high", or "max".
|
||||
// Providers that cannot represent the requested semantics must reject the
|
||||
// request instead of silently changing it.
|
||||
type NativeReasoningConfig struct {
|
||||
Type string
|
||||
BudgetTokens int64
|
||||
Effort string
|
||||
Display string
|
||||
// OutputFormat is the provider-native structured-output format object.
|
||||
// It is kept as JSON so a protocol proxy can preserve schemas without
|
||||
// forcing provider-specific types into the portable llm package.
|
||||
OutputFormat json.RawMessage
|
||||
}
|
||||
|
||||
// Enabled reports whether the client explicitly requested reasoning.
|
||||
func (c *NativeReasoningConfig) Enabled() bool {
|
||||
return c != nil && (c.Type == "adaptive" || c.Type == "enabled")
|
||||
}
|
||||
|
||||
// ParseReasoningMode parses a config string into a ReasoningMode.
|
||||
// Accepts "" or "off" for ReasoningOff; "low", "medium", "high" for
|
||||
// the named levels. Case-sensitive. Returns an error for unknown values.
|
||||
@@ -103,12 +153,15 @@ func ParseReasoningMode(s string) (ReasoningMode, error) {
|
||||
|
||||
// ChatRequest is the input to a streaming chat call.
|
||||
type ChatRequest struct {
|
||||
Model string
|
||||
Messages []Message
|
||||
Tools []ToolDef
|
||||
MaxTokens int
|
||||
Temperature float64
|
||||
SystemPrompt string
|
||||
Model string
|
||||
Messages []Message
|
||||
Tools []ToolDef
|
||||
MaxTokens int
|
||||
Temperature float64
|
||||
// TemperatureSet distinguishes an omitted sampling parameter from an
|
||||
// explicit zero, which is material when proxying an existing API request.
|
||||
TemperatureSet bool
|
||||
SystemPrompt string
|
||||
// SystemPromptParts, when non-empty, replaces SystemPrompt. Providers
|
||||
// that support caching emit one block per part, attaching cache markers
|
||||
// per Cache flag. Providers that don't support caching concatenate
|
||||
@@ -117,7 +170,14 @@ type ChatRequest struct {
|
||||
// CacheLastMessage requests that the final block of the final user
|
||||
// message also be cache-marked. Anthropic-only; ignored elsewhere.
|
||||
CacheLastMessage bool
|
||||
Reasoning ReasoningMode // zero value = ReasoningOff; safe default
|
||||
// CacheControl enables provider-level automatic prompt caching.
|
||||
CacheControl *CacheControl
|
||||
// SessionID is routing metadata only and is not sent to providers.
|
||||
SessionID string
|
||||
Reasoning ReasoningMode // zero value = ReasoningOff; safe default
|
||||
// NativeReasoning takes precedence over the portable Reasoning knob and
|
||||
// preserves exact inbound proxy semantics, including omitted vs disabled.
|
||||
NativeReasoning *NativeReasoningConfig
|
||||
}
|
||||
|
||||
// Usage tracks token usage.
|
||||
@@ -130,13 +190,29 @@ type Usage struct {
|
||||
|
||||
// ChatEvent is a single streaming event from the LLM.
|
||||
type ChatEvent struct {
|
||||
Type EventType
|
||||
Text string
|
||||
ToolCall *ToolCall
|
||||
Usage *Usage
|
||||
Error error
|
||||
Type EventType
|
||||
Text string
|
||||
ToolCall *ToolCall
|
||||
ThinkingBlock *ThinkingBlock // populated on EventThinkingBlock
|
||||
Usage *Usage
|
||||
Error error
|
||||
// StopReason carries the provider's terminal stop reason on EventDone
|
||||
// ("end_turn", "tool_use", "max_tokens", "refusal", ...). Empty when
|
||||
// the provider doesn't report one. StopReasonRefusal is the value the
|
||||
// runtime branches on: Claude Fable 5 safety classifiers decline a
|
||||
// request with HTTP 200 + stop_reason=refusal and empty content —
|
||||
// without surfacing it the turn looks like a silent empty success.
|
||||
StopReason string
|
||||
// StopCategory is the refusal policy category from stop_details
|
||||
// ("cyber", "bio", "reasoning_extraction"); informational only and
|
||||
// may be empty even on a refusal.
|
||||
StopCategory string
|
||||
}
|
||||
|
||||
// StopReasonRefusal is the StopReason value for safety-classifier and
|
||||
// model-initiated refusals (Claude Fable 5+).
|
||||
const StopReasonRefusal = "refusal"
|
||||
|
||||
// ModelInfo describes an available model.
|
||||
type ModelInfo struct {
|
||||
ID string
|
||||
@@ -171,6 +247,18 @@ type NonStreamingProvider interface {
|
||||
ChatNonStreaming(ctx context.Context, req ChatRequest) (<-chan ChatEvent, error)
|
||||
}
|
||||
|
||||
// PromptCachingProvider is an optional capability interface: providers
|
||||
// that implement Anthropic-style explicit prompt caching (cache_control
|
||||
// breakpoints, CacheLastMessage) declare it here. The runtime gates
|
||||
// caching on this capability rather than on the provider's configured
|
||||
// NAME — a user-named provider block ("platformai", "bedrock", any
|
||||
// relay) wrapping an Anthropic-shaped API must still get caching;
|
||||
// matching the name string alone silently disabled it for every
|
||||
// renamed provider.
|
||||
type PromptCachingProvider interface {
|
||||
SupportsPromptCaching() bool
|
||||
}
|
||||
|
||||
// ParseProviderModel splits "provider/model" into (provider, model).
|
||||
// If no slash is present, returns ("", name) and the caller should use a default.
|
||||
func ParseProviderModel(name string) (provider, model string) {
|
||||
|
||||
+26
-6
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"google.golang.org/genai"
|
||||
)
|
||||
|
||||
// IsRetryableModelError reports whether err is a transient capacity
|
||||
@@ -14,14 +15,17 @@ import (
|
||||
//
|
||||
// - Anthropic 429 (rate limit) and 529 (overloaded)
|
||||
// - OpenAI 429 (rate limit) and 5xx (server / overloaded)
|
||||
// - Gemini 429 (quota/RESOURCE_EXHAUSTED) and 5xx (overloaded/unavailable),
|
||||
// recognized via a typed genai.APIError path (Gemini's error string
|
||||
// "Error 429, ... Status: RESOURCE_EXHAUSTED" does not match the
|
||||
// bounded substring forms, so the typed path is required).
|
||||
//
|
||||
// Anything else (including 4xx auth/validation errors) returns false:
|
||||
// retrying with a different model wouldn't fix the underlying problem.
|
||||
//
|
||||
// Errors from local providers (Ollama, etc.) and Gemini are NOT
|
||||
// classified as retryable here; their failure modes are different
|
||||
// and a model swap rarely helps. Add cases as new providers
|
||||
// accumulate retry experience.
|
||||
// Errors from local providers (Ollama, etc.) are NOT classified as
|
||||
// retryable here; their failure modes are different and a model swap
|
||||
// rarely helps. Add cases as new providers accumulate retry experience.
|
||||
func IsRetryableModelError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
@@ -47,13 +51,29 @@ func IsRetryableModelError(err error) bool {
|
||||
return openaiReqErr.HTTPStatusCode == 429 ||
|
||||
(openaiReqErr.HTTPStatusCode >= 500 && openaiReqErr.HTTPStatusCode < 600)
|
||||
}
|
||||
// genai.APIError.Error() is a value receiver, so the error interface is
|
||||
// satisfied by the value; errors.As targets the value type.
|
||||
var genaiErr genai.APIError
|
||||
if errors.As(err, &genaiErr) {
|
||||
return genaiErr.Code == 429 ||
|
||||
(genaiErr.Code >= 500 && genaiErr.Code < 600)
|
||||
}
|
||||
|
||||
// Last-ditch: substring match on common SDK error wrappers that
|
||||
// don't unwrap cleanly to typed errors. Cheap belt-and-braces;
|
||||
// only reached when no typed match found above.
|
||||
msg := strings.ToLower(err.Error())
|
||||
if strings.Contains(msg, "429") || strings.Contains(msg, "529") ||
|
||||
strings.Contains(msg, "rate limit") || strings.Contains(msg, "overloaded") {
|
||||
// Bounded forms so a bare "429"/"529" inside a request id or unrelated
|
||||
// digits doesn't trigger a retry. Word matches stay as-is (specific).
|
||||
for _, sig := range []string{
|
||||
"status 429", "code: 429", "code:429", " 429 ", "429 too many requests",
|
||||
"status 529", "code: 529", "code:529", " 529 ", "529 overloaded",
|
||||
} {
|
||||
if strings.Contains(msg, sig) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if strings.Contains(msg, "rate limit") || strings.Contains(msg, "overloaded") {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
|
||||
@@ -8,8 +8,26 @@ import (
|
||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/genai"
|
||||
)
|
||||
|
||||
func TestIsRetryable_Gemini429(t *testing.T) {
|
||||
// Mirror genai.APIError's real shape.
|
||||
err := genai.APIError{Code: 429, Message: "Resource has been exhausted (e.g. check quota).", Status: "RESOURCE_EXHAUSTED"}
|
||||
require.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryable_Gemini503(t *testing.T) {
|
||||
err := genai.APIError{Code: 503, Message: "The model is overloaded.", Status: "UNAVAILABLE"}
|
||||
require.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryable_Gemini400NotRetryable(t *testing.T) {
|
||||
err := genai.APIError{Code: 400, Message: "Invalid argument", Status: "INVALID_ARGUMENT"}
|
||||
require.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorAnthropic429(t *testing.T) {
|
||||
err := &anthropic.Error{StatusCode: 429}
|
||||
assert.True(t, IsRetryableModelError(err))
|
||||
@@ -89,3 +107,13 @@ func TestIsRetryableModelErrorUnrelatedError(t *testing.T) {
|
||||
err := errors.New("some other failure")
|
||||
assert.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestRetry_DigitsInRequestIDNotRetryable(t *testing.T) {
|
||||
err := errors.New("request failed: req_abc429def something went wrong")
|
||||
require.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestRetry_RealStatus429Retryable(t *testing.T) {
|
||||
err := errors.New("openai: error, status 429 too many requests")
|
||||
require.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
@@ -28,6 +29,11 @@ func NewAnthropicProvider(apiKey, baseURL string) *AnthropicProvider {
|
||||
return &AnthropicProvider{client: client}
|
||||
}
|
||||
|
||||
// SupportsPromptCaching implements llm.PromptCachingProvider: the
|
||||
// Anthropic Messages API honours cache_control breakpoints regardless
|
||||
// of what the provider block is named in user config.
|
||||
func (p *AnthropicProvider) SupportsPromptCaching() bool { return true }
|
||||
|
||||
func (p *AnthropicProvider) Models() []llm.ModelInfo {
|
||||
return []llm.ModelInfo{
|
||||
{ID: "claude-sonnet-4-5-20250514", Name: "Claude Sonnet 4.5", Provider: "anthropic"},
|
||||
@@ -55,16 +61,18 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
|
||||
props = schema.Properties
|
||||
required = schema.Required
|
||||
}
|
||||
tools = append(tools, anthropic.ToolUnionParam{
|
||||
OfTool: &anthropic.ToolParam{
|
||||
Name: t.Name,
|
||||
Description: anthropic.String(t.Description),
|
||||
InputSchema: anthropic.ToolInputSchemaParam{
|
||||
Properties: props,
|
||||
Required: required,
|
||||
},
|
||||
tool := anthropic.ToolParam{
|
||||
Name: t.Name,
|
||||
Description: anthropic.String(t.Description),
|
||||
InputSchema: anthropic.ToolInputSchemaParam{
|
||||
Properties: props,
|
||||
Required: required,
|
||||
},
|
||||
})
|
||||
}
|
||||
if cacheRequested(t.CacheControl) {
|
||||
tool.CacheControl = anthropicCacheControl(t.CacheControl)
|
||||
}
|
||||
tools = append(tools, anthropic.ToolUnionParam{OfTool: &tool})
|
||||
}
|
||||
|
||||
maxTokens := int64(req.MaxTokens)
|
||||
@@ -81,16 +89,94 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
|
||||
MaxTokens: maxTokens,
|
||||
Messages: msgs,
|
||||
}
|
||||
if cacheRequested(req.CacheControl) {
|
||||
params.CacheControl = anthropicCacheControl(req.CacheControl)
|
||||
}
|
||||
if len(tools) > 0 {
|
||||
params.Tools = tools
|
||||
}
|
||||
if sys := buildAnthropicSystem(req); len(sys) > 0 {
|
||||
params.System = sys
|
||||
}
|
||||
if req.Temperature > 0 {
|
||||
if req.TemperatureSet {
|
||||
// Protocol-proxy requests must preserve even an explicit zero. Let the
|
||||
// upstream API reject an incompatible client combination unchanged.
|
||||
params.Temperature = anthropic.Float(req.Temperature)
|
||||
} else if req.Temperature > 0 && !anthropicAdaptiveThinkingOnly(model) {
|
||||
// Portable Harness callers retain the provider's compatibility guard:
|
||||
// adaptive-only models reject sampling parameters while thinking.
|
||||
params.Temperature = anthropic.Float(req.Temperature)
|
||||
}
|
||||
if cfg, ok := p.BuildThinkingConfig(model, req.Reasoning); ok {
|
||||
if native := req.NativeReasoning; native != nil {
|
||||
// Proxy mode preserves exactly what the client requested. Do not infer a
|
||||
// model default, silently remove sampling controls, or enlarge max_tokens:
|
||||
// the upstream should accept or reject the same semantics as a direct call.
|
||||
switch native.Type {
|
||||
case "adaptive":
|
||||
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||
OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{
|
||||
Display: anthropic.ThinkingConfigAdaptiveDisplay(native.Display),
|
||||
},
|
||||
}
|
||||
case "enabled":
|
||||
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||
OfEnabled: &anthropic.ThinkingConfigEnabledParam{
|
||||
BudgetTokens: native.BudgetTokens,
|
||||
Display: anthropic.ThinkingConfigEnabledDisplay(native.Display),
|
||||
},
|
||||
}
|
||||
case "disabled":
|
||||
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||
OfDisabled: &anthropic.ThinkingConfigDisabledParam{},
|
||||
}
|
||||
}
|
||||
if native.Effort != "" {
|
||||
params.OutputConfig = anthropic.OutputConfigParam{
|
||||
Effort: anthropic.OutputConfigEffort(native.Effort),
|
||||
}
|
||||
}
|
||||
if len(native.OutputFormat) > 0 {
|
||||
var format anthropic.JSONOutputFormatParam
|
||||
if err := json.Unmarshal(native.OutputFormat, &format); err == nil {
|
||||
params.OutputConfig.Format = format
|
||||
} else {
|
||||
// Decoders are expected to validate this before constructing the
|
||||
// request. Keep this defensive diagnostic for direct Harness callers.
|
||||
slog.Error("invalid native Anthropic output format", "err", err)
|
||||
}
|
||||
}
|
||||
} else if anthropicAdaptiveThinkingOnly(model) {
|
||||
// Fable 5 / Mythos 5 / Opus 4.7+ / Opus 5 / Sonnet 5 reject the
|
||||
// legacy enabled+budget_tokens config (400 "thinking.type.enabled
|
||||
// is not supported"). They take {type:"adaptive"} plus
|
||||
// output_config.effort; sampling params are also removed.
|
||||
if req.Reasoning != llm.ReasoningOff {
|
||||
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||
OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{},
|
||||
}
|
||||
params.OutputConfig = anthropic.OutputConfigParam{
|
||||
Effort: anthropicEffort(req.Reasoning),
|
||||
}
|
||||
slog.Info("anthropic adaptive thinking",
|
||||
"model", model,
|
||||
"effort", string(anthropicEffort(req.Reasoning)))
|
||||
} else if anthropicThinksByDefault(model) {
|
||||
// Opus 5 and Sonnet 5 think by default when the thinking
|
||||
// param is omitted entirely (unlike Opus 4.7/4.8, Fable 5,
|
||||
// and Mythos, where omitting it means no thinking) — so
|
||||
// expressing "reasoning off" here requires an explicit
|
||||
// {type:"disabled"}. Accepted at effort high or below;
|
||||
// our ReasoningMode never asks for more than high.
|
||||
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||
OfDisabled: &anthropic.ThinkingConfigDisabledParam{},
|
||||
}
|
||||
}
|
||||
// Else (Fable 5 / Mythos / Opus 4.7/4.8, reasoning off): omit
|
||||
// thinking entirely. Fable 5 and Mythos reject an explicit
|
||||
// {type:"disabled"} at any effort; Opus 4.7/4.8 already default
|
||||
// to no thinking when the param is omitted, so there's nothing
|
||||
// to disable.
|
||||
} else if cfg, ok := p.BuildThinkingConfig(model, req.Reasoning); ok {
|
||||
required := cfg.BudgetTokens + 4096
|
||||
if maxTokens < required {
|
||||
maxTokens = required
|
||||
@@ -141,12 +227,14 @@ 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
|
||||
var inputTokens, cacheCreationTokens, cacheReadTokens int64
|
||||
var pendingThinking strings.Builder
|
||||
var pendingThinkingSignature string
|
||||
|
||||
for stream.Next() {
|
||||
event := stream.Current()
|
||||
@@ -163,6 +251,10 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
||||
switch cb.Type {
|
||||
case "text":
|
||||
currentBlockType = "text"
|
||||
case "thinking":
|
||||
currentBlockType = "thinking"
|
||||
pendingThinking.Reset()
|
||||
pendingThinkingSignature = ""
|
||||
case "tool_use":
|
||||
currentBlockType = "tool_use"
|
||||
pending := pendingTC{
|
||||
@@ -195,20 +287,38 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
||||
Type: llm.EventTextDelta,
|
||||
Text: delta.Text,
|
||||
}
|
||||
case "thinking_delta":
|
||||
pendingThinking.WriteString(delta.Thinking)
|
||||
case "signature_delta":
|
||||
pendingThinkingSignature += delta.Signature
|
||||
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 == "thinking" {
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventThinkingBlock,
|
||||
ThinkingBlock: &llm.ThinkingBlock{
|
||||
Thinking: pendingThinking.String(),
|
||||
Signature: pendingThinkingSignature,
|
||||
},
|
||||
}
|
||||
pendingThinking.Reset()
|
||||
pendingThinkingSignature = ""
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -227,7 +337,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
||||
currentBlockType = ""
|
||||
|
||||
case "message_delta":
|
||||
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 {
|
||||
stopReason := string(event.Delta.StopReason)
|
||||
stopCategory := string(event.Delta.StopDetails.Category)
|
||||
if stopReason == llm.StopReasonRefusal {
|
||||
slog.Warn("anthropic refusal stop reason",
|
||||
"category", stopCategory,
|
||||
"output_tokens", event.Usage.OutputTokens)
|
||||
}
|
||||
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 || stopReason != "" {
|
||||
slog.Info("anthropic stream usage",
|
||||
"input_tokens", inputTokens,
|
||||
"output_tokens", event.Usage.OutputTokens,
|
||||
@@ -242,6 +359,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
||||
CacheCreationInputTokens: int(cacheCreationTokens),
|
||||
CacheReadInputTokens: int(cacheReadTokens),
|
||||
},
|
||||
StopReason: stopReason,
|
||||
StopCategory: stopCategory,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,7 +368,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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,8 +397,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
||||
// mid-flight; the partial output of the failed stream is discarded so
|
||||
// the prompt cache prefix on the next turn stays byte-identical.
|
||||
//
|
||||
// Note: thinking blocks (when reasoning is enabled) are NOT surfaced —
|
||||
// matches the streaming path which also doesn't emit thinking deltas.
|
||||
// Thinking blocks are surfaced as EventThinkingBlock events so the runtime
|
||||
// can store and echo them back in subsequent turns.
|
||||
// Tool-use input is converted to JSON via the SDK's RawJSON field.
|
||||
func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
params := p.buildMessageParams(req)
|
||||
@@ -286,6 +412,16 @@ func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRe
|
||||
defer close(events)
|
||||
for _, block := range msg.Content {
|
||||
switch block.Type {
|
||||
case "thinking":
|
||||
if block.Thinking != "" || block.Signature != "" {
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventThinkingBlock,
|
||||
ThinkingBlock: &llm.ThinkingBlock{
|
||||
Thinking: block.Thinking,
|
||||
Signature: block.Signature,
|
||||
},
|
||||
}
|
||||
}
|
||||
case "text":
|
||||
if block.Text != "" {
|
||||
events <- llm.ChatEvent{Type: llm.EventTextDelta, Text: block.Text}
|
||||
@@ -326,6 +462,8 @@ func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRe
|
||||
CacheCreationInputTokens: int(msg.Usage.CacheCreationInputTokens),
|
||||
CacheReadInputTokens: int(msg.Usage.CacheReadInputTokens),
|
||||
},
|
||||
StopReason: string(msg.StopReason),
|
||||
StopCategory: string(msg.StopDetails.Category),
|
||||
}
|
||||
}()
|
||||
return events, nil
|
||||
@@ -374,6 +512,64 @@ func (p *AnthropicProvider) BuildThinkingConfig(model string, mode llm.Reasoning
|
||||
}
|
||||
}
|
||||
|
||||
// anthropicAdaptiveThinkingOnly reports whether the model accepts ONLY
|
||||
// adaptive thinking: Claude Fable 5, Claude Mythos 5, Opus 4.7+, Opus 5,
|
||||
// and Sonnet 5. On these the legacy {type:"enabled", budget_tokens:N}
|
||||
// config and sampling params (temperature/top_p/top_k) return HTTP 400.
|
||||
// Matched by substring so gateway model-group names
|
||||
// (claude-fable-5-global) and Bedrock-style IDs
|
||||
// (us.anthropic.claude-opus-4-8-v1) are covered.
|
||||
func anthropicAdaptiveThinkingOnly(model string) bool {
|
||||
adaptiveOnly := []string{
|
||||
"claude-fable-5",
|
||||
"claude-mythos-5",
|
||||
"claude-mythos-preview",
|
||||
"claude-opus-4-7",
|
||||
"claude-opus-4-8",
|
||||
"claude-opus-4-9", // future-proof within the 4.x line
|
||||
"claude-opus-5",
|
||||
"claude-sonnet-5",
|
||||
}
|
||||
for _, marker := range adaptiveOnly {
|
||||
if strings.Contains(model, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// anthropicThinksByDefault reports whether the model runs adaptive
|
||||
// thinking when the thinking param is omitted entirely — true for Opus 5
|
||||
// and Sonnet 5 only. Fable 5, Mythos, and Opus 4.7/4.8 do NOT think by
|
||||
// default (omitting thinking means no thinking on those), so expressing
|
||||
// "reasoning off" there is a no-op omission; on Opus 5 / Sonnet 5 it
|
||||
// requires an explicit {type:"disabled"} or the model thinks anyway.
|
||||
func anthropicThinksByDefault(model string) bool {
|
||||
thinksByDefault := []string{
|
||||
"claude-opus-5",
|
||||
"claude-sonnet-5",
|
||||
}
|
||||
for _, marker := range thinksByDefault {
|
||||
if strings.Contains(model, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// anthropicEffort maps the unified ReasoningMode onto output_config.effort
|
||||
// for adaptive-thinking-only models.
|
||||
func anthropicEffort(mode llm.ReasoningMode) anthropic.OutputConfigEffort {
|
||||
switch mode {
|
||||
case llm.ReasoningLow:
|
||||
return anthropic.OutputConfigEffortLow
|
||||
case llm.ReasoningMedium:
|
||||
return anthropic.OutputConfigEffortMedium
|
||||
default:
|
||||
return anthropic.OutputConfigEffortHigh
|
||||
}
|
||||
}
|
||||
|
||||
// anthropicSupportsThinking returns true for Claude models that accept
|
||||
// extended thinking. Conservative — unknown IDs default to true so we
|
||||
// let the API decide rather than silently drop a knob the user set.
|
||||
@@ -414,7 +610,11 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
|
||||
i-- // un-consume; outer loop will re-process
|
||||
break
|
||||
}
|
||||
blocks = append(blocks, buildToolResultBlock(cur))
|
||||
block := buildToolResultBlock(cur)
|
||||
if cacheRequested(cur.CacheControl) {
|
||||
setCacheControlOnBlock(&block, cur.CacheControl)
|
||||
}
|
||||
blocks = append(blocks, block)
|
||||
}
|
||||
msgs = append(msgs, anthropic.NewUserMessage(blocks...))
|
||||
} else if len(m.Images) > 0 {
|
||||
@@ -426,12 +626,29 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
|
||||
if m.Content != "" {
|
||||
blocks = append(blocks, anthropic.NewTextBlock(m.Content))
|
||||
}
|
||||
if cacheRequested(m.CacheControl) && len(blocks) > 0 {
|
||||
setCacheControlOnBlock(&blocks[len(blocks)-1], m.CacheControl)
|
||||
}
|
||||
msgs = append(msgs, anthropic.NewUserMessage(blocks...))
|
||||
} else {
|
||||
msgs = append(msgs, anthropic.NewUserMessage(anthropic.NewTextBlock(m.Content)))
|
||||
block := anthropic.NewTextBlock(m.Content)
|
||||
if cacheRequested(m.CacheControl) {
|
||||
setCacheControlOnBlock(&block, m.CacheControl)
|
||||
}
|
||||
msgs = append(msgs, anthropic.NewUserMessage(block))
|
||||
}
|
||||
case "assistant":
|
||||
var blocks []anthropic.ContentBlockParamUnion
|
||||
// Thinking blocks must come first, before text and tool_use.
|
||||
for _, tb := range m.ThinkingBlocks {
|
||||
blocks = append(blocks, anthropic.ContentBlockParamUnion{
|
||||
OfThinking: &anthropic.ThinkingBlockParam{
|
||||
Type: "thinking",
|
||||
Thinking: tb.Thinking,
|
||||
Signature: tb.Signature,
|
||||
},
|
||||
})
|
||||
}
|
||||
if m.Content != "" {
|
||||
blocks = append(blocks, anthropic.NewTextBlock(m.Content))
|
||||
}
|
||||
@@ -443,6 +660,9 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
|
||||
blocks = append(blocks, anthropic.NewToolUseBlock(tc.ID, input, tc.Name))
|
||||
}
|
||||
if len(blocks) > 0 {
|
||||
if cacheRequested(m.CacheControl) {
|
||||
setCacheControlOnBlock(&blocks[len(blocks)-1], m.CacheControl)
|
||||
}
|
||||
msgs = append(msgs, anthropic.NewAssistantMessage(blocks...))
|
||||
}
|
||||
}
|
||||
@@ -453,7 +673,7 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
|
||||
if cacheLast && len(msgs) > 0 {
|
||||
tail := &msgs[len(msgs)-1]
|
||||
if len(tail.Content) > 0 {
|
||||
setCacheControlOnBlock(&tail.Content[len(tail.Content)-1])
|
||||
setCacheControlOnBlock(&tail.Content[len(tail.Content)-1], nil)
|
||||
}
|
||||
}
|
||||
return msgs
|
||||
@@ -465,8 +685,8 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
|
||||
// so we mutate the variant struct directly. Variants other than text /
|
||||
// tool_result / image / tool_use are out of scope; the runtime never
|
||||
// produces them as the tail of a user message.
|
||||
func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion) {
|
||||
cc := anthropic.NewCacheControlEphemeralParam()
|
||||
func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion, cache *llm.CacheControl) {
|
||||
cc := anthropicCacheControl(cache)
|
||||
switch {
|
||||
case block.OfText != nil:
|
||||
block.OfText.CacheControl = cc
|
||||
@@ -528,8 +748,8 @@ func buildAnthropicSystem(req llm.ChatRequest) []anthropic.TextBlockParam {
|
||||
continue
|
||||
}
|
||||
b := anthropic.TextBlockParam{Text: p.Text}
|
||||
if p.Cache {
|
||||
b.CacheControl = anthropic.NewCacheControlEphemeralParam()
|
||||
if p.Cache || cacheRequested(p.CacheControl) {
|
||||
b.CacheControl = anthropicCacheControl(p.CacheControl)
|
||||
}
|
||||
blocks = append(blocks, b)
|
||||
}
|
||||
@@ -543,3 +763,15 @@ func buildAnthropicSystem(req llm.ChatRequest) []anthropic.TextBlockParam {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cacheRequested(cache *llm.CacheControl) bool {
|
||||
return cache != nil && (cache.Type == "" || cache.Type == "ephemeral")
|
||||
}
|
||||
|
||||
func anthropicCacheControl(cache *llm.CacheControl) anthropic.CacheControlEphemeralParam {
|
||||
cc := anthropic.NewCacheControlEphemeralParam()
|
||||
if cache != nil && cache.TTL != "" {
|
||||
cc.TTL = anthropic.CacheControlEphemeralTTL(cache.TTL)
|
||||
}
|
||||
return cc
|
||||
}
|
||||
@@ -6,12 +6,13 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
// helper: extract tool_use IDs (in order) from an assistant MessageParam.
|
||||
@@ -234,6 +235,65 @@ func TestAnthropicSystemPromptPartsEmitCacheControl(t *testing.T) {
|
||||
require.Empty(t, string(got[1].CacheControl.Type), "second block must not be cache-marked")
|
||||
}
|
||||
|
||||
func TestAnthropicCacheControlPreservesTTLAtEveryWireLocation(t *testing.T) {
|
||||
cache1h := &llm.CacheControl{Type: "ephemeral", TTL: "1h"}
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
params := p.buildMessageParams(llm.ChatRequest{
|
||||
Model: "claude-test",
|
||||
MaxTokens: 10,
|
||||
CacheControl: cache1h,
|
||||
SystemPromptParts: []llm.SystemPromptPart{
|
||||
{Text: "stable system", CacheControl: cache1h},
|
||||
},
|
||||
Tools: []llm.ToolDef{{
|
||||
Name: "lookup", Parameters: json.RawMessage(`{"type":"object","properties":{}}`), CacheControl: cache1h,
|
||||
}},
|
||||
Messages: []llm.Message{{Role: "user", Content: "hello", CacheControl: cache1h}},
|
||||
})
|
||||
|
||||
require.Equal(t, "ephemeral", string(params.CacheControl.Type))
|
||||
require.Equal(t, "1h", string(params.CacheControl.TTL))
|
||||
require.Len(t, params.System, 1)
|
||||
require.Equal(t, "1h", string(params.System[0].CacheControl.TTL))
|
||||
require.Len(t, params.Tools, 1)
|
||||
require.NotNil(t, params.Tools[0].OfTool)
|
||||
require.Equal(t, "1h", string(params.Tools[0].OfTool.CacheControl.TTL))
|
||||
require.Len(t, params.Messages, 1)
|
||||
messageCache := params.Messages[0].Content[0].GetCacheControl()
|
||||
require.NotNil(t, messageCache)
|
||||
require.Equal(t, "1h", string(messageCache.TTL))
|
||||
}
|
||||
|
||||
func TestAnthropicCacheControlAppearsOnActualHTTPRequest(t *testing.T) {
|
||||
bodyCh := make(chan map[string]any, 1)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
|
||||
bodyCh <- body
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-test\",\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
cache := &llm.CacheControl{Type: "ephemeral", TTL: "1h"}
|
||||
p := NewAnthropicProvider("test-key", srv.URL)
|
||||
events, err := p.ChatStream(context.Background(), llm.ChatRequest{
|
||||
Model: "claude-test", MaxTokens: 10, CacheControl: cache,
|
||||
SystemPromptParts: []llm.SystemPromptPart{{Text: "system", CacheControl: cache}},
|
||||
Tools: []llm.ToolDef{{Name: "lookup", Parameters: json.RawMessage(`{"type":"object","properties":{}}`), CacheControl: cache}},
|
||||
Messages: []llm.Message{{Role: "user", Content: "hello", CacheControl: cache}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
body := <-bodyCh
|
||||
require.Equal(t, "1h", body["cache_control"].(map[string]any)["ttl"])
|
||||
require.Equal(t, "1h", body["system"].([]any)[0].(map[string]any)["cache_control"].(map[string]any)["ttl"])
|
||||
require.Equal(t, "1h", body["tools"].([]any)[0].(map[string]any)["cache_control"].(map[string]any)["ttl"])
|
||||
message := body["messages"].([]any)[0].(map[string]any)
|
||||
require.Equal(t, "1h", message["content"].([]any)[0].(map[string]any)["cache_control"].(map[string]any)["ttl"])
|
||||
}
|
||||
|
||||
func TestAnthropicSystemPromptStringFallback(t *testing.T) {
|
||||
got := buildAnthropicSystem(llm.ChatRequest{SystemPrompt: "legacy"})
|
||||
require.Len(t, got, 1)
|
||||
@@ -521,3 +581,281 @@ data: {"type":"message_stop"}
|
||||
assert.Equal(t, `{}`, string(toolDone.ToolCall.Input),
|
||||
"argument-less tool call must serialize as {} so MCP transport accepts it")
|
||||
}
|
||||
|
||||
// --- Adaptive-thinking model mapping ---------------------------------
|
||||
//
|
||||
// Claude Fable 5, Claude Mythos 5, Opus 4.7/4.8, Opus 5, and Sonnet 5
|
||||
// reject the legacy thinking config: `thinking: {type:"enabled",
|
||||
// budget_tokens:N}` returns HTTP 400 ("thinking.type.enabled is not
|
||||
// supported for this model"). They also removed sampling params —
|
||||
// sending `temperature` is a 400. For these models the provider must
|
||||
// emit `thinking: {type:"adaptive"}` plus `output_config.effort`, and
|
||||
// drop temperature.
|
||||
//
|
||||
// Opus 5 and Sonnet 5 additionally think BY DEFAULT when the thinking
|
||||
// param is omitted — unlike Fable 5/Mythos/Opus 4.7/4.8, where omitting
|
||||
// it means no thinking. So "reasoning off" on Opus 5/Sonnet 5 must send
|
||||
// an explicit {type:"disabled"} rather than omit the param.
|
||||
|
||||
func wireJSON(t *testing.T, p *AnthropicProvider, req llm.ChatRequest) string {
|
||||
t.Helper()
|
||||
params := p.buildMessageParams(req)
|
||||
b, err := json.Marshal(params)
|
||||
require.NoError(t, err)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestAdaptiveThinkingModels_EmitAdaptiveNotEnabled(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
models := []string{
|
||||
"claude-fable-5",
|
||||
"claude-fable-5-global", // LiteLLM / gateway model-group names
|
||||
"claude-mythos-5",
|
||||
"claude-opus-4-7",
|
||||
"claude-opus-4-8",
|
||||
"us.anthropic.claude-opus-4-8-v1", // Bedrock-style ID
|
||||
"claude-opus-5",
|
||||
"claude-sonnet-5",
|
||||
}
|
||||
for _, model := range models {
|
||||
t.Run(model, func(t *testing.T) {
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: model,
|
||||
Reasoning: llm.ReasoningHigh,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.Contains(t, got, `"thinking":{"type":"adaptive"}`,
|
||||
"adaptive-only models must send thinking.type=adaptive")
|
||||
assert.NotContains(t, got, `"budget_tokens"`,
|
||||
"budget_tokens is rejected with 400 on adaptive-only models")
|
||||
assert.Contains(t, got, `"output_config":{"effort":"high"}`,
|
||||
"reasoning mode maps to output_config.effort on adaptive-only models")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdaptiveThinkingModels_EffortMapping(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
cases := []struct {
|
||||
mode llm.ReasoningMode
|
||||
effort string
|
||||
}{
|
||||
{llm.ReasoningLow, "low"},
|
||||
{llm.ReasoningMedium, "medium"},
|
||||
{llm.ReasoningHigh, "high"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(string(c.mode), func(t *testing.T) {
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: "claude-opus-4-8",
|
||||
Reasoning: c.mode,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.Contains(t, got, `"output_config":{"effort":"`+c.effort+`"}`)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdaptiveThinkingModels_ReasoningOffOmitsThinking(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: "claude-fable-5",
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.NotContains(t, got, `"thinking"`,
|
||||
"reasoning off must omit the thinking param entirely — Fable 5 "+
|
||||
"rejects an explicit {type:disabled} with 400")
|
||||
assert.NotContains(t, got, `"output_config"`)
|
||||
}
|
||||
|
||||
func TestNativeReasoningConfigPreservesInboundProxySemantics(t *testing.T) {
|
||||
p := &AnthropicProvider{}
|
||||
tests := []struct {
|
||||
name string
|
||||
config *llm.NativeReasoningConfig
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "adaptive effort max",
|
||||
config: &llm.NativeReasoningConfig{Type: "adaptive", Effort: "max"},
|
||||
want: []string{`"thinking":{"type":"adaptive"}`, `"output_config":{"effort":"max"}`},
|
||||
},
|
||||
{
|
||||
name: "enabled exact budget",
|
||||
config: &llm.NativeReasoningConfig{Type: "enabled", BudgetTokens: 3072},
|
||||
want: []string{`"thinking":{"budget_tokens":3072,"type":"enabled"}`},
|
||||
},
|
||||
{
|
||||
name: "explicit disabled",
|
||||
config: &llm.NativeReasoningConfig{Type: "disabled"},
|
||||
want: []string{`"thinking":{"type":"disabled"}`},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
params := p.buildMessageParams(llm.ChatRequest{
|
||||
Model: "claude-opus-4-8-global", MaxTokens: 2048,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hello"}},
|
||||
NativeReasoning: test.config,
|
||||
})
|
||||
raw, err := json.Marshal(params)
|
||||
require.NoError(t, err)
|
||||
for _, want := range test.want {
|
||||
assert.Contains(t, string(raw), want)
|
||||
}
|
||||
assert.Contains(t, string(raw), `"max_tokens":2048`, "proxy mode must not enlarge max_tokens")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeProxyPreservesExplicitZeroTemperature(t *testing.T) {
|
||||
p := &AnthropicProvider{}
|
||||
params := p.buildMessageParams(llm.ChatRequest{
|
||||
Model: "claude-opus-4-8-global", MaxTokens: 32, Temperature: 0, TemperatureSet: true,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hello"}},
|
||||
})
|
||||
raw, err := json.Marshal(params)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(raw), `"temperature":0`)
|
||||
}
|
||||
|
||||
func TestAdaptiveThinkingModels_TemperatureDropped(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
for _, model := range []string{
|
||||
"claude-fable-5", "claude-opus-4-7", "claude-opus-4-8",
|
||||
"claude-opus-5", "claude-sonnet-5",
|
||||
} {
|
||||
t.Run(model, func(t *testing.T) {
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: model,
|
||||
Temperature: 0.7,
|
||||
Reasoning: llm.ReasoningMedium,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.NotContains(t, got, `"temperature"`,
|
||||
"sampling params are removed on these models — sending temperature is a 400")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpus5AndSonnet5_ThinkByDefault_ReasoningOffSendsDisabled reproduces
|
||||
// the bug this test guards against: Opus 5 and Sonnet 5 think adaptively
|
||||
// when `thinking` is omitted (unlike every other adaptive-only model),
|
||||
// so simply omitting the param to express "reasoning off" leaves
|
||||
// thinking on. The provider must send an explicit {type:"disabled"}.
|
||||
func TestOpus5AndSonnet5_ThinkByDefault_ReasoningOffSendsDisabled(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
for _, model := range []string{"claude-opus-5", "claude-sonnet-5"} {
|
||||
t.Run(model, func(t *testing.T) {
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: model,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.Contains(t, got, `"thinking":{"type":"disabled"}`,
|
||||
"Opus 5/Sonnet 5 think by default when thinking is omitted; "+
|
||||
"reasoning off must send an explicit disabled config")
|
||||
assert.NotContains(t, got, `"output_config"`)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyThinkingModels_KeepBudgetTokens(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: "claude-sonnet-4-5",
|
||||
Reasoning: llm.ReasoningHigh,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.Contains(t, got, `"budget_tokens":16384`,
|
||||
"pre-4.7 models keep the enabled+budget_tokens config")
|
||||
assert.NotContains(t, got, `"output_config"`)
|
||||
}
|
||||
|
||||
// TestAnthropicStream_RefusalStopReasonSurfaced reproduces the Claude
|
||||
// Fable 5 classifier refusal: HTTP 200, a message_delta carrying
|
||||
// stop_reason=refusal + stop_details.category, and NO content blocks.
|
||||
// The parser previously dropped stop_reason entirely, so the runtime
|
||||
// saw an empty-but-successful turn and the user saw a silent nothing.
|
||||
func TestAnthropicStream_RefusalStopReasonSurfaced(t *testing.T) {
|
||||
const sseBody = `event: message_start
|
||||
data: {"type":"message_start","message":{"id":"msg_r","type":"message","role":"assistant","content":[],"model":"claude-fable-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":29,"output_tokens":0}}}
|
||||
|
||||
event: message_delta
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"refusal","stop_sequence":null,"stop_details":{"type":"refusal","category":"bio","explanation":null}},"usage":{"output_tokens":4}}
|
||||
|
||||
event: message_stop
|
||||
data: {"type":"message_stop"}
|
||||
|
||||
`
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(sseBody))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewAnthropicProvider("test-key", srv.URL)
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-fable-5"})
|
||||
require.NoError(t, err)
|
||||
|
||||
var done *llm.ChatEvent
|
||||
for ev := range stream {
|
||||
if ev.Type == llm.EventDone {
|
||||
ev := ev
|
||||
done = &ev
|
||||
}
|
||||
}
|
||||
require.NotNil(t, done, "stream must emit EventDone")
|
||||
assert.Equal(t, "refusal", done.StopReason)
|
||||
assert.Equal(t, "bio", done.StopCategory)
|
||||
}
|
||||
|
||||
// Normal end_turn streams must carry the stop reason too (and no category).
|
||||
func TestAnthropicStream_EndTurnStopReason(t *testing.T) {
|
||||
const sseBody = `event: message_start
|
||||
data: {"type":"message_start","message":{"id":"msg_n","type":"message","role":"assistant","content":[],"model":"claude-fable-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0}}}
|
||||
|
||||
event: content_block_start
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
|
||||
|
||||
event: content_block_delta
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}
|
||||
|
||||
event: content_block_stop
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
event: message_delta
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}
|
||||
|
||||
event: message_stop
|
||||
data: {"type":"message_stop"}
|
||||
|
||||
`
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(sseBody))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewAnthropicProvider("test-key", srv.URL)
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-fable-5"})
|
||||
require.NoError(t, err)
|
||||
|
||||
var done *llm.ChatEvent
|
||||
for ev := range stream {
|
||||
if ev.Type == llm.EventDone {
|
||||
ev := ev
|
||||
done = &ev
|
||||
}
|
||||
}
|
||||
require.NotNil(t, done)
|
||||
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())
|
||||
}
|
||||
@@ -2,10 +2,15 @@ package gemini
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"google.golang.org/genai"
|
||||
"github.com/sausheong/harness/llm"
|
||||
@@ -182,6 +187,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 +196,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 {
|
||||
@@ -215,9 +218,25 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
||||
if err != nil {
|
||||
argsJSON = []byte("{}")
|
||||
}
|
||||
// Gemini's FunctionCall.ID is optional and is
|
||||
// frequently empty (single, non-parallel calls
|
||||
// commonly omit it). Falling back to fc.Name is
|
||||
// wrong on two counts: it isn't a valid
|
||||
// provider-neutral tool-call ID shape, and it
|
||||
// isn't unique — two calls to the same tool in
|
||||
// one turn, or the same tool called again later
|
||||
// in the conversation (routine for a coding
|
||||
// agent re-reading files), collide on the same
|
||||
// ID. When that history is later replayed to
|
||||
// Anthropic on a routing switch, duplicate
|
||||
// tool_use ids across the conversation are
|
||||
// rejected with a 400. Mint a synthetic
|
||||
// toolu_-shaped ID instead, matching Anthropic's
|
||||
// own ID shape so a later replay to Anthropic
|
||||
// looks like any other tool_use id.
|
||||
id := fc.ID
|
||||
if id == "" {
|
||||
id = fc.Name
|
||||
id = syntheticToolCallID()
|
||||
}
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventToolCallStart,
|
||||
@@ -240,12 +259,37 @@ 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}
|
||||
}
|
||||
|
||||
// syntheticToolCallID mints a unique, Anthropic-shaped tool-call ID
|
||||
// ("toolu_" + 16 hex chars) for Gemini function calls that arrive with
|
||||
// no ID of their own. Uniqueness (not just shape) is the point: a
|
||||
// name-based fallback collides whenever the same tool is called more
|
||||
// than once in a conversation, which produces duplicate tool_use ids if
|
||||
// that history is later replayed to Anthropic. Falls back to a
|
||||
// time+PID-derived suffix if crypto/rand is unavailable — still unique
|
||||
// within one process lifetime, which is all a single conversation needs.
|
||||
func syntheticToolCallID() string {
|
||||
b := make([]byte, 8)
|
||||
if _, err := rand.Read(b); err == nil {
|
||||
return "toolu_" + hex.EncodeToString(b)
|
||||
}
|
||||
mix := uint64(time.Now().UnixNano()) ^ uint64(os.Getpid())
|
||||
binary.BigEndian.PutUint64(b, mix)
|
||||
return "toolu_" + hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package gemini
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -24,3 +25,31 @@ 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)
|
||||
}
|
||||
|
||||
// TestSyntheticToolCallID_UniqueAndAnthropicShaped guards against the bug
|
||||
// where an empty Gemini FunctionCall.ID fell back to the function name.
|
||||
// That fallback isn't a valid provider-neutral tool-call ID shape, and
|
||||
// worse, it isn't unique: two calls to the same tool (parallel calls, or
|
||||
// the same tool called again later in a conversation — routine for a
|
||||
// coding agent re-reading files) collided on one ID. When that history
|
||||
// was later replayed to Anthropic on a routing switch, the duplicate
|
||||
// tool_use ids were rejected with a 400.
|
||||
func TestSyntheticToolCallID_UniqueAndAnthropicShaped(t *testing.T) {
|
||||
seen := make(map[string]bool)
|
||||
for range 100 {
|
||||
id := syntheticToolCallID()
|
||||
require.True(t, strings.HasPrefix(id, "toolu_"),
|
||||
"synthetic ID must be shaped like an Anthropic tool_use id so a later replay to Anthropic is accepted")
|
||||
require.False(t, seen[id], "synthetic IDs must be unique across calls in the same process")
|
||||
seen[id] = true
|
||||
}
|
||||
}
|
||||
+38
-19
@@ -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
|
||||
@@ -337,25 +332,13 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
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-
|
||||
// calling schema rejects. anyOf/oneOf/format are accepted and kept.
|
||||
var openaiUnsupportedFields = []string{"$ref", "definitions"}
|
||||
|
||||
@@ -73,3 +73,22 @@ 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) {
|
||||
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")
|
||||
}
|
||||
+43
-23
@@ -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 {
|
||||
@@ -169,10 +204,11 @@ func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-c
|
||||
}
|
||||
|
||||
openaiReq := openai.ChatCompletionRequest{
|
||||
Model: model,
|
||||
Messages: msgs,
|
||||
MaxTokens: maxTokens,
|
||||
Stream: true,
|
||||
Model: model,
|
||||
Messages: msgs,
|
||||
MaxCompletionTokens: maxTokens,
|
||||
Stream: true,
|
||||
StreamOptions: &openai.StreamOptions{IncludeUsage: true},
|
||||
}
|
||||
|
||||
if len(tools) > 0 {
|
||||
@@ -217,11 +253,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 +302,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
+63
-7
@@ -246,7 +246,7 @@ func TestPruneToolResults(t *testing.T) {
|
||||
}
|
||||
|
||||
// Empty spillConfig → legacy in-place truncation path.
|
||||
pruneToolResults(msgs, 10000, spillConfig{})
|
||||
pruneToolResults(msgs, 10000, spillConfig{}, nil)
|
||||
|
||||
// User message should be unchanged
|
||||
assert.Equal(t, "hello", msgs[0].Content)
|
||||
@@ -261,7 +261,7 @@ func TestPruneToolResultsShort(t *testing.T) {
|
||||
{Role: "user", Content: "short output", ToolCallID: "tc_1"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, spillConfig{})
|
||||
pruneToolResults(msgs, 10000, spillConfig{}, nil)
|
||||
|
||||
assert.Equal(t, "short output", msgs[0].Content)
|
||||
}
|
||||
@@ -279,7 +279,7 @@ func TestPruneToolResultsNewlineBoundary(t *testing.T) {
|
||||
{Role: "user", Content: content, ToolCallID: "tc_1"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, spillConfig{})
|
||||
pruneToolResults(msgs, 10000, spillConfig{}, nil)
|
||||
|
||||
// Should be truncated and contain the truncation marker
|
||||
truncated := msgs[0].Content
|
||||
@@ -298,7 +298,7 @@ func TestPruneToolResultsSpillsToDisk(t *testing.T) {
|
||||
{Role: "user", Content: original, ToolCallID: "tc_42"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_abc"})
|
||||
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_abc"}, nil)
|
||||
|
||||
// Message rewritten to head + spill marker pointing at the file.
|
||||
got := msgs[0].Content
|
||||
@@ -324,14 +324,14 @@ func TestPruneToolResultsIdempotentAfterSpill(t *testing.T) {
|
||||
{Role: "user", Content: strings.Repeat("b", 20000), ToolCallID: "tc_99"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, cfg)
|
||||
pruneToolResults(msgs, 10000, cfg, nil)
|
||||
afterFirst := msgs[0].Content
|
||||
require.Contains(t, afterFirst, spillMarker)
|
||||
|
||||
// Second call: marker is present, so the message must be untouched.
|
||||
// Mutating it (e.g. spilling again or appending another marker)
|
||||
// would silently grow the prefill across turns and burn cache.
|
||||
pruneToolResults(msgs, 10000, cfg)
|
||||
pruneToolResults(msgs, 10000, cfg, nil)
|
||||
assert.Equal(t, afterFirst, msgs[0].Content)
|
||||
}
|
||||
|
||||
@@ -349,7 +349,7 @@ func TestPruneToolResultsFallsBackToTruncationWhenSpillFails(t *testing.T) {
|
||||
{Role: "user", Content: strings.Repeat("c", 20000), ToolCallID: "tc_fail"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_fail"})
|
||||
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_fail"}, nil)
|
||||
|
||||
got := msgs[0].Content
|
||||
assert.Less(t, len(got), 20000, "fallback must still bound the message")
|
||||
@@ -357,6 +357,31 @@ func TestPruneToolResultsFallsBackToTruncationWhenSpillFails(t *testing.T) {
|
||||
assert.NotContains(t, got, spillMarker, "spilled marker must not appear when write failed")
|
||||
}
|
||||
|
||||
func TestPruneToolResultsSpillsOncePerID(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
cfg := spillConfig{Workspace: workspace, SessionKey: "sess_once"}
|
||||
spilled := map[string]bool{}
|
||||
|
||||
big := strings.Repeat("x", 50000)
|
||||
mk := func() []llm.Message {
|
||||
return []llm.Message{{ToolCallID: "call_big", Content: big}}
|
||||
}
|
||||
|
||||
m1 := mk()
|
||||
pruneToolResults(m1, 10000, cfg, spilled)
|
||||
require.Contains(t, m1[0].Content, spillMarker)
|
||||
spillPath := filepath.Join(workspace, ".harness", "spill", "sess_once", "call_big.txt")
|
||||
require.FileExists(t, spillPath)
|
||||
require.True(t, spilled["call_big"], "ID recorded as spilled")
|
||||
|
||||
require.NoError(t, os.Remove(spillPath))
|
||||
|
||||
m2 := mk()
|
||||
pruneToolResults(m2, 10000, cfg, spilled)
|
||||
require.Contains(t, m2[0].Content, spillMarker, "message still rewritten to the marker")
|
||||
require.NoFileExists(t, spillPath, "turn 2 must NOT re-write the spill file (idempotent via spilled set)")
|
||||
}
|
||||
|
||||
// --- Runtime tests ---
|
||||
|
||||
func TestRuntimeRun(t *testing.T) {
|
||||
@@ -871,6 +896,37 @@ func TestRun_AbortMidDispatchProducesPairedSession(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunSync_ReturnsErrorOnAbort verifies that RunSync surfaces an aborted run
|
||||
// as a non-nil error (context.Canceled) rather than returning (partialText,
|
||||
// nil). Cron/sync callers must be able to distinguish a completed run from a
|
||||
// cancelled one. Reuses the same abort scaffolding as
|
||||
// TestRun_AbortMidDispatchProducesPairedSession (a tool batch + cancelOnNth).
|
||||
func TestRunSync_ReturnsErrorOnAbort(t *testing.T) {
|
||||
threeToolCalls := []llm.ToolCall{
|
||||
{ID: "tc_0", Name: "noop", Input: json.RawMessage(`{}`)},
|
||||
{ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`)},
|
||||
{ID: "tc_2", Name: "noop", Input: json.RawMessage(`{}`)},
|
||||
}
|
||||
llmFake := &threeToolCallLLM{toolCalls: threeToolCalls}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
count := 0
|
||||
exec := &cancelOnNthExecutor{n: 1, cancel: cancel, count: &count}
|
||||
|
||||
r := &Runtime{
|
||||
LLM: llmFake,
|
||||
Tools: exec,
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test-model",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
|
||||
_, err := r.RunSync(ctx, "go", nil)
|
||||
require.Error(t, err)
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
}
|
||||
|
||||
// threeToolCallLLM emits the configured tool_calls as one assistant turn,
|
||||
// then EventDone. On the next call (after tool results, if the runtime
|
||||
// loops back), emits only EventDone with no tool_calls so Run terminates.
|
||||
|
||||
+39
-1
@@ -166,6 +166,8 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
}
|
||||
}
|
||||
|
||||
loop := mergeLoopConfig(deps.AgentLoop, spec.Loop)
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: inputs.Provider,
|
||||
Tools: inputs.Tools,
|
||||
@@ -186,7 +188,7 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
Permission: deps.Permission,
|
||||
Compaction: inputs.Compaction,
|
||||
IngestSource: inputs.IngestSource,
|
||||
AgentLoop: deps.AgentLoop,
|
||||
AgentLoop: loop,
|
||||
StaticSystemPrompt: staticPrompt,
|
||||
CalibratorStore: deps.CalibratorStore,
|
||||
mcpClients: mcpClients,
|
||||
@@ -206,3 +208,39 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
|
||||
return rt, nil
|
||||
}
|
||||
|
||||
// mergeLoopConfig applies the per-agent non-zero settings over the shared
|
||||
// defaults. LoopConfig intentionally uses zero values as "inherit/default",
|
||||
// so this preserves existing RuntimeDeps.AgentLoop behavior while making the
|
||||
// documented AgentSpec.Loop override effective.
|
||||
func mergeLoopConfig(base, override LoopConfig) LoopConfig {
|
||||
out := base
|
||||
if override.MaxToolConcurrency > 0 {
|
||||
out.MaxToolConcurrency = override.MaxToolConcurrency
|
||||
}
|
||||
if override.MaxAgentDepth > 0 {
|
||||
out.MaxAgentDepth = override.MaxAgentDepth
|
||||
}
|
||||
if override.StreamingTools {
|
||||
out.StreamingTools = true
|
||||
}
|
||||
if override.MaxToolResultLen > 0 {
|
||||
out.MaxToolResultLen = override.MaxToolResultLen
|
||||
}
|
||||
if override.Hooks.OnUserPromptSubmit != nil {
|
||||
out.Hooks.OnUserPromptSubmit = override.Hooks.OnUserPromptSubmit
|
||||
}
|
||||
if override.Hooks.OnSessionStart != nil {
|
||||
out.Hooks.OnSessionStart = override.Hooks.OnSessionStart
|
||||
}
|
||||
if override.Hooks.BeforeToolUse != nil {
|
||||
out.Hooks.BeforeToolUse = override.Hooks.BeforeToolUse
|
||||
}
|
||||
if override.Hooks.AfterToolUse != nil {
|
||||
out.Hooks.AfterToolUse = override.Hooks.AfterToolUse
|
||||
}
|
||||
if override.Hooks.OnStop != nil {
|
||||
out.Hooks.OnStop = override.Hooks.OnStop
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
@@ -38,6 +39,39 @@ func TestBuildRuntimeMinimalSpecSafe(t *testing.T) {
|
||||
require.NotEmpty(t, rt.StaticSystemPrompt)
|
||||
}
|
||||
|
||||
func TestBuildRuntimeMergesSpecLoopOverSharedDefaults(t *testing.T) {
|
||||
baseCalled := false
|
||||
specCalled := false
|
||||
baseStop := func(context.Context, string) { baseCalled = true }
|
||||
specStop := func(context.Context, string) { specCalled = true }
|
||||
rt, err := BuildRuntime(
|
||||
RuntimeDeps{AgentLoop: LoopConfig{
|
||||
MaxToolConcurrency: 3,
|
||||
MaxAgentDepth: 2,
|
||||
MaxToolResultLen: 8000,
|
||||
Hooks: LifecycleHooks{OnStop: baseStop},
|
||||
}},
|
||||
RuntimeInputs{},
|
||||
AgentSpec{
|
||||
ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5",
|
||||
Loop: LoopConfig{
|
||||
MaxToolConcurrency: 7,
|
||||
StreamingTools: true,
|
||||
Hooks: LifecycleHooks{OnStop: specStop},
|
||||
},
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 7, rt.AgentLoop.MaxToolConcurrency)
|
||||
assert.Equal(t, 2, rt.AgentLoop.MaxAgentDepth, "zero spec fields inherit shared defaults")
|
||||
assert.Equal(t, 8000, rt.AgentLoop.MaxToolResultLen)
|
||||
assert.True(t, rt.AgentLoop.StreamingTools)
|
||||
require.NotNil(t, rt.AgentLoop.Hooks.OnStop)
|
||||
rt.AgentLoop.Hooks.OnStop(context.Background(), "completed")
|
||||
assert.False(t, baseCalled)
|
||||
assert.True(t, specCalled)
|
||||
}
|
||||
|
||||
func TestBuildRuntimeUsesCallerProvidedMemoryFiles(t *testing.T) {
|
||||
// Caller composes memoryFiles however they want — typical patterns
|
||||
// include walking AGENTS.md from workspace + $HOME, building from a
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tokens"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// usageDoneProvider emits a usage-bearing EventDone so the agent loop can
|
||||
// populate (and persist) the per-session token calibrator.
|
||||
type usageDoneProvider struct {
|
||||
llmtest.Base
|
||||
}
|
||||
|
||||
func (p *usageDoneProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "answer"}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 1000, OutputTokens: 10}}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// TestCalibratorPersistsByEndOfRun guards that the per-session calibrator is
|
||||
// persisted to the CalibratorStore by the time Run completes. After the P8
|
||||
// debounce change the Save moves from per-round to a single deferred flush at
|
||||
// Run end; this test asserts the observable end state (persisted) is unchanged.
|
||||
func TestCalibratorPersistsByEndOfRun(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := tokens.NewCalibratorStore(dir)
|
||||
rt := &Runtime{
|
||||
LLM: &usageDoneProvider{},
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-sonnet-4-5",
|
||||
// Compaction must be non-nil for the runtime to lazily create the
|
||||
// per-session calibrator (the calibrator-creation path is gated on
|
||||
// it). MessageCap/threshold left at defaults so no compaction fires
|
||||
// during this short run.
|
||||
Compaction: newCompactionMgr(),
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 2,
|
||||
Workspace: t.TempDir(),
|
||||
CalibratorStore: store,
|
||||
}
|
||||
_, err := rt.RunSync(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
ratio, count := tokens.NewCalibratorStore(dir).Load("a", "k")
|
||||
require.Greater(t, count, 0, "calibrator must be persisted by end of Run")
|
||||
require.Greater(t, ratio, 0.0)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// maxToolResultLen returns the per-result truncation cap (chars) for tool
|
||||
// results in the in-context message history. Precedence:
|
||||
// 1. Runtime.AgentLoop.MaxToolResultLen (>0) — config wins.
|
||||
// 2. HARNESS_MAX_TOOL_RESULT_LEN env var (>0) — env fallback.
|
||||
// 3. defaultMaxToolResultLen (4000).
|
||||
//
|
||||
// Tool results longer than this are truncated (or spilled to disk via
|
||||
// spillConfig when supplied). 4000 is conservative; engineering-style
|
||||
// agents that read source files and run tests typically want 16000-25000.
|
||||
func (r *Runtime) maxToolResultLen() int {
|
||||
if r.AgentLoop.MaxToolResultLen > 0 {
|
||||
return r.AgentLoop.MaxToolResultLen
|
||||
}
|
||||
if v := os.Getenv("HARNESS_MAX_TOOL_RESULT_LEN"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return defaultMaxToolResultLen
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestMaxToolResultLen_Precedence locks in the config > env > default
|
||||
// precedence so a regression here doesn't silently swap one source for
|
||||
// another.
|
||||
func TestMaxToolResultLen_Precedence(t *testing.T) {
|
||||
t.Run("default when nothing set", func(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "")
|
||||
r := &Runtime{}
|
||||
if got := r.maxToolResultLen(); got != defaultMaxToolResultLen {
|
||||
t.Fatalf("want %d, got %d", defaultMaxToolResultLen, got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("env overrides default", func(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "12345")
|
||||
r := &Runtime{}
|
||||
if got := r.maxToolResultLen(); got != 12345 {
|
||||
t.Fatalf("want 12345, got %d", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config overrides env", func(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "12345")
|
||||
r := &Runtime{AgentLoop: LoopConfig{MaxToolResultLen: 25000}}
|
||||
if got := r.maxToolResultLen(); got != 25000 {
|
||||
t.Fatalf("want 25000, got %d", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("zero env is ignored", func(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "0")
|
||||
r := &Runtime{}
|
||||
if got := r.maxToolResultLen(); got != defaultMaxToolResultLen {
|
||||
t.Fatalf("want %d, got %d", defaultMaxToolResultLen, got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("garbage env is ignored", func(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "not-a-number")
|
||||
r := &Runtime{}
|
||||
if got := r.maxToolResultLen(); got != defaultMaxToolResultLen {
|
||||
t.Fatalf("want %d, got %d", defaultMaxToolResultLen, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
anthropicprovider "github.com/sausheong/harness/providers/anthropic"
|
||||
)
|
||||
|
||||
// cachingCapableFake implements llm.LLMProvider plus the
|
||||
// llm.PromptCachingProvider capability.
|
||||
type cachingCapableFake struct {
|
||||
llmtest.Stub
|
||||
}
|
||||
|
||||
func (*cachingCapableFake) SupportsPromptCaching() bool { return true }
|
||||
|
||||
// TestProviderSupportsCaching_CapabilityInterfaceWins: an Anthropic-shaped
|
||||
// provider registered under a custom name (platformai, bedrock, any relay)
|
||||
// must still get prompt caching. Gating on the config block's NAME meant
|
||||
// every turn on a renamed provider re-processed the full history uncached.
|
||||
func TestProviderSupportsCaching_CapabilityInterfaceWins(t *testing.T) {
|
||||
r := &Runtime{Provider: "platformai", LLM: &cachingCapableFake{}}
|
||||
assert.True(t, r.providerSupportsCaching(),
|
||||
"capability interface must win over the provider name")
|
||||
}
|
||||
|
||||
func TestProviderSupportsCaching_NameFallbackStillWorks(t *testing.T) {
|
||||
r := &Runtime{Provider: "anthropic", LLM: &llmtest.Stub{}}
|
||||
assert.True(t, r.providerSupportsCaching(),
|
||||
"legacy name-based gate kept for providers without the capability interface")
|
||||
}
|
||||
|
||||
func TestProviderSupportsCaching_NonCachingProviderFalse(t *testing.T) {
|
||||
r := &Runtime{Provider: "local", LLM: &llmtest.Stub{}}
|
||||
assert.False(t, r.providerSupportsCaching())
|
||||
}
|
||||
|
||||
// TestAnthropicProviderDeclaresPromptCaching pins the wiring end-to-end:
|
||||
// the real Anthropic provider must implement the capability interface.
|
||||
func TestAnthropicProviderDeclaresPromptCaching(t *testing.T) {
|
||||
p := anthropicprovider.NewAnthropicProvider("k", "")
|
||||
pc, ok := any(p).(llm.PromptCachingProvider)
|
||||
assert.True(t, ok, "AnthropicProvider must implement llm.PromptCachingProvider")
|
||||
if ok {
|
||||
assert.True(t, pc.SupportsPromptCaching())
|
||||
}
|
||||
}
|
||||
|
||||
// Mid-loop compaction was gated on the same name list; an Anthropic-shaped
|
||||
// provider under a custom name must support it too.
|
||||
func TestProviderSupportsMidLoopCompaction_CapabilityInterfaceWins(t *testing.T) {
|
||||
r := &Runtime{Provider: "platformai", LLM: &cachingCapableFake{}}
|
||||
assert.True(t, r.providerSupportsMidLoopCompaction())
|
||||
}
|
||||
+33
-18
@@ -11,9 +11,15 @@ import (
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
const maxToolResultLen = 4000 // truncate tool results longer than this
|
||||
// defaultMaxToolResultLen is the fallback cap used when LoopConfig.MaxToolResultLen
|
||||
// is unset and the HARNESS_MAX_TOOL_RESULT_LEN env var is unset/invalid. Tool
|
||||
// results longer than this get truncated (or spilled to disk + truncated-with-
|
||||
// marker when spillConfig is supplied). 4000 chars (~1000 tokens) is conservative
|
||||
// so behaviour is unchanged for callers that don't opt into a larger budget.
|
||||
const defaultMaxToolResultLen = 4000
|
||||
|
||||
// detectImageMIME returns the actual MIME type based on magic bytes.
|
||||
// Falls back to the provided hint if the format is unrecognized.
|
||||
@@ -162,17 +168,6 @@ func buildDynamicSystemPromptSuffix(dateLine, cortexContext string) string {
|
||||
// corresponding tool_result in the next user message. Orphaned tool calls
|
||||
// (e.g. from interrupted sessions) get synthetic error results injected.
|
||||
func assembleMessages(history []session.SessionEntry) []llm.Message {
|
||||
// First pass: collect tool result IDs so we can detect orphaned tool calls.
|
||||
resultIDs := make(map[string]bool)
|
||||
for _, entry := range history {
|
||||
if entry.Type == session.EntryTypeToolResult {
|
||||
var tr session.ToolResultData
|
||||
if err := json.Unmarshal(entry.Data, &tr); err == nil {
|
||||
resultIDs[tr.ToolCallID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var msgs []llm.Message
|
||||
|
||||
for _, entry := range history {
|
||||
@@ -213,13 +208,19 @@ func assembleMessages(history []session.SessionEntry) []llm.Message {
|
||||
if err := json.Unmarshal(entry.Data, &md); err != nil {
|
||||
continue
|
||||
}
|
||||
// Before appending a new message, check if the last assistant
|
||||
// message has orphaned tool calls that need synthetic results.
|
||||
msgs = injectMissingToolResults(msgs)
|
||||
msg := llm.Message{
|
||||
Role: entry.Role,
|
||||
Content: md.Text,
|
||||
}
|
||||
// Restore thinking blocks for assistant messages (must be echoed back).
|
||||
if entry.Role == "assistant" {
|
||||
for _, tb := range md.ThinkingBlocks {
|
||||
msg.ThinkingBlocks = append(msg.ThinkingBlocks, llm.ThinkingBlock{
|
||||
Thinking: tb.Thinking,
|
||||
Signature: tb.Signature,
|
||||
})
|
||||
}
|
||||
}
|
||||
// Convert session images to LLM image content
|
||||
if entry.Role == "user" {
|
||||
for _, img := range md.Images {
|
||||
@@ -428,7 +429,7 @@ func spillToolResult(cfg spillConfig, toolCallID, content string) (string, error
|
||||
return "", fmt.Errorf("spill mkdir: %w", err)
|
||||
}
|
||||
path := filepath.Join(dir, toolCallID+".txt")
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
if err := tool.WriteFileAtomic(path, []byte(content), 0o600); err != nil {
|
||||
return "", fmt.Errorf("spill write: %w", err)
|
||||
}
|
||||
return path, nil
|
||||
@@ -455,7 +456,7 @@ func spillToolResult(cfg spillConfig, toolCallID, content string) (string, error
|
||||
// nearest newline boundary — most tool outputs (file reads, command
|
||||
// output) are front-loaded with the most relevant info, so the head
|
||||
// preview is usually enough on its own.
|
||||
func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig) {
|
||||
func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig, spilled map[string]bool) {
|
||||
for i := range msgs {
|
||||
if msgs[i].ToolCallID == "" || len(msgs[i].Content) <= maxLen {
|
||||
continue
|
||||
@@ -475,11 +476,25 @@ func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig) {
|
||||
// Try spill first if configured. On any failure, fall through to
|
||||
// legacy truncation so the prefill stays bounded either way.
|
||||
if cfg.Workspace != "" && cfg.SessionKey != "" {
|
||||
if path, err := spillToolResult(cfg, msgs[i].ToolCallID, msgs[i].Content); err == nil {
|
||||
id := msgs[i].ToolCallID
|
||||
// Spill content is immutable per ToolCallID and lands at a
|
||||
// deterministic path. If this Run already spilled this ID,
|
||||
// skip the (multi-MB) disk re-write and just rebuild the
|
||||
// in-memory marker pointing at the same path.
|
||||
if spilled != nil && spilled[id] {
|
||||
path := filepath.Join(cfg.Workspace, ".harness", "spill", cfg.SessionKey, id+".txt")
|
||||
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars saved to %s; use read_file to access the full output]",
|
||||
head, spillMarker, len(head), originalLen, path)
|
||||
continue
|
||||
}
|
||||
if writtenPath, err := spillToolResult(cfg, id, msgs[i].Content); err == nil {
|
||||
if spilled != nil {
|
||||
spilled[id] = true
|
||||
}
|
||||
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars saved to %s; use read_file to access the full output]",
|
||||
head, spillMarker, len(head), originalLen, writtenPath)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars; re-run the tool with offset/limit to see more]",
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
jsonpkg "encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -123,3 +125,28 @@ func TestFormatDateLine(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func mustJSON(t *testing.T, v any) jsonpkg.RawMessage {
|
||||
t.Helper()
|
||||
b, err := jsonpkg.Marshal(v)
|
||||
require.NoError(t, err)
|
||||
return b
|
||||
}
|
||||
|
||||
func TestAssembleMessagesInjectsOrphanedToolResult(t *testing.T) {
|
||||
history := []session.SessionEntry{
|
||||
{Type: session.EntryTypeMessage, Role: "user", Data: mustJSON(t, session.MessageData{Text: "hi"})},
|
||||
{Type: session.EntryTypeToolCall, Role: "assistant", Data: mustJSON(t, session.ToolCallData{
|
||||
ID: "call_1", Tool: "bash", Input: jsonpkg.RawMessage(`{}`),
|
||||
})},
|
||||
{Type: session.EntryTypeMessage, Role: "user", Data: mustJSON(t, session.MessageData{Text: "still there?"})},
|
||||
}
|
||||
msgs := assembleMessages(history)
|
||||
var found bool
|
||||
for _, m := range msgs {
|
||||
if m.ToolCallID == "call_1" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
require.True(t, found, "orphaned tool call must get a synthetic tool result from the terminal pass")
|
||||
}
|
||||
@@ -266,3 +266,110 @@ func TestBuildRuntimeRejectsCrossProviderFallback(t *testing.T) {
|
||||
func decodeMessage(e session.SessionEntry, dst *session.MessageData) error {
|
||||
return json.Unmarshal(e.Data, dst)
|
||||
}
|
||||
|
||||
// refusalThenSuccessProvider returns a classifier-refusal stream (HTTP
|
||||
// 200, EventDone with StopReason=refusal, no content) on the first call
|
||||
// and a normal text stream on the second. Mirrors Claude Fable 5 safety
|
||||
// classifier behavior: refusals are NOT transport errors, so the
|
||||
// existing IsRetryableModelError path never sees them.
|
||||
type refusalThenSuccessProvider struct {
|
||||
llmtest.Base
|
||||
calls int
|
||||
modelsSeen []string
|
||||
finalText string
|
||||
}
|
||||
|
||||
func (p *refusalThenSuccessProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.calls++
|
||||
p.modelsSeen = append(p.modelsSeen, req.Model)
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
if p.calls == 1 {
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: llm.StopReasonRefusal, StopCategory: "bio"}
|
||||
} else {
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: p.finalText}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: "end_turn"}
|
||||
}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// TestRuntimeRefusalRetriesOnFallbackModel: a refusal turn with a
|
||||
// configured fallback must transparently re-run the turn on the
|
||||
// fallback model instead of surfacing an empty response.
|
||||
func TestRuntimeRefusalRetriesOnFallbackModel(t *testing.T) {
|
||||
prov := &refusalThenSuccessProvider{finalText: "fallback answered"}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-fable-5",
|
||||
FallbackModel: "claude-opus-4-8",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 3,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
out, err := rt.RunSync(context.Background(), "summarise the biology article", nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "fallback answered", out)
|
||||
require.Equal(t, 2, prov.calls, "refusal + fallback retry = 2 calls")
|
||||
assert.Equal(t, "claude-fable-5", prov.modelsSeen[0])
|
||||
assert.Equal(t, "claude-opus-4-8", prov.modelsSeen[1])
|
||||
}
|
||||
|
||||
// alwaysRefusalProvider refuses every call — covers the no-fallback and
|
||||
// fallback-also-refused paths.
|
||||
type alwaysRefusalProvider struct {
|
||||
llmtest.Base
|
||||
calls int
|
||||
}
|
||||
|
||||
func (p *alwaysRefusalProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.calls++
|
||||
ch := make(chan llm.ChatEvent, 2)
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: llm.StopReasonRefusal, StopCategory: "cyber"}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// TestRuntimeRefusalWithoutFallbackSurfacesVisibleText: with no fallback
|
||||
// the user must see an explanation, not an empty response.
|
||||
func TestRuntimeRefusalWithoutFallbackSurfacesVisibleText(t *testing.T) {
|
||||
prov := &alwaysRefusalProvider{}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-fable-5",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 3,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
out, err := rt.RunSync(context.Background(), "do something", nil)
|
||||
require.NoError(t, err, "a refusal is a model decision, not a transport error")
|
||||
assert.Contains(t, out, "declined", "refusal must produce visible explanation text")
|
||||
assert.Contains(t, out, "cyber", "category should be included when present")
|
||||
assert.Equal(t, 1, prov.calls, "no fallback configured → no retry")
|
||||
}
|
||||
|
||||
// TestRuntimeRefusalFallbackAlsoRefusesSurfacesText: when the fallback
|
||||
// refuses too, stop (no infinite retry) and surface the explanation.
|
||||
func TestRuntimeRefusalFallbackAlsoRefusesSurfacesText(t *testing.T) {
|
||||
prov := &alwaysRefusalProvider{}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-fable-5",
|
||||
FallbackModel: "claude-opus-4-8",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 3,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
out, err := rt.RunSync(context.Background(), "do something", nil)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, out, "declined")
|
||||
assert.Equal(t, 2, prov.calls, "primary + one fallback attempt, then stop")
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// twoTurnUsageLLM: turn 1 emits a noop tool call + EventDone{Usage:u1};
|
||||
// turn 2 (after the tool result) emits text + EventDone{Usage:u2} and stops.
|
||||
type twoTurnUsageLLM struct {
|
||||
llmtest.Base
|
||||
u1, u2 *llm.Usage
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *twoTurnUsageLLM) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
ch := make(chan llm.ChatEvent, 8)
|
||||
first := f.calls == 0
|
||||
f.calls++
|
||||
go func() {
|
||||
defer close(ch)
|
||||
if first {
|
||||
tc := llm.ToolCall{ID: "tc_0", Name: "noop", Input: json.RawMessage(`{}`)}
|
||||
ch <- llm.ChatEvent{Type: llm.EventToolCallStart, ToolCall: &tc}
|
||||
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &tc}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: f.u1}
|
||||
return
|
||||
}
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "done"}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: f.u2}
|
||||
}()
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// usageNoopExecutor returns "ok" for a "noop" tool. (Distinct from the
|
||||
// error-returning noopExecutor in agent_test.go, which has no tool defs.)
|
||||
type usageNoopExecutor struct{}
|
||||
|
||||
func (usageNoopExecutor) Execute(_ context.Context, _ string, _ json.RawMessage) (tool.ToolResult, error) {
|
||||
return tool.ToolResult{Output: "ok"}, nil
|
||||
}
|
||||
func (usageNoopExecutor) ToolDefs() []llm.ToolDef { return []llm.ToolDef{{Name: "noop"}} }
|
||||
func (usageNoopExecutor) Names() []string { return []string{"noop"} }
|
||||
func (usageNoopExecutor) Get(string) (tool.Tool, bool) { return nil, false }
|
||||
|
||||
func drainUsage(t *testing.T, events <-chan AgentEvent) *llm.Usage {
|
||||
t.Helper()
|
||||
var done *llm.Usage
|
||||
var sawDone bool
|
||||
for ev := range events {
|
||||
if ev.Type == EventDone {
|
||||
done = ev.Usage
|
||||
sawDone = true
|
||||
}
|
||||
}
|
||||
require.True(t, sawDone, "expected a terminal EventDone")
|
||||
return done
|
||||
}
|
||||
|
||||
func TestRun_UsageAccumulatesAcrossTurns(t *testing.T) {
|
||||
r := &Runtime{
|
||||
LLM: &twoTurnUsageLLM{
|
||||
u1: &llm.Usage{InputTokens: 100, OutputTokens: 40, CacheCreationInputTokens: 10, CacheReadInputTokens: 6},
|
||||
u2: &llm.Usage{InputTokens: 10, OutputTokens: 5, CacheCreationInputTokens: 1, CacheReadInputTokens: 2},
|
||||
},
|
||||
Tools: usageNoopExecutor{},
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test-model",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
events, err := r.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
got := drainUsage(t, events)
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, 110, got.InputTokens)
|
||||
assert.Equal(t, 45, got.OutputTokens)
|
||||
assert.Equal(t, 11, got.CacheCreationInputTokens)
|
||||
assert.Equal(t, 8, got.CacheReadInputTokens)
|
||||
}
|
||||
|
||||
func TestRun_UsageSingleTurn(t *testing.T) {
|
||||
r := &Runtime{
|
||||
LLM: &twoTurnUsageLLM{
|
||||
u2: &llm.Usage{InputTokens: 7, OutputTokens: 3},
|
||||
},
|
||||
Tools: usageNoopExecutor{},
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test-model",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
// calls=0 path emits a tool call; to get a pure single turn, mark calls so
|
||||
// the first ChatStream takes the text+stop branch.
|
||||
r.LLM.(*twoTurnUsageLLM).calls = 1
|
||||
events, err := r.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
got := drainUsage(t, events)
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, 7, got.InputTokens)
|
||||
assert.Equal(t, 3, got.OutputTokens)
|
||||
}
|
||||
|
||||
func TestRun_UsageNilWhenProviderSilent(t *testing.T) {
|
||||
r := &Runtime{
|
||||
LLM: &twoTurnUsageLLM{calls: 1}, // single turn, u2 nil → EventDone with nil usage
|
||||
Tools: usageNoopExecutor{},
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test-model",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
events, err := r.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
got := drainUsage(t, events)
|
||||
assert.Nil(t, got, "usage must stay nil when the provider never reports it")
|
||||
}
|
||||
+240
-49
@@ -45,7 +45,7 @@ type AgentEvent struct {
|
||||
Result *tool.ToolResult
|
||||
Error error
|
||||
Compaction *compaction.Result // populated for EventCompaction* events
|
||||
Usage *llm.Usage // populated for EventDone when the provider reported it
|
||||
Usage *llm.Usage // on the terminal EventDone, the token total accumulated across all turns of the run (nil if the provider never reported usage); per-turn figures are available via RunTurn's TurnResult.Usage
|
||||
}
|
||||
|
||||
// Runtime is the agent think-act loop.
|
||||
@@ -105,6 +105,14 @@ type Runtime struct {
|
||||
touchedMu sync.Mutex
|
||||
touchedFiles []string
|
||||
|
||||
// spilledIDs records ToolCallIDs whose oversized results have already
|
||||
// been written to the deterministic spill path during this Runtime's
|
||||
// lifetime. Content is immutable per ToolCallID, so once spilled we
|
||||
// skip the (multi-MB) disk re-write on subsequent turns and only
|
||||
// rebuild the in-memory marker.
|
||||
spilledMu sync.Mutex
|
||||
spilledIDs map[string]bool
|
||||
|
||||
// IngestSource controls whether this run's thread is ingested into the KG.
|
||||
// "chat" (or empty) ingests; any other value skips ingest.
|
||||
IngestSource string
|
||||
@@ -114,10 +122,21 @@ type Runtime struct {
|
||||
|
||||
calibrator *tokens.Calibrator
|
||||
|
||||
// calibratorDirty records that the calibrator was updated during this
|
||||
// Run and must be flushed to CalibratorStore once at Run end. Accessed
|
||||
// only on the Run goroutine (EventDone handling + deferred flush), so no
|
||||
// lock is needed.
|
||||
calibratorDirty bool
|
||||
|
||||
// mcpClients holds the MCP client sessions resolved from
|
||||
// AgentSpec.MCPServers. Released by Close. Untouched when MCP is
|
||||
// not used.
|
||||
mcpClients []*mcp.Client
|
||||
|
||||
// runMu enforces the Runtime contract that one session exchange runs at a
|
||||
// time. TryLock lets a second caller receive a normal error instead of
|
||||
// corrupting the shared event channel and run-scoped state.
|
||||
runMu sync.Mutex
|
||||
}
|
||||
|
||||
// Close releases external resources owned by the Runtime — currently
|
||||
@@ -181,14 +200,26 @@ func (r *Runtime) maybeKickoffAsyncCompaction(msgs []llm.Message, parts []llm.Sy
|
||||
}
|
||||
|
||||
// providerSupportsCaching returns true when the runtime's provider implements
|
||||
// Anthropic-style explicit prompt caching.
|
||||
// Anthropic-style explicit prompt caching. The capability interface wins:
|
||||
// a provider block named "platformai" (or "bedrock", or anything else)
|
||||
// wrapping the Anthropic implementation still caches. The name check is
|
||||
// the legacy fallback for custom LLMProvider impls that predate the
|
||||
// capability interface.
|
||||
func (r *Runtime) providerSupportsCaching() bool {
|
||||
if pc, ok := r.LLM.(llm.PromptCachingProvider); ok {
|
||||
return pc.SupportsPromptCaching()
|
||||
}
|
||||
return r.Provider == "anthropic"
|
||||
}
|
||||
|
||||
// providerSupportsMidLoopCompaction returns true for hosted frontier
|
||||
// providers that handle mid-loop summary injection cleanly.
|
||||
// providers that handle mid-loop summary injection cleanly. Same
|
||||
// capability-over-name rule as providerSupportsCaching: an
|
||||
// Anthropic-shaped provider under a custom name qualifies.
|
||||
func (r *Runtime) providerSupportsMidLoopCompaction() bool {
|
||||
if pc, ok := r.LLM.(llm.PromptCachingProvider); ok && pc.SupportsPromptCaching() {
|
||||
return true
|
||||
}
|
||||
switch r.Provider {
|
||||
case "anthropic", "openai", "gemini":
|
||||
return true
|
||||
@@ -223,6 +254,18 @@ func (r *Runtime) snapshotTouchedFiles() []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// prune shortens oversized tool results in msgs, spilling to disk where
|
||||
// configured. It carries the Runtime's per-Run spilled-ID set so a result
|
||||
// already spilled this Run is not re-written to disk on subsequent turns.
|
||||
func (r *Runtime) prune(msgs []llm.Message, spillCfg spillConfig) {
|
||||
r.spilledMu.Lock()
|
||||
if r.spilledIDs == nil {
|
||||
r.spilledIDs = map[string]bool{}
|
||||
}
|
||||
pruneToolResults(msgs, r.maxToolResultLen(), spillCfg, r.spilledIDs)
|
||||
r.spilledMu.Unlock()
|
||||
}
|
||||
|
||||
// isFileTool reports whether a tool name's input contains a "path" field.
|
||||
func isFileTool(name string) bool {
|
||||
switch name {
|
||||
@@ -234,22 +277,46 @@ func isFileTool(name string) bool {
|
||||
|
||||
// Run executes the agent loop for a user message, returning a channel of events.
|
||||
func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageContent) (<-chan AgentEvent, error) {
|
||||
r.events = make(chan AgentEvent, 100)
|
||||
if !r.runMu.TryLock() {
|
||||
return nil, fmt.Errorf("runtime is already running")
|
||||
}
|
||||
events := make(chan AgentEvent, 100)
|
||||
r.events = events
|
||||
tr := TraceFrom(ctx)
|
||||
tr.Mark("agent.run.start", "user_msg_len", len(userMsg), "images", len(images))
|
||||
|
||||
go func() {
|
||||
defer close(r.events)
|
||||
defer close(events)
|
||||
defer r.runMu.Unlock()
|
||||
defer tr.Summary()
|
||||
|
||||
// Flush the per-session calibrator once at Run end (all exit paths:
|
||||
// normal, error, abort) instead of writing to disk on every LLM
|
||||
// round. EventDone sets calibratorDirty when it folds in a usage
|
||||
// sample; this defer persists the final state. Registered here so it
|
||||
// runs regardless of which return below fires.
|
||||
defer func() {
|
||||
if r.calibratorDirty && r.CalibratorStore != nil && r.Session != nil && r.calibrator != nil {
|
||||
ratio, count := r.calibrator.Snapshot()
|
||||
r.CalibratorStore.Save(r.AgentID, r.Session.Key, ratio, count)
|
||||
}
|
||||
}()
|
||||
|
||||
// stopReason is read by the OnStop deferred hook below. Each early
|
||||
// return path reassigns it before returning. Default is "max_turns"
|
||||
// so the natural fall-through (loop exhausted MaxTurns) records the
|
||||
// right reason without an explicit assignment at that exit.
|
||||
stopReason := "max_turns"
|
||||
if hook := r.AgentLoop.Hooks.OnStop; hook != nil {
|
||||
defer func() { hook(ctx, stopReason) }()
|
||||
defer func() { callOnStopHook(ctx, hook, stopReason) }()
|
||||
}
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
stopReason = "error"
|
||||
err := recoveredPanicError("runtime", recovered)
|
||||
r.emit(AgentEvent{Type: EventError, Error: err})
|
||||
}
|
||||
}()
|
||||
|
||||
// OnUserPromptSubmit may rewrite prompt and/or images BEFORE the
|
||||
// session sees them. Returning err aborts Run with EventError.
|
||||
@@ -326,6 +393,26 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
// Computed once per Run so the date stays stable across turns.
|
||||
dateLine := FormatDateLine(time.Now())
|
||||
|
||||
// Tool defs are invariant for the whole Run (tools and permission don't
|
||||
// change mid-Run), so normalize once instead of per turn (P3).
|
||||
toolDefs := r.Tools.ToolDefs()
|
||||
if r.Permission != nil {
|
||||
toolDefs = r.Permission.FilterToolDefs(toolDefs, r.AgentID)
|
||||
}
|
||||
sort.SliceStable(toolDefs, func(i, j int) bool {
|
||||
return toolDefs[i].Name < toolDefs[j].Name
|
||||
})
|
||||
toolDefs, diags := r.LLM.NormalizeToolSchema(toolDefs)
|
||||
for _, d := range diags {
|
||||
slog.Info("tool schema normalized",
|
||||
"tool", d.ToolName,
|
||||
"field", d.Field,
|
||||
"action", d.Action,
|
||||
"reason", d.Reason)
|
||||
}
|
||||
|
||||
var runUsage *llm.Usage // accumulated across all turns; nil until first reported
|
||||
|
||||
for turn := 0; turn < maxTurns; turn++ {
|
||||
if ctx.Err() != nil {
|
||||
stopReason = "aborted"
|
||||
@@ -364,23 +451,8 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
msgs := assembleMessages(history)
|
||||
|
||||
spillCfg := spillConfig{Workspace: r.Workspace, SessionKey: r.Session.Key}
|
||||
pruneToolResults(msgs, maxToolResultLen, spillCfg)
|
||||
r.prune(msgs, spillCfg)
|
||||
|
||||
toolDefs := r.Tools.ToolDefs()
|
||||
if r.Permission != nil {
|
||||
toolDefs = r.Permission.FilterToolDefs(toolDefs, r.AgentID)
|
||||
}
|
||||
sort.SliceStable(toolDefs, func(i, j int) bool {
|
||||
return toolDefs[i].Name < toolDefs[j].Name
|
||||
})
|
||||
toolDefs, diags := r.LLM.NormalizeToolSchema(toolDefs)
|
||||
for _, d := range diags {
|
||||
slog.Info("tool schema normalized",
|
||||
"tool", d.ToolName,
|
||||
"field", d.Field,
|
||||
"action", d.Action,
|
||||
"reason", d.Reason)
|
||||
}
|
||||
tr.Mark("context.assemble", "turn", turn, "msgs", len(msgs), "tools", len(toolDefs), "sysprompt_chars", len(staticText)+len(dynamicSuffix), "dur_ms_local", time.Since(phaseStart).Milliseconds())
|
||||
|
||||
// Wait briefly on any in-flight async compaction kicked off by
|
||||
@@ -390,7 +462,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
|
||||
history = r.Session.View()
|
||||
msgs = assembleMessages(history)
|
||||
pruneToolResults(msgs, maxToolResultLen, spillCfg)
|
||||
r.prune(msgs, spillCfg)
|
||||
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
|
||||
}
|
||||
}
|
||||
@@ -416,7 +488,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
|
||||
history = r.Session.View()
|
||||
msgs = assembleMessages(history)
|
||||
pruneToolResults(msgs, maxToolResultLen, spillCfg)
|
||||
r.prune(msgs, spillCfg)
|
||||
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
|
||||
} else {
|
||||
r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res})
|
||||
@@ -449,7 +521,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
|
||||
history = r.Session.View()
|
||||
msgs = assembleMessages(history)
|
||||
pruneToolResults(msgs, maxToolResultLen, spillCfg)
|
||||
r.prune(msgs, spillCfg)
|
||||
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
|
||||
req.Messages = msgs
|
||||
stream, err = r.LLM.ChatStream(ctx, req)
|
||||
@@ -475,8 +547,8 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
}
|
||||
|
||||
var textContent strings.Builder
|
||||
var lastUsage *llm.Usage
|
||||
var toolCalls []llm.ToolCall
|
||||
var thinkingBlocks []session.ThinkingBlockData
|
||||
gotFirstToken := false
|
||||
|
||||
streamingOn := r.streamingToolsEnabled()
|
||||
@@ -485,6 +557,10 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
|
||||
streamSource := stream
|
||||
retriedNonStreaming := false
|
||||
preTokenRetried := false
|
||||
retriedRefusal := false
|
||||
var refused bool
|
||||
var refusalCategory string
|
||||
streamLoop:
|
||||
for {
|
||||
for event := range streamSource {
|
||||
@@ -504,6 +580,14 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
}
|
||||
r.emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall})
|
||||
|
||||
case llm.EventThinkingBlock:
|
||||
if event.ThinkingBlock != nil {
|
||||
thinkingBlocks = append(thinkingBlocks, session.ThinkingBlockData{
|
||||
Thinking: event.ThinkingBlock.Thinking,
|
||||
Signature: event.ThinkingBlock.Signature,
|
||||
})
|
||||
}
|
||||
|
||||
case llm.EventToolCallDone:
|
||||
if event.ToolCall == nil {
|
||||
continue
|
||||
@@ -527,18 +611,35 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
}()
|
||||
|
||||
case llm.EventDone:
|
||||
refused = event.StopReason == llm.StopReasonRefusal
|
||||
refusalCategory = event.StopCategory
|
||||
if event.Usage != nil {
|
||||
lastUsage = event.Usage
|
||||
runUsage = addUsage(runUsage, event.Usage)
|
||||
}
|
||||
if event.Usage != nil && r.calibrator != nil {
|
||||
// Recompute the estimate on the CURRENT msgs (which may
|
||||
// have been reassembled by mid-turn compaction) so the
|
||||
// calibration ratio matches event.Usage.InputTokens, as
|
||||
// the pre-debounce code did. The P8 change only debounces
|
||||
// the disk write (calibratorDirty + deferred flush), not
|
||||
// the estimate computation.
|
||||
r.calibrator.Update(event.Usage.InputTokens, tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs))
|
||||
if r.CalibratorStore != nil && r.Session != nil {
|
||||
ratio, count := r.calibrator.Snapshot()
|
||||
r.CalibratorStore.Save(r.AgentID, r.Session.Key, ratio, count)
|
||||
}
|
||||
r.calibratorDirty = true
|
||||
}
|
||||
|
||||
case llm.EventError:
|
||||
if !gotFirstToken && !preTokenRetried {
|
||||
if newStream, ok := r.recoverFromPreTokenError(ctx, event.Error, &req, &msgs, spillCfg); ok {
|
||||
preTokenRetried = true
|
||||
drainKickoffs(kickoffs)
|
||||
kickoffs = map[string]chan kickoffResult{}
|
||||
textContent.Reset()
|
||||
toolCalls = nil
|
||||
kickoffStopped = false
|
||||
streamSource = newStream
|
||||
continue streamLoop
|
||||
}
|
||||
}
|
||||
if gotFirstToken && !retriedNonStreaming {
|
||||
if ns, ok := r.LLM.(llm.NonStreamingProvider); ok {
|
||||
slog.Warn("stream died mid-flight; retrying as non-streaming",
|
||||
@@ -567,6 +668,53 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Classifier/model refusal (Claude Fable 5+): HTTP 200,
|
||||
// stop_reason=refusal, usually no content. Without handling,
|
||||
// the turn ends as a silent empty success. Retry once on the
|
||||
// fallback model (refusals are model-specific — Opus-tier
|
||||
// has no bio/cyber classifiers); otherwise synthesize a
|
||||
// visible explanation. Mid-stream refusals discard partial
|
||||
// output per the API contract.
|
||||
if refused {
|
||||
if !retriedRefusal && r.FallbackModel != "" && r.FallbackModel != req.Model {
|
||||
slog.Warn("model refused; retrying on fallback model",
|
||||
"agent", r.AgentID,
|
||||
"primary", req.Model,
|
||||
"fallback", r.FallbackModel,
|
||||
"category", refusalCategory)
|
||||
tr.Mark("llm.refusal_fallback", "turn", turn,
|
||||
"primary", req.Model, "fallback", r.FallbackModel,
|
||||
"category", refusalCategory)
|
||||
textContent.Reset()
|
||||
toolCalls = nil
|
||||
drainKickoffs(kickoffs)
|
||||
kickoffs = map[string]chan kickoffResult{}
|
||||
gotFirstToken = false
|
||||
kickoffStopped = false
|
||||
refused = false
|
||||
retriedRefusal = true
|
||||
req.Model = r.FallbackModel
|
||||
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
|
||||
if retryErr != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: retryErr})
|
||||
return
|
||||
}
|
||||
streamSource = retryStream
|
||||
continue streamLoop
|
||||
}
|
||||
textContent.Reset()
|
||||
toolCalls = nil
|
||||
drainKickoffs(kickoffs)
|
||||
note := "The model declined this request (safety classifier"
|
||||
if refusalCategory != "" {
|
||||
note += ", category: " + refusalCategory
|
||||
}
|
||||
note += "). Try rephrasing, or switch this agent to a model without these classifiers."
|
||||
textContent.WriteString(note)
|
||||
r.emit(AgentEvent{Type: EventTextDelta, Text: note})
|
||||
}
|
||||
break streamLoop
|
||||
}
|
||||
tr.Mark("llm.stream_end", "turn", turn,
|
||||
@@ -574,8 +722,13 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
"text_chars", textContent.Len(),
|
||||
"tool_calls", len(toolCalls))
|
||||
|
||||
if textContent.Len() > 0 {
|
||||
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
|
||||
if textContent.Len() > 0 || len(thinkingBlocks) > 0 {
|
||||
if len(thinkingBlocks) > 0 {
|
||||
r.Session.Append(session.AssistantMessageEntryWithThinking(textContent.String(), thinkingBlocks))
|
||||
} else {
|
||||
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
|
||||
}
|
||||
thinkingBlocks = nil
|
||||
if r.KG != nil {
|
||||
r.kgMu.Lock()
|
||||
thread = append(thread, Message{
|
||||
@@ -592,7 +745,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
}
|
||||
tr.Mark("agent.done", "turn", turn, "reason", "no_tool_calls")
|
||||
stopReason = "completed"
|
||||
r.emit(AgentEvent{Type: EventDone, Usage: lastUsage})
|
||||
r.emit(AgentEvent{Type: EventDone, Usage: runUsage})
|
||||
r.maybeKickoffAsyncCompaction(msgs, parts, toolDefs)
|
||||
return
|
||||
}
|
||||
@@ -676,7 +829,43 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
})
|
||||
}()
|
||||
|
||||
return r.events, nil
|
||||
return events, nil
|
||||
}
|
||||
|
||||
// recoverFromPreTokenError attempts the same recovery the synchronous
|
||||
// ChatStream-error path performs, for an error delivered via EventError
|
||||
// before any token arrived (Anthropic/Gemini deliver HTTP errors this way).
|
||||
// Returns a fresh stream to resume from and true if recovered; false if the
|
||||
// error is not recoverable (caller should abort). May mutate *req (model
|
||||
// swap) and the session (compaction), and reassigns *msgs on compaction.
|
||||
func (r *Runtime) recoverFromPreTokenError(ctx context.Context, err error, req *llm.ChatRequest, msgs *[]llm.Message, spillCfg spillConfig) (<-chan llm.ChatEvent, bool) {
|
||||
if compaction.IsContextOverflow(err) && r.Compaction != nil {
|
||||
r.emit(AgentEvent{Type: EventCompactionStart})
|
||||
res, _ := r.Compaction.MaybeCompact(ctx, r.Session, compaction.ReasonReactive, "")
|
||||
if res.Compacted {
|
||||
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
|
||||
history := r.Session.View()
|
||||
newMsgs := assembleMessages(history)
|
||||
r.prune(newMsgs, spillCfg)
|
||||
newMsgs = prependPostCompactRestore(newMsgs, r.snapshotTouchedFiles())
|
||||
*msgs = newMsgs
|
||||
req.Messages = newMsgs
|
||||
if s, e := r.LLM.ChatStream(ctx, *req); e == nil {
|
||||
return s, true
|
||||
}
|
||||
} else {
|
||||
r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res})
|
||||
}
|
||||
}
|
||||
if r.FallbackModel != "" && r.FallbackModel != req.Model && llm.IsRetryableModelError(err) {
|
||||
slog.Info("llm fallback model engaged (stream error)",
|
||||
"agent", r.AgentID, "primary", req.Model, "fallback", r.FallbackModel, "err", err.Error())
|
||||
req.Model = r.FallbackModel
|
||||
if s, e := r.LLM.ChatStream(ctx, *req); e == nil {
|
||||
return s, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// RunSync is a convenience method that runs the agent and collects the
|
||||
@@ -692,6 +881,8 @@ func (r *Runtime) RunSync(ctx context.Context, userMsg string, images []llm.Imag
|
||||
switch event.Type {
|
||||
case EventTextDelta:
|
||||
response.WriteString(event.Text)
|
||||
case EventAborted:
|
||||
return response.String(), context.Canceled
|
||||
case EventError:
|
||||
return response.String(), event.Error
|
||||
}
|
||||
@@ -721,28 +912,28 @@ func (r *Runtime) dispatchTool(
|
||||
// BeforeToolUse fires before the PermissionChecker. A hook denial
|
||||
// has the same observable shape as a Permission.Check denial.
|
||||
if hook := r.AgentLoop.Hooks.BeforeToolUse; hook != nil {
|
||||
d, err := hook(ctx, tc.Name, tc.Input)
|
||||
d, err := callBeforeToolHook(ctx, hook, tc.Name, tc.Input)
|
||||
if err != nil {
|
||||
res := r.appendDenialResult(tc.ID, err.Error(), kgThread)
|
||||
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
|
||||
after(ctx, tc.Name, tc.Input, res)
|
||||
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
|
||||
}
|
||||
return res, false
|
||||
}
|
||||
if !d.Allow {
|
||||
res := r.appendDenialResult(tc.ID, d.Reason, kgThread)
|
||||
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
|
||||
after(ctx, tc.Name, tc.Input, res)
|
||||
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
|
||||
}
|
||||
return res, false
|
||||
}
|
||||
}
|
||||
|
||||
if r.Permission != nil {
|
||||
if d := r.Permission.Check(ctx, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
|
||||
if d := callPermissionCheck(ctx, r.Permission, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
|
||||
res := r.appendDenialResult(tc.ID, d.Reason, kgThread)
|
||||
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
|
||||
after(ctx, tc.Name, tc.Input, res)
|
||||
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
|
||||
}
|
||||
return res, false
|
||||
}
|
||||
@@ -752,7 +943,7 @@ func (r *Runtime) dispatchTool(
|
||||
return r.appendAbortedResult(tc.ID, kgThread), true
|
||||
}
|
||||
|
||||
result, err := r.Tools.Execute(ctx, tc.Name, tc.Input)
|
||||
result, err := callToolExecute(ctx, r.Tools, tc.Name, tc.Input)
|
||||
if err != nil {
|
||||
result = tool.ToolResult{Error: err.Error()}
|
||||
}
|
||||
@@ -778,7 +969,7 @@ func (r *Runtime) dispatchTool(
|
||||
}
|
||||
|
||||
if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil {
|
||||
hook(ctx, tc.Name, tc.Input, result)
|
||||
callAfterToolHook(ctx, hook, tc.Name, tc.Input, result)
|
||||
}
|
||||
|
||||
return result, false
|
||||
@@ -789,27 +980,27 @@ func (r *Runtime) dispatchTool(
|
||||
// streaming kickoff goroutines.
|
||||
func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (result tool.ToolResult, aborted bool) {
|
||||
if hook := r.AgentLoop.Hooks.BeforeToolUse; hook != nil {
|
||||
d, err := hook(ctx, tc.Name, tc.Input)
|
||||
d, err := callBeforeToolHook(ctx, hook, tc.Name, tc.Input)
|
||||
if err != nil {
|
||||
res := tool.ToolResult{Error: err.Error()}
|
||||
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
|
||||
after(ctx, tc.Name, tc.Input, res)
|
||||
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
|
||||
}
|
||||
return res, false
|
||||
}
|
||||
if !d.Allow {
|
||||
res := tool.ToolResult{Error: d.Reason}
|
||||
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
|
||||
after(ctx, tc.Name, tc.Input, res)
|
||||
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
|
||||
}
|
||||
return res, false
|
||||
}
|
||||
}
|
||||
if r.Permission != nil {
|
||||
if d := r.Permission.Check(ctx, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
|
||||
if d := callPermissionCheck(ctx, r.Permission, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
|
||||
res := tool.ToolResult{Error: d.Reason}
|
||||
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
|
||||
after(ctx, tc.Name, tc.Input, res)
|
||||
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
|
||||
}
|
||||
return res, false
|
||||
}
|
||||
@@ -817,7 +1008,7 @@ func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (resu
|
||||
if ctx.Err() != nil {
|
||||
return tool.ToolResult{Error: "aborted by user"}, true
|
||||
}
|
||||
result, err := r.Tools.Execute(ctx, tc.Name, tc.Input)
|
||||
result, err := callToolExecute(ctx, r.Tools, tc.Name, tc.Input)
|
||||
if err != nil {
|
||||
result = tool.ToolResult{Error: err.Error()}
|
||||
}
|
||||
@@ -828,7 +1019,7 @@ func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (resu
|
||||
r.recordFileTouch(extractPathFromInput(tc.Input))
|
||||
}
|
||||
if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil {
|
||||
hook(ctx, tc.Name, tc.Input, result)
|
||||
callAfterToolHook(ctx, hook, tc.Name, tc.Input, result)
|
||||
}
|
||||
return result, false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
// TurnResult describes the outcome of a single RunTurn call.
|
||||
type TurnResult struct {
|
||||
Done bool // true when no tool calls were produced (loop should stop)
|
||||
StopReason string // "continue" | "completed" | "error" | "aborted"
|
||||
Entries []session.SessionEntry // entries appended during THIS turn, in order
|
||||
Err error
|
||||
Usage *llm.Usage
|
||||
}
|
||||
|
||||
// TurnEmit is an optional live-streaming callback. Pass nil for headless
|
||||
// execution (e.g. durable replay, where live emission must be suppressed).
|
||||
type TurnEmit func(AgentEvent)
|
||||
|
||||
// RunTurn executes exactly one turn of the agent loop against the current
|
||||
// session and returns the entries it produced. The first call of a session
|
||||
// passes the user message; continuation calls pass "".
|
||||
//
|
||||
// RunTurn is the durable unit for a per-turn driver: each call can be wrapped
|
||||
// as a checkpointed step whose return value (TurnResult.Entries) rebuilds
|
||||
// session state on replay. It differs from Run by design: it is headless
|
||||
// (live events go only through the emit callback, never an internal channel),
|
||||
// it dispatches tool calls serially (Run parallelizes concurrency-safe
|
||||
// batches), and it does NOT perform compaction, streaming-tool kickoff, or the
|
||||
// trace/slog emissions that Run's emitToolResult produces (those remain Run's
|
||||
// responsibility). It DOES perform bounded-synchronous knowledge-graph recall on
|
||||
// the first round of an exchange (folding the hint into the system prompt) and
|
||||
// async knowledge-graph ingest on the completing round.
|
||||
func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.ImageContent, emit TurnEmit) (TurnResult, error) {
|
||||
if emit == nil {
|
||||
emit = func(AgentEvent) {}
|
||||
}
|
||||
startLen := len(r.Session.Entries())
|
||||
|
||||
if userMsg != "" || len(images) > 0 {
|
||||
if len(images) > 0 {
|
||||
var imgData []session.ImageData
|
||||
for _, img := range images {
|
||||
imgData = append(imgData, session.ImageData{
|
||||
MimeType: img.MimeType,
|
||||
Data: base64.StdEncoding.EncodeToString(img.Data),
|
||||
})
|
||||
}
|
||||
r.Session.Append(session.UserMessageWithImagesEntry(userMsg, imgData))
|
||||
} else {
|
||||
r.Session.Append(session.UserMessageEntry(userMsg))
|
||||
}
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return r.turnSlice(startLen, true, "aborted", nil, ctx.Err()), nil
|
||||
}
|
||||
|
||||
history := r.Session.View()
|
||||
msgs := assembleMessages(history)
|
||||
toolDefs := r.Tools.ToolDefs()
|
||||
if r.Permission != nil {
|
||||
toolDefs = r.Permission.FilterToolDefs(toolDefs, r.AgentID)
|
||||
}
|
||||
sort.SliceStable(toolDefs, func(i, j int) bool { return toolDefs[i].Name < toolDefs[j].Name })
|
||||
toolDefs, _ = r.LLM.NormalizeToolSchema(toolDefs)
|
||||
|
||||
// KG recall (first round of the exchange only): bounded-synchronous so a
|
||||
// slow embedder cannot stall the turn. The hint is a non-cached suffix —
|
||||
// it varies per query, so caching it would poison the static prefix cache.
|
||||
var kgHint string
|
||||
if r.KG != nil && (userMsg != "" || len(images) > 0) && r.KG.ShouldRecall(userMsg) {
|
||||
rctx, cancel := context.WithTimeout(ctx, 800*time.Millisecond)
|
||||
kgHint = r.KG.Recall(rctx, userMsg)
|
||||
cancel()
|
||||
}
|
||||
|
||||
parts := []llm.SystemPromptPart{{Text: r.StaticSystemPrompt, Cache: true}}
|
||||
if kgHint != "" {
|
||||
parts = append(parts, llm.SystemPromptPart{Text: kgHint, Cache: false})
|
||||
}
|
||||
req := llm.ChatRequest{
|
||||
Model: r.Model,
|
||||
Messages: msgs,
|
||||
Tools: toolDefs,
|
||||
MaxTokens: 8192,
|
||||
SystemPromptParts: parts,
|
||||
CacheLastMessage: r.providerSupportsCaching(),
|
||||
Reasoning: r.Reasoning,
|
||||
}
|
||||
|
||||
stream, err := r.LLM.ChatStream(ctx, req)
|
||||
if err != nil {
|
||||
if r.FallbackModel != "" && r.FallbackModel != req.Model && llm.IsRetryableModelError(err) {
|
||||
req.Model = r.FallbackModel
|
||||
stream, err = r.LLM.ChatStream(ctx, req)
|
||||
}
|
||||
if err != nil {
|
||||
emit(AgentEvent{Type: EventError, Error: fmt.Errorf("llm error: %w", err)})
|
||||
return r.turnSlice(startLen, true, "error", nil, err), nil
|
||||
}
|
||||
}
|
||||
|
||||
var textContent strings.Builder
|
||||
var toolCalls []llm.ToolCall
|
||||
var thinkingBlocks []session.ThinkingBlockData
|
||||
var lastUsage *llm.Usage
|
||||
retriedRefusal := false
|
||||
streamLoop:
|
||||
for {
|
||||
var refused bool
|
||||
var refusalCategory string
|
||||
for event := range stream {
|
||||
switch event.Type {
|
||||
case llm.EventTextDelta:
|
||||
textContent.WriteString(event.Text)
|
||||
emit(AgentEvent{Type: EventTextDelta, Text: event.Text})
|
||||
case llm.EventToolCallStart:
|
||||
emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall})
|
||||
case llm.EventThinkingBlock:
|
||||
if event.ThinkingBlock != nil {
|
||||
thinkingBlocks = append(thinkingBlocks, session.ThinkingBlockData{
|
||||
Thinking: event.ThinkingBlock.Thinking,
|
||||
Signature: event.ThinkingBlock.Signature,
|
||||
})
|
||||
}
|
||||
case llm.EventToolCallDone:
|
||||
if event.ToolCall != nil {
|
||||
toolCalls = append(toolCalls, *event.ToolCall)
|
||||
}
|
||||
case llm.EventDone:
|
||||
refused = event.StopReason == llm.StopReasonRefusal
|
||||
refusalCategory = event.StopCategory
|
||||
if event.Usage != nil {
|
||||
lastUsage = event.Usage
|
||||
}
|
||||
case llm.EventError:
|
||||
emit(AgentEvent{Type: EventError, Error: event.Error})
|
||||
return r.turnSlice(startLen, true, "error", lastUsage, event.Error), nil
|
||||
}
|
||||
}
|
||||
|
||||
// Same refusal contract as Run: retry once on the fallback model,
|
||||
// else surface a visible explanation instead of empty silence.
|
||||
if refused {
|
||||
if !retriedRefusal && r.FallbackModel != "" && r.FallbackModel != req.Model {
|
||||
retriedRefusal = true
|
||||
textContent.Reset()
|
||||
toolCalls = nil
|
||||
req.Model = r.FallbackModel
|
||||
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
|
||||
if retryErr != nil {
|
||||
emit(AgentEvent{Type: EventError, Error: retryErr})
|
||||
return r.turnSlice(startLen, true, "error", lastUsage, retryErr), nil
|
||||
}
|
||||
stream = retryStream
|
||||
continue streamLoop
|
||||
}
|
||||
textContent.Reset()
|
||||
toolCalls = nil
|
||||
note := "The model declined this request (safety classifier"
|
||||
if refusalCategory != "" {
|
||||
note += ", category: " + refusalCategory
|
||||
}
|
||||
note += "). Try rephrasing, or switch this agent to a model without these classifiers."
|
||||
textContent.WriteString(note)
|
||||
emit(AgentEvent{Type: EventTextDelta, Text: note})
|
||||
}
|
||||
break streamLoop
|
||||
}
|
||||
|
||||
if textContent.Len() > 0 || len(thinkingBlocks) > 0 {
|
||||
if len(thinkingBlocks) > 0 {
|
||||
r.Session.Append(session.AssistantMessageEntryWithThinking(textContent.String(), thinkingBlocks))
|
||||
} else {
|
||||
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
|
||||
}
|
||||
}
|
||||
|
||||
if len(toolCalls) == 0 {
|
||||
// Exchange complete: ingest the full thread once. Background + best-effort
|
||||
// (the KG spawns its own bounded goroutine), so it never delays the turn.
|
||||
// context.Background() because the request ctx may be cancelling and the
|
||||
// ingest goroutine deliberately outlives the turn. Unlike Run, RunTurn does
|
||||
// not pre-filter trivial threads or gate on IngestSource: the KG impl owns
|
||||
// its own growth gate (so single-message threads are skipped there), and the
|
||||
// only RunTurn caller today is the chat serve loop. TODO: if a reviewer or
|
||||
// subagent path is ever migrated to RunTurn, add an IngestSource-style gate
|
||||
// here so non-chat transcripts are not ingested.
|
||||
if r.KG != nil {
|
||||
r.KG.Ingest(context.Background(), sessionThread(r.Session.View()))
|
||||
}
|
||||
emit(AgentEvent{Type: EventDone, Usage: lastUsage})
|
||||
return r.turnSlice(startLen, true, "completed", lastUsage, nil), nil
|
||||
}
|
||||
|
||||
// RunTurn dispatches tool calls serially by design: deterministic
|
||||
// ordering keeps durable replay simple, and parallel/concurrency-safe
|
||||
// batching deliberately stays in Run (see the doc comment). dispatchTool
|
||||
// appends the tool_call and tool_result entries to the session.
|
||||
for _, tc := range toolCalls {
|
||||
result, aborted := r.dispatchTool(ctx, tc, nil)
|
||||
emit(AgentEvent{Type: EventToolResult, ToolCall: &tc, Result: &result})
|
||||
if aborted {
|
||||
return r.turnSlice(startLen, true, "aborted", lastUsage, ctx.Err()), nil
|
||||
}
|
||||
}
|
||||
|
||||
return r.turnSlice(startLen, false, "continue", lastUsage, nil), nil
|
||||
}
|
||||
|
||||
// turnSlice builds a TurnResult from the entries appended since startLen.
|
||||
// It assumes a single active turn per session: the delta entries[startLen:]
|
||||
// is correct only because no other goroutine appends to this session
|
||||
// concurrently during the turn.
|
||||
func (r *Runtime) turnSlice(startLen int, done bool, reason string, usage *llm.Usage, err error) TurnResult {
|
||||
all := r.Session.Entries()
|
||||
var delta []session.SessionEntry
|
||||
if startLen <= len(all) {
|
||||
delta = append(delta, all[startLen:]...)
|
||||
}
|
||||
return TurnResult{Done: done, StopReason: reason, Entries: delta, Usage: usage, Err: err}
|
||||
}
|
||||
|
||||
// sessionThread converts session history into the minimal []Message the
|
||||
// KnowledgeGraph ingests, mirroring how Run accumulates its thread: user and
|
||||
// assistant messages by role+text, tool calls as "[tool: name]\n<input>"
|
||||
// (assistant), tool results as their output or "[error] <err>" (user).
|
||||
// Compaction/meta and non-user/assistant message entries are skipped — the
|
||||
// thread carries only conversation turns and tool exchanges.
|
||||
// On the runtime's per-turn serve path each call sees one turn's fresh session,
|
||||
// so a compaction summary's absence here is intentional, not a gap.
|
||||
func sessionThread(history []session.SessionEntry) []Message {
|
||||
var thread []Message
|
||||
for _, e := range history {
|
||||
switch e.Type {
|
||||
case session.EntryTypeMessage:
|
||||
if e.Role != "user" && e.Role != "assistant" {
|
||||
continue // skip system/summary messages
|
||||
}
|
||||
var d session.MessageData
|
||||
if json.Unmarshal(e.Data, &d) != nil {
|
||||
continue
|
||||
}
|
||||
thread = append(thread, Message{Role: e.Role, Content: d.Text})
|
||||
case session.EntryTypeToolCall:
|
||||
var d session.ToolCallData
|
||||
if json.Unmarshal(e.Data, &d) != nil {
|
||||
continue
|
||||
}
|
||||
thread = append(thread, Message{
|
||||
Role: "assistant",
|
||||
Content: fmt.Sprintf("[tool: %s]\n%s", d.Tool, string(d.Input)),
|
||||
})
|
||||
case session.EntryTypeToolResult:
|
||||
var d session.ToolResultData
|
||||
if json.Unmarshal(e.Data, &d) != nil {
|
||||
continue
|
||||
}
|
||||
content := d.Output
|
||||
if d.Error != "" {
|
||||
content = "[error] " + d.Error
|
||||
}
|
||||
thread = append(thread, Message{Role: "user", Content: content})
|
||||
}
|
||||
}
|
||||
return thread
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSessionThread_RendersEntries(t *testing.T) {
|
||||
sess := session.NewSession("a", "k")
|
||||
sess.Append(session.UserMessageEntry("hello"))
|
||||
sess.Append(session.AssistantMessageEntry("hi there"))
|
||||
sess.Append(session.ToolCallEntry("tc1", "echo", json.RawMessage(`{"x":1}`)))
|
||||
sess.Append(session.ToolResultEntry("tc1", "echoed", "", nil))
|
||||
sess.Append(session.ToolResultEntry("tc2", "", "boom", nil))
|
||||
|
||||
thread := sessionThread(sess.View())
|
||||
|
||||
require.Equal(t, []Message{
|
||||
{Role: "user", Content: "hello"},
|
||||
{Role: "assistant", Content: "hi there"},
|
||||
{Role: "assistant", Content: "[tool: echo]\n{\"x\":1}"},
|
||||
{Role: "user", Content: "echoed"},
|
||||
{Role: "user", Content: "[error] boom"},
|
||||
}, thread)
|
||||
}
|
||||
|
||||
func TestSessionThread_SkipsCompaction(t *testing.T) {
|
||||
sess := session.NewSession("a", "k")
|
||||
// Compaction is appended FIRST so the entries that follow remain on the
|
||||
// View() walk-back path. View() stops its back-walk at the most recent
|
||||
// compaction (inclusive), so appending user/assistant AFTER it yields
|
||||
// View() == [compaction, user, assistant] — the compaction is genuinely
|
||||
// present in the slice handed to sessionThread, exercising the skip path.
|
||||
// (Appending compaction last would make it the leaf, and View() would
|
||||
// return only [compaction], never reaching the messages.)
|
||||
sess.Append(session.CompactionEntry("summary", "", "", "m", 0, 0, 0))
|
||||
sess.Append(session.UserMessageEntry("hello"))
|
||||
sess.Append(session.AssistantMessageEntry("hi"))
|
||||
|
||||
view := sess.View()
|
||||
require.Equal(t, session.EntryTypeCompaction, view[0].Type, "View() must include the compaction entry to exercise the skip")
|
||||
|
||||
got := sessionThread(view)
|
||||
require.Equal(t, []Message{
|
||||
{Role: "user", Content: "hello"},
|
||||
{Role: "assistant", Content: "hi"},
|
||||
}, got)
|
||||
}
|
||||
|
||||
func TestSessionThread_SkipsUndecodableEntry(t *testing.T) {
|
||||
history := []session.SessionEntry{
|
||||
{Type: session.EntryTypeToolCall, Data: []byte("not json")},
|
||||
session.UserMessageEntry("after"),
|
||||
}
|
||||
got := sessionThread(history)
|
||||
require.Equal(t, []Message{{Role: "user", Content: "after"}}, got)
|
||||
}
|
||||
|
||||
func TestSessionThread_Empty(t *testing.T) {
|
||||
require.Nil(t, sessionThread(nil))
|
||||
}
|
||||
|
||||
// fakeKG is a controllable KnowledgeGraph for RunTurn wiring tests.
|
||||
type fakeKG struct {
|
||||
shouldRecall bool
|
||||
recallReturn string
|
||||
recallDelay time.Duration
|
||||
recallCalls int
|
||||
recallQuery string
|
||||
|
||||
ingestCalls int
|
||||
ingestThreads [][]Message
|
||||
}
|
||||
|
||||
func (f *fakeKG) ShouldRecall(q string) bool { return f.shouldRecall }
|
||||
func (f *fakeKG) Recall(ctx context.Context, q string) string {
|
||||
f.recallCalls++
|
||||
f.recallQuery = q
|
||||
if f.recallDelay > 0 {
|
||||
select {
|
||||
case <-time.After(f.recallDelay):
|
||||
case <-ctx.Done():
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return f.recallReturn
|
||||
}
|
||||
func (f *fakeKG) Ingest(_ context.Context, thread []Message) {
|
||||
f.ingestCalls++
|
||||
f.ingestThreads = append(f.ingestThreads, thread)
|
||||
}
|
||||
|
||||
func TestRunTurn_RecallInjectedIntoPrompt(t *testing.T) {
|
||||
var captured []llm.SystemPromptPart
|
||||
cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }}
|
||||
kg := &fakeKG{shouldRecall: true, recallReturn: "Relevant memories:\n- the user likes tea\n"}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
|
||||
AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg,
|
||||
}
|
||||
_, err := rt.RunTurn(context.Background(), "what do I like?", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, kg.recallCalls)
|
||||
require.Equal(t, "what do I like?", kg.recallQuery)
|
||||
|
||||
require.GreaterOrEqual(t, len(captured), 2, "expected static + recall parts")
|
||||
require.Equal(t, "STATIC", captured[0].Text)
|
||||
require.True(t, captured[0].Cache)
|
||||
require.Equal(t, "Relevant memories:\n- the user likes tea\n", captured[len(captured)-1].Text)
|
||||
require.False(t, captured[len(captured)-1].Cache, "recall hint must NOT be cached")
|
||||
}
|
||||
|
||||
func TestRunTurn_NoRecallWhenShouldRecallFalse(t *testing.T) {
|
||||
var captured []llm.SystemPromptPart
|
||||
cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }}
|
||||
kg := &fakeKG{shouldRecall: false, recallReturn: "should not appear"}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
|
||||
AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg,
|
||||
}
|
||||
_, err := rt.RunTurn(context.Background(), "hi", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, kg.recallCalls, "ShouldRecall false ⇒ Recall not called")
|
||||
require.Len(t, captured, 1, "only the static part")
|
||||
require.Equal(t, "STATIC", captured[0].Text)
|
||||
}
|
||||
|
||||
func TestRunTurn_NoRecallOnContinuationRound(t *testing.T) {
|
||||
var captured []llm.SystemPromptPart
|
||||
cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }}
|
||||
kg := &fakeKG{shouldRecall: true, recallReturn: "hint"}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
|
||||
AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg,
|
||||
}
|
||||
_, err := rt.RunTurn(context.Background(), "", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 0, kg.recallCalls, "continuation round must not recall")
|
||||
require.Len(t, captured, 1)
|
||||
}
|
||||
|
||||
func TestRunTurn_RecallTimeoutInjectsNothing(t *testing.T) {
|
||||
var captured []llm.SystemPromptPart
|
||||
cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }}
|
||||
kg := &fakeKG{shouldRecall: true, recallReturn: "late", recallDelay: 2 * time.Second}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
|
||||
AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg,
|
||||
}
|
||||
start := time.Now()
|
||||
_, err := rt.RunTurn(context.Background(), "slow?", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Less(t, time.Since(start), 1500*time.Millisecond, "recall must be bounded ~800ms")
|
||||
require.Len(t, captured, 1, "timed-out recall injects nothing")
|
||||
}
|
||||
|
||||
func TestRunTurn_IngestOnCompletion(t *testing.T) {
|
||||
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventTextDelta, text: "done"},
|
||||
{typ: llm.EventDone},
|
||||
}}
|
||||
kg := &fakeKG{}
|
||||
rt := &Runtime{
|
||||
LLM: llmProvider, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
|
||||
AgentID: "a", Model: "test", StaticSystemPrompt: "S", KG: kg,
|
||||
}
|
||||
res, err := rt.RunTurn(context.Background(), "remember I like tea", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, res.Done)
|
||||
require.Equal(t, 1, kg.ingestCalls, "ingest fires once on the completing round")
|
||||
require.NotEmpty(t, kg.ingestThreads[0], "ingest gets a non-empty thread")
|
||||
require.Equal(t, "user", kg.ingestThreads[0][0].Role)
|
||||
require.Equal(t, "remember I like tea", kg.ingestThreads[0][0].Content)
|
||||
}
|
||||
|
||||
func TestRunTurn_NoIngestOnToolRound(t *testing.T) {
|
||||
tc := &llm.ToolCall{ID: "tc_1", Name: "echo", Input: json.RawMessage(`{"x":1}`)}
|
||||
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventToolCallStart, toolCall: tc},
|
||||
{typ: llm.EventToolCallDone, toolCall: tc},
|
||||
{typ: llm.EventDone},
|
||||
}}
|
||||
kg := &fakeKG{}
|
||||
rt := &Runtime{
|
||||
LLM: llmProvider, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
|
||||
AgentID: "a", Model: "test", StaticSystemPrompt: "S", KG: kg,
|
||||
}
|
||||
res, err := rt.RunTurn(context.Background(), "use echo", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.False(t, res.Done, "tool round is not terminal")
|
||||
require.Equal(t, 0, kg.ingestCalls, "no ingest on a round that produced tool calls")
|
||||
}
|
||||
|
||||
func TestRunTurn_NoIngestWhenKGNil(t *testing.T) {
|
||||
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventTextDelta, text: "done"},
|
||||
{typ: llm.EventDone},
|
||||
}}
|
||||
rt := &Runtime{
|
||||
LLM: llmProvider, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
|
||||
AgentID: "a", Model: "test", StaticSystemPrompt: "S", KG: nil,
|
||||
}
|
||||
res, err := rt.RunTurn(context.Background(), "hi", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, res.Done)
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// echoTool is a minimal tool.Tool implementation for RunTurn tests. It
|
||||
// satisfies the real tool.Tool interface (Name/Description/Parameters/
|
||||
// Execute/IsConcurrencySafe) and echoes its raw input back as output.
|
||||
type echoTool struct{}
|
||||
|
||||
func (echoTool) Name() string { return "echo" }
|
||||
func (echoTool) Description() string { return "echoes its input" }
|
||||
func (echoTool) Parameters() json.RawMessage { return json.RawMessage(`{"type":"object"}`) }
|
||||
func (echoTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||
return tool.ToolResult{Output: string(input)}, nil
|
||||
}
|
||||
func (echoTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
|
||||
|
||||
// newEchoRegistry returns a tool.Registry containing only echoTool.
|
||||
func newEchoRegistry() *tool.Registry {
|
||||
reg := tool.NewRegistry()
|
||||
reg.Register(echoTool{})
|
||||
return reg
|
||||
}
|
||||
|
||||
// TestRunTurn_TextOnly_IsDone: provider emits a text delta then EventDone
|
||||
// with NO tool calls. The turn must be terminal (Done=true, StopReason
|
||||
// "completed") and append exactly two entries: the user message and the
|
||||
// assistant message.
|
||||
func TestRunTurn_TextOnly_IsDone(t *testing.T) {
|
||||
// scriptedStreamLLM emits its scripted events only on the FIRST call;
|
||||
// subsequent calls emit a bare EventDone. For a text-only first turn we
|
||||
// script text + done directly.
|
||||
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventTextDelta, text: "hello world"},
|
||||
{typ: llm.EventDone},
|
||||
}}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: llmProvider,
|
||||
Tools: newEchoRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test",
|
||||
}
|
||||
|
||||
res, err := rt.RunTurn(context.Background(), "hi", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, res.Done, "text-only turn should be terminal")
|
||||
require.Equal(t, "completed", res.StopReason)
|
||||
require.Len(t, res.Entries, 2, "expected user + assistant entries")
|
||||
require.Equal(t, session.EntryTypeMessage, res.Entries[0].Type)
|
||||
require.Equal(t, "user", res.Entries[0].Role)
|
||||
require.Equal(t, session.EntryTypeMessage, res.Entries[1].Type)
|
||||
require.Equal(t, "assistant", res.Entries[1].Role)
|
||||
}
|
||||
|
||||
// TestRunTurn_ToolCall_NotDone_ThenDone: turn 1 the model calls echo ⇒ the
|
||||
// turn is NOT done and the entries include a tool_result entry. Turn 2
|
||||
// (continuation, empty userMsg) the model emits text only ⇒ the turn is done.
|
||||
func TestRunTurn_ToolCall_NotDone_ThenDone(t *testing.T) {
|
||||
tc := &llm.ToolCall{ID: "tc_1", Name: "echo", Input: json.RawMessage(`{"x":1}`)}
|
||||
|
||||
// scriptedStreamLLM emits the scripted events on call 1 and a bare
|
||||
// EventDone on every subsequent call — which is exactly the turn-2
|
||||
// text-only/no-tool-calls behavior we need.
|
||||
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventToolCallStart, toolCall: tc},
|
||||
{typ: llm.EventToolCallDone, toolCall: tc},
|
||||
{typ: llm.EventDone},
|
||||
}}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: llmProvider,
|
||||
Tools: newEchoRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test",
|
||||
}
|
||||
|
||||
// Turn 1: tool call ⇒ not done, has a tool_result entry.
|
||||
res1, err := rt.RunTurn(context.Background(), "use echo", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.False(t, res1.Done, "a turn that produced tool calls must not be terminal")
|
||||
require.Equal(t, "continue", res1.StopReason)
|
||||
|
||||
var sawToolResult bool
|
||||
for _, e := range res1.Entries {
|
||||
if e.Type == session.EntryTypeToolResult {
|
||||
sawToolResult = true
|
||||
}
|
||||
}
|
||||
require.True(t, sawToolResult, "turn 1 entries should include a tool_result")
|
||||
|
||||
// Turn 2: continuation with empty userMsg ⇒ model emits no tool calls
|
||||
// (bare EventDone) ⇒ terminal.
|
||||
res2, err := rt.RunTurn(context.Background(), "", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.True(t, res2.Done, "second turn (no tool calls) should be terminal")
|
||||
require.Equal(t, "completed", res2.StopReason)
|
||||
}
|
||||
|
||||
// TestRunTurn_LLMError: the provider emits a mid-stream EventError. RunTurn
|
||||
// does NOT use Run's stream-fallback path, so the error surfaces directly:
|
||||
// the turn is terminal with StopReason "error" and a non-nil Err.
|
||||
//
|
||||
// Note on the fake: scriptedStreamLLM's scriptedStreamEvent cannot carry an
|
||||
// error value (it has no error field), so it cannot emit a meaningful
|
||||
// EventError. We reuse streamingOnlyProvider from streamfallback_test.go —
|
||||
// the same-package fake the streaming tests use to simulate a mid-stream
|
||||
// error (text delta then EventError with a real error).
|
||||
func TestRunTurn_LLMError(t *testing.T) {
|
||||
llmProvider := &streamingOnlyProvider{}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: llmProvider,
|
||||
Tools: newEchoRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test",
|
||||
}
|
||||
|
||||
res, err := rt.RunTurn(context.Background(), "do it", nil, nil)
|
||||
require.NoError(t, err, "RunTurn surfaces stream errors via TurnResult.Err, not its own error return")
|
||||
require.True(t, res.Done, "an errored turn must be terminal")
|
||||
require.Equal(t, "error", res.StopReason)
|
||||
require.Error(t, res.Err)
|
||||
require.EqualValues(t, 1, llmProvider.streamCalls.Load(), "stream hit exactly once (no fallback in RunTurn)")
|
||||
}
|
||||
|
||||
// TestRunTurn_PreCancelledContext: a context cancelled before RunTurn runs
|
||||
// must short-circuit to an aborted turn with a non-nil Err, and the LLM must
|
||||
// never be called. scriptedStreamLLM exposes a `calls` counter, so we assert
|
||||
// the provider was never invoked.
|
||||
func TestRunTurn_PreCancelledContext(t *testing.T) {
|
||||
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventTextDelta, text: "should never run"},
|
||||
{typ: llm.EventDone},
|
||||
}}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: llmProvider,
|
||||
Tools: newEchoRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test",
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
res, err := rt.RunTurn(ctx, "hi", nil, nil)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "aborted", res.StopReason)
|
||||
require.Error(t, res.Err)
|
||||
require.EqualValues(t, 0, llmProvider.calls.Load(), "LLM must not be called when context is pre-cancelled")
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
func recoveredPanicError(component string, recovered any) error {
|
||||
err := fmt.Errorf("%s panicked: %v", component, recovered)
|
||||
slog.Error("recovered extension panic", "component", component, "error", err, "stack", string(debug.Stack()))
|
||||
return err
|
||||
}
|
||||
|
||||
func callToolExecute(ctx context.Context, ex tool.Executor, name string, input json.RawMessage) (result tool.ToolResult, err error) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
err = recoveredPanicError("tool "+name, recovered)
|
||||
}
|
||||
}()
|
||||
return ex.Execute(ctx, name, input)
|
||||
}
|
||||
|
||||
func callBeforeToolHook(ctx context.Context, hook func(context.Context, string, json.RawMessage) (HookDecision, error), name string, input json.RawMessage) (decision HookDecision, err error) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
err = recoveredPanicError("BeforeToolUse hook", recovered)
|
||||
}
|
||||
}()
|
||||
return hook(ctx, name, input)
|
||||
}
|
||||
|
||||
func callAfterToolHook(ctx context.Context, hook func(context.Context, string, json.RawMessage, tool.ToolResult), name string, input json.RawMessage, result tool.ToolResult) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
_ = recoveredPanicError("AfterToolUse hook", recovered)
|
||||
}
|
||||
}()
|
||||
hook(ctx, name, input, result)
|
||||
}
|
||||
|
||||
func callOnStopHook(ctx context.Context, hook func(context.Context, string), reason string) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
_ = recoveredPanicError("OnStop hook", recovered)
|
||||
}
|
||||
}()
|
||||
hook(ctx, reason)
|
||||
}
|
||||
|
||||
func callPermissionCheck(ctx context.Context, checker tool.PermissionChecker, agentID, name string, input json.RawMessage) (decision tool.Decision) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
decision = tool.Decision{Behavior: tool.DecisionDeny, Reason: recoveredPanicError("permission checker", recovered).Error()}
|
||||
}
|
||||
}()
|
||||
return checker.Check(ctx, agentID, name, input)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type panickingTool struct{}
|
||||
|
||||
func (*panickingTool) Name() string { return "panic_tool" }
|
||||
func (*panickingTool) Description() string { return "panics for testing" }
|
||||
func (*panickingTool) Parameters() json.RawMessage { return json.RawMessage(`{"type":"object"}`) }
|
||||
func (*panickingTool) IsConcurrencySafe(json.RawMessage) bool { return false }
|
||||
func (*panickingTool) Execute(context.Context, json.RawMessage) (tool.ToolResult, error) {
|
||||
panic("boom")
|
||||
}
|
||||
|
||||
type panickingPermission struct{}
|
||||
|
||||
func (panickingPermission) Check(context.Context, string, string, json.RawMessage) tool.Decision {
|
||||
panic("permission boom")
|
||||
}
|
||||
func (panickingPermission) FilterToolDefs(defs []llm.ToolDef, _ string) []llm.ToolDef {
|
||||
return defs
|
||||
}
|
||||
|
||||
func TestDispatchToolRecoversExecutePanicAndPreservesPairing(t *testing.T) {
|
||||
reg := tool.NewRegistry()
|
||||
reg.Register(&panickingTool{})
|
||||
rt := &Runtime{Tools: reg, Session: session.NewSession("agent", "key")}
|
||||
|
||||
result, aborted := rt.dispatchTool(context.Background(), llm.ToolCall{
|
||||
ID: "call-1", Name: "panic_tool", Input: json.RawMessage(`{}`),
|
||||
}, nil)
|
||||
|
||||
assert.False(t, aborted)
|
||||
assert.Contains(t, result.Error, "tool panic_tool panicked: boom")
|
||||
entries := rt.Session.Entries()
|
||||
require.Len(t, entries, 2)
|
||||
assert.Equal(t, session.EntryTypeToolCall, entries[0].Type)
|
||||
assert.Equal(t, session.EntryTypeToolResult, entries[1].Type)
|
||||
}
|
||||
|
||||
func TestDispatchToolFailsClosedWhenPermissionPanics(t *testing.T) {
|
||||
reg := tool.NewRegistry()
|
||||
reg.Register(&mockTool{name: "safe", output: "must not execute"})
|
||||
rt := &Runtime{
|
||||
Tools: reg, Session: session.NewSession("agent", "key"),
|
||||
Permission: panickingPermission{},
|
||||
}
|
||||
|
||||
result, aborted := rt.dispatchTool(context.Background(), llm.ToolCall{
|
||||
ID: "call-1", Name: "safe", Input: json.RawMessage(`{}`),
|
||||
}, nil)
|
||||
|
||||
assert.False(t, aborted)
|
||||
assert.Contains(t, result.Error, "permission checker panicked")
|
||||
assert.NotContains(t, result.Output, "must not execute")
|
||||
require.Len(t, rt.Session.Entries(), 2)
|
||||
}
|
||||
|
||||
func TestRunRecoversHookPanicAsEventError(t *testing.T) {
|
||||
rt := hookFixture(t, LifecycleHooks{
|
||||
OnUserPromptSubmit: func(context.Context, string, []llm.ImageContent) (string, []llm.ImageContent, error) {
|
||||
panic("hook boom")
|
||||
},
|
||||
}, nil, nil)
|
||||
|
||||
events, err := rt.Run(context.Background(), "hello", nil)
|
||||
require.NoError(t, err)
|
||||
var got error
|
||||
for event := range events {
|
||||
if event.Type == EventError {
|
||||
got = event.Error
|
||||
}
|
||||
}
|
||||
require.Error(t, got)
|
||||
assert.Contains(t, got.Error(), "runtime panicked: hook boom")
|
||||
}
|
||||
|
||||
func TestRunRejectsConcurrentCall(t *testing.T) {
|
||||
started := make(chan struct{})
|
||||
provider := &llmtest.Stub{Text: "done", Delay: 50 * time.Millisecond, Started: started}
|
||||
rt := &Runtime{
|
||||
LLM: provider, Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("agent", "key"), Model: "mock", MaxTurns: 1,
|
||||
}
|
||||
|
||||
first, err := rt.Run(context.Background(), "first", nil)
|
||||
require.NoError(t, err)
|
||||
<-started
|
||||
second, err := rt.Run(context.Background(), "second", nil)
|
||||
require.ErrorContains(t, err, "already running")
|
||||
assert.Nil(t, second)
|
||||
for range first {
|
||||
}
|
||||
|
||||
third, err := rt.Run(context.Background(), "third", nil)
|
||||
require.NoError(t, err, "runtime must become available after the first run ends")
|
||||
for range third {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// streamErrThenOKProvider emits EventError (no token) on the first stream
|
||||
// call, then clean text on the second.
|
||||
type streamErrThenOKProvider struct {
|
||||
llmtest.Base
|
||||
calls atomic.Int64
|
||||
streamErr error
|
||||
finalText string
|
||||
}
|
||||
|
||||
func (p *streamErrThenOKProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
n := p.calls.Add(1)
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
if n == 1 {
|
||||
ch <- llm.ChatEvent{Type: llm.EventError, Error: p.streamErr}
|
||||
} else {
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: p.finalText}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func TestStreamErrorRetryableEngagesFallback(t *testing.T) {
|
||||
prov := &streamErrThenOKProvider{
|
||||
streamErr: errors.New("429 rate limit exceeded"),
|
||||
finalText: "RECOVERED_VIA_FALLBACK",
|
||||
}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-opus-4-8",
|
||||
FallbackModel: "claude-sonnet-4-5",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 2,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
out, err := rt.RunSync(context.Background(), "do it", nil)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, out, "RECOVERED_VIA_FALLBACK")
|
||||
assert.EqualValues(t, 2, prov.calls.Load(), "must retry once after the pre-first-token 429")
|
||||
}
|
||||
|
||||
func TestStreamErrorNonRetryableStillAborts(t *testing.T) {
|
||||
prov := &streamErrThenOKProvider{
|
||||
streamErr: errors.New("400 invalid input"),
|
||||
finalText: "SHOULD_NOT_BE_REACHED",
|
||||
}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-opus-4-8",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 2,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
_, err := rt.RunSync(context.Background(), "do it", nil)
|
||||
require.Error(t, err)
|
||||
assert.EqualValues(t, 1, prov.calls.Load(), "non-retryable pre-first-token error must abort, not retry")
|
||||
}
|
||||
+12
-3
@@ -46,9 +46,10 @@ type AgentSpec struct {
|
||||
// Reasoning maps to each provider's native reasoning knob. Use
|
||||
// llm.ReasoningOff (zero value), Low, Medium, or High.
|
||||
Reasoning string
|
||||
// Loop controls the runtime's tool-execution behavior (concurrency
|
||||
// cap, depth cap, streaming-tools toggle). Zero value ⇒ env-var
|
||||
// fallback then compiled-in defaults.
|
||||
// Loop controls the runtime's per-agent tool-execution behavior
|
||||
// (concurrency cap, depth cap, streaming-tools toggle). Non-zero fields
|
||||
// and non-nil hooks override RuntimeDeps.AgentLoop; remaining zero values
|
||||
// inherit the shared setting, then its env/default fallback.
|
||||
Loop LoopConfig
|
||||
// MCPServers, when non-empty, are connected by BuildRuntime: each
|
||||
// server's tools are namespaced ("mcp__<Name>__<tool>") and added
|
||||
@@ -71,6 +72,14 @@ type LoopConfig struct {
|
||||
// StreamingTools enables mid-stream concurrency-safe tool kickoff.
|
||||
// false ⇒ env fallback (HARNESS_STREAMING_TOOLS=1) then off.
|
||||
StreamingTools bool
|
||||
// MaxToolResultLen caps the in-context length of any single tool
|
||||
// result; longer results are truncated to their first MaxToolResultLen
|
||||
// chars (cut at a newline boundary) with the remainder either spilled
|
||||
// to disk via spillConfig or simply dropped. 0 ⇒ env fallback
|
||||
// (HARNESS_MAX_TOOL_RESULT_LEN) then default 4000. Common pick for
|
||||
// engineering-style agents (reading source files, running tests) is
|
||||
// 16000-25000.
|
||||
MaxToolResultLen int
|
||||
// Hooks are optional callbacks the runtime fires at well-known
|
||||
// points in the loop. Zero value (all nil fields) disables every
|
||||
// hook with no overhead.
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
package runtime
|
||||
|
||||
import "github.com/sausheong/harness/llm"
|
||||
|
||||
// addUsage returns the field-wise sum of two usage snapshots. A nil operand is
|
||||
// treated as zero. It returns a fresh pointer and never mutates its arguments,
|
||||
// so callers may safely pass a pointer that aliases a provider stream event.
|
||||
// Returns nil only when BOTH operands are nil, preserving the contract that
|
||||
// EventDone.Usage stays nil for providers that never report usage.
|
||||
func addUsage(acc, turn *llm.Usage) *llm.Usage {
|
||||
if acc == nil && turn == nil {
|
||||
return nil
|
||||
}
|
||||
var out llm.Usage
|
||||
if acc != nil {
|
||||
out = *acc
|
||||
}
|
||||
if turn != nil {
|
||||
out.InputTokens += turn.InputTokens
|
||||
out.OutputTokens += turn.OutputTokens
|
||||
out.CacheCreationInputTokens += turn.CacheCreationInputTokens
|
||||
out.CacheReadInputTokens += turn.CacheReadInputTokens
|
||||
}
|
||||
return &out
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAddUsage_BothNil(t *testing.T) {
|
||||
assert.Nil(t, addUsage(nil, nil))
|
||||
}
|
||||
|
||||
func TestAddUsage_AccNil(t *testing.T) {
|
||||
turn := &llm.Usage{InputTokens: 7, OutputTokens: 3, CacheCreationInputTokens: 2, CacheReadInputTokens: 1}
|
||||
got := addUsage(nil, turn)
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, llm.Usage{InputTokens: 7, OutputTokens: 3, CacheCreationInputTokens: 2, CacheReadInputTokens: 1}, *got)
|
||||
// input not mutated, and the result must be a distinct pointer (the
|
||||
// non-mutating/aliasing-safety contract the accumulator relies on).
|
||||
assert.NotSame(t, turn, got)
|
||||
assert.Equal(t, 7, turn.InputTokens)
|
||||
}
|
||||
|
||||
func TestAddUsage_TurnNil(t *testing.T) {
|
||||
acc := &llm.Usage{InputTokens: 5}
|
||||
got := addUsage(acc, nil)
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, 5, got.InputTokens)
|
||||
}
|
||||
|
||||
func TestAddUsage_SumsAllFourFields(t *testing.T) {
|
||||
acc := &llm.Usage{InputTokens: 100, OutputTokens: 40, CacheCreationInputTokens: 10, CacheReadInputTokens: 6}
|
||||
turn := &llm.Usage{InputTokens: 10, OutputTokens: 5, CacheCreationInputTokens: 1, CacheReadInputTokens: 2}
|
||||
got := addUsage(acc, turn)
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, 110, got.InputTokens)
|
||||
assert.Equal(t, 45, got.OutputTokens)
|
||||
assert.Equal(t, 11, got.CacheCreationInputTokens)
|
||||
assert.Equal(t, 8, got.CacheReadInputTokens)
|
||||
// neither input mutated
|
||||
assert.Equal(t, 100, acc.InputTokens)
|
||||
assert.Equal(t, 10, turn.InputTokens)
|
||||
}
|
||||
+40
-6
@@ -36,10 +36,18 @@ type ImageData struct {
|
||||
Data string `json:"data"` // base64-encoded
|
||||
}
|
||||
|
||||
// ThinkingBlockData stores a thinking block from a model response.
|
||||
// It must be echoed back verbatim in subsequent turns.
|
||||
type ThinkingBlockData struct {
|
||||
Thinking string `json:"thinking"`
|
||||
Signature string `json:"signature,omitempty"`
|
||||
}
|
||||
|
||||
// MessageData holds text message content.
|
||||
type MessageData struct {
|
||||
Text string `json:"text"`
|
||||
Images []ImageData `json:"images,omitempty"`
|
||||
Text string `json:"text"`
|
||||
Images []ImageData `json:"images,omitempty"`
|
||||
ThinkingBlocks []ThinkingBlockData `json:"thinking_blocks,omitempty"`
|
||||
}
|
||||
|
||||
// ToolCallData holds a tool call's details.
|
||||
@@ -85,6 +93,12 @@ type Session struct {
|
||||
entryMap map[string]*SessionEntry
|
||||
leafID string // current leaf for history traversal
|
||||
store *Store
|
||||
|
||||
// writeMu serializes store writes and preserves their order. Acquired in
|
||||
// Append while s.mu is still held (lock-coupling), then s.mu is released
|
||||
// before the disk write — so disk latency stays off s.mu while on-disk
|
||||
// order still matches in-memory append order under concurrent callers. (P5)
|
||||
writeMu sync.Mutex
|
||||
}
|
||||
|
||||
// NewSession creates a new empty session.
|
||||
@@ -100,7 +114,6 @@ func NewSession(agentID, key string) *Session {
|
||||
// Append adds an entry to the session.
|
||||
func (s *Session) Append(entry SessionEntry) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if entry.ID == "" {
|
||||
entry.ID = generateID("e")
|
||||
}
|
||||
@@ -115,9 +128,19 @@ func (s *Session) Append(entry SessionEntry) {
|
||||
s.entryMap[entry.ID] = &s.entries[len(s.entries)-1]
|
||||
s.leafID = entry.ID
|
||||
|
||||
// Persist if store is set
|
||||
if s.store != nil {
|
||||
s.store.AppendEntry(s, entry)
|
||||
finalized := entry // value copy with all fields set
|
||||
store := s.store
|
||||
|
||||
// Lock-coupling: take writeMu BEFORE releasing s.mu so the disk-write
|
||||
// order matches the in-memory append order even under concurrent callers,
|
||||
// then release s.mu so disk latency doesn't block concurrent View()/append.
|
||||
if store != nil {
|
||||
s.writeMu.Lock()
|
||||
s.mu.Unlock()
|
||||
store.AppendEntry(s, finalized)
|
||||
s.writeMu.Unlock()
|
||||
} else {
|
||||
s.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,6 +346,17 @@ func AssistantMessageEntry(text string) SessionEntry {
|
||||
}
|
||||
}
|
||||
|
||||
// AssistantMessageEntryWithThinking creates an assistant message entry that
|
||||
// includes thinking blocks which must be echoed back in subsequent turns.
|
||||
func AssistantMessageEntryWithThinking(text string, blocks []ThinkingBlockData) SessionEntry {
|
||||
data, _ := json.Marshal(MessageData{Text: text, ThinkingBlocks: blocks})
|
||||
return SessionEntry{
|
||||
Type: EntryTypeMessage,
|
||||
Role: "assistant",
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// ToolCallEntry creates a tool call entry.
|
||||
//
|
||||
// input is sanitised to "{}" when empty or not valid JSON. The
|
||||
|
||||
@@ -350,3 +350,60 @@ func TestSession_ViewReturnsCopy(t *testing.T) {
|
||||
require.Len(t, v2, 1)
|
||||
require.Equal(t, "e_1", v2[0].ID, "internal state must not be mutated by caller's slice modification")
|
||||
}
|
||||
|
||||
func TestConcurrentAppendAndViewNoRace(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := NewStore(dir)
|
||||
require.NoError(t, store.Create("a", "k"))
|
||||
sess := NewSession("a", "k")
|
||||
sess.SetStore(store)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 500; i++ {
|
||||
sess.Append(SessionEntry{Type: EntryTypeMessage, Role: "user", Data: []byte(`{"text":"x"}`)})
|
||||
}
|
||||
}()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 500; i++ {
|
||||
_ = sess.View()
|
||||
}
|
||||
}()
|
||||
wg.Wait()
|
||||
|
||||
require.Len(t, sess.Entries(), 500)
|
||||
}
|
||||
|
||||
// TestAppendPreservesDiskOrder verifies that the P5 lock-coupling keeps the
|
||||
// on-disk JSONL order identical to the in-memory append order: sequential
|
||||
// appends must persist in order, and reloading from disk must round-trip them
|
||||
// in the same sequence.
|
||||
func TestAppendPreservesDiskOrder(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := NewStore(dir)
|
||||
require.NoError(t, store.Create("a", "k"))
|
||||
sess := NewSession("a", "k")
|
||||
sess.SetStore(store)
|
||||
|
||||
const n = 200
|
||||
for i := 0; i < n; i++ {
|
||||
sess.Append(SessionEntry{
|
||||
Type: EntryTypeMessage,
|
||||
Role: "user",
|
||||
Data: json.RawMessage(fmt.Sprintf(`{"text":"%d"}`, i)),
|
||||
})
|
||||
}
|
||||
|
||||
reloaded, err := store.Load("a", "k")
|
||||
require.NoError(t, err)
|
||||
got := reloaded.Entries()
|
||||
require.Len(t, got, n)
|
||||
for i := 0; i < n; i++ {
|
||||
require.JSONEq(t, fmt.Sprintf(`{"text":"%d"}`, i), string(got[i].Data),
|
||||
"on-disk entry %d out of order", i)
|
||||
}
|
||||
}
|
||||
+69
-2
@@ -9,6 +9,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -22,8 +23,19 @@ type SessionInfo struct {
|
||||
|
||||
// Store handles JSONL file I/O for sessions.
|
||||
type Store struct {
|
||||
baseDir string
|
||||
mu sync.Mutex
|
||||
baseDir string
|
||||
mu sync.Mutex
|
||||
degraded atomic.Bool
|
||||
}
|
||||
|
||||
// markDegraded emits a single warning the first time session persistence
|
||||
// fails, so a user notices that in-memory state may not survive a restart.
|
||||
// Subsequent failures stay at their existing Error level to avoid log spam.
|
||||
func (s *Store) markDegraded(reason string, err error) {
|
||||
if s.degraded.CompareAndSwap(false, true) {
|
||||
slog.Warn("session persistence degraded; in-memory state may not survive restart",
|
||||
"reason", reason, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// NewStore creates a new session store.
|
||||
@@ -41,8 +53,29 @@ func (s *Store) sessionPath(agentID, key string) string {
|
||||
return filepath.Join(s.sessionDir(agentID), key+".jsonl")
|
||||
}
|
||||
|
||||
// validateStoreComponent keeps caller-provided identifiers as one filesystem
|
||||
// path component. Empty values remain supported for backward compatibility,
|
||||
// but separators, volume names, and dot traversal are rejected.
|
||||
func validateStoreComponent(kind, value string) error {
|
||||
if value == "." || value == ".." || filepath.VolumeName(value) != "" ||
|
||||
strings.ContainsAny(value, `/\`) {
|
||||
return fmt.Errorf("invalid %s %q: must be a single path component", kind, value)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateStoreIDs(agentID, key string) error {
|
||||
if err := validateStoreComponent("agent ID", agentID); err != nil {
|
||||
return err
|
||||
}
|
||||
return validateStoreComponent("session key", key)
|
||||
}
|
||||
|
||||
// Load reads a session from its JSONL file.
|
||||
func (s *Store) Load(agentID, key string) (*Session, error) {
|
||||
if err := validateStoreIDs(agentID, key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
path := s.sessionPath(agentID, key)
|
||||
|
||||
f, err := os.Open(path)
|
||||
@@ -91,9 +124,15 @@ func (s *Store) Load(agentID, key string) (*Session, error) {
|
||||
func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := validateStoreIDs(sess.AgentID, sess.Key); err != nil {
|
||||
s.markDegraded("invalid session path", err)
|
||||
slog.Error("refusing to persist session outside store", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
dir := s.sessionDir(sess.AgentID)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
s.markDegraded("create session dir", err)
|
||||
slog.Error("failed to create session dir", "error", err)
|
||||
return
|
||||
}
|
||||
@@ -101,6 +140,7 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
|
||||
path := s.sessionPath(sess.AgentID, sess.Key)
|
||||
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
s.markDegraded("open session file", err)
|
||||
slog.Error("failed to open session file", "error", err)
|
||||
return
|
||||
}
|
||||
@@ -114,12 +154,16 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
|
||||
|
||||
data = append(data, '\n')
|
||||
if _, err := f.Write(data); err != nil {
|
||||
s.markDegraded("write session entry", err)
|
||||
slog.Error("failed to write session entry", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create creates an empty session file on disk so it shows up in List.
|
||||
func (s *Store) Create(agentID, key string) error {
|
||||
if err := validateStoreIDs(agentID, key); err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
@@ -138,6 +182,9 @@ func (s *Store) Create(agentID, key string) error {
|
||||
|
||||
// List returns metadata for all sessions belonging to the given agent.
|
||||
func (s *Store) List(agentID string) ([]SessionInfo, error) {
|
||||
if err := validateStoreComponent("agent ID", agentID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dir := s.sessionDir(agentID)
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
@@ -209,6 +256,9 @@ func (s *Store) List(agentID string) ([]SessionInfo, error) {
|
||||
|
||||
// Exists checks whether a session file exists for the given agent and key.
|
||||
func (s *Store) Exists(agentID, key string) bool {
|
||||
if validateStoreIDs(agentID, key) != nil {
|
||||
return false
|
||||
}
|
||||
path := s.sessionPath(agentID, key)
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
@@ -216,6 +266,12 @@ func (s *Store) Exists(agentID, key string) bool {
|
||||
|
||||
// Rename renames a session file from oldKey to newKey.
|
||||
func (s *Store) Rename(agentID, oldKey, newKey string) error {
|
||||
if err := validateStoreIDs(agentID, oldKey); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateStoreComponent("session key", newKey); err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
@@ -234,6 +290,9 @@ func (s *Store) Rename(agentID, oldKey, newKey string) error {
|
||||
|
||||
// Delete removes a session's JSONL file.
|
||||
func (s *Store) Delete(agentID, key string) error {
|
||||
if err := validateStoreIDs(agentID, key); err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
@@ -249,9 +308,15 @@ func (s *Store) Delete(agentID, key string) error {
|
||||
func (s *Store) Rewrite(sess *Session) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := validateStoreIDs(sess.AgentID, sess.Key); err != nil {
|
||||
s.markDegraded("invalid session path", err)
|
||||
slog.Error("refusing to rewrite session outside store", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
dir := s.sessionDir(sess.AgentID)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
s.markDegraded("create session dir", err)
|
||||
slog.Error("failed to create session dir", "error", err)
|
||||
return
|
||||
}
|
||||
@@ -260,6 +325,7 @@ func (s *Store) Rewrite(sess *Session) {
|
||||
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
s.markDegraded("create session file for rewrite", err)
|
||||
slog.Error("failed to create session file for rewrite", "error", err)
|
||||
return
|
||||
}
|
||||
@@ -277,6 +343,7 @@ func (s *Store) Rewrite(sess *Session) {
|
||||
}
|
||||
|
||||
if err := w.Flush(); err != nil {
|
||||
s.markDegraded("flush session file", err)
|
||||
slog.Error("failed to flush session file", "error", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestStore_DegradedPersistenceWarnsOnce(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
prev := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})))
|
||||
defer slog.SetDefault(prev)
|
||||
|
||||
// Make a path where the agent dir cannot be created: a regular FILE used
|
||||
// as baseDir means sessionDir(agentID) = <file>/<agentID> and MkdirAll fails.
|
||||
tmp := t.TempDir()
|
||||
blocker := filepath.Join(tmp, "blocker")
|
||||
require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600))
|
||||
s := NewStore(blocker)
|
||||
|
||||
sess := &Session{AgentID: "a", Key: "k"}
|
||||
s.AppendEntry(sess, SessionEntry{})
|
||||
s.AppendEntry(sess, SessionEntry{})
|
||||
s.AppendEntry(sess, SessionEntry{})
|
||||
|
||||
require.Equal(t, 1, strings.Count(buf.String(), "session persistence degraded"),
|
||||
"degraded warning must fire exactly once across multiple failures")
|
||||
}
|
||||
|
||||
func TestStore_RewriteDegradedWarns(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
prev := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})))
|
||||
defer slog.SetDefault(prev)
|
||||
|
||||
tmp := t.TempDir()
|
||||
blocker := filepath.Join(tmp, "blocker")
|
||||
require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600))
|
||||
s := NewStore(blocker)
|
||||
|
||||
sess := &Session{AgentID: "a", Key: "k"}
|
||||
s.Rewrite(sess)
|
||||
|
||||
require.Equal(t, 1, strings.Count(buf.String(), "session persistence degraded"),
|
||||
"Rewrite failure must emit the degraded warning")
|
||||
}
|
||||
|
||||
func TestStoreRejectsPathTraversalIdentifiers(t *testing.T) {
|
||||
s := NewStore(t.TempDir())
|
||||
|
||||
_, err := s.Load("../outside", "key")
|
||||
require.ErrorContains(t, err, "invalid agent ID")
|
||||
require.ErrorContains(t, s.Create("agent", "../outside"), "invalid session key")
|
||||
require.ErrorContains(t, s.Rename("agent", "../old", "new"), "invalid session key")
|
||||
require.ErrorContains(t, s.Delete("agent", "../outside"), "invalid session key")
|
||||
require.False(t, s.Exists("agent", "../outside"))
|
||||
_, err = s.List("../outside")
|
||||
require.ErrorContains(t, err, "invalid agent ID")
|
||||
}
|
||||
+23
-1
@@ -21,6 +21,10 @@ func Estimate(msgs []llm.Message, systemPrompt string, tools []llm.ToolDef) int
|
||||
for _, tc := range m.ToolCalls {
|
||||
total += len(tc.ID) + len(tc.Name) + len(tc.Input)
|
||||
}
|
||||
// Images are not part of Content (Images is json:"-"); approximate
|
||||
// each attached image's token cost. perImageTokens is expressed in
|
||||
// tokens, so multiply by 4 to survive the final divide-by-4.
|
||||
total += len(m.Images) * perImageTokens * 4
|
||||
}
|
||||
for _, t := range tools {
|
||||
total += len(t.Name) + len(t.Description) + len(t.Parameters)
|
||||
@@ -33,6 +37,12 @@ func Estimate(msgs []llm.Message, systemPrompt string, tools []llm.ToolDef) int
|
||||
// since the final divide-by-4 maps it back to tokens.
|
||||
const perMessageOverhead = 3
|
||||
|
||||
// perImageTokens approximates the token cost of one attached image. Vision
|
||||
// models bill images by tiles/resolution; ~1500 tokens is a deliberately
|
||||
// conservative flat estimate so image-heavy sessions trigger preventive
|
||||
// compaction rather than hitting a reactive overflow.
|
||||
const perImageTokens = 1500
|
||||
|
||||
// ContextWindow returns the maximum input tokens for the given
|
||||
// "provider/model" identifier.
|
||||
//
|
||||
@@ -110,8 +120,20 @@ func windowByModelFamily(modelID string) int {
|
||||
leaf = leaf[i+1:]
|
||||
}
|
||||
switch {
|
||||
case strings.Contains(id, "claude-fable"),
|
||||
strings.Contains(id, "claude-mythos"),
|
||||
strings.Contains(id, "claude-opus-4-6"),
|
||||
strings.Contains(id, "claude-opus-4-7"),
|
||||
strings.Contains(id, "claude-opus-4-8"),
|
||||
strings.Contains(id, "claude-opus-4-9"),
|
||||
strings.Contains(id, "claude-sonnet-4-6"):
|
||||
// The 1M-window Claude generation: Fable 5, Mythos 5,
|
||||
// Opus 4.6+, Sonnet 4.6. Matching the 200k blanket rule below
|
||||
// would make preventive compaction fire ~5x too early.
|
||||
return 1000000
|
||||
case strings.Contains(id, "claude"):
|
||||
// All current Claude chat models share a 200k window.
|
||||
// Older Claude chat models (3.x through the 4.5 era, Haiku 4.5)
|
||||
// share a 200k window.
|
||||
return 200000
|
||||
case strings.HasPrefix(leaf, "gpt-4o"), strings.HasPrefix(leaf, "gpt-4-turbo"):
|
||||
return 128000
|
||||
|
||||
+42
-1
@@ -4,6 +4,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
@@ -84,7 +85,7 @@ func TestContextWindowProxyProviderDetectedByModelFamily(t *testing.T) {
|
||||
model string
|
||||
want int
|
||||
}{
|
||||
{"platformai/claude-sonnet-4-6-asia-southeast1", 200000},
|
||||
{"platformai/claude-sonnet-4-6-asia-southeast1", 1000000},
|
||||
{"openrouter/anthropic/claude-3-opus", 200000},
|
||||
{"bedrock/anthropic.claude-3-haiku", 200000},
|
||||
{"vertex/gemini-1.5-pro-001", 2000000},
|
||||
@@ -97,6 +98,17 @@ func TestContextWindowProxyProviderDetectedByModelFamily(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEstimate_CountsImages(t *testing.T) {
|
||||
textOnly := []llm.Message{{Role: "user", Content: "hello"}}
|
||||
withImg := []llm.Message{{Role: "user", Content: "hello", Images: []llm.ImageContent{
|
||||
{MimeType: "image/png", Data: []byte("x")},
|
||||
{MimeType: "image/png", Data: []byte("y")},
|
||||
}}}
|
||||
base := Estimate(textOnly, "", nil)
|
||||
withImages := Estimate(withImg, "", nil)
|
||||
require.GreaterOrEqual(t, withImages-base, 2*perImageTokens)
|
||||
}
|
||||
|
||||
func TestContextWindowOllamaDefault(t *testing.T) {
|
||||
// Without RegisterOllamaContext call, ollama models fall back to a sane default
|
||||
assert.Equal(t, 32000, ContextWindow("local/qwen2.5:3b-instruct"))
|
||||
@@ -135,3 +147,32 @@ func TestCalibratorIgnoresZeroOrNegative(t *testing.T) {
|
||||
c.Update(-5, 100)
|
||||
assert.Equal(t, 100, c.Adjust(100), "bad samples must be ignored")
|
||||
}
|
||||
|
||||
// TestContextWindow1MClaudeFamily pins the 1M-window Claude generation:
|
||||
// Fable 5, Mythos 5, Opus 4.6+, and Sonnet 4.6 all ship a 1M context
|
||||
// window. The old blanket claude→200k rule made compaction fire ~5x too
|
||||
// early on these models. Older Claude (3.x, 4.0-4.5 era) stays 200k.
|
||||
func TestContextWindow1MClaudeFamily(t *testing.T) {
|
||||
tests := []struct {
|
||||
model string
|
||||
want int
|
||||
}{
|
||||
{"anthropic/claude-fable-5", 1000000},
|
||||
{"platformai/claude-fable-5-global", 1000000},
|
||||
{"anthropic/claude-mythos-5", 1000000},
|
||||
{"anthropic/claude-opus-4-6", 1000000},
|
||||
{"anthropic/claude-opus-4-7", 1000000},
|
||||
{"anthropic/claude-opus-4-8", 1000000},
|
||||
{"platformai/claude-sonnet-4-6-asia-southeast1", 1000000},
|
||||
// Older generations keep 200k.
|
||||
{"anthropic/claude-haiku-4-5-20251001", 200000},
|
||||
{"anthropic/claude-sonnet-4-5", 200000},
|
||||
{"anthropic/claude-3-5-sonnet-20241022", 200000},
|
||||
{"anthropic/claude-opus-4-0-20250514", 200000},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.model, func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, ContextWindow(tc.model))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// WriteFileAtomic writes data to path atomically: it writes to a temp file in
|
||||
// the same directory, fsyncs, sets perm, then renames over path. A crash
|
||||
// mid-write leaves either the old file or the complete new file, never a
|
||||
// truncated one. The rename is atomic on POSIX within a single filesystem.
|
||||
func WriteFileAtomic(path string, data []byte, perm os.FileMode) error {
|
||||
dir := filepath.Dir(path)
|
||||
tmp, err := os.CreateTemp(dir, ".tmp-"+filepath.Base(path)+"-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create temp: %w", err)
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
defer func() { _ = os.Remove(tmpName) }()
|
||||
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return fmt.Errorf("write temp: %w", err)
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
_ = tmp.Close()
|
||||
return fmt.Errorf("sync temp: %w", err)
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return fmt.Errorf("close temp: %w", err)
|
||||
}
|
||||
if err := os.Chmod(tmpName, perm); err != nil {
|
||||
return fmt.Errorf("chmod temp: %w", err)
|
||||
}
|
||||
if err := os.Rename(tmpName, path); err != nil {
|
||||
return fmt.Errorf("rename temp: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestWriteFileAtomic(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "out.txt")
|
||||
|
||||
require.NoError(t, WriteFileAtomic(path, []byte("hello"), 0o600))
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "hello", string(data))
|
||||
|
||||
info, err := os.Stat(path)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
|
||||
|
||||
require.NoError(t, WriteFileAtomic(path, []byte("world"), 0o644))
|
||||
data, _ = os.ReadFile(path)
|
||||
require.Equal(t, "world", string(data))
|
||||
|
||||
entries, err := os.ReadDir(dir)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
require.Equal(t, "out.txt", entries[0].Name())
|
||||
}
|
||||
+12
-3
@@ -291,14 +291,24 @@ func ValidatePathInWorkDir(path, workDir string) error {
|
||||
realWork = absWork // workspace might not exist yet
|
||||
}
|
||||
|
||||
// For the target path, resolve the parent directory (file may not exist yet)
|
||||
// Resolve an existing target itself so a final-component symlink cannot
|
||||
// escape the workspace. For a path that does not exist yet, resolve its
|
||||
// parent directory instead so callers can safely create a new file.
|
||||
realPath, targetErr := filepath.EvalSymlinks(absPath)
|
||||
if targetErr == nil {
|
||||
if !strings.HasPrefix(realPath, realWork+string(filepath.Separator)) && realPath != realWork {
|
||||
return fmt.Errorf("path %q is outside workspace %q", path, workDir)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
parentDir := filepath.Dir(absPath)
|
||||
realParent, err := filepath.EvalSymlinks(parentDir)
|
||||
if err != nil {
|
||||
// Parent doesn't exist — use the unresolved absolute path
|
||||
realParent = parentDir
|
||||
}
|
||||
realPath := filepath.Join(realParent, filepath.Base(absPath))
|
||||
realPath = filepath.Join(realParent, filepath.Base(absPath))
|
||||
|
||||
if !strings.HasPrefix(realPath, realWork+string(filepath.Separator)) && realPath != realWork {
|
||||
return fmt.Errorf("path %q is outside workspace %q", path, workDir)
|
||||
@@ -313,4 +323,3 @@ func ValidatePathInWorkDir(path, workDir string) error {
|
||||
func RegisterCron(reg *Registry, agentID string, scheduler JobScheduler) {
|
||||
reg.Register(&CronTool{AgentID: agentID, Scheduler: scheduler})
|
||||
}
|
||||
|
||||
+21
-11
@@ -11,6 +11,7 @@ import (
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
@@ -57,8 +58,7 @@ func resolveBashCommandPaths(cmd string) (string, [][2]string) {
|
||||
return out, subs
|
||||
}
|
||||
|
||||
// shellSingleQuote wraps s in single quotes, escaping any embedded single
|
||||
// quotes via the standard '\'' dance.
|
||||
// shellSingleQuote wraps s in single quotes, safely escaping embedded quotes.
|
||||
func shellSingleQuote(s string) string {
|
||||
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
|
||||
}
|
||||
@@ -83,7 +83,7 @@ const defaultBashTimeout = 120 * time.Second
|
||||
|
||||
// ExecPolicy controls which commands the bash tool is allowed to execute.
|
||||
type ExecPolicy struct {
|
||||
Level string // "deny", "allowlist", "full"
|
||||
Level string // "deny", "allowlist", "full"; any other value denies execution
|
||||
Allowlist []string // command basenames allowed when Level is "allowlist"
|
||||
}
|
||||
|
||||
@@ -132,10 +132,12 @@ func extractCommands(cmd string) []string {
|
||||
// Find the earliest operator
|
||||
minIdx := len(remaining)
|
||||
opLen := 0
|
||||
for _, op := range []string{"&&", "||", "|", ";"} {
|
||||
if idx := strings.Index(remaining, op); idx != -1 && idx < minIdx {
|
||||
minIdx = idx
|
||||
opLen = len(op)
|
||||
for _, op := range []string{"&&", "||", "|", ";", "&"} {
|
||||
if idx := strings.Index(remaining, op); idx != -1 {
|
||||
if idx < minIdx || (idx == minIdx && len(op) > opLen) {
|
||||
minIdx = idx
|
||||
opLen = len(op)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,9 +192,14 @@ func (t *BashTool) Execute(ctx context.Context, input json.RawMessage) (tool.Too
|
||||
case "deny":
|
||||
return tool.ToolResult{Error: "bash execution is disabled by policy"}, nil
|
||||
case "allowlist":
|
||||
// Block shell metacharacters that can execute arbitrary code
|
||||
// inside an otherwise-allowed command (e.g. ls $(curl evil.com))
|
||||
for _, meta := range []string{"$(", "`", "<(", ">(", "${", "\\n"} {
|
||||
// Block shell metacharacters that can execute arbitrary code or
|
||||
// write files inside an otherwise-allowed command. Covers command
|
||||
// substitution (e.g. ls $(curl evil.com)), real newline/CR bytes
|
||||
// (bash -c treats them as command separators, so trailing lines
|
||||
// would run unvalidated), and output redirection (">" matches ">",
|
||||
// ">>", "2>", "&>", "2>&1" — all write/overwrite primitives).
|
||||
// Input redirection "<" is intentionally allowed (not a write/exec bypass).
|
||||
for _, meta := range []string{"$(", "`", "<(", ">(", "${", "\n", "\r", ">"} {
|
||||
if strings.Contains(in.Command, meta) {
|
||||
return tool.ToolResult{Error: "command contains shell metacharacters not allowed in allowlist mode"}, nil
|
||||
}
|
||||
@@ -207,8 +214,11 @@ func (t *BashTool) Execute(ctx context.Context, input json.RawMessage) (tool.Too
|
||||
return tool.ToolResult{Error: fmt.Sprintf("command %q is not in the exec allowlist", cmd)}, nil
|
||||
}
|
||||
}
|
||||
case "full":
|
||||
// Explicitly unrestricted.
|
||||
default:
|
||||
return tool.ToolResult{Error: fmt.Sprintf("invalid bash execution policy %q; execution denied", t.ExecPolicy.Level)}, nil
|
||||
}
|
||||
// "full" or unrecognized: allow everything
|
||||
}
|
||||
|
||||
timeout := defaultBashTimeout
|
||||
|
||||
+89
-4
@@ -1,13 +1,63 @@
|
||||
package bash
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// runAllowlist executes cmd under an allowlist policy and returns the
|
||||
// ToolResult.Error (empty string = the command was permitted by policy).
|
||||
func runAllowlist(t *testing.T, allow []string, command string) string {
|
||||
t.Helper()
|
||||
bt := &BashTool{ExecPolicy: &ExecPolicy{Level: "allowlist", Allowlist: allow}}
|
||||
in, err := json.Marshal(bashInput{Command: command})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
res, err := bt.Execute(context.Background(), in)
|
||||
if err != nil {
|
||||
t.Fatalf("Execute returned a Go error (should use ToolResult.Error): %v", err)
|
||||
}
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func TestExtractCommands_BackgroundAmpersand(t *testing.T) {
|
||||
// "ls & curl ..." must validate BOTH sides; curl is not allowed →
|
||||
// rejected by policy BEFORE any command executes. Asserting the policy
|
||||
// rejection message (not just a non-empty Error) is essential: without
|
||||
// the fix, curl actually runs and its own runtime stderr lands in
|
||||
// res.Error, which would mask the bypass.
|
||||
got := runAllowlist(t, []string{"ls"}, "ls & curl http://evil")
|
||||
if !strings.Contains(got, "not in the exec allowlist") {
|
||||
t.Fatalf("background-& bypass: expected allowlist rejection of curl, got %q", got)
|
||||
}
|
||||
// "ls && echo hi" must still split on && (both allowed) → permitted.
|
||||
if got := runAllowlist(t, []string{"ls", "echo"}, "ls && echo hi"); got != "" {
|
||||
t.Fatalf("&& chain wrongly rejected: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownExecPolicyFailsClosed(t *testing.T) {
|
||||
bt := &BashTool{ExecPolicy: &ExecPolicy{Level: "allowlits", Allowlist: []string{"echo"}}}
|
||||
in, err := json.Marshal(bashInput{Command: "echo should-not-run"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, err := bt.Execute(context.Background(), in)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(res.Error, "invalid bash execution policy") {
|
||||
t.Fatalf("unknown policy must fail closed, got %q", res.Error)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeLLMText(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -51,10 +101,10 @@ func TestResolveBashCommandPaths(t *testing.T) {
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
cmd string
|
||||
wantCmd string
|
||||
wantSubs int
|
||||
name string
|
||||
cmd string
|
||||
wantCmd string
|
||||
wantSubs int
|
||||
}{
|
||||
{
|
||||
name: "backslash-escaped path with ascii spaces resolves to nbsp file",
|
||||
@@ -142,3 +192,38 @@ func TestResolveExistingPath(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllowlist_RejectsNewlineCRAndRedirection(t *testing.T) {
|
||||
allow := []string{"ls", "echo", "cat"}
|
||||
const metaMsg = "shell metacharacters not allowed"
|
||||
|
||||
// The live exploit: a real newline runs a second, unvalidated line.
|
||||
if got := runAllowlist(t, allow, "ls\ncurl http://evil"); !strings.Contains(got, metaMsg) {
|
||||
t.Fatalf("newline bypass: expected metacharacter rejection, got %q", got)
|
||||
}
|
||||
// Carriage return likewise.
|
||||
if got := runAllowlist(t, allow, "ls\rcurl http://evil"); !strings.Contains(got, metaMsg) {
|
||||
t.Fatalf("CR bypass: expected metacharacter rejection, got %q", got)
|
||||
}
|
||||
// Redirection write-primitive (allowed cmd overwriting a file).
|
||||
if got := runAllowlist(t, allow, "echo hi > /tmp/s1_x"); !strings.Contains(got, metaMsg) {
|
||||
t.Fatalf("redirection > not rejected, got %q", got)
|
||||
}
|
||||
if got := runAllowlist(t, allow, "echo hi >> /tmp/s1_x"); !strings.Contains(got, metaMsg) {
|
||||
t.Fatalf("append redirection >> not rejected, got %q", got)
|
||||
}
|
||||
// fd redirection also contains '>' so it is caught too.
|
||||
if got := runAllowlist(t, allow, "cat a 2>&1"); !strings.Contains(got, metaMsg) {
|
||||
t.Fatalf("fd redirection 2>&1 not rejected, got %q", got)
|
||||
}
|
||||
// Sanity: a plain allowed command still passes the policy gate.
|
||||
if got := runAllowlist(t, allow, "ls -l"); got != "" {
|
||||
t.Fatalf("plain allowed command wrongly rejected: %q", got)
|
||||
}
|
||||
// Sanity: input redirection '<' is NOT blocked (deliberate scope boundary);
|
||||
// cat is allowed so policy permits it (it may still fail at runtime if the
|
||||
// file is missing, but it must NOT be a policy rejection).
|
||||
if got := runAllowlist(t, allow, "cat < /etc/hostname"); strings.Contains(got, "metacharacters") || strings.Contains(got, "not in the exec allowlist") {
|
||||
t.Fatalf("input redirection wrongly rejected by policy: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,24 @@ const (
|
||||
janitorInterval = 1 * time.Minute
|
||||
)
|
||||
|
||||
// hostResolverRules forces Chrome to fail DNS resolution for private/internal
|
||||
// IP ranges and localhost, so in-page fetch() and evaluate()'d JS cannot reach
|
||||
// cloud-metadata endpoints or localhost services — the Go-side
|
||||
// ValidateURLNotInternal check only sees the top-level URL, so this covers
|
||||
// sub-resource and script-initiated requests. (S3)
|
||||
//
|
||||
// Residual gap: name-based rules do not stop a page that dials a *literal*
|
||||
// private IP URL in some Chrome builds; the complete fix is an allowlisting
|
||||
// proxy (deferred). See the security-deeper spec's limitations section.
|
||||
const hostResolverRules = "MAP localhost ~NOTFOUND," +
|
||||
"MAP *.localhost ~NOTFOUND," +
|
||||
"MAP 127.0.0.0/8 ~NOTFOUND," +
|
||||
"MAP 10.0.0.0/8 ~NOTFOUND," +
|
||||
"MAP 172.16.0.0/12 ~NOTFOUND," +
|
||||
"MAP 169.254.0.0/16 ~NOTFOUND," +
|
||||
"MAP 192.168.0.0/16 ~NOTFOUND," +
|
||||
"MAP [::1] ~NOTFOUND"
|
||||
|
||||
// stealthScript runs before any page script on every new document. It hides the
|
||||
// most common headless/automation tells that JS-heavy sites use to refuse to
|
||||
// render content (Cloudflare, Akamai, anti-bot scripts, "please enable JS"
|
||||
@@ -271,6 +289,10 @@ func (t *BrowserTool) Execute(ctx context.Context, input json.RawMessage) (tool.
|
||||
if in.Script == "" {
|
||||
return tool.ToolResult{Error: "script is required for evaluate action"}, nil
|
||||
}
|
||||
case "navigate", "get_text", "screenshot":
|
||||
// No additional required fields beyond the checks above.
|
||||
default:
|
||||
return tool.ToolResult{Error: fmt.Sprintf("unknown action: %q (valid: navigate, click, type, get_text, screenshot, evaluate, close)", in.Action)}, nil
|
||||
}
|
||||
|
||||
// Catch the about:blank trap: any post-navigation action (screenshot,
|
||||
@@ -372,7 +394,7 @@ func (t *BrowserTool) getOrCreateSession(name string) (*browserSession, error) {
|
||||
// both — wrap it.
|
||||
sess := &browserSession{
|
||||
taskCtx: taskCtx,
|
||||
taskCancel: cleanup, // cleanup tears down both task + alloc
|
||||
taskCancel: cleanup, // cleanup tears down both task + alloc
|
||||
allocCancel: func() {}, // no-op; cleanup already covers alloc
|
||||
lastUsed: time.Now(),
|
||||
}
|
||||
@@ -474,6 +496,7 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc,
|
||||
chromedp.UserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"),
|
||||
chromedp.Flag("disable-blink-features", "AutomationControlled"),
|
||||
chromedp.Flag("lang", "en-US"),
|
||||
chromedp.Flag("host-resolver-rules", hostResolverRules),
|
||||
chromedp.UserDataDir(udd),
|
||||
)...,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//go:build live
|
||||
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/chromedp/cdproto/runtime"
|
||||
"github.com/chromedp/chromedp"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestInPageFetchPrivateIPBlocked_Live verifies host-resolver-rules stops an
|
||||
// in-page fetch to a metadata IP. Requires a real Chrome. Run:
|
||||
// go test -tags live ./tools/browser/ -run TestInPageFetchPrivateIPBlocked_Live
|
||||
func TestInPageFetchPrivateIPBlocked_Live(t *testing.T) {
|
||||
tool := NewBrowserTool()
|
||||
defer tool.Shutdown()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
taskCtx, ccancel, err := launchBrowser(ctx)
|
||||
require.NoError(t, err)
|
||||
defer ccancel()
|
||||
|
||||
require.NoError(t, chromedp.Run(taskCtx, chromedp.Navigate("https://example.com")))
|
||||
|
||||
var result string
|
||||
script := `(async () => {
|
||||
try {
|
||||
await fetch('http://169.254.169.254/latest/meta-data/', {mode:'no-cors'});
|
||||
return 'REACHED';
|
||||
} catch (e) {
|
||||
return 'BLOCKED';
|
||||
}
|
||||
})()`
|
||||
err = chromedp.Run(taskCtx, chromedp.Evaluate(script, &result, func(p *runtime.EvaluateParams) *runtime.EvaluateParams {
|
||||
return p.WithAwaitPromise(true)
|
||||
}))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "BLOCKED", result, "in-page fetch to metadata IP must be blocked by host-resolver-rules")
|
||||
}
|
||||
@@ -4,12 +4,23 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestHostResolverRules_BlocksPrivateRanges(t *testing.T) {
|
||||
require.Contains(t, hostResolverRules, "127.0.0.0/8")
|
||||
require.Contains(t, hostResolverRules, "169.254.0.0/16")
|
||||
require.Contains(t, hostResolverRules, "10.0.0.0/8")
|
||||
require.Contains(t, hostResolverRules, "192.168.0.0/16")
|
||||
require.Contains(t, hostResolverRules, "172.16.0.0/12")
|
||||
require.Contains(t, hostResolverRules, "localhost")
|
||||
require.True(t, strings.Contains(hostResolverRules, "~NOTFOUND"))
|
||||
}
|
||||
|
||||
func TestBrowserToolName(t *testing.T) {
|
||||
tool := &BrowserTool{}
|
||||
assert.Equal(t, "browser", tool.Name())
|
||||
|
||||
+19
-2
@@ -5,7 +5,9 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
@@ -50,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
|
||||
@@ -61,6 +63,9 @@ func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
|
||||
}
|
||||
|
||||
in.Path = tool.ExpandHome(in.Path)
|
||||
if t.WorkDir != "" && !filepath.IsAbs(in.Path) {
|
||||
in.Path = filepath.Join(t.WorkDir, in.Path)
|
||||
}
|
||||
in.Path = tool.ResolveExistingPath(in.Path)
|
||||
|
||||
if t.WorkDir != "" {
|
||||
@@ -69,6 +74,14 @@ 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
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(in.Path)
|
||||
if err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil
|
||||
@@ -86,7 +99,11 @@ func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
|
||||
|
||||
newContent := strings.Replace(content, in.OldString, in.NewString, 1)
|
||||
|
||||
if err := os.WriteFile(in.Path, []byte(newContent), 0o644); err != nil {
|
||||
mode := os.FileMode(0o600)
|
||||
if info, statErr := os.Stat(in.Path); statErr == nil {
|
||||
mode = info.Mode().Perm()
|
||||
}
|
||||
if err := tool.WriteFileAtomic(in.Path, []byte(newContent), mode); err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("failed to write file: %v", err)}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestEditFilePreservesMode(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "code.txt")
|
||||
require.NoError(t, os.WriteFile(path, []byte("alpha beta"), 0o640))
|
||||
|
||||
tool := &EditFileTool{WorkDir: dir}
|
||||
in, _ := json.Marshal(map[string]string{
|
||||
"path": path,
|
||||
"old_string": "alpha",
|
||||
"new_string": "gamma",
|
||||
})
|
||||
res, err := tool.Execute(context.Background(), in)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, res.Error)
|
||||
|
||||
data, _ := os.ReadFile(path)
|
||||
require.Equal(t, "gamma beta", string(data))
|
||||
|
||||
info, err := os.Stat(path)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, os.FileMode(0o640), info.Mode().Perm())
|
||||
}
|
||||
@@ -48,6 +48,30 @@ func TestReadFileToolWorkDirClamps(t *testing.T) {
|
||||
"reads outside the workspace must be rejected when WorkDir is set")
|
||||
}
|
||||
|
||||
func TestReadFileToolWorkDirRejectsEscapingFileSymlink(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
outside := filepath.Join(t.TempDir(), "secret.txt")
|
||||
require.NoError(t, os.WriteFile(outside, []byte("nope"), 0o644))
|
||||
link := filepath.Join(workspace, "secret-link")
|
||||
require.NoError(t, os.Symlink(outside, link))
|
||||
|
||||
readTool := &ReadFileTool{WorkDir: workspace}
|
||||
input, _ := json.Marshal(readFileInput{Path: link})
|
||||
result, err := readTool.Execute(context.Background(), input)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, result.Error, "outside workspace")
|
||||
assert.Empty(t, result.Output)
|
||||
|
||||
writeTool := &WriteFileTool{WorkDir: workspace}
|
||||
writeInput, _ := json.Marshal(writeFileInput{Path: link, Content: "overwritten"})
|
||||
result, err = writeTool.Execute(context.Background(), writeInput)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, result.Error, "outside workspace")
|
||||
data, readErr := os.ReadFile(outside)
|
||||
require.NoError(t, readErr)
|
||||
assert.Equal(t, "nope", string(data))
|
||||
}
|
||||
|
||||
func TestWriteFileTool(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "subdir", "output.txt")
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
const (
|
||||
maxTextFileSize = 10 * 1024 * 1024 // 10 MB
|
||||
maxImageFileSize = 5 * 1024 * 1024 // 5 MB
|
||||
)
|
||||
|
||||
// checkFileSize stats path and returns a non-empty error string if the file
|
||||
// exceeds limit. kind is "text" or "image" for the message. Empty return means
|
||||
// within bounds (or stat failed, in which case the caller's read surfaces the
|
||||
// real error).
|
||||
func checkFileSize(path string, limit int64, kind string) string {
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if fi.Size() > limit {
|
||||
return fmt.Sprintf("file too large: %d bytes exceeds the %d byte limit for %s files; read a specific range or use a different tool",
|
||||
fi.Size(), limit, kind)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
+29
-3
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -71,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
|
||||
@@ -82,6 +83,9 @@ func (t *ReadFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
|
||||
}
|
||||
|
||||
in.Path = tool.ExpandHome(in.Path)
|
||||
if t.WorkDir != "" && !filepath.IsAbs(in.Path) {
|
||||
in.Path = filepath.Join(t.WorkDir, in.Path)
|
||||
}
|
||||
in.Path = tool.ResolveExistingPath(in.Path)
|
||||
|
||||
if t.WorkDir != "" {
|
||||
@@ -90,13 +94,35 @@ func (t *ReadFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
|
||||
}
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(in.Path)
|
||||
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"
|
||||
if _, isImg := imageExtMap[ext]; isImg {
|
||||
limit = int64(maxImageFileSize)
|
||||
kind = "image"
|
||||
}
|
||||
if msg := checkFileSize(in.Path, limit, kind); msg != "" {
|
||||
return tool.ToolResult{Error: msg}, nil
|
||||
}
|
||||
|
||||
f, err := os.Open(in.Path)
|
||||
if err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil
|
||||
}
|
||||
defer f.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(f, limit+1))
|
||||
if err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("file too large: exceeds the %d byte limit for %s files; read a specific range or use a different tool", limit, kind)}, nil
|
||||
}
|
||||
|
||||
// Check if this is an image file
|
||||
ext := strings.ToLower(filepath.Ext(in.Path))
|
||||
if mimeType, ok := imageExtMap[ext]; ok {
|
||||
mimeType = detectImageMIMEFromBytes(data, mimeType)
|
||||
return tool.ToolResult{
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func writeSized(t *testing.T, dir, name string, n int) string {
|
||||
t.Helper()
|
||||
p := filepath.Join(dir, name)
|
||||
require.NoError(t, os.WriteFile(p, make([]byte, n), 0o600))
|
||||
return p
|
||||
}
|
||||
|
||||
func TestReadFile_RejectsOversizedText(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
p := writeSized(t, dir, "big.txt", maxTextFileSize+1)
|
||||
tool := &ReadFileTool{}
|
||||
in, _ := json.Marshal(map[string]string{"path": p})
|
||||
res, err := tool.Execute(context.Background(), in)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, res.Error, "too large")
|
||||
}
|
||||
|
||||
func TestReadFile_AllowsNormalText(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "ok.txt")
|
||||
require.NoError(t, os.WriteFile(p, []byte("hello"), 0o600))
|
||||
tool := &ReadFileTool{}
|
||||
in, _ := json.Marshal(map[string]string{"path": p})
|
||||
res, err := tool.Execute(context.Background(), in)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, res.Error)
|
||||
require.Equal(t, "hello", res.Output)
|
||||
}
|
||||
|
||||
func TestReadFile_RejectsOversizedImage(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
p := writeSized(t, dir, "big.png", maxImageFileSize+1)
|
||||
tool := &ReadFileTool{}
|
||||
in, _ := json.Marshal(map[string]string{"path": p})
|
||||
res, err := tool.Execute(context.Background(), in)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, res.Error, "too large")
|
||||
}
|
||||
|
||||
func TestEditFile_RejectsOversized(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
p := writeSized(t, dir, "big.txt", maxTextFileSize+1)
|
||||
tool := &EditFileTool{}
|
||||
in, _ := json.Marshal(map[string]string{"path": p, "old_string": "a", "new_string": "b"})
|
||||
res, err := tool.Execute(context.Background(), in)
|
||||
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")
|
||||
}
|
||||
@@ -56,6 +56,9 @@ func (t *WriteFileTool) Execute(_ context.Context, input json.RawMessage) (tool.
|
||||
}
|
||||
|
||||
in.Path = tool.ExpandHome(in.Path)
|
||||
if t.WorkDir != "" && !filepath.IsAbs(in.Path) {
|
||||
in.Path = filepath.Join(t.WorkDir, in.Path)
|
||||
}
|
||||
|
||||
if t.WorkDir != "" {
|
||||
if err := tool.ValidatePathInWorkDir(in.Path, t.WorkDir); err != nil {
|
||||
@@ -69,7 +72,7 @@ func (t *WriteFileTool) Execute(_ context.Context, input json.RawMessage) (tool.
|
||||
return tool.ToolResult{Error: fmt.Sprintf("failed to create directory: %v", err)}, nil
|
||||
}
|
||||
|
||||
if err := os.WriteFile(in.Path, []byte(in.Content), 0o644); err != nil {
|
||||
if err := tool.WriteFileAtomic(in.Path, []byte(in.Content), 0o600); err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("failed to write file: %v", err)}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestWriteFileIsRestrictive(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "secret.txt")
|
||||
|
||||
tool := &WriteFileTool{WorkDir: dir}
|
||||
in, _ := json.Marshal(map[string]string{"path": path, "content": "data"})
|
||||
res, err := tool.Execute(context.Background(), in)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, res.Error)
|
||||
|
||||
info, err := os.Stat(path)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
|
||||
}
|
||||
@@ -125,6 +125,13 @@ func (c *Client) Tools() []tool.Tool { return c.tools }
|
||||
// Name returns the configured server name.
|
||||
func (c *Client) Name() string { return c.name }
|
||||
|
||||
// Ping verifies the session is alive by sending an MCP ping. A non-nil
|
||||
// error means the session (and for stdio servers, likely the child
|
||||
// process) is no longer usable.
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
return c.session.Ping(ctx, nil)
|
||||
}
|
||||
|
||||
// Close releases the underlying MCP session. Safe to call multiple
|
||||
// times — subsequent calls are no-ops.
|
||||
func (c *Client) Close() error {
|
||||
|
||||
@@ -150,6 +150,29 @@ func TestMCPClient_ConnectDiscovers(t *testing.T) {
|
||||
assert.ElementsMatch(t, []string{"mcp__srv__a", "mcp__srv__b"}, got)
|
||||
}
|
||||
|
||||
func TestMCPClient_PingLiveAndDead(t *testing.T) {
|
||||
// Built inline (not via startInProcessServer) because the test needs the
|
||||
// server session to kill the connection mid-life.
|
||||
ctx := context.Background()
|
||||
server := sdk.NewServer(&sdk.Implementation{Name: "test-server", Version: "v0"}, nil)
|
||||
tf := stringArgTool("noop", "no-op", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: ""}}}, nil
|
||||
})
|
||||
server.AddTool(tf.Tool, tf.Handler)
|
||||
clientTransport, serverTransport := sdk.NewInMemoryTransports()
|
||||
serverSession, err := server.Connect(ctx, serverTransport, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
cli, err := connectWithTransport(ctx, "srv", clientTransport, nil)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = cli.Close() })
|
||||
|
||||
require.NoError(t, cli.Ping(ctx), "ping against a live session must succeed")
|
||||
|
||||
require.NoError(t, serverSession.Close())
|
||||
assert.Error(t, cli.Ping(ctx), "ping after the server side died must fail")
|
||||
}
|
||||
|
||||
func TestMCPClient_CloseIsIdempotent(t *testing.T) {
|
||||
cli := startInProcessServer(t, "srv", []sdkToolFixture{
|
||||
stringArgTool("noop", "no-op", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SafeHTTPClient returns an *http.Client whose transport resolves and validates
|
||||
// the destination host, then dials the exact validated IP — closing the
|
||||
// TOCTOU/DNS-rebinding window where a stock http.Client would re-resolve the
|
||||
// hostname independently of ValidateURLNotInternal. Redirects are re-validated.
|
||||
func SafeHTTPClient(timeout time.Duration) *http.Client {
|
||||
dialer := &net.Dialer{Timeout: timeout}
|
||||
transport := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot resolve %q — blocking to prevent SSRF", host)
|
||||
}
|
||||
// Fail closed: if ANY resolved IP is private, refuse — this defeats
|
||||
// DNS-rebinding where one A record is public and another is private.
|
||||
for _, ip := range ips {
|
||||
if isPrivateIP(ip) {
|
||||
return nil, fmt.Errorf("access to internal address %s (%s) is blocked", host, ip)
|
||||
}
|
||||
}
|
||||
if len(ips) == 0 {
|
||||
return nil, fmt.Errorf("no usable address for %q", host)
|
||||
}
|
||||
// Try each validated public IP in order, falling back on dial
|
||||
// failure so dual-stack hosts still connect on IPv4-only or
|
||||
// IPv6-broken networks (stock happy-eyeballs is bypassed because we
|
||||
// dial literal IPs to pin the validated address).
|
||||
var lastErr error
|
||||
for _, ip := range ips {
|
||||
conn, derr := dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
|
||||
if derr == nil {
|
||||
return conn, nil
|
||||
}
|
||||
lastErr = derr
|
||||
}
|
||||
return nil, lastErr
|
||||
},
|
||||
}
|
||||
return &http.Client{
|
||||
Timeout: timeout,
|
||||
Transport: transport,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 {
|
||||
return fmt.Errorf("too many redirects (max 10)")
|
||||
}
|
||||
if err := ValidateURLNotInternal(req.URL.String()); err != nil {
|
||||
return fmt.Errorf("redirect blocked: %w", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSafeHTTPClient_BlocksPrivateAtDial(t *testing.T) {
|
||||
client := SafeHTTPClient(5 * time.Second)
|
||||
// 127.0.0.1 is itself private, so dialing it directly must be refused.
|
||||
_, err := client.Get("http://127.0.0.1:9/")
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "internal address")
|
||||
}
|
||||
|
||||
func TestSafeHTTPClient_AllowsPublic(t *testing.T) {
|
||||
client := SafeHTTPClient(5 * time.Second)
|
||||
tr, ok := client.Transport.(*http.Transport)
|
||||
require.True(t, ok)
|
||||
require.NotNil(t, tr.DialContext)
|
||||
require.NotNil(t, client.CheckRedirect)
|
||||
require.Equal(t, 5*time.Second, client.Timeout)
|
||||
}
|
||||
|
||||
func TestSafeHTTPClient_RedirectToPrivateBlocked(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "http://169.254.169.254/latest/meta-data/", http.StatusFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
client := SafeHTTPClient(5 * time.Second)
|
||||
// The httptest server binds loopback (private), so the FIRST dial is already blocked.
|
||||
_, err := client.Get(srv.URL)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestSafeHTTPClient_PublicUnreachableReturnsDialError(t *testing.T) {
|
||||
// 192.0.2.1 is RFC5737 TEST-NET-1 (public, unrouteable). It is NOT in the
|
||||
// private blocklist, so validation passes and we should get a DIAL error
|
||||
// (timeout/unreachable), not a "blocked" validation error — proving the
|
||||
// path dials rather than rejecting.
|
||||
client := SafeHTTPClient(2 * time.Second)
|
||||
_, err := client.Get("http://192.0.2.1/")
|
||||
require.Error(t, err)
|
||||
require.NotContains(t, err.Error(), "internal address")
|
||||
}
|
||||
|
||||
var _ = isPrivateIP(net.IPv4(127, 0, 0, 1))
|
||||
var _ = strings.TrimSpace
|
||||
@@ -14,9 +14,13 @@ var privateNetworks = []string{
|
||||
"172.16.0.0/12", // RFC 1918
|
||||
"192.168.0.0/16", // RFC 1918
|
||||
"169.254.0.0/16", // link-local
|
||||
"0.0.0.0/8", // "this" network / unspecified; routes to loopback on Linux
|
||||
"100.64.0.0/10", // CGNAT (RFC 6598)
|
||||
"192.0.0.0/24", // IETF protocol assignments (RFC 6890)
|
||||
"::1/128", // IPv6 loopback
|
||||
"fc00::/7", // IPv6 unique local
|
||||
"fe80::/10", // IPv6 link-local
|
||||
"::/128", // IPv6 unspecified
|
||||
}
|
||||
|
||||
var parsedPrivateNets []*net.IPNet
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestValidateURLNotInternal_BlocksLoopback(t *testing.T) {
|
||||
@@ -45,3 +47,28 @@ func TestValidateURLNotInternal_RejectsBadScheme(t *testing.T) {
|
||||
assert.Error(t, err, "non-http schemes must be rejected")
|
||||
_ = strings.TrimSpace(err.Error())
|
||||
}
|
||||
|
||||
func TestIsPrivateIP_BlocksReservedRanges(t *testing.T) {
|
||||
blocked := []string{
|
||||
"0.0.0.0", // unspecified / routes to loopback on Linux
|
||||
"0.0.0.1", // 0.0.0.0/8
|
||||
"100.64.0.0", // CGNAT 100.64.0.0/10
|
||||
"100.127.255.255", // CGNAT upper
|
||||
"192.0.0.1", // 192.0.0.0/24 IETF protocol assignments
|
||||
"::", // IPv6 unspecified ::/128
|
||||
}
|
||||
for _, s := range blocked {
|
||||
ip := net.ParseIP(s)
|
||||
require.NotNil(t, ip, "parse %s", s)
|
||||
require.True(t, isPrivateIP(ip), "%s must be treated as private/blocked", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsPrivateIP_AllowsPublic(t *testing.T) {
|
||||
pub := []string{"8.8.8.8", "1.1.1.1", "93.184.216.34", "2606:2800:220:1:248:1893:25c8:1946"}
|
||||
for _, s := range pub {
|
||||
ip := net.ParseIP(s)
|
||||
require.NotNil(t, ip, "parse %s", s)
|
||||
require.False(t, isPrivateIP(ip), "%s must be allowed (public)", s)
|
||||
}
|
||||
}
|
||||
+1
-13
@@ -85,19 +85,7 @@ func (t *WebFetchTool) Execute(ctx context.Context, input json.RawMessage) (tool
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: fetchTimeout,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 10 {
|
||||
return fmt.Errorf("too many redirects (max 10)")
|
||||
}
|
||||
// Re-validate each redirect destination against SSRF blocklist
|
||||
if err := ValidateURLNotInternal(req.URL.String()); err != nil {
|
||||
return fmt.Errorf("redirect blocked: %w", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
client := SafeHTTPClient(fetchTimeout)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestWebFetch_BlocksPrivateHost(t *testing.T) {
|
||||
tool := &WebFetchTool{}
|
||||
res, err := tool.Execute(context.Background(),
|
||||
[]byte(`{"url":"http://169.254.169.254/latest/meta-data/"}`))
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, res.Error, "private metadata IP must be rejected")
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -14,6 +15,11 @@ import (
|
||||
|
||||
const searchTimeout = 15 * time.Second
|
||||
|
||||
// searchClient is the shared SSRF-safe HTTP client for all web_search
|
||||
// backends. It pins the validated IP and re-validates redirects, bringing
|
||||
// web_search to parity with web_fetch. (N4)
|
||||
var searchClient = SafeHTTPClient(searchTimeout)
|
||||
|
||||
// WebSearchTool searches the web and returns results via a configurable
|
||||
// backend. The default backend (when Backend is nil) scrapes DuckDuckGo's
|
||||
// HTML interface — no API key required, but fragile to upstream HTML
|
||||
@@ -131,7 +137,7 @@ func duckDuckGoSearch(ctx context.Context, query string, maxResults int) ([]sear
|
||||
}
|
||||
req.Header.Set("User-Agent", "harness/1.0 (Go agent framework)")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
resp, err := searchClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -266,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)
|
||||
}
|
||||
@@ -17,6 +17,10 @@ import (
|
||||
// are constructed with their config (API key, base URL, etc.) at
|
||||
// registration time and remain immutable thereafter. This keeps the tool
|
||||
// dispatch path zero-allocation in the hot loop.
|
||||
//
|
||||
// Implementations that make outbound HTTP calls MUST use the package
|
||||
// searchClient (SafeHTTPClient) so a configured/typo'd internal base URL
|
||||
// cannot be used for SSRF. (N4)
|
||||
type WebSearchBackend interface {
|
||||
Name() string
|
||||
Search(ctx context.Context, query string, maxResults int) ([]searchResult, error)
|
||||
@@ -58,7 +62,7 @@ func (b *braveBackend) Search(ctx context.Context, q string, n int) ([]searchRes
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("X-Subscription-Token", b.apiKey)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
resp, err := searchClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -119,7 +123,7 @@ func (b *tavilyBackend) Search(ctx context.Context, q string, n int) ([]searchRe
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
resp, err := searchClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -169,7 +173,7 @@ func (b *searxngBackend) Search(ctx context.Context, q string, n int) ([]searchR
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
resp, err := searchClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func testCtx(t *testing.T) context.Context {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
return ctx
|
||||
}
|
||||
|
||||
func TestSearchClient_IsSafe(t *testing.T) {
|
||||
require.NotNil(t, searchClient)
|
||||
require.NotNil(t, searchClient.Transport)
|
||||
require.NotNil(t, searchClient.CheckRedirect)
|
||||
require.Equal(t, searchTimeout, searchClient.Timeout)
|
||||
}
|
||||
|
||||
func TestSearxng_BlocksPrivateBaseURL(t *testing.T) {
|
||||
b := newSearxngBackend("http://127.0.0.1:8080")
|
||||
_, err := b.Search(testCtx(t), "hello", 3)
|
||||
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