Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
897643db18 | ||
|
|
0ccfdb2a24 | ||
|
|
f624e4c7bd | ||
|
|
0ba1b4dbcc | ||
|
|
986c233d39 | ||
|
|
8e92125fb6 | ||
|
|
eb4fa67976 | ||
|
|
445614757b | ||
|
|
c7846eeab9 |
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
|
||||
@@ -87,8 +87,9 @@ a lot. The package is optimized for the use cases above, not these.
|
||||
hardened in 1.25. Older toolchains will fail at `go build`.
|
||||
- **An LLM API key**, depending on which provider(s) you wire in:
|
||||
`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, Google ADC for Gemini, or a
|
||||
Qwen DashScope key. For local models, point `openai.NewOpenAIProviderWithKind`
|
||||
at an Ollama endpoint — no key required.
|
||||
LiteLLM/OpenRouter key for those aggregators. For local models, point
|
||||
`openai.NewOpenAIProviderWithKind` at an Ollama endpoint — no key
|
||||
required.
|
||||
- **Optional: an MCP server** for `tools/mcp` integrations (any
|
||||
binary that speaks the Model Context Protocol — `npx
|
||||
@modelcontextprotocol/server-filesystem`, etc.).
|
||||
@@ -121,7 +122,8 @@ github.com/sausheong/harness/
|
||||
│ ├── anthropic/ # Anthropic LLMProvider (with prompt caching)
|
||||
│ ├── openai/ # OpenAI / OpenAI-compatible / local Ollama
|
||||
│ ├── gemini/ # Google Gemini via google.golang.org/genai
|
||||
│ └── qwen/ # Alibaba Qwen (OpenAI-compatible endpoint)
|
||||
│ ├── litellm/ # Self-hosted LiteLLM proxy (OpenAI-compatible)
|
||||
│ └── openrouter/ # OpenRouter aggregator (OpenAI-compatible)
|
||||
└── tools/ # Batteries-included concrete tools (each importable separately)
|
||||
├── file/ # read_file (with vision), write_file, edit_file
|
||||
├── bash/ # bash (with ExecPolicy: deny | allowlist | full)
|
||||
@@ -229,6 +231,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
|
||||
@@ -310,9 +315,12 @@ Deliberately not in scope (numbers from the same conceptual list):
|
||||
`clientcredentials.Config.Client(ctx)`) as `HTTPClient` —
|
||||
auto-refresh comes for free. Call `Runtime.Close()` to release
|
||||
sessions.
|
||||
- **Four providers, one interface.** Anthropic, OpenAI (and
|
||||
OpenAI-compatible / local Ollama), Gemini, and Qwen ship built-in.
|
||||
Adding a fifth is implementing `llm.Provider` (~300 LOC).
|
||||
- **Five providers, one interface.** Anthropic, OpenAI (and
|
||||
OpenAI-compatible / local Ollama), Gemini, LiteLLM, and OpenRouter ship
|
||||
built-in — LiteLLM and OpenRouter cost none of that ~300 LOC each,
|
||||
since both are thin constructors over the existing OpenAI-compatible
|
||||
path. Adding a genuinely new wire format is implementing
|
||||
`llm.Provider` (~300 LOC).
|
||||
|
||||
See [`developer.md`](./developer.md) for a step-by-step guide to
|
||||
building agents on top of Harness, including diagrams of the
|
||||
@@ -373,12 +381,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:
|
||||
|
||||
+5
-3
@@ -59,7 +59,8 @@ required pieces are inside `inputs`; everything in `deps` is optional;
|
||||
The four mandatory pieces:
|
||||
|
||||
* **`llm.LLMProvider`** (in `RuntimeInputs.Provider`) — a streaming
|
||||
chat client (Anthropic / OpenAI / Gemini / Qwen, or your own).
|
||||
chat client (Anthropic / OpenAI / Gemini / LiteLLM / OpenRouter, or
|
||||
your own).
|
||||
* **`tool.Registry`** (in `RuntimeInputs.Tools`) — the tools the LLM
|
||||
may invoke. Each tool implements `tool.Tool`.
|
||||
* **`session.Session`** (in `RuntimeInputs.Session`) — append-only
|
||||
@@ -387,9 +388,10 @@ Each provider has its own constructor. All return an `llm.LLMProvider`.
|
||||
|--------------|--------------------------------------------------------|-------------------------------------|
|
||||
| Anthropic | `anthropic.NewAnthropicProvider(apiKey, baseURL)` | `baseURL == ""` → official endpoint |
|
||||
| OpenAI | `openai.NewOpenAIProvider(apiKey, baseURL)` | `baseURL == ""` → official endpoint |
|
||||
| OpenAI-compat| `openai.NewOpenAIProviderWithKind(apiKey, baseURL, "ollama"\|"compat")` | for local Ollama, etc. |
|
||||
| OpenAI-compat| `openai.NewOpenAIProviderWithKind(apiKey, baseURL, "local"\|"openai-compatible")` | for local Ollama, etc. |
|
||||
| Gemini | `gemini.NewGeminiProvider(ctx, apiKey)` | takes `context.Context` |
|
||||
| Qwen | `qwen.NewQwenProvider(apiKey, baseURL)` | OpenAI-compatible endpoint |
|
||||
| LiteLLM | `litellm.NewLiteLLMProvider(apiKey, baseURL)` | `baseURL` required (self-hosted) |
|
||||
| OpenRouter | `openrouter.NewOpenRouterProvider(apiKey, baseURL)` | `baseURL == ""` → OpenRouter's public endpoint |
|
||||
|
||||
The provider you pass on `RuntimeInputs.Provider` only needs to match the
|
||||
provider prefix in `AgentSpec.Model` — `runtime.BuildRuntime` parses
|
||||
|
||||
@@ -1,387 +0,0 @@
|
||||
# Run-Total Token Usage Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Make `Runtime.Run`'s terminal `EventDone.Usage` carry the token total accumulated across all turns, instead of only the last turn.
|
||||
|
||||
**Architecture:** Add a pure, non-mutating `addUsage` helper that field-wise sums two `*llm.Usage` snapshots; declare a run-scoped accumulator in `Run` outside the turn loop; fold each turn's provider usage into it; emit the accumulator (not `lastUsage`) on the single terminal `EventDone`. `RunTurn` is unchanged (one turn per call, already correct).
|
||||
|
||||
**Tech Stack:** Go 1.25, harness `runtime` + `llm` packages, `llmtest.Base`, testify.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- Module `github.com/sausheong/harness`. Work on branch `run-total-usage` — do NOT switch branches.
|
||||
- `EventDone` stays the SINGLE terminal event (subagent layer keys `Done` on it). No new events, no new fields.
|
||||
- Behavior preserved: usage-less providers → terminal `EventDone.Usage` stays nil; single-turn runs → identical to today; the calibrator block keeps using the per-turn `event.Usage`, NOT the accumulator.
|
||||
- Only `runtime/runtime.go`'s `Run` changes. Do NOT modify `RunTurn` (`runtime/runturn.go`).
|
||||
- Sum ALL FOUR `llm.Usage` fields: `InputTokens`, `OutputTokens`, `CacheCreationInputTokens`, `CacheReadInputTokens`.
|
||||
- Gates per task: `go build ./...`, `go vet ./...` clean; named tests pass.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: addUsage helper (pure)
|
||||
|
||||
**Files:**
|
||||
- Modify: `runtime/runtime.go` (add the helper; or create `runtime/usage.go` — implementer's choice, but keep it in package `runtime`)
|
||||
- Test: `runtime/usage_test.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `llm.Usage` (fields `InputTokens`, `OutputTokens`, `CacheCreationInputTokens`, `CacheReadInputTokens`, all `int`).
|
||||
- Produces: `func addUsage(acc, turn *llm.Usage) *llm.Usage` — field-wise sum; nil treated as zero; returns a fresh pointer; returns nil only when both args are nil; never mutates either argument.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
Create `runtime/usage_test.go`:
|
||||
|
||||
```go
|
||||
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
|
||||
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)
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `go test ./runtime/ -run TestAddUsage -v`
|
||||
Expected: FAIL — `addUsage` undefined.
|
||||
|
||||
- [ ] **Step 3: Implement the helper**
|
||||
|
||||
Add to `runtime/runtime.go` (near other unexported helpers) or a new `runtime/usage.go`:
|
||||
|
||||
```go
|
||||
// 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
|
||||
}
|
||||
```
|
||||
|
||||
If creating `runtime/usage.go`, start it with `package runtime` and `import "github.com/sausheong/harness/llm"`.
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `go test ./runtime/ -run TestAddUsage -v`
|
||||
Expected: PASS (4 tests).
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add runtime/usage.go runtime/usage_test.go runtime/runtime.go
|
||||
git commit -m "feat(runtime): add pure addUsage helper for field-wise usage summation"
|
||||
```
|
||||
|
||||
(Adjust `git add` to whichever files you actually touched.)
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Accumulate run-total usage in Run
|
||||
|
||||
**Files:**
|
||||
- Modify: `runtime/runtime.go` (the `Run` method — accumulator decl, the `llm.EventDone` case ~line 586-591, the terminal emit ~line 716)
|
||||
- Test: `runtime/run_usage_test.go`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `addUsage` (Task 1); harness `llmtest.Base`, `llm.ChatEvent`, `llm.EventDone`, `llm.Usage`; `runtime.AgentEvent`, `runtime.EventDone`.
|
||||
- Produces: corrected terminal `EventDone.Usage` (run total). No new exported symbols.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
Create `runtime/run_usage_test.go`. This uses a scripted provider that emits a tool call on turn 1 (forcing a second turn) with usage, then text + usage on turn 2, mirroring the `threeToolCallLLM` pattern already in `agent_test.go`.
|
||||
|
||||
```go
|
||||
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
|
||||
}
|
||||
|
||||
// noopExecutor returns "ok" for a "noop" tool.
|
||||
type noopExecutor struct{}
|
||||
|
||||
func (noopExecutor) Execute(_ context.Context, _ string, _ json.RawMessage) (tool.ToolResult, error) {
|
||||
return tool.ToolResult{Output: "ok"}, nil
|
||||
}
|
||||
func (noopExecutor) ToolDefs() []llm.ToolDef { return []llm.ToolDef{{Name: "noop"}} }
|
||||
func (noopExecutor) Names() []string { return []string{"noop"} }
|
||||
func (noopExecutor) 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: noopExecutor{},
|
||||
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: noopExecutor{},
|
||||
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: noopExecutor{},
|
||||
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")
|
||||
}
|
||||
```
|
||||
|
||||
Note: confirm the exact `tool.Executor` interface method set by reading `tool/registry.go` or an existing fake in `agent_test.go` (e.g. `cancelOnNthExecutor`). Match its method signatures exactly — `Execute`, `ToolDefs`, `Names`, `Get` are what the existing fake implements; adjust if the interface differs.
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `go test ./runtime/ -run TestRun_Usage -v`
|
||||
Expected: FAIL — `TestRun_UsageAccumulatesAcrossTurns` gets 10/5 (last turn only), not 110/45, because Run still emits `lastUsage`.
|
||||
|
||||
- [ ] **Step 3: Implement the accumulation**
|
||||
|
||||
In `runtime/runtime.go`, in the `Run` method:
|
||||
|
||||
(a) Declare the accumulator just BEFORE the turn loop `for turn := 0; turn < maxTurns; turn++ {` (~line 397):
|
||||
|
||||
```go
|
||||
var runUsage *llm.Usage // accumulated across all turns; nil until first reported
|
||||
```
|
||||
|
||||
(b) In the `case llm.EventDone:` block (~line 586-591), after `lastUsage = event.Usage`, fold into the accumulator:
|
||||
|
||||
```go
|
||||
case llm.EventDone:
|
||||
refused = event.StopReason == llm.StopReasonRefusal
|
||||
refusalCategory = event.StopCategory
|
||||
if event.Usage != nil {
|
||||
lastUsage = event.Usage
|
||||
runUsage = addUsage(runUsage, event.Usage)
|
||||
}
|
||||
// (existing calibrator block below stays exactly as-is —
|
||||
// it uses event.Usage, the per-turn figure, not runUsage)
|
||||
```
|
||||
|
||||
(c) At the terminal completed emit (~line 716), change `lastUsage` to `runUsage`:
|
||||
|
||||
```go
|
||||
stopReason = "completed"
|
||||
r.emit(AgentEvent{Type: EventDone, Usage: runUsage})
|
||||
```
|
||||
|
||||
Do NOT change the calibrator block, `lastUsage`'s other uses, or any other emission. Confirm via `grep -n "EventDone" runtime/runtime.go` that line 716 is the only `AgentEvent{Type: EventDone}` emit in `Run` (it is, per the spec); if there are others on terminal paths, switch them to `runUsage` too and note it in the report.
|
||||
|
||||
- [ ] **Step 4: Run tests to verify they pass**
|
||||
|
||||
Run: `go test ./runtime/ -run 'TestRun_Usage|TestAddUsage' -v`
|
||||
Expected: PASS (accumulate=110/45/11/8; single-turn=7/3; nil-when-silent=nil).
|
||||
|
||||
- [ ] **Step 5: Full runtime suite (no regression)**
|
||||
|
||||
Run: `go test ./runtime/... && go vet ./... && go build ./...`
|
||||
Expected: all PASS / clean. If any pre-existing test asserted the old last-turn-only usage, investigate and report before "fixing" it — that would be a behavior the change intentionally alters; flag it rather than silently editing.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add runtime/runtime.go runtime/run_usage_test.go
|
||||
git commit -m "fix(runtime): emit run-total token usage on terminal EventDone
|
||||
|
||||
Run accumulated only the last turn's usage into the terminal EventDone, so
|
||||
multi-turn runs under-reported tokens to consumers metering AgentEvent.Usage.
|
||||
Sum all four usage fields across turns; RunTurn is unchanged (one turn/call)."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Document the field semantics
|
||||
|
||||
**Files:**
|
||||
- Modify: `runtime/runtime.go` (the `AgentEvent.Usage` field doc comment, line ~48)
|
||||
- Modify: `developer.md` (the usage example region, ~line 471 — only if it characterizes the figure; otherwise leave)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: nothing.
|
||||
- Produces: accurate doc comment.
|
||||
|
||||
- [ ] **Step 1: Update the field doc comment**
|
||||
|
||||
In `runtime/runtime.go`, change the `AgentEvent.Usage` comment (~line 48) from:
|
||||
|
||||
```go
|
||||
Usage *llm.Usage // populated for EventDone when the provider reported it
|
||||
```
|
||||
|
||||
to:
|
||||
|
||||
```go
|
||||
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
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Check developer.md**
|
||||
|
||||
Read `developer.md` around line 471. If the surrounding prose describes `ev.Usage` as per-call/per-turn in a way the change now contradicts, update it to say the terminal `EventDone` carries the run total. If it only prints the numbers without characterizing them, leave it unchanged.
|
||||
|
||||
- [ ] **Step 3: Verify build (docs/comment only)**
|
||||
|
||||
Run: `go build ./... && go vet ./...`
|
||||
Expected: clean.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add runtime/runtime.go developer.md
|
||||
git commit -m "docs(runtime): clarify EventDone.Usage is the run total"
|
||||
```
|
||||
|
||||
(Drop `developer.md` from the add if you didn't change it.)
|
||||
|
||||
---
|
||||
|
||||
## Self-Review Notes
|
||||
|
||||
- **Spec coverage:** addUsage helper (T1), accumulator + terminal emit + preserved calibrator/nil/single-turn behavior (T2), field doc (T3). All spec items mapped.
|
||||
- **Scope guard:** plan explicitly forbids touching `RunTurn` and the calibrator block; T2 step 3 calls this out.
|
||||
- **Type consistency:** `addUsage(acc, turn *llm.Usage) *llm.Usage` used identically in T1 and T2; the four `llm.Usage` field names match across tests and helper.
|
||||
- **Behavior preservation** is directly tested: single-turn (T2 test 2) and nil-when-silent (T2 test 3), not just asserted in prose.
|
||||
- **Test-fixture risk flagged:** T2 step 1 tells the implementer to verify the `tool.Executor` interface method set against the real interface / existing fakes rather than trust the snippet.
|
||||
@@ -1,155 +0,0 @@
|
||||
# Design: Run-Total Token Usage on Terminal EventDone
|
||||
|
||||
**Date:** 2026-06-26
|
||||
**Project:** harness (`github.com/sausheong/harness`)
|
||||
**Status:** Approved (design)
|
||||
|
||||
## Motivation
|
||||
|
||||
`Runtime.Run` executes a multi-turn agent loop. Each turn captures the provider's
|
||||
per-turn token usage into a local `lastUsage`, but the terminal
|
||||
`AgentEvent{Type: EventDone}` is emitted once carrying only the **last turn's**
|
||||
usage (`runtime/runtime.go:716`). For a multi-turn run, all prior turns' tokens
|
||||
are silently dropped.
|
||||
|
||||
Downstream consumers that meter spend from `AgentEvent.Usage` (e.g. sidecar's
|
||||
daily token budget cap) therefore undercount multi-turn runs — the cap reads one
|
||||
turn instead of the whole run. The field's doc comment ("populated for EventDone
|
||||
when the provider reported it") implies a complete figure; today it is partial.
|
||||
|
||||
## Goal
|
||||
|
||||
Make the terminal `EventDone.Usage` carry the **accumulated total across all
|
||||
turns of the run**, summing all four `llm.Usage` fields (InputTokens,
|
||||
OutputTokens, CacheCreationInputTokens, CacheReadInputTokens).
|
||||
|
||||
## Non-goals
|
||||
|
||||
- No new events and no new fields: `EventDone` stays the single terminal event
|
||||
(the subagent layer keys `Done` on it — `runtime/subagent.go:134` — so adding
|
||||
per-turn `EventDone`s would break that contract). This is a value-correctness
|
||||
fix to the existing field, not a protocol change.
|
||||
- No per-turn usage telemetry surface. (Out of scope; `RunTurn` already exposes
|
||||
per-turn usage via `TurnResult.Usage` for callers that want it.)
|
||||
|
||||
## Scope: `Run` only, not `RunTurn`
|
||||
|
||||
`RunTurn` executes **exactly one turn per call** by contract; its caller drives
|
||||
the loop and accumulates `TurnResult.Usage` itself. Its `EventDone.Usage` (one
|
||||
turn) is therefore already correct. **Do not change `RunTurn`.** The bug is
|
||||
solely in `Run`'s internal `for turn := 0; turn < maxTurns; turn++` loop.
|
||||
|
||||
## Design
|
||||
|
||||
In `Runtime.Run` (`runtime/runtime.go`), introduce a run-scoped accumulator
|
||||
declared **outside** the turn loop (the loop starts at line 397):
|
||||
|
||||
```go
|
||||
var runUsage *llm.Usage // accumulated across all turns; nil until first reported
|
||||
```
|
||||
|
||||
Inside the turn loop, at the point where the provider's `llm.EventDone` is
|
||||
handled and `lastUsage = event.Usage` is set (currently ~line 589–591), fold the
|
||||
turn's usage into the accumulator:
|
||||
|
||||
```go
|
||||
case llm.EventDone:
|
||||
refused = event.StopReason == llm.StopReasonRefusal
|
||||
refusalCategory = event.StopCategory
|
||||
if event.Usage != nil {
|
||||
lastUsage = event.Usage
|
||||
runUsage = addUsage(runUsage, event.Usage)
|
||||
}
|
||||
// ... existing calibrator block unchanged (it still uses event.Usage,
|
||||
// the per-turn figure — calibration is per-request, not per-run) ...
|
||||
```
|
||||
|
||||
The terminal completed emission (line 716) changes from `lastUsage` to the
|
||||
accumulator:
|
||||
|
||||
```go
|
||||
stopReason = "completed"
|
||||
r.emit(AgentEvent{Type: EventDone, Usage: runUsage})
|
||||
```
|
||||
|
||||
### Helper
|
||||
|
||||
Add an unexported helper (in `runtime/runtime.go` or a small `usage.go` in
|
||||
package runtime):
|
||||
|
||||
```go
|
||||
// addUsage returns the field-wise sum of two usage snapshots. A nil operand is
|
||||
// treated as zero. Returns a new pointer; never mutates its arguments. Returns
|
||||
// nil only when both are nil (so EventDone.Usage stays nil when the provider
|
||||
// never reported usage — preserving today's behavior for usage-less providers).
|
||||
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
|
||||
}
|
||||
```
|
||||
|
||||
### Why a non-mutating helper
|
||||
|
||||
`event.Usage` points into the provider's stream event; mutating it could corrupt
|
||||
provider-side state or other observers. `addUsage` always returns a fresh value.
|
||||
|
||||
## Behavior preservation
|
||||
|
||||
- **Usage-less providers** (never send `llm.EventDone.Usage`): `runUsage` stays
|
||||
nil → terminal `EventDone.Usage` is nil, exactly as today.
|
||||
- **Single-turn runs:** `runUsage` == that turn's usage → identical to today.
|
||||
- **Calibrator:** unchanged — it consumes the per-turn `event.Usage`
|
||||
(per-request calibration), not the run total.
|
||||
- **`lastUsage`:** retained; still used by the non-streaming/other terminal
|
||||
paths if any reference it. (Verify during implementation that every terminal
|
||||
`EventDone` emission in `Run` uses `runUsage`; if there is more than one, all
|
||||
must switch. The known one is line 716.)
|
||||
|
||||
## Error handling
|
||||
|
||||
No new failure modes. `addUsage` is pure and total. nil-safe on both operands.
|
||||
|
||||
## Testing
|
||||
|
||||
Mirror the existing scripted-provider pattern in `runtime/agent_test.go` (a fake
|
||||
`llm.LLMProvider` whose `ChatStream` emits canned events including
|
||||
`llm.EventDone` with a `*llm.Usage`).
|
||||
|
||||
| Test | Setup | Assert |
|
||||
|------|-------|--------|
|
||||
| `TestRun_UsageAccumulatesAcrossTurns` | scripted provider: turn 1 emits a tool call + `EventDone{Usage: 100/40/…}`, turn 2 emits text + `EventDone{Usage: 10/5/…}` and stops | terminal `AgentEvent{EventDone}.Usage` == field-wise sum (110 in / 45 out / summed cache) |
|
||||
| `TestRun_UsageSingleTurn` | one turn, `EventDone{Usage: 7/3}` | terminal usage == 7/3 (no regression) |
|
||||
| `TestRun_UsageNilWhenProviderSilent` | provider never sets `EventDone.Usage` | terminal `EventDone.Usage` == nil |
|
||||
| `TestAddUsage` (pure) | nil+nil, nil+x, x+nil, x+y across all four fields | correct sums; inputs not mutated |
|
||||
|
||||
Gate: `go test ./runtime/...`, `go vet ./...`, `go build ./...` clean. Run the
|
||||
broader `go test ./...` to confirm no other runtime test asserted the old
|
||||
last-turn-only behavior.
|
||||
|
||||
## Downstream note (sidecar)
|
||||
|
||||
This fixes the root cause of sidecar's documented budget undercount for the
|
||||
**coding** runtime (multi-turn) and the **evaluator** (up to 8 turns). After
|
||||
harness ships this, sidecar's CLAUDE.md / sidecar.yaml caveat about multi-turn
|
||||
undercount can be softened to note only provider-reported-usage caveats. (Triage
|
||||
is single-turn and already exact.) That doc update is a separate sidecar change,
|
||||
not part of this harness spec.
|
||||
|
||||
## Files
|
||||
|
||||
- Modified: `runtime/runtime.go` (accumulator + helper + terminal emission).
|
||||
- New test cases: `runtime/runtime_usage_test.go` (or appended to
|
||||
`runtime/agent_test.go`).
|
||||
- New: this design doc.
|
||||
+13
-2
@@ -34,8 +34,8 @@ const stripCacheMax = 256
|
||||
// ApplyStripList runs StripFields over each tool's Parameters with the
|
||||
// given field-strip list, preserving input order and accumulating
|
||||
// diagnostics across all tools. The per-provider NormalizeToolSchema
|
||||
// methods (OpenAI, Qwen, Gemini) are thin wrappers over this helper —
|
||||
// only the strip list differs. Anthropic doesn't use this (identity).
|
||||
// methods (OpenAI, Gemini) are thin wrappers over this helper — only the
|
||||
// strip list differs. Anthropic doesn't use this (identity).
|
||||
//
|
||||
// Memoized: identical inputs return cached output without re-walking
|
||||
// the JSON Schema. Cache key is a SHA-256 over (sorted fields, tool
|
||||
@@ -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")
|
||||
}
|
||||
+70
-23
@@ -41,11 +41,14 @@ type ThinkingBlock struct {
|
||||
type Message struct {
|
||||
Role string `json:"role"` // "user", "assistant", "system"
|
||||
Content string `json:"content,omitempty"`
|
||||
Images []ImageContent `json:"-"` // image attachments (not serialized)
|
||||
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
|
||||
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.
|
||||
@@ -57,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
|
||||
@@ -79,14 +90,15 @@ 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.
|
||||
// Zero value (ReasoningOff) means no extended reasoning — safe default
|
||||
// for existing call sites that don't set the field. Each provider maps
|
||||
// this to its native config (Anthropic thinking budget, OpenAI
|
||||
// reasoning_effort, Gemini ThinkingConfig, Qwen enable_thinking).
|
||||
// reasoning_effort, Gemini ThinkingConfig).
|
||||
type ReasoningMode string
|
||||
|
||||
const (
|
||||
@@ -96,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.
|
||||
@@ -116,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
|
||||
@@ -130,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.
|
||||
@@ -143,12 +190,12 @@ type Usage struct {
|
||||
|
||||
// ChatEvent is a single streaming event from the LLM.
|
||||
type ChatEvent struct {
|
||||
Type EventType
|
||||
Text string
|
||||
ToolCall *ToolCall
|
||||
Type EventType
|
||||
Text string
|
||||
ToolCall *ToolCall
|
||||
ThinkingBlock *ThinkingBlock // populated on EventThinkingBlock
|
||||
Usage *Usage
|
||||
Error error
|
||||
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
|
||||
@@ -248,10 +295,10 @@ func JoinSystemPromptParts(parts []SystemPromptPart) string {
|
||||
// ProviderOptions holds connection details for creating an LLM provider.
|
||||
// Kept here so consumers can pass a single struct around even though the
|
||||
// concrete provider constructors live in subpackages
|
||||
// (harness/providers/{anthropic,openai,gemini,qwen}). Each subpackage's
|
||||
// New() takes the relevant fields directly.
|
||||
// (harness/providers/{anthropic,openai,gemini,litellm,openrouter}). Each
|
||||
// subpackage's New() takes the relevant fields directly.
|
||||
type ProviderOptions struct {
|
||||
APIKey string
|
||||
BaseURL string
|
||||
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini" | "qwen"
|
||||
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini"
|
||||
}
|
||||
@@ -61,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)
|
||||
@@ -87,22 +89,67 @@ 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 && !anthropicAdaptiveThinkingOnly(model) {
|
||||
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 anthropicAdaptiveThinkingOnly(model) {
|
||||
// Fable 5 / Mythos 5 / Opus 4.7+ reject the legacy
|
||||
// enabled+budget_tokens config (400 "thinking.type.enabled is
|
||||
// not supported"). They take {type:"adaptive"} plus
|
||||
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.
|
||||
// Reasoning off → omit thinking entirely (Fable 5 rejects an
|
||||
// explicit {type:"disabled"} too).
|
||||
if req.Reasoning != llm.ReasoningOff {
|
||||
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||
OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{},
|
||||
@@ -113,7 +160,22 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
|
||||
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 {
|
||||
@@ -451,11 +513,12 @@ func (p *AnthropicProvider) BuildThinkingConfig(model string, mode llm.Reasoning
|
||||
}
|
||||
|
||||
// anthropicAdaptiveThinkingOnly reports whether the model accepts ONLY
|
||||
// adaptive thinking: Claude Fable 5, Claude Mythos 5, and Opus 4.7+.
|
||||
// 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.
|
||||
// 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",
|
||||
@@ -464,6 +527,8 @@ func anthropicAdaptiveThinkingOnly(model string) bool {
|
||||
"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) {
|
||||
@@ -473,6 +538,25 @@ func anthropicAdaptiveThinkingOnly(model string) bool {
|
||||
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 {
|
||||
@@ -526,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 {
|
||||
@@ -538,9 +626,16 @@ 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
|
||||
@@ -565,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...))
|
||||
}
|
||||
}
|
||||
@@ -575,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
|
||||
@@ -587,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
|
||||
@@ -650,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)
|
||||
}
|
||||
@@ -665,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
|
||||
}
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
"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.
|
||||
@@ -235,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)
|
||||
@@ -525,12 +584,18 @@ data: {"type":"message_stop"}
|
||||
|
||||
// --- Adaptive-thinking model mapping ---------------------------------
|
||||
//
|
||||
// Claude Fable 5, Claude Mythos 5, and Opus 4.7/4.8 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.
|
||||
// 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()
|
||||
@@ -544,11 +609,13 @@ 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-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) {
|
||||
@@ -601,9 +668,63 @@ func TestAdaptiveThinkingModels_ReasoningOffOmitsThinking(t *testing.T) {
|
||||
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"} {
|
||||
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,
|
||||
@@ -617,6 +738,27 @@ func TestAdaptiveThinkingModels_TemperatureDropped(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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{
|
||||
|
||||
@@ -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"
|
||||
@@ -213,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,
|
||||
@@ -251,6 +272,24 @@ 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.
|
||||
@@ -300,7 +339,7 @@ func geminiSupportsThinking(model string) bool {
|
||||
}
|
||||
|
||||
// geminiResolveSystemPrompt returns the effective system prompt string,
|
||||
// preferring SystemPromptParts when present. Mirrors the OpenAI/Qwen
|
||||
// preferring SystemPromptParts when present. Mirrors the OpenAI
|
||||
// resolution path but the per-provider helper avoids importing the
|
||||
// genai SDK in test code.
|
||||
func geminiResolveSystemPrompt(req llm.ChatRequest) string {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package gemini
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -33,3 +34,22 @@ func TestGeminiUsageBuffer_KeepsLast(t *testing.T) {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Package litellm provides an llm.LLMProvider for a self-hosted LiteLLM
|
||||
// proxy. LiteLLM speaks the OpenAI chat-completions wire format and
|
||||
// itself routes to dozens of underlying vendors, so this package adds no
|
||||
// new request/stream-translation code of its own — it's a thin
|
||||
// constructor around harness's existing OpenAI-compatible support.
|
||||
package litellm
|
||||
|
||||
import "github.com/sausheong/harness/providers/openai"
|
||||
|
||||
// NewLiteLLMProvider returns an OpenAI-compatible provider pointed at
|
||||
// baseURL, a self-hosted LiteLLM proxy endpoint. Unlike OpenRouter,
|
||||
// LiteLLM has no public default endpoint — callers must supply a
|
||||
// non-empty baseURL (cmd/hand's buildProvider, for example, rejects an
|
||||
// empty one with a clear error before ever reaching here).
|
||||
// kind="openai-compatible" suppresses reasoning_effort, since not every
|
||||
// model LiteLLM routes a request to is guaranteed to support it.
|
||||
func NewLiteLLMProvider(apiKey, baseURL string) *openai.OpenAIProvider {
|
||||
return openai.NewOpenAIProviderWithKind(apiKey, baseURL, "openai-compatible")
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package litellm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
// TestNewLiteLLMProvider_HitsGivenBaseURL confirms the provider actually
|
||||
// targets the baseURL it was constructed with, and that a streamed
|
||||
// response comes back through it — not re-testing OpenAI wire-format
|
||||
// translation itself (already covered by providers/openai's own tests),
|
||||
// just that this thin constructor wires the base URL through correctly.
|
||||
func TestNewLiteLLMProvider_HitsGivenBaseURL(t *testing.T) {
|
||||
var hit bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hit = true
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: [DONE]\n\n"))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewLiteLLMProvider("test-key", srv.URL+"/v1")
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{SystemPrompt: "hi"})
|
||||
require.NoError(t, err)
|
||||
for range stream {
|
||||
}
|
||||
require.True(t, hit, "provider did not hit the configured baseURL")
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Package openrouter provides an llm.LLMProvider for OpenRouter, an
|
||||
// aggregator that fronts hundreds of underlying models behind one
|
||||
// OpenAI-compatible endpoint. Like providers/litellm, this adds no new
|
||||
// request/stream-translation code of its own — it's a thin constructor
|
||||
// around harness's existing OpenAI-compatible support.
|
||||
package openrouter
|
||||
|
||||
import "github.com/sausheong/harness/providers/openai"
|
||||
|
||||
// DefaultBaseURL is OpenRouter's public API endpoint, used when
|
||||
// NewOpenRouterProvider is called with an empty baseURL.
|
||||
const DefaultBaseURL = "https://openrouter.ai/api/v1"
|
||||
|
||||
// NewOpenRouterProvider returns an OpenAI-compatible provider pointed at
|
||||
// baseURL, or DefaultBaseURL when baseURL is empty. kind="openai-compatible"
|
||||
// suppresses reasoning_effort, since OpenRouter's underlying models don't
|
||||
// uniformly support it.
|
||||
func NewOpenRouterProvider(apiKey, baseURL string) *openai.OpenAIProvider {
|
||||
if baseURL == "" {
|
||||
baseURL = DefaultBaseURL
|
||||
}
|
||||
return openai.NewOpenAIProviderWithKind(apiKey, baseURL, "openai-compatible")
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package openrouter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
func TestDefaultBaseURL(t *testing.T) {
|
||||
require.Equal(t, "https://openrouter.ai/api/v1", DefaultBaseURL)
|
||||
}
|
||||
|
||||
// TestNewOpenRouterProvider_HitsGivenBaseURL confirms a custom baseURL
|
||||
// overrides the default and is actually what the provider talks to.
|
||||
func TestNewOpenRouterProvider_HitsGivenBaseURL(t *testing.T) {
|
||||
var hit bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hit = true
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: [DONE]\n\n"))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewOpenRouterProvider("test-key", srv.URL+"/v1")
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{SystemPrompt: "hi"})
|
||||
require.NoError(t, err)
|
||||
for range stream {
|
||||
}
|
||||
require.True(t, hit, "provider did not hit the configured baseURL")
|
||||
}
|
||||
|
||||
// TestNewOpenRouterProvider_EmptyBaseURLDoesNotPanic confirms the empty
|
||||
// -> DefaultBaseURL fallback path constructs a usable provider (the
|
||||
// actual outbound host isn't inspectable from outside the openai
|
||||
// package — OpenAIProvider's client config is unexported — so this
|
||||
// checks the fallback doesn't panic or return nil, and DefaultBaseURL's
|
||||
// own value is asserted separately above).
|
||||
func TestNewOpenRouterProvider_EmptyBaseURLDoesNotPanic(t *testing.T) {
|
||||
p := NewOpenRouterProvider("test-key", "")
|
||||
require.NotNil(t, p)
|
||||
}
|
||||
@@ -1,370 +0,0 @@
|
||||
package qwen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"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 {
|
||||
client *openai.Client
|
||||
}
|
||||
|
||||
// NewQwenProvider creates a new Qwen LLM provider.
|
||||
// The Qwen API is OpenAI-compatible, so we use the go-openai client
|
||||
// with Qwen's base URL.
|
||||
func NewQwenProvider(apiKey, baseURL string) *QwenProvider {
|
||||
cfg := openai.DefaultConfig(apiKey)
|
||||
if baseURL != "" {
|
||||
cfg.BaseURL = baseURL
|
||||
} else {
|
||||
// Default to Qwen's official API endpoint
|
||||
cfg.BaseURL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
|
||||
}
|
||||
client := openai.NewClientWithConfig(cfg)
|
||||
return &QwenProvider{client: client}
|
||||
}
|
||||
|
||||
func (p *QwenProvider) Models() []llm.ModelInfo {
|
||||
return []llm.ModelInfo{
|
||||
{ID: "qwen-plus", Name: "Qwen Plus", Provider: "qwen"},
|
||||
{ID: "qwen-turbo", Name: "Qwen Turbo", Provider: "qwen"},
|
||||
{ID: "qwen-max", Name: "Qwen Max", Provider: "qwen"},
|
||||
{ID: "qwen-coder-plus", Name: "Qwen Coder Plus", Provider: "qwen"},
|
||||
{ID: "qwen-vl-plus", Name: "Qwen VL Plus", Provider: "qwen"},
|
||||
}
|
||||
}
|
||||
|
||||
func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
// Build messages
|
||||
msgs := make([]openai.ChatCompletionMessage, 0, len(req.Messages)+1)
|
||||
|
||||
if sysPrompt := qwenResolveSystemPrompt(req); sysPrompt != "" {
|
||||
msgs = append(msgs, openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleSystem,
|
||||
Content: sysPrompt,
|
||||
})
|
||||
}
|
||||
|
||||
for _, m := range req.Messages {
|
||||
switch m.Role {
|
||||
case "user":
|
||||
if m.ToolCallID != "" {
|
||||
if len(m.Images) > 0 {
|
||||
// Tool result with images: use multi-content parts
|
||||
var parts []openai.ChatMessagePart
|
||||
for _, img := range m.Images {
|
||||
encoded := base64.StdEncoding.EncodeToString(img.Data)
|
||||
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
|
||||
parts = append(parts, openai.ChatMessagePart{
|
||||
Type: openai.ChatMessagePartTypeImageURL,
|
||||
ImageURL: &openai.ChatMessageImageURL{
|
||||
URL: dataURI,
|
||||
Detail: openai.ImageURLDetailAuto,
|
||||
},
|
||||
})
|
||||
}
|
||||
if m.Content != "" {
|
||||
parts = append(parts, openai.ChatMessagePart{
|
||||
Type: openai.ChatMessagePartTypeText,
|
||||
Text: m.Content,
|
||||
})
|
||||
}
|
||||
msgs = append(msgs, openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleTool,
|
||||
MultiContent: parts,
|
||||
ToolCallID: m.ToolCallID,
|
||||
})
|
||||
} else {
|
||||
msgs = append(msgs, openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleTool,
|
||||
Content: m.Content,
|
||||
ToolCallID: m.ToolCallID,
|
||||
})
|
||||
}
|
||||
} else if len(m.Images) > 0 {
|
||||
var parts []openai.ChatMessagePart
|
||||
for _, img := range m.Images {
|
||||
encoded := base64.StdEncoding.EncodeToString(img.Data)
|
||||
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
|
||||
parts = append(parts, openai.ChatMessagePart{
|
||||
Type: openai.ChatMessagePartTypeImageURL,
|
||||
ImageURL: &openai.ChatMessageImageURL{
|
||||
URL: dataURI,
|
||||
Detail: openai.ImageURLDetailAuto,
|
||||
},
|
||||
})
|
||||
}
|
||||
if m.Content != "" {
|
||||
parts = append(parts, openai.ChatMessagePart{
|
||||
Type: openai.ChatMessagePartTypeText,
|
||||
Text: m.Content,
|
||||
})
|
||||
}
|
||||
msgs = append(msgs, openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleUser,
|
||||
MultiContent: parts,
|
||||
})
|
||||
} else {
|
||||
msgs = append(msgs, openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleUser,
|
||||
Content: m.Content,
|
||||
})
|
||||
}
|
||||
case "assistant":
|
||||
msg := openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleAssistant,
|
||||
Content: m.Content,
|
||||
}
|
||||
for _, tc := range m.ToolCalls {
|
||||
msg.ToolCalls = append(msg.ToolCalls, openai.ToolCall{
|
||||
ID: tc.ID,
|
||||
Type: openai.ToolTypeFunction,
|
||||
Function: openai.FunctionCall{
|
||||
Name: tc.Name,
|
||||
Arguments: string(tc.Input),
|
||||
},
|
||||
})
|
||||
}
|
||||
msgs = append(msgs, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// Build tools
|
||||
var tools []openai.Tool
|
||||
for _, t := range req.Tools {
|
||||
var params any
|
||||
if err := json.Unmarshal(t.Parameters, ¶ms); err != nil {
|
||||
params = map[string]any{"type": "object", "properties": map[string]any{}}
|
||||
}
|
||||
|
||||
tools = append(tools, openai.Tool{
|
||||
Type: openai.ToolTypeFunction,
|
||||
Function: &openai.FunctionDefinition{
|
||||
Name: t.Name,
|
||||
Description: t.Description,
|
||||
Parameters: params,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
model := req.Model
|
||||
if model == "" {
|
||||
model = "qwen-plus"
|
||||
}
|
||||
|
||||
maxTokens := req.MaxTokens
|
||||
if maxTokens == 0 {
|
||||
maxTokens = 4096
|
||||
}
|
||||
|
||||
openaiReq := openai.ChatCompletionRequest{
|
||||
Model: model,
|
||||
Messages: msgs,
|
||||
MaxCompletionTokens: maxTokens,
|
||||
Stream: true,
|
||||
StreamOptions: &openai.StreamOptions{IncludeUsage: true},
|
||||
}
|
||||
|
||||
if len(tools) > 0 {
|
||||
openaiReq.Tools = tools
|
||||
}
|
||||
|
||||
if req.Temperature > 0 {
|
||||
openaiReq.Temperature = float32(req.Temperature)
|
||||
}
|
||||
|
||||
if enabled, diag, ok := p.BuildEnableThinking(model, req.Reasoning); ok {
|
||||
// TODO: Qwen DashScope expects a custom top-level "enable_thinking"
|
||||
// JSON field that go-openai v1.41 does not expose via any
|
||||
// ExtraBody/RawJSON mechanism. Wiring it requires either upgrading
|
||||
// to a go-openai version with custom-field support or adding a
|
||||
// custom HTTP roundtripper. Tracked as a Phase 2 follow-up.
|
||||
_ = enabled
|
||||
_ = diag
|
||||
slog.Info("qwen thinking requested",
|
||||
"model", model,
|
||||
"requested", string(req.Reasoning),
|
||||
"clamped_to_bool", true,
|
||||
"reason", diag.Reason,
|
||||
"sdk_limitation", "enable_thinking not yet wired to wire format")
|
||||
} else if req.Reasoning != llm.ReasoningOff {
|
||||
slog.Info("reasoning ignored",
|
||||
"provider", "qwen",
|
||||
"model", model,
|
||||
"requested", string(req.Reasoning),
|
||||
"reason", "model does not support thinking")
|
||||
}
|
||||
|
||||
stream, err := p.client.CreateChatCompletionStream(ctx, openaiReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
events := make(chan llm.ChatEvent, 100)
|
||||
|
||||
go func() {
|
||||
defer close(events)
|
||||
defer stream.Close()
|
||||
|
||||
// Track tool calls being built up across deltas
|
||||
toolCalls := make(map[int]*pendingTC)
|
||||
|
||||
for {
|
||||
resp, err := stream.Recv()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
|
||||
return
|
||||
}
|
||||
|
||||
for _, choice := range resp.Choices {
|
||||
delta := choice.Delta
|
||||
|
||||
// Text content
|
||||
if delta.Content != "" {
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventTextDelta,
|
||||
Text: delta.Content,
|
||||
}
|
||||
}
|
||||
|
||||
// Tool calls
|
||||
for _, tc := range delta.ToolCalls {
|
||||
idx := 0
|
||||
if tc.Index != nil {
|
||||
idx = *tc.Index
|
||||
}
|
||||
pending, exists := toolCalls[idx]
|
||||
if !exists {
|
||||
pending = &pendingTC{}
|
||||
toolCalls[idx] = pending
|
||||
}
|
||||
|
||||
if tc.ID != "" {
|
||||
pending.id = tc.ID
|
||||
}
|
||||
if tc.Function.Name != "" {
|
||||
pending.name = tc.Function.Name
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventToolCallStart,
|
||||
ToolCall: &llm.ToolCall{
|
||||
ID: pending.id,
|
||||
Name: pending.name,
|
||||
},
|
||||
}
|
||||
}
|
||||
if tc.Function.Arguments != "" {
|
||||
pending.args.WriteString(tc.Function.Arguments)
|
||||
}
|
||||
}
|
||||
|
||||
// Finish reason
|
||||
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
|
||||
// Emit completed tool calls in index order.
|
||||
emitToolCalls(events, toolCalls)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
events <- llm.ChatEvent{Type: llm.EventDone}
|
||||
}()
|
||||
|
||||
return events, nil
|
||||
}
|
||||
|
||||
// NormalizeToolSchema strips $ref and definitions from each tool's
|
||||
// JSON Schema. Qwen DashScope tracks the OpenAI function-calling
|
||||
// shape, so the same restricted JSON Schema subset applies (and the
|
||||
// same openaiUnsupportedFields list is reused).
|
||||
func (p *QwenProvider) NormalizeToolSchema(tools []llm.ToolDef) ([]llm.ToolDef, []llm.Diagnostic) {
|
||||
return llm.ApplyStripList(tools, []string{"$ref", "definitions"})
|
||||
}
|
||||
|
||||
// BuildEnableThinking maps a llm.ReasoningMode to Qwen's enable_thinking
|
||||
// boolean. Returns (false, empty diag, false) when off or the model
|
||||
// doesn't support thinking. For any non-off mode on a supported model,
|
||||
// returns (true, clamped diag, true) — the boolean toggle loses the
|
||||
// requested low/medium/high granularity, so the diag always fires.
|
||||
func (p *QwenProvider) BuildEnableThinking(model string, mode llm.ReasoningMode) (bool, llm.Diagnostic, bool) {
|
||||
if mode == llm.ReasoningOff {
|
||||
return false, llm.Diagnostic{}, false
|
||||
}
|
||||
if !qwenSupportsThinking(model) {
|
||||
return false, llm.Diagnostic{}, false
|
||||
}
|
||||
return true, llm.Diagnostic{
|
||||
Action: "clamped",
|
||||
Reason: "qwen reasoning is boolean; granularity ignored",
|
||||
}, true
|
||||
}
|
||||
|
||||
// qwenSupportsThinking returns true for Qwen models that support the
|
||||
// enable_thinking parameter. Conservative — unknown IDs default to
|
||||
// false (only QwQ and Qwen3 family models accept this field).
|
||||
func qwenSupportsThinking(model string) bool {
|
||||
prefixes := []string{"qwen-qwq", "qwen3"}
|
||||
for _, prefix := range prefixes {
|
||||
if strings.HasPrefix(model, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// qwenResolveSystemPrompt returns the effective system prompt string,
|
||||
// preferring SystemPromptParts when present. Mirrors the OpenAI/Gemini
|
||||
// resolution helpers.
|
||||
func qwenResolveSystemPrompt(req llm.ChatRequest) string {
|
||||
if len(req.SystemPromptParts) > 0 {
|
||||
return llm.JoinSystemPromptParts(req.SystemPromptParts)
|
||||
}
|
||||
return req.SystemPrompt
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package qwen
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
func TestQwenResolveSystemPromptPrefersParts(t *testing.T) {
|
||||
got := qwenResolveSystemPrompt(llm.ChatRequest{
|
||||
SystemPrompt: "legacy",
|
||||
SystemPromptParts: []llm.SystemPromptPart{{Text: "new-a"}, {Text: "new-b"}},
|
||||
})
|
||||
require.Equal(t, "new-a\nnew-b", got)
|
||||
}
|
||||
|
||||
func TestQwenResolveSystemPromptFallback(t *testing.T) {
|
||||
got := qwenResolveSystemPrompt(llm.ChatRequest{SystemPrompt: "legacy"})
|
||||
require.Equal(t, "legacy", got)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
+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
|
||||
|
||||
@@ -443,8 +443,8 @@ func TestRuntimeDynamicSuffixIncludesDate(t *testing.T) {
|
||||
// this proves the date is stable across turns of a single Run.
|
||||
func TestRuntimeDateLineComputedOncePerRun(t *testing.T) {
|
||||
dl := "Today's date is 2026-05-01."
|
||||
a := buildDynamicSystemPromptSuffix(dl, "")
|
||||
b := buildDynamicSystemPromptSuffix(dl, "")
|
||||
a := buildDynamicSystemPromptSuffix("", dl, "")
|
||||
b := buildDynamicSystemPromptSuffix("", dl, "")
|
||||
require.Equal(t, a, b)
|
||||
}
|
||||
|
||||
|
||||
+10
-5
@@ -142,18 +142,23 @@ func BuildStaticSystemPrompt(
|
||||
}
|
||||
|
||||
// buildDynamicSystemPromptSuffix concatenates the per-turn dynamic context
|
||||
// — the date line and the cortex hint — into a single string the runtime
|
||||
// sends as the second (un-cached) SystemPromptPart. The date line, when
|
||||
// non-empty, appears at the top so the model anchors on "today" before
|
||||
// the per-turn content. Returns "" when all inputs are empty/nil.
|
||||
// — the identity hint, date line, and cortex hint — into a single string
|
||||
// the runtime sends as the second (un-cached) SystemPromptPart. identityHint
|
||||
// leads (see Runtime.DynamicIdentityHint: it needs to outweigh the model's
|
||||
// own prior in-conversation statements, so it gets the most prominent
|
||||
// position), then the date line so the model anchors on "today" before the
|
||||
// per-turn content. Returns "" when all inputs are empty/nil.
|
||||
//
|
||||
// As of sub-project 5, skill bodies and memory entries are no longer
|
||||
// auto-injected here. Their indices live in the cached static prompt
|
||||
// and the agent loads bodies on demand via the load_skill / load_memory
|
||||
// tools. This trims 5–15 KB of speculative skill bodies and 5–10 KB of
|
||||
// speculative memory bodies from every prefill.
|
||||
func buildDynamicSystemPromptSuffix(dateLine, cortexContext string) string {
|
||||
func buildDynamicSystemPromptSuffix(identityHint, dateLine, cortexContext string) string {
|
||||
var sb strings.Builder
|
||||
if identityHint != "" {
|
||||
sb.WriteString(identityHint)
|
||||
}
|
||||
if dateLine != "" {
|
||||
sb.WriteString(dateLine)
|
||||
}
|
||||
|
||||
+12
-4
@@ -85,17 +85,17 @@ func TestBuildStaticSystemPromptIncludesMemoryFiles(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestBuildDynamicSystemPromptSuffixEmpty(t *testing.T) {
|
||||
got := buildDynamicSystemPromptSuffix("", "")
|
||||
got := buildDynamicSystemPromptSuffix("", "", "")
|
||||
require.Equal(t, "", got)
|
||||
}
|
||||
|
||||
func TestBuildDynamicSystemPromptSuffixHintOnly(t *testing.T) {
|
||||
got := buildDynamicSystemPromptSuffix("", "\n\nHINT")
|
||||
got := buildDynamicSystemPromptSuffix("", "", "\n\nHINT")
|
||||
require.Equal(t, "\n\nHINT", got)
|
||||
}
|
||||
|
||||
func TestBuildDynamicSystemPromptSuffixDateAndHint(t *testing.T) {
|
||||
got := buildDynamicSystemPromptSuffix("Today's date is 2026-05-01.", "\n\nKG_HINT")
|
||||
got := buildDynamicSystemPromptSuffix("", "Today's date is 2026-05-01.", "\n\nKG_HINT")
|
||||
dateIdx := strings.Index(got, "Today's date is")
|
||||
hintIdx := strings.Index(got, "KG_HINT")
|
||||
require.True(t, dateIdx >= 0 && hintIdx > dateIdx,
|
||||
@@ -103,11 +103,19 @@ func TestBuildDynamicSystemPromptSuffixDateAndHint(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestBuildDynamicSystemPromptSuffixIncludesDate(t *testing.T) {
|
||||
got := buildDynamicSystemPromptSuffix("Today's date is 2026-05-01.", "")
|
||||
got := buildDynamicSystemPromptSuffix("", "Today's date is 2026-05-01.", "")
|
||||
require.True(t, strings.HasPrefix(got, "Today's date is 2026-05-01."),
|
||||
"date line must appear at the top of the dynamic suffix")
|
||||
}
|
||||
|
||||
func TestBuildDynamicSystemPromptSuffixIdentityHintLeadsDate(t *testing.T) {
|
||||
got := buildDynamicSystemPromptSuffix("IDENTITY_HINT", "Today's date is 2026-05-01.", "\n\nKG_HINT")
|
||||
identityIdx := strings.Index(got, "IDENTITY_HINT")
|
||||
dateIdx := strings.Index(got, "Today's date is")
|
||||
require.True(t, identityIdx == 0 && dateIdx > identityIdx,
|
||||
"order must be identity hint < date; got %d %d", identityIdx, dateIdx)
|
||||
}
|
||||
|
||||
func TestFormatDateLine(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// TestModelSwitchMidSession_ActuallyChangesRequestModelAndHint reproduces,
|
||||
// at the harness level, exactly what a caller like hand's tui.Controller
|
||||
// does on a live model switch: mutate Model and DynamicIdentityHint on an
|
||||
// already-running Runtime between two Run calls in the same session. This
|
||||
// is the mechanism a caller-side fix for "the model still thinks it's the
|
||||
// old one" ultimately rests on — if the second Run's actual ChatRequest
|
||||
// didn't target the new model, no amount of system-prompt wording could
|
||||
// have fixed the symptom, since the model actually being queried would
|
||||
// still be the old one.
|
||||
func TestModelSwitchMidSession_ActuallyChangesRequestModelAndHint(t *testing.T) {
|
||||
rec := &recordingProvider{reply: "ok"}
|
||||
sess := session.NewSession("test-agent", "test-key")
|
||||
reg := tool.NewRegistry()
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: rec,
|
||||
Tools: reg,
|
||||
Session: sess,
|
||||
Model: "meta/muse-spark-1.3",
|
||||
Provider: "openrouter",
|
||||
Workspace: t.TempDir(),
|
||||
MaxTurns: 5,
|
||||
DynamicIdentityHint: "You are running as the model \"openrouter/meta/muse-spark-1.3\".",
|
||||
}
|
||||
|
||||
events, err := rt.Run(context.Background(), "which model am I using", nil)
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
|
||||
// Simulate exactly what Controller.SwitchModel does.
|
||||
rt.Model = "anthropic/claude-sonnet-5"
|
||||
rt.DynamicIdentityHint = "You are running as the model \"openrouter/anthropic/claude-sonnet-5\"."
|
||||
|
||||
events, err = rt.Run(context.Background(), "which model am I using now", nil)
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
require.Len(t, rec.requests, 2)
|
||||
require.Equal(t, "meta/muse-spark-1.3", rec.requests[0].Model)
|
||||
require.Equal(t, "anthropic/claude-sonnet-5", rec.requests[1].Model, "second request must target the switched model")
|
||||
|
||||
part2 := rec.requests[1].SystemPromptParts
|
||||
require.Len(t, part2, 2, "expected static + dynamic system prompt parts")
|
||||
require.Contains(t, part2[1].Text, "openrouter/anthropic/claude-sonnet-5")
|
||||
require.NotContains(t, part2[1].Text, "muse-spark-1.3", "dynamic hint must not still name the old model")
|
||||
}
|
||||
+49
-19
@@ -85,6 +85,19 @@ type Runtime struct {
|
||||
// prompt cache hits.
|
||||
StaticSystemPrompt string
|
||||
|
||||
// DynamicIdentityHint is caller-set text re-sent, uncached, in every
|
||||
// turn's system prompt (see buildDynamicSystemPromptSuffix) — unlike
|
||||
// StaticSystemPrompt, safe to mutate mid-conversation (e.g. after a
|
||||
// live model switch) and have the very next turn pick it up. Exists
|
||||
// because a fact baked only into the cached static prompt competes
|
||||
// poorly against the model's own prior statements already visible in
|
||||
// message history: asked "which model are you" a second time, a model
|
||||
// tends to just repeat what it told the user earlier in the same
|
||||
// conversation over a background instruction it read once at the top
|
||||
// of a large cached block. Resending the fact fresh, every turn, gives
|
||||
// it the same recency the model grants its own last answer.
|
||||
DynamicIdentityHint string
|
||||
|
||||
// Permission gates tool execution at dispatch time. nil → allow-all.
|
||||
Permission tool.PermissionChecker
|
||||
|
||||
@@ -132,6 +145,11 @@ type Runtime struct {
|
||||
// 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
|
||||
@@ -272,12 +290,17 @@ 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:
|
||||
@@ -298,8 +321,15 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
// 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.
|
||||
@@ -420,7 +450,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
kgCh = nil
|
||||
}
|
||||
|
||||
dynamicSuffix := buildDynamicSystemPromptSuffix(dateLine, kgContext)
|
||||
dynamicSuffix := buildDynamicSystemPromptSuffix(r.DynamicIdentityHint, dateLine, kgContext)
|
||||
|
||||
staticText := r.StaticSystemPrompt
|
||||
parts := []llm.SystemPromptPart{
|
||||
@@ -812,7 +842,7 @@ 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
|
||||
@@ -895,28 +925,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
|
||||
}
|
||||
@@ -926,7 +956,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()}
|
||||
}
|
||||
@@ -952,7 +982,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
|
||||
@@ -963,27 +993,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
|
||||
}
|
||||
@@ -991,7 +1021,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()}
|
||||
}
|
||||
@@ -1002,7 +1032,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
|
||||
}
|
||||
|
||||
+3
-2
@@ -84,9 +84,10 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
|
||||
cancel()
|
||||
}
|
||||
|
||||
dynamicSuffix := buildDynamicSystemPromptSuffix(r.DynamicIdentityHint, "", kgHint)
|
||||
parts := []llm.SystemPromptPart{{Text: r.StaticSystemPrompt, Cache: true}}
|
||||
if kgHint != "" {
|
||||
parts = append(parts, llm.SystemPromptPart{Text: kgHint, Cache: false})
|
||||
if dynamicSuffix != "" {
|
||||
parts = append(parts, llm.SystemPromptPart{Text: dynamicSuffix, Cache: false})
|
||||
}
|
||||
req := llm.ChatRequest{
|
||||
Model: r.Model,
|
||||
|
||||
@@ -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 {
|
||||
}
|
||||
}
|
||||
+4
-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
|
||||
|
||||
@@ -53,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)
|
||||
@@ -103,6 +124,11 @@ 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 {
|
||||
@@ -135,6 +161,9 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
|
||||
|
||||
// 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()
|
||||
|
||||
@@ -153,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 {
|
||||
@@ -224,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
|
||||
@@ -231,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()
|
||||
|
||||
@@ -249,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()
|
||||
|
||||
@@ -264,6 +308,11 @@ 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 {
|
||||
|
||||
@@ -50,3 +50,16 @@ func TestStore_RewriteDegradedWarns(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
+17
-3
@@ -141,10 +141,24 @@ func windowByModelFamily(modelID string) int {
|
||||
return 8192
|
||||
case strings.HasPrefix(leaf, "gpt-3.5"):
|
||||
return 16385
|
||||
case strings.Contains(id, "gemini-1.5-pro"):
|
||||
case strings.Contains(id, "gemini") && strings.Contains(id, "pro"):
|
||||
// Every "Pro"-tier Gemini release so far (1.5 Pro onward) has
|
||||
// shipped the largest window in its generation. Matching on the
|
||||
// tier rather than enumerating each version keeps a future Pro
|
||||
// release (2.5, 3, ...) from falling through to the
|
||||
// flash/other-tier case below, let alone all the way to
|
||||
// defaultRemoteUnknownWindow.
|
||||
return 2000000
|
||||
case strings.Contains(id, "gemini-1.5-flash"),
|
||||
strings.Contains(id, "gemini-2"):
|
||||
case strings.Contains(id, "gemini"):
|
||||
// Every non-Pro Gemini model since 1.5 (Flash and other tiers)
|
||||
// has shipped at least a 1M window. Matching on the family alone
|
||||
// — not "gemini-1.5-flash"/"gemini-2" by exact version — means a
|
||||
// new Gemini generation (3.x and beyond) gets a realistic window
|
||||
// immediately instead of silently falling back to
|
||||
// defaultRemoteUnknownWindow (128k), which made preventive
|
||||
// compaction fire far too early and the context-usage gauge
|
||||
// read a nonsensical >100% for a model this table simply hadn't
|
||||
// been updated for yet.
|
||||
return 1000000
|
||||
}
|
||||
return 0
|
||||
|
||||
@@ -52,6 +52,29 @@ func TestContextWindowKnown(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Regression: a Gemini generation newer than the ones explicitly
|
||||
// enumerated (3.x and beyond) must not fall through to
|
||||
// defaultRemoteUnknownWindow (128k) just because this table hasn't been
|
||||
// updated with its exact version string yet — every non-Pro Gemini
|
||||
// model since 1.5 has shipped at least a 1M window, and every Pro-tier
|
||||
// release has shipped at least 2M.
|
||||
func TestContextWindowGeminiFutureGenerationsDefaultByTier(t *testing.T) {
|
||||
tests := []struct {
|
||||
model string
|
||||
want int
|
||||
}{
|
||||
{"openai/gemini-3.8-flash-global", 1000000}, // proxied under an unrelated provider label, as via a LiteLLM gateway
|
||||
{"google/gemini-3-flash", 1000000},
|
||||
{"google/gemini-3-pro", 2000000},
|
||||
{"google/gemini-4.0-flash-lite", 1000000},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.model, func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, ContextWindow(tc.model))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextWindowUnknownRemoteReturnsRemoteFallback(t *testing.T) {
|
||||
// Non-local unknown models default to 128k — frontier proxies are
|
||||
// overwhelmingly 128k+, and reactive compaction handles overflow.
|
||||
|
||||
+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})
|
||||
}
|
||||
|
||||
+7
-4
@@ -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"
|
||||
}
|
||||
|
||||
@@ -214,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
|
||||
|
||||
+19
-4
@@ -43,6 +43,21 @@ func TestExtractCommands_BackgroundAmpersand(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
@@ -86,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",
|
||||
|
||||
@@ -289,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,
|
||||
@@ -390,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(),
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user