67 Commits
Author SHA1 Message Date
sausheong d3c74e5681 docs: drop Co-Authored-By trailer references from run-total-usage plan 2026-06-26 23:35:05 -07:00
sausheong d1c63cac56 Merge run-total-usage: emit run-total token usage on terminal EventDone
Runtime.Run now accumulates token usage across all turns (summing all four
llm.Usage fields via a pure addUsage helper) and emits the run total on the
terminal EventDone, instead of only the last turn. Fixes multi-turn undercount
for consumers metering AgentEvent.Usage. RunTurn unchanged (one turn per call).
2026-06-26 22:28:04 -07:00
sausheong ef3a1d4927 test(runtime): assert addUsage returns a distinct pointer (aliasing safety) 2026-06-26 21:41:23 -07:00
sausheong 2f97b1cf78 docs(runtime): clarify EventDone.Usage is the run total 2026-06-26 21:37:28 -07:00
sausheong 69f58903eb 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).
2026-06-26 21:33:58 -07:00
sausheong 1ec0f9cac3 feat(runtime): add pure addUsage helper for field-wise usage summation 2026-06-26 21:29:27 -07:00
sausheong 2630d88245 docs: implementation plan for run-total token usage 2026-06-26 21:28:10 -07:00
sausheong a797d446f8 docs: design for run-total token usage on terminal EventDone 2026-06-26 21:07:11 -07:00
sausheong ac724d18e1 Merge branch 'security/s1-bash-bypass': close S1 bash allowlist bypass
Fix the CRITICAL allowlist-confinement escape: the metacharacter guard
checked the two-byte literal "\\n" instead of a real newline, so a
newline in the command ran subsequent lines unchecked via bash -c. Also
treat background & as a command separator and reject output redirection
(>) in allowlist mode.
2026-06-13 16:34:00 +08:00
sausheong 7f0c3fd23d fix(bash): reject real newline/CR and redirection in allowlist mode (S1) 2026-06-13 16:25:44 +08:00
sausheong a5f21d3a2c fix(bash): treat background & as a command separator in allowlist mode (S1) 2026-06-13 16:23:51 +08:00
sausheong 34435736c5 Merge branch 'cleanup/low-batch': low-priority sweep (L1/L3/L4/L5/L10)
tokens image accounting, Qwen usage stats, one-time degraded-persistence
warning (AppendEntry+Rewrite), RunSync abort surfacing, retry classifier
bounded 429/529 forms + typed Gemini APIError path.
2026-06-13 15:57:04 +08:00
sausheong 3da8fe8ed3 fix(llm): recognize Gemini 429/5xx as retryable via typed APIError path 2026-06-13 15:52:33 +08:00
sausheong 9292731d79 fix(llm): scope retry classifier to bounded 429/529 forms 2026-06-13 15:34:19 +08:00
sausheong 04f02c56d6 fix(runtime): RunSync returns context.Canceled on aborted run 2026-06-13 15:33:02 +08:00
sausheong 3eb9596ee6 fix(session): extend degraded-persistence warning to Rewrite path 2026-06-13 15:31:27 +08:00
sausheong 275636ed20 fix(session): emit one-time warning when persistence is degraded 2026-06-13 15:29:57 +08:00
sausheong 754721bc30 fix(qwen): request usage stats (IncludeUsage) and use MaxCompletionTokens
no request-capture seam; covered by build + openai sibling parity
2026-06-13 15:28:29 +08:00
sausheong 22f4329f44 fix(tokens): count attached images in Estimate (~1500 tokens each) 2026-06-13 15:27:43 +08:00
sausheong 8c9bc2963d Merge branch 'correctness/round5': provider stream + file correctness (R7/N11/N12) 2026-06-13 13:42:59 +08:00
sausheong 1752cbf2fb fix(file): honor ctx cancellation in read_file/edit_file (N12) 2026-06-13 12:51:30 +08:00
sausheong e133f97e1e fix(web): decode all HTML entities via html.UnescapeString (N11) 2026-06-13 12:50:07 +08:00
sausheong 373e44b9c7 fix(anthropic): surface in-band stream error + Builder accumulation (R7c) 2026-06-13 12:48:10 +08:00
sausheong d0cd0989a9 fix(gemini): emit a single EventDone with final usage (R7b) 2026-06-13 12:45:56 +08:00
sausheong 385cd26e4b fix(openai): strings.Builder for tool-arg accumulation (R7c) 2026-06-13 12:44:06 +08:00
sausheong 79a69e5dce fix(qwen): index-order tool emit + strings.Builder accumulation (R7a/R7c) 2026-06-13 12:42:41 +08:00
sausheong e40733145f fix(openai): emit tool calls in index order for prompt-cache determinism (R7a) 2026-06-13 12:40:57 +08:00
sausheong b85ffeac69 Merge branch 'security/round4': SSRF + file-size hardening (S2/N4/S3/N5) 2026-06-13 12:06:50 +08:00
sausheong d6db565d7c fix(web): dial all validated IPs for dual-stack fallback (I1); fix live SSRF test to await fetch (M1) 2026-06-13 11:56:30 +08:00
sausheong fb5103fb87 feat(file): cap read_file/edit_file size to prevent OOM (N5) 2026-06-13 11:27:34 +08:00
sausheong 01b55a1446 fix(browser): block private-IP resolution via host-resolver-rules (S3) 2026-06-13 11:25:22 +08:00
sausheong 7d85074509 fix(web): all web_search backends use SafeHTTPClient (N4) 2026-06-13 11:22:15 +08:00
sausheong d7777f7c89 fix(web): web_fetch uses SafeHTTPClient — pins validated IP (S2) 2026-06-13 11:20:12 +08:00
sausheong 1e00916a82 fix(web): block 0.0.0.0/8, CGNAT, and reserved ranges in isPrivateIP (S2 hardening) 2026-06-13 11:19:03 +08:00
sausheong 083122a81f feat(web): add SafeHTTPClient with IP-pinning transport (S2) 2026-06-13 11:15:26 +08:00
sausheong 5d5dcd1902 Merge branch 'perf/round3': agent hot-path performance (P2/P3/P8/P1/P5)
Drop dead O(n^2) message-assembly work and a never-read tool-result map;
hoist tool-def normalization out of the turn loop; debounce calibrator
persistence to once per Run; skip re-writing spilled tool results each
turn; move the session disk write off the session lock (order-preserving
via lock-coupling). Zero observable behavior change.
2026-06-13 10:29:52 +08:00
sausheong 34ebfc5e95 fix(session): lock-couple writeMu to preserve disk order under concurrent Append (P5)
The earlier P5 change released s.mu before the store write, which let
concurrent appends on one Session reach the disk writer out of in-memory
order. Acquire a dedicated writeMu while still holding s.mu, then release
s.mu before the disk write — disk latency stays off s.mu while on-disk
order still matches append order. Adds a disk-order regression test.
2026-06-13 10:29:07 +08:00
sausheong e1fd4dc689 fix(runtime): recompute calibrator estimate at EventDone (P8 stale-estimate bug)
The earlier P8 change reused the pre-compaction turnEstimate at EventDone,
but mid-turn compaction reassembles msgs without recomputing it — so the
persisted calibration ratio diverged from main whenever compaction fired,
changing future compaction timing. Recompute fresh at EventDone exactly as
the pre-debounce code did; keep only the disk-write debounce (the real win).
2026-06-13 10:27:53 +08:00
sausheong 25b2e9163f perf(session): persist entry after releasing the session lock (P5) 2026-06-13 10:06:43 +08:00
sausheong c710ea5a94 perf(runtime): track spilled tool-call IDs to skip re-writing spills each turn (P1) 2026-06-13 10:04:46 +08:00
sausheong 671c10e89a perf(runtime): persist calibrator once per Run; reuse per-turn estimate (P8) 2026-06-13 10:00:52 +08:00
sausheong 1da0584530 perf(runtime): hoist tool-def filter/sort/normalize out of the turn loop (P3) 2026-06-13 09:57:39 +08:00
sausheong 7151562d99 perf(runtime): drop dead resultIDs map and mid-loop tool-result injection (P2) 2026-06-13 09:55:58 +08:00
sausheong 86ad622144 Merge branch 'reliability/round2': pre-first-token stream-error recovery (R1)
EventError delivered before the first token now runs the same reactive
compaction + fallback-model recovery as the synchronous ChatStream-error
path, via recoverFromPreTokenError (single-shot per turn). Fixes the
primary Anthropic/Gemini path where 429/overflow aborted the turn.
2026-06-13 01:52:25 +08:00
sausheong 7052a66e38 fix(runtime): recover from pre-first-token stream errors (compaction/fallback) — R1 2026-06-13 01:46:38 +08:00
sausheong de23ad986a Merge branch 'harden/safe-defaults': atomic file writes + 0600 perms
WriteFileAtomic helper; write_file/edit_file atomic + restrictive perms;
spill files 0600. Part of the cross-repo safe-by-default hardening.
2026-06-13 01:13:06 +08:00
sausheong 27fecf4588 feat(runtime): spill files 0600 via atomic write 2026-06-13 00:53:22 +08:00
sausheong 87f77c76ba feat(tools/file): edit_file atomic + preserve existing mode 2026-06-13 00:51:57 +08:00
sausheong 7ae944f0eb feat(tools/file): write_file atomic + 0600 2026-06-13 00:50:46 +08:00
sausheong c4750347e6 feat(tool): add WriteFileAtomic helper 2026-06-13 00:49:50 +08:00
sausheong 7fa3e75ad1 feat(llm): PromptCachingProvider capability — cache on renamed providers
providerSupportsCaching gated on the provider NAME being literally
'anthropic', so an Anthropic-shaped provider registered under a custom
config name (platformai, bedrock, any relay) never set
CacheLastMessage — every turn re-processed the full conversation
history uncached (~120K input tokens and 4-6s TTFT per turn on a
large session).

Add llm.PromptCachingProvider capability interface; AnthropicProvider
declares it; runtime gates providerSupportsCaching and
providerSupportsMidLoopCompaction on the capability first, with the
name check kept as legacy fallback for custom impls.
2026-06-11 22:02:37 +08:00
sausheong d5e8abf492 feat(runtime): surface and recover from model refusals
Claude Fable 5 safety classifiers decline requests with HTTP 200 +
stop_reason=refusal and empty content. The Anthropic stream parser
never read stop_reason, so a refused turn looked like a successful
empty response — the UI showed nothing and the agent appeared hung.

- llm: ChatEvent carries StopReason/StopCategory on EventDone;
  StopReasonRefusal constant
- anthropic: parse stop_reason + stop_details.category from
  message_delta (streaming) and the message (non-streaming); WARN log
  on refusal
- runtime Run + RunTurn: on refusal, retry the turn once on
  FallbackModel (refusals are model-specific; Opus-tier has no
  bio/cyber classifiers), discarding any partial output; without a
  fallback (or if the fallback also refuses) synthesize a visible
  'model declined this request' message with the policy category
  instead of silent emptiness
2026-06-10 21:13:48 +08:00
sausheong 3064a0da14 fix(tokens): 1M context window for Fable 5 / Mythos 5 / Opus 4.6+ / Sonnet 4.6
The blanket claude→200k rule predates the 1M-window generation. With
a 200k detected window, preventive compaction (threshold 0.6) fired
at ~120k tokens on models that actually hold 1M — 5x too early.

Match the 1M family explicitly (claude-fable, claude-mythos,
claude-opus-4-6/7/8/9, claude-sonnet-4-6) before the 200k fallback;
older Claude models (3.x, 4.0-4.5 era, Haiku 4.5) keep 200k.
2026-06-10 19:32:09 +08:00
sausheong cf47b2fca8 feat(mcp): expose session Ping on Client
Gateway supervisors need a cheap liveness probe to detect mid-flight
upstream death (crashed stdio child, restarted HTTP server). Client.Ping
forwards to the SDK session's MCP ping; a non-nil error means the
session is no longer usable.

Also moves examples/minimal's keep-import-live statement above the REPL
loop — it sat after an infinite for loop, tripping go vet's unreachable
code check.
2026-06-10 12:44:21 +08:00
sausheong 6f0040f606 fix(anthropic): adaptive thinking for Fable 5 / Mythos 5 / Opus 4.7+
These models reject the legacy thinking config — sending
{type:"enabled", budget_tokens:N} returns HTTP 400
("thinking.type.enabled is not supported for this model"), and
sampling params (temperature) are removed too.

For adaptive-only models (matched by substring so gateway model-group
names like claude-fable-5-global and Bedrock-style IDs are covered):
- emit thinking: {type:"adaptive"} plus output_config.effort
  (low/medium/high mapped from the unified ReasoningMode)
- omit thinking entirely when reasoning is off (Fable 5 also rejects
  an explicit {type:"disabled"})
- drop temperature

Pre-4.7 models keep the existing enabled+budget_tokens behavior.
2026-06-10 12:41:01 +08:00
sausheong 0341628068 Merge: wire KnowledgeGraph (recall+ingest) into RunTurn
RunTurn now consults r.KG — bounded-synchronous semantic recall folded into
the prompt on the first round of an exchange, async auto-ingest on the
completing round. Fixes the gap where the KG seam was inert on the runtime's
serve path (RunTurn never read r.KG). Interface + BuildRuntime unchanged.
2026-06-10 00:23:53 +08:00
sausheong 5d6326981e docs(runtime): update RunTurn contract — it now does KG recall/ingest 2026-06-09 23:58:21 +08:00
sausheong b7cbfc584c docs(runtime): note IngestSource/growth-gate rationale at RunTurn ingest 2026-06-09 23:42:58 +08:00
sausheong 8f8d75cd06 feat(runtime): KG ingest on RunTurn exchange completion 2026-06-09 23:39:26 +08:00
sausheong fe71e7b36d feat(runtime): bounded-synchronous KG recall in RunTurn 2026-06-09 23:34:44 +08:00
sausheong f35070594f test(runtime): strengthen sessionThread compaction-skip + undecodable coverage 2026-06-09 23:32:30 +08:00
sausheong 67178e018a feat(runtime): sessionThread helper for KG ingest in RunTurn 2026-06-09 23:28:16 +08:00
sausheong ecdf97ca79 Merge feat/run-turn-api: add RunTurn single-turn API 2026-06-08 01:04:42 +08:00
sausheong b7f4cfcf4a refactor(runtime): serial tool dispatch in RunTurn + error/abort tests
- Drop the wasted partitionToolCalls call; RunTurn dispatches serially by
  design (deterministic ordering for durable replay), so loop toolCalls directly.
- Fix doc-comment overclaim: RunTurn is headless and does not emit Run's
  trace/slog tool-result lines nor parallelize batches.
- Make TurnResult.Err consistent: mid-dispatch abort now passes ctx.Err().
- Document single-active-turn invariant on turnSlice.
- Add TestRunTurn_LLMError and TestRunTurn_PreCancelledContext.
2026-06-07 23:47:32 +08:00
sausheong 35896d215a feat(runtime): add single-turn RunTurn API
RunTurn executes exactly one turn of the agent loop against the current
session and returns the SessionEntries it produced, enabling external
platforms to drive the loop one turn at a time (e.g. for durable
per-turn checkpointing). Purely additive: Run() is unchanged.

RunTurn reuses the existing tested helpers (assembleMessages,
dispatchTool, partitionToolCalls) and deliberately omits compaction,
knowledge-graph, and streaming-tool kickoff, which remain in Run.
2026-06-07 23:40:07 +08:00
Chang Sau Sheong 1c6a05c0d8 Merge pull request #1 from sausheong/feat/configurable-tool-result-cap
feat(runtime): configurable per-tool-result truncation cap
2026-05-21 07:55:33 +08:00
sausheong e5c9b5dbb5 feat(runtime): configurable per-tool-result truncation cap
Adds LoopConfig.MaxToolResultLen with the same config > env > default precedence as the existing MaxToolConcurrency / MaxAgentDepth knobs:

  1. Runtime.AgentLoop.MaxToolResultLen (>0) — config wins
  2. HARNESS_MAX_TOOL_RESULT_LEN env (>0) — env fallback
  3. defaultMaxToolResultLen (4000) — unchanged for back-compat

The previous 4000-char cap was conservative for agents doing real engineering work (read_file, web_fetch, browser, bash output). Setting MaxToolResultLen to 16000-25000 lets a typical source file or test run land in-context without hitting spillover; spill remains the safety net for genuinely large outputs.

No behaviour change for callers that don't set the field.
2026-05-21 07:55:16 +08:00
62 changed files with 3490 additions and 164 deletions

No files matched your search

@@ -0,0 +1,387 @@
# 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.
@@ -0,0 +1,155 @@
# 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.
+2 -1
View File
@@ -82,6 +82,8 @@ func main() {
}
defer rt.Close() // no-op here (no MCP), but idiomatic
_ = llm.ReasoningOff // keep llm import live for clarity in the demo
// 5. REPL loop.
in := bufio.NewScanner(os.Stdin)
fmt.Println("harness demo — type a message, blank line to exit")
@@ -115,5 +117,4 @@ func main() {
}
}
}
_ = llm.ReasoningOff // keep llm import live for clarity in the demo
}
+27
View File
@@ -135,8 +135,23 @@ type ChatEvent struct {
ToolCall *ToolCall
Usage *Usage
Error error
// StopReason carries the provider's terminal stop reason on EventDone
// ("end_turn", "tool_use", "max_tokens", "refusal", ...). Empty when
// the provider doesn't report one. StopReasonRefusal is the value the
// runtime branches on: Claude Fable 5 safety classifiers decline a
// request with HTTP 200 + stop_reason=refusal and empty content —
// without surfacing it the turn looks like a silent empty success.
StopReason string
// StopCategory is the refusal policy category from stop_details
// ("cyber", "bio", "reasoning_extraction"); informational only and
// may be empty even on a refusal.
StopCategory string
}
// StopReasonRefusal is the StopReason value for safety-classifier and
// model-initiated refusals (Claude Fable 5+).
const StopReasonRefusal = "refusal"
// ModelInfo describes an available model.
type ModelInfo struct {
ID string
@@ -171,6 +186,18 @@ type NonStreamingProvider interface {
ChatNonStreaming(ctx context.Context, req ChatRequest) (<-chan ChatEvent, error)
}
// PromptCachingProvider is an optional capability interface: providers
// that implement Anthropic-style explicit prompt caching (cache_control
// breakpoints, CacheLastMessage) declare it here. The runtime gates
// caching on this capability rather than on the provider's configured
// NAME — a user-named provider block ("platformai", "bedrock", any
// relay) wrapping an Anthropic-shaped API must still get caching;
// matching the name string alone silently disabled it for every
// renamed provider.
type PromptCachingProvider interface {
SupportsPromptCaching() bool
}
// ParseProviderModel splits "provider/model" into (provider, model).
// If no slash is present, returns ("", name) and the caller should use a default.
func ParseProviderModel(name string) (provider, model string) {
+26 -6
View File
@@ -6,6 +6,7 @@ import (
anthropic "github.com/anthropics/anthropic-sdk-go"
openai "github.com/sashabaranov/go-openai"
"google.golang.org/genai"
)
// IsRetryableModelError reports whether err is a transient capacity
@@ -14,14 +15,17 @@ import (
//
// - Anthropic 429 (rate limit) and 529 (overloaded)
// - OpenAI 429 (rate limit) and 5xx (server / overloaded)
// - Gemini 429 (quota/RESOURCE_EXHAUSTED) and 5xx (overloaded/unavailable),
// recognized via a typed genai.APIError path (Gemini's error string
// "Error 429, ... Status: RESOURCE_EXHAUSTED" does not match the
// bounded substring forms, so the typed path is required).
//
// Anything else (including 4xx auth/validation errors) returns false:
// retrying with a different model wouldn't fix the underlying problem.
//
// Errors from local providers (Ollama, etc.) and Gemini are NOT
// classified as retryable here; their failure modes are different
// and a model swap rarely helps. Add cases as new providers
// accumulate retry experience.
// Errors from local providers (Ollama, etc.) are NOT classified as
// retryable here; their failure modes are different and a model swap
// rarely helps. Add cases as new providers accumulate retry experience.
func IsRetryableModelError(err error) bool {
if err == nil {
return false
@@ -47,13 +51,29 @@ func IsRetryableModelError(err error) bool {
return openaiReqErr.HTTPStatusCode == 429 ||
(openaiReqErr.HTTPStatusCode >= 500 && openaiReqErr.HTTPStatusCode < 600)
}
// genai.APIError.Error() is a value receiver, so the error interface is
// satisfied by the value; errors.As targets the value type.
var genaiErr genai.APIError
if errors.As(err, &genaiErr) {
return genaiErr.Code == 429 ||
(genaiErr.Code >= 500 && genaiErr.Code < 600)
}
// Last-ditch: substring match on common SDK error wrappers that
// don't unwrap cleanly to typed errors. Cheap belt-and-braces;
// only reached when no typed match found above.
msg := strings.ToLower(err.Error())
if strings.Contains(msg, "429") || strings.Contains(msg, "529") ||
strings.Contains(msg, "rate limit") || strings.Contains(msg, "overloaded") {
// Bounded forms so a bare "429"/"529" inside a request id or unrelated
// digits doesn't trigger a retry. Word matches stay as-is (specific).
for _, sig := range []string{
"status 429", "code: 429", "code:429", " 429 ", "429 too many requests",
"status 529", "code: 529", "code:529", " 529 ", "529 overloaded",
} {
if strings.Contains(msg, sig) {
return true
}
}
if strings.Contains(msg, "rate limit") || strings.Contains(msg, "overloaded") {
return true
}
return false
+28
View File
@@ -8,8 +8,26 @@ import (
anthropic "github.com/anthropics/anthropic-sdk-go"
openai "github.com/sashabaranov/go-openai"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/genai"
)
func TestIsRetryable_Gemini429(t *testing.T) {
// Mirror genai.APIError's real shape.
err := genai.APIError{Code: 429, Message: "Resource has been exhausted (e.g. check quota).", Status: "RESOURCE_EXHAUSTED"}
require.True(t, IsRetryableModelError(err))
}
func TestIsRetryable_Gemini503(t *testing.T) {
err := genai.APIError{Code: 503, Message: "The model is overloaded.", Status: "UNAVAILABLE"}
require.True(t, IsRetryableModelError(err))
}
func TestIsRetryable_Gemini400NotRetryable(t *testing.T) {
err := genai.APIError{Code: 400, Message: "Invalid argument", Status: "INVALID_ARGUMENT"}
require.False(t, IsRetryableModelError(err))
}
func TestIsRetryableModelErrorAnthropic429(t *testing.T) {
err := &anthropic.Error{StatusCode: 429}
assert.True(t, IsRetryableModelError(err))
@@ -89,3 +107,13 @@ func TestIsRetryableModelErrorUnrelatedError(t *testing.T) {
err := errors.New("some other failure")
assert.False(t, IsRetryableModelError(err))
}
func TestRetry_DigitsInRequestIDNotRetryable(t *testing.T) {
err := errors.New("request failed: req_abc429def something went wrong")
require.False(t, IsRetryableModelError(err))
}
func TestRetry_RealStatus429Retryable(t *testing.T) {
err := errors.New("openai: error, status 429 too many requests")
require.True(t, IsRetryableModelError(err))
}
+90 -9
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log/slog"
"strings"
@@ -28,6 +29,11 @@ func NewAnthropicProvider(apiKey, baseURL string) *AnthropicProvider {
return &AnthropicProvider{client: client}
}
// SupportsPromptCaching implements llm.PromptCachingProvider: the
// Anthropic Messages API honours cache_control breakpoints regardless
// of what the provider block is named in user config.
func (p *AnthropicProvider) SupportsPromptCaching() bool { return true }
func (p *AnthropicProvider) Models() []llm.ModelInfo {
return []llm.ModelInfo{
{ID: "claude-sonnet-4-5-20250514", Name: "Claude Sonnet 4.5", Provider: "anthropic"},
@@ -87,10 +93,28 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
if sys := buildAnthropicSystem(req); len(sys) > 0 {
params.System = sys
}
if req.Temperature > 0 {
if req.Temperature > 0 && !anthropicAdaptiveThinkingOnly(model) {
params.Temperature = anthropic.Float(req.Temperature)
}
if cfg, ok := p.BuildThinkingConfig(model, req.Reasoning); ok {
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
// 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{},
}
params.OutputConfig = anthropic.OutputConfigParam{
Effort: anthropicEffort(req.Reasoning),
}
slog.Info("anthropic adaptive thinking",
"model", model,
"effort", string(anthropicEffort(req.Reasoning)))
}
} else if cfg, ok := p.BuildThinkingConfig(model, req.Reasoning); ok {
required := cfg.BudgetTokens + 4096
if maxTokens < required {
maxTokens = required
@@ -141,8 +165,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
type pendingTC struct {
id string
name string
inputJSON string // built from input_json_delta events
startInput string // captured from content_block_start (proxy fallback)
inputJSON strings.Builder // built from input_json_delta events
startInput string // captured from content_block_start (proxy fallback)
}
var pendingTools []pendingTC
var currentBlockType string
@@ -197,18 +221,21 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
}
case "input_json_delta":
if len(pendingTools) > 0 {
pendingTools[len(pendingTools)-1].inputJSON += delta.PartialJSON
pendingTools[len(pendingTools)-1].inputJSON.WriteString(delta.PartialJSON)
}
}
case "content_block_stop":
if currentBlockType == "tool_use" && len(pendingTools) > 0 {
tc := pendingTools[len(pendingTools)-1]
// Index in place rather than copying the element: the
// pendingTC holds a strings.Builder, which must not be
// copied after first write (vet copylock).
tc := &pendingTools[len(pendingTools)-1]
// Prefer streamed deltas (canonical Anthropic). Fall
// back to start-time input (proxy emitting full input
// upfront). Default to "{}" so MCP servers receive a
// valid empty-args envelope rather than null/empty.
inp := tc.inputJSON
inp := tc.inputJSON.String()
if inp == "" {
inp = tc.startInput
}
@@ -227,7 +254,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
currentBlockType = ""
case "message_delta":
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 {
stopReason := string(event.Delta.StopReason)
stopCategory := string(event.Delta.StopDetails.Category)
if stopReason == llm.StopReasonRefusal {
slog.Warn("anthropic refusal stop reason",
"category", stopCategory,
"output_tokens", event.Usage.OutputTokens)
}
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 || stopReason != "" {
slog.Info("anthropic stream usage",
"input_tokens", inputTokens,
"output_tokens", event.Usage.OutputTokens,
@@ -242,6 +276,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
CacheCreationInputTokens: int(cacheCreationTokens),
CacheReadInputTokens: int(cacheReadTokens),
},
StopReason: stopReason,
StopCategory: stopCategory,
}
}
@@ -249,7 +285,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
// Final event — nothing extra to emit
case "error":
slog.Error("anthropic stream error", "event", event.Type)
// The SDK surfaces error detail via stream.Err() (handled after
// the loop); this in-band branch must not be a silent no-op —
// emit an EventError so the runtime treats it as a failure.
slog.Error("anthropic stream error event", "event", event.Type)
events <- llm.ChatEvent{
Type: llm.EventError,
Error: fmt.Errorf("anthropic stream error event"),
}
}
}
@@ -326,6 +369,8 @@ func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRe
CacheCreationInputTokens: int(msg.Usage.CacheCreationInputTokens),
CacheReadInputTokens: int(msg.Usage.CacheReadInputTokens),
},
StopReason: string(msg.StopReason),
StopCategory: string(msg.StopDetails.Category),
}
}()
return events, nil
@@ -374,6 +419,42 @@ 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.
func anthropicAdaptiveThinkingOnly(model string) bool {
adaptiveOnly := []string{
"claude-fable-5",
"claude-mythos-5",
"claude-mythos-preview",
"claude-opus-4-7",
"claude-opus-4-8",
"claude-opus-4-9", // future-proof within the 4.x line
}
for _, marker := range adaptiveOnly {
if strings.Contains(model, marker) {
return true
}
}
return false
}
// anthropicEffort maps the unified ReasoningMode onto output_config.effort
// for adaptive-thinking-only models.
func anthropicEffort(mode llm.ReasoningMode) anthropic.OutputConfigEffort {
switch mode {
case llm.ReasoningLow:
return anthropic.OutputConfigEffortLow
case llm.ReasoningMedium:
return anthropic.OutputConfigEffortMedium
default:
return anthropic.OutputConfigEffortHigh
}
}
// anthropicSupportsThinking returns true for Claude models that accept
// extended thinking. Conservative — unknown IDs default to true so we
// let the API decide rather than silently drop a knob the user set.
+196
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
anthropic "github.com/anthropics/anthropic-sdk-go"
@@ -521,3 +522,198 @@ data: {"type":"message_stop"}
assert.Equal(t, `{}`, string(toolDone.ToolCall.Input),
"argument-less tool call must serialize as {} so MCP transport accepts it")
}
// --- Adaptive-thinking model mapping ---------------------------------
//
// Claude Fable 5, Claude Mythos 5, 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.
func wireJSON(t *testing.T, p *AnthropicProvider, req llm.ChatRequest) string {
t.Helper()
params := p.buildMessageParams(req)
b, err := json.Marshal(params)
require.NoError(t, err)
return string(b)
}
func TestAdaptiveThinkingModels_EmitAdaptiveNotEnabled(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
models := []string{
"claude-fable-5",
"claude-fable-5-global", // LiteLLM / gateway model-group names
"claude-mythos-5",
"claude-opus-4-7",
"claude-opus-4-8",
"us.anthropic.claude-opus-4-8-v1", // Bedrock-style ID
}
for _, model := range models {
t.Run(model, func(t *testing.T) {
got := wireJSON(t, p, llm.ChatRequest{
Model: model,
Reasoning: llm.ReasoningHigh,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.Contains(t, got, `"thinking":{"type":"adaptive"}`,
"adaptive-only models must send thinking.type=adaptive")
assert.NotContains(t, got, `"budget_tokens"`,
"budget_tokens is rejected with 400 on adaptive-only models")
assert.Contains(t, got, `"output_config":{"effort":"high"}`,
"reasoning mode maps to output_config.effort on adaptive-only models")
})
}
}
func TestAdaptiveThinkingModels_EffortMapping(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
cases := []struct {
mode llm.ReasoningMode
effort string
}{
{llm.ReasoningLow, "low"},
{llm.ReasoningMedium, "medium"},
{llm.ReasoningHigh, "high"},
}
for _, c := range cases {
t.Run(string(c.mode), func(t *testing.T) {
got := wireJSON(t, p, llm.ChatRequest{
Model: "claude-opus-4-8",
Reasoning: c.mode,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.Contains(t, got, `"output_config":{"effort":"`+c.effort+`"}`)
})
}
}
func TestAdaptiveThinkingModels_ReasoningOffOmitsThinking(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
got := wireJSON(t, p, llm.ChatRequest{
Model: "claude-fable-5",
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.NotContains(t, got, `"thinking"`,
"reasoning off must omit the thinking param entirely — Fable 5 "+
"rejects an explicit {type:disabled} with 400")
assert.NotContains(t, got, `"output_config"`)
}
func TestAdaptiveThinkingModels_TemperatureDropped(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
for _, model := range []string{"claude-fable-5", "claude-opus-4-7", "claude-opus-4-8"} {
t.Run(model, func(t *testing.T) {
got := wireJSON(t, p, llm.ChatRequest{
Model: model,
Temperature: 0.7,
Reasoning: llm.ReasoningMedium,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.NotContains(t, got, `"temperature"`,
"sampling params are removed on these models — sending temperature is a 400")
})
}
}
func TestLegacyThinkingModels_KeepBudgetTokens(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
got := wireJSON(t, p, llm.ChatRequest{
Model: "claude-sonnet-4-5",
Reasoning: llm.ReasoningHigh,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.Contains(t, got, `"budget_tokens":16384`,
"pre-4.7 models keep the enabled+budget_tokens config")
assert.NotContains(t, got, `"output_config"`)
}
// TestAnthropicStream_RefusalStopReasonSurfaced reproduces the Claude
// Fable 5 classifier refusal: HTTP 200, a message_delta carrying
// stop_reason=refusal + stop_details.category, and NO content blocks.
// The parser previously dropped stop_reason entirely, so the runtime
// saw an empty-but-successful turn and the user saw a silent nothing.
func TestAnthropicStream_RefusalStopReasonSurfaced(t *testing.T) {
const sseBody = `event: message_start
data: {"type":"message_start","message":{"id":"msg_r","type":"message","role":"assistant","content":[],"model":"claude-fable-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":29,"output_tokens":0}}}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"refusal","stop_sequence":null,"stop_details":{"type":"refusal","category":"bio","explanation":null}},"usage":{"output_tokens":4}}
event: message_stop
data: {"type":"message_stop"}
`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(sseBody))
}))
t.Cleanup(srv.Close)
p := NewAnthropicProvider("test-key", srv.URL)
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-fable-5"})
require.NoError(t, err)
var done *llm.ChatEvent
for ev := range stream {
if ev.Type == llm.EventDone {
ev := ev
done = &ev
}
}
require.NotNil(t, done, "stream must emit EventDone")
assert.Equal(t, "refusal", done.StopReason)
assert.Equal(t, "bio", done.StopCategory)
}
// Normal end_turn streams must carry the stop reason too (and no category).
func TestAnthropicStream_EndTurnStopReason(t *testing.T) {
const sseBody = `event: message_start
data: {"type":"message_start","message":{"id":"msg_n","type":"message","role":"assistant","content":[],"model":"claude-fable-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0}}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}
event: message_stop
data: {"type":"message_stop"}
`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(sseBody))
}))
t.Cleanup(srv.Close)
p := NewAnthropicProvider("test-key", srv.URL)
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-fable-5"})
require.NoError(t, err)
var done *llm.ChatEvent
for ev := range stream {
if ev.Type == llm.EventDone {
ev := ev
done = &ev
}
}
require.NotNil(t, done)
assert.Equal(t, "end_turn", done.StopReason)
assert.Empty(t, done.StopCategory)
}
func TestAnthropicInputAccumulation(t *testing.T) {
var b strings.Builder
for _, part := range []string{`{"a"`, `:1`, `}`} {
b.WriteString(part)
}
require.Equal(t, `{"a":1}`, b.String())
}
+13 -8
View File
@@ -182,6 +182,8 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
go func() {
defer close(events)
var lastUsage *llm.Usage
for resp, err := range p.client.Models.GenerateContentStream(ctx, model, contents, config) {
if err != nil {
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
@@ -189,13 +191,9 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
if resp.UsageMetadata != nil {
events <- llm.ChatEvent{
Type: llm.EventDone,
Usage: &llm.Usage{
InputTokens: int(resp.UsageMetadata.PromptTokenCount),
OutputTokens: int(resp.UsageMetadata.CandidatesTokenCount),
},
}
lastUsage = updateUsage(lastUsage,
int(resp.UsageMetadata.PromptTokenCount),
int(resp.UsageMetadata.CandidatesTokenCount))
}
for _, cand := range resp.Candidates {
@@ -240,12 +238,19 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
// Ensure a Done event is always sent
events <- llm.ChatEvent{Type: llm.EventDone}
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
}()
return events, nil
}
// updateUsage returns a *llm.Usage carrying the latest cumulative counts.
// Gemini sends cumulative usage on multiple chunks; we keep only the last and
// emit a single EventDone at stream end (mirrors the OpenAI provider's lastUsage).
func updateUsage(_ *llm.Usage, prompt, candidates int) *llm.Usage {
return &llm.Usage{InputTokens: prompt, OutputTokens: candidates}
}
// geminiUnsupportedFields are JSON Schema fields Gemini's "OpenAPI 3.0
// subset" rejects. This is the broadest strip set across the four
// providers — most of the cross-provider portability gap shows up here.
+9
View File
@@ -24,3 +24,12 @@ func TestGeminiResolveSystemPromptEmpty(t *testing.T) {
got := geminiResolveSystemPrompt(llm.ChatRequest{})
require.Equal(t, "", got)
}
func TestGeminiUsageBuffer_KeepsLast(t *testing.T) {
var last *llm.Usage
last = updateUsage(last, 10, 5)
last = updateUsage(last, 20, 9) // final cumulative
require.NotNil(t, last)
require.Equal(t, 20, last.InputTokens)
require.Equal(t, 9, last.OutputTokens)
}
+38 -19
View File
@@ -271,11 +271,6 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
defer stream.Close()
// Track tool calls being built up across deltas
type pendingTC struct {
id string
name string
argsJSON string
}
toolCalls := make(map[int]*pendingTC)
var lastUsage *llm.Usage
@@ -337,25 +332,13 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
}
if tc.Function.Arguments != "" {
pending.argsJSON += tc.Function.Arguments
pending.args.WriteString(tc.Function.Arguments)
}
}
// Finish reason
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
// Emit completed tool calls
for _, tc := range toolCalls {
if tc.name != "" {
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: tc.id,
Name: tc.name,
Input: json.RawMessage(tc.argsJSON),
},
}
}
}
emitToolCalls(events, toolCalls)
}
}
}
@@ -366,6 +349,42 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
return events, nil
}
// pendingTC accumulates a single streamed tool call across deltas. The
// streamed tool-call index is the map key in toolCalls; the id, name, and
// arguments arrive in separate chunks.
type pendingTC struct {
id string
name string
args strings.Builder
}
// emitToolCalls sends EventToolCallDone for each completed tool call in
// ascending index order. The map key is the streamed tool-call index;
// iterating in order keeps the assistant message's tool_use block order
// deterministic across turns so the prompt cache stays warm.
func emitToolCalls(events chan<- llm.ChatEvent, toolCalls map[int]*pendingTC) {
maxIdx := -1
for idx := range toolCalls {
if idx > maxIdx {
maxIdx = idx
}
}
for idx := 0; idx <= maxIdx; idx++ {
tc, ok := toolCalls[idx]
if !ok || tc.name == "" {
continue
}
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: tc.id,
Name: tc.name,
Input: json.RawMessage(tc.args.String()),
},
}
}
}
// openaiUnsupportedFields are JSON Schema fields the OpenAI function-
// calling schema rejects. anyOf/oneOf/format are accepted and kept.
var openaiUnsupportedFields = []string{"$ref", "definitions"}
+19
View File
@@ -73,3 +73,22 @@ func TestOpenAIChatStreamPartsBeatString(t *testing.T) {
require.GreaterOrEqual(t, len(captured.Messages), 1)
require.Equal(t, "new", captured.Messages[0].Content)
}
func TestEmitToolCalls_OrderedByIndex(t *testing.T) {
mk := func(id, name string) *pendingTC {
p := &pendingTC{id: id, name: name}
p.args.WriteString("{}")
return p
}
toolCalls := map[int]*pendingTC{2: mk("c", "third"), 0: mk("a", "first"), 1: mk("b", "second")}
ch := make(chan llm.ChatEvent, 10)
emitToolCalls(ch, toolCalls)
close(ch)
var ids []string
for ev := range ch {
if ev.Type == llm.EventToolCallDone {
ids = append(ids, ev.ToolCall.ID)
}
}
require.Equal(t, []string{"a", "b", "c"}, ids, "tool calls must emit in index order")
}
+43 -23
View File
@@ -14,6 +14,41 @@ import (
"github.com/sausheong/harness/llm"
)
// pendingTC accumulates a streamed tool call across deltas. args uses
// strings.Builder so repeated argument fragments append in O(n) total
// (not O(n²) from string concatenation).
type pendingTC struct {
id string
name string
args strings.Builder
}
// emitToolCalls sends EventToolCallDone for each completed tool call in
// ascending index order so tool_use block order is deterministic across
// turns (prompt-cache stability).
func emitToolCalls(events chan<- llm.ChatEvent, toolCalls map[int]*pendingTC) {
maxIdx := -1
for idx := range toolCalls {
if idx > maxIdx {
maxIdx = idx
}
}
for idx := 0; idx <= maxIdx; idx++ {
tc, ok := toolCalls[idx]
if !ok || tc.name == "" {
continue
}
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: tc.id,
Name: tc.name,
Input: json.RawMessage(tc.args.String()),
},
}
}
}
// QwenProvider implements llm.LLMProvider using the Qwen Chat Completions API.
// Qwen uses an OpenAI-compatible API, so we reuse the go-openai client.
type QwenProvider struct {
@@ -169,10 +204,11 @@ func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-c
}
openaiReq := openai.ChatCompletionRequest{
Model: model,
Messages: msgs,
MaxTokens: maxTokens,
Stream: true,
Model: model,
Messages: msgs,
MaxCompletionTokens: maxTokens,
Stream: true,
StreamOptions: &openai.StreamOptions{IncludeUsage: true},
}
if len(tools) > 0 {
@@ -217,11 +253,6 @@ func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-c
defer stream.Close()
// Track tool calls being built up across deltas
type pendingTC struct {
id string
name string
argsJSON string
}
toolCalls := make(map[int]*pendingTC)
for {
@@ -271,25 +302,14 @@ func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-c
}
}
if tc.Function.Arguments != "" {
pending.argsJSON += tc.Function.Arguments
pending.args.WriteString(tc.Function.Arguments)
}
}
// Finish reason
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
// Emit completed tool calls
for _, tc := range toolCalls {
if tc.name != "" {
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: tc.id,
Name: tc.name,
Input: json.RawMessage(tc.argsJSON),
},
}
}
}
// Emit completed tool calls in index order.
emitToolCalls(events, toolCalls)
}
}
}
+19
View File
@@ -24,3 +24,22 @@ func TestQwenResolveSystemPromptEmpty(t *testing.T) {
got := qwenResolveSystemPrompt(llm.ChatRequest{})
require.Equal(t, "", got)
}
func TestEmitToolCalls_OrderedByIndex(t *testing.T) {
mk := func(id, name string) *pendingTC {
p := &pendingTC{id: id, name: name}
p.args.WriteString("{}")
return p
}
toolCalls := map[int]*pendingTC{1: mk("b", "second"), 0: mk("a", "first")}
ch := make(chan llm.ChatEvent, 10)
emitToolCalls(ch, toolCalls)
close(ch)
var ids []string
for ev := range ch {
if ev.Type == llm.EventToolCallDone {
ids = append(ids, ev.ToolCall.ID)
}
}
require.Equal(t, []string{"a", "b"}, ids)
}
+63 -7
View File
@@ -246,7 +246,7 @@ func TestPruneToolResults(t *testing.T) {
}
// Empty spillConfig → legacy in-place truncation path.
pruneToolResults(msgs, 10000, spillConfig{})
pruneToolResults(msgs, 10000, spillConfig{}, nil)
// User message should be unchanged
assert.Equal(t, "hello", msgs[0].Content)
@@ -261,7 +261,7 @@ func TestPruneToolResultsShort(t *testing.T) {
{Role: "user", Content: "short output", ToolCallID: "tc_1"},
}
pruneToolResults(msgs, 10000, spillConfig{})
pruneToolResults(msgs, 10000, spillConfig{}, nil)
assert.Equal(t, "short output", msgs[0].Content)
}
@@ -279,7 +279,7 @@ func TestPruneToolResultsNewlineBoundary(t *testing.T) {
{Role: "user", Content: content, ToolCallID: "tc_1"},
}
pruneToolResults(msgs, 10000, spillConfig{})
pruneToolResults(msgs, 10000, spillConfig{}, nil)
// Should be truncated and contain the truncation marker
truncated := msgs[0].Content
@@ -298,7 +298,7 @@ func TestPruneToolResultsSpillsToDisk(t *testing.T) {
{Role: "user", Content: original, ToolCallID: "tc_42"},
}
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_abc"})
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_abc"}, nil)
// Message rewritten to head + spill marker pointing at the file.
got := msgs[0].Content
@@ -324,14 +324,14 @@ func TestPruneToolResultsIdempotentAfterSpill(t *testing.T) {
{Role: "user", Content: strings.Repeat("b", 20000), ToolCallID: "tc_99"},
}
pruneToolResults(msgs, 10000, cfg)
pruneToolResults(msgs, 10000, cfg, nil)
afterFirst := msgs[0].Content
require.Contains(t, afterFirst, spillMarker)
// Second call: marker is present, so the message must be untouched.
// Mutating it (e.g. spilling again or appending another marker)
// would silently grow the prefill across turns and burn cache.
pruneToolResults(msgs, 10000, cfg)
pruneToolResults(msgs, 10000, cfg, nil)
assert.Equal(t, afterFirst, msgs[0].Content)
}
@@ -349,7 +349,7 @@ func TestPruneToolResultsFallsBackToTruncationWhenSpillFails(t *testing.T) {
{Role: "user", Content: strings.Repeat("c", 20000), ToolCallID: "tc_fail"},
}
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_fail"})
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_fail"}, nil)
got := msgs[0].Content
assert.Less(t, len(got), 20000, "fallback must still bound the message")
@@ -357,6 +357,31 @@ func TestPruneToolResultsFallsBackToTruncationWhenSpillFails(t *testing.T) {
assert.NotContains(t, got, spillMarker, "spilled marker must not appear when write failed")
}
func TestPruneToolResultsSpillsOncePerID(t *testing.T) {
workspace := t.TempDir()
cfg := spillConfig{Workspace: workspace, SessionKey: "sess_once"}
spilled := map[string]bool{}
big := strings.Repeat("x", 50000)
mk := func() []llm.Message {
return []llm.Message{{ToolCallID: "call_big", Content: big}}
}
m1 := mk()
pruneToolResults(m1, 10000, cfg, spilled)
require.Contains(t, m1[0].Content, spillMarker)
spillPath := filepath.Join(workspace, ".harness", "spill", "sess_once", "call_big.txt")
require.FileExists(t, spillPath)
require.True(t, spilled["call_big"], "ID recorded as spilled")
require.NoError(t, os.Remove(spillPath))
m2 := mk()
pruneToolResults(m2, 10000, cfg, spilled)
require.Contains(t, m2[0].Content, spillMarker, "message still rewritten to the marker")
require.NoFileExists(t, spillPath, "turn 2 must NOT re-write the spill file (idempotent via spilled set)")
}
// --- Runtime tests ---
func TestRuntimeRun(t *testing.T) {
@@ -871,6 +896,37 @@ func TestRun_AbortMidDispatchProducesPairedSession(t *testing.T) {
}
}
// TestRunSync_ReturnsErrorOnAbort verifies that RunSync surfaces an aborted run
// as a non-nil error (context.Canceled) rather than returning (partialText,
// nil). Cron/sync callers must be able to distinguish a completed run from a
// cancelled one. Reuses the same abort scaffolding as
// TestRun_AbortMidDispatchProducesPairedSession (a tool batch + cancelOnNth).
func TestRunSync_ReturnsErrorOnAbort(t *testing.T) {
threeToolCalls := []llm.ToolCall{
{ID: "tc_0", Name: "noop", Input: json.RawMessage(`{}`)},
{ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`)},
{ID: "tc_2", Name: "noop", Input: json.RawMessage(`{}`)},
}
llmFake := &threeToolCallLLM{toolCalls: threeToolCalls}
ctx, cancel := context.WithCancel(context.Background())
count := 0
exec := &cancelOnNthExecutor{n: 1, cancel: cancel, count: &count}
r := &Runtime{
LLM: llmFake,
Tools: exec,
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test-model",
MaxTurns: 5,
}
_, err := r.RunSync(ctx, "go", nil)
require.Error(t, err)
require.ErrorIs(t, err, context.Canceled)
}
// threeToolCallLLM emits the configured tool_calls as one assistant turn,
// then EventDone. On the next call (after tool results, if the runtime
// loops back), emits only EventDone with no tool_calls so Run terminates.
+58
View File
@@ -0,0 +1,58 @@
package runtime
import (
"context"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tokens"
"github.com/sausheong/harness/tool"
"github.com/stretchr/testify/require"
)
// usageDoneProvider emits a usage-bearing EventDone so the agent loop can
// populate (and persist) the per-session token calibrator.
type usageDoneProvider struct {
llmtest.Base
}
func (p *usageDoneProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
ch := make(chan llm.ChatEvent, 4)
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "answer"}
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 1000, OutputTokens: 10}}
close(ch)
return ch, nil
}
// TestCalibratorPersistsByEndOfRun guards that the per-session calibrator is
// persisted to the CalibratorStore by the time Run completes. After the P8
// debounce change the Save moves from per-round to a single deferred flush at
// Run end; this test asserts the observable end state (persisted) is unchanged.
func TestCalibratorPersistsByEndOfRun(t *testing.T) {
dir := t.TempDir()
store := tokens.NewCalibratorStore(dir)
rt := &Runtime{
LLM: &usageDoneProvider{},
Tools: tool.NewRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "claude-sonnet-4-5",
// Compaction must be non-nil for the runtime to lazily create the
// per-session calibrator (the calibrator-creation path is gated on
// it). MessageCap/threshold left at defaults so no compaction fires
// during this short run.
Compaction: newCompactionMgr(),
Provider: "anthropic",
MaxTurns: 2,
Workspace: t.TempDir(),
CalibratorStore: store,
}
_, err := rt.RunSync(context.Background(), "go", nil)
require.NoError(t, err)
ratio, count := tokens.NewCalibratorStore(dir).Load("a", "k")
require.Greater(t, count, 0, "calibrator must be persisted by end of Run")
require.Greater(t, ratio, 0.0)
}
+27
View File
@@ -0,0 +1,27 @@
package runtime
import (
"os"
"strconv"
)
// maxToolResultLen returns the per-result truncation cap (chars) for tool
// results in the in-context message history. Precedence:
// 1. Runtime.AgentLoop.MaxToolResultLen (>0) — config wins.
// 2. HARNESS_MAX_TOOL_RESULT_LEN env var (>0) — env fallback.
// 3. defaultMaxToolResultLen (4000).
//
// Tool results longer than this are truncated (or spilled to disk via
// spillConfig when supplied). 4000 is conservative; engineering-style
// agents that read source files and run tests typically want 16000-25000.
func (r *Runtime) maxToolResultLen() int {
if r.AgentLoop.MaxToolResultLen > 0 {
return r.AgentLoop.MaxToolResultLen
}
if v := os.Getenv("HARNESS_MAX_TOOL_RESULT_LEN"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
return n
}
}
return defaultMaxToolResultLen
}
+50
View File
@@ -0,0 +1,50 @@
package runtime
import (
"testing"
)
// TestMaxToolResultLen_Precedence locks in the config > env > default
// precedence so a regression here doesn't silently swap one source for
// another.
func TestMaxToolResultLen_Precedence(t *testing.T) {
t.Run("default when nothing set", func(t *testing.T) {
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "")
r := &Runtime{}
if got := r.maxToolResultLen(); got != defaultMaxToolResultLen {
t.Fatalf("want %d, got %d", defaultMaxToolResultLen, got)
}
})
t.Run("env overrides default", func(t *testing.T) {
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "12345")
r := &Runtime{}
if got := r.maxToolResultLen(); got != 12345 {
t.Fatalf("want 12345, got %d", got)
}
})
t.Run("config overrides env", func(t *testing.T) {
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "12345")
r := &Runtime{AgentLoop: LoopConfig{MaxToolResultLen: 25000}}
if got := r.maxToolResultLen(); got != 25000 {
t.Fatalf("want 25000, got %d", got)
}
})
t.Run("zero env is ignored", func(t *testing.T) {
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "0")
r := &Runtime{}
if got := r.maxToolResultLen(); got != defaultMaxToolResultLen {
t.Fatalf("want %d, got %d", defaultMaxToolResultLen, got)
}
})
t.Run("garbage env is ignored", func(t *testing.T) {
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "not-a-number")
r := &Runtime{}
if got := r.maxToolResultLen(); got != defaultMaxToolResultLen {
t.Fatalf("want %d, got %d", defaultMaxToolResultLen, got)
}
})
}
+57
View File
@@ -0,0 +1,57 @@
package runtime
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
anthropicprovider "github.com/sausheong/harness/providers/anthropic"
)
// cachingCapableFake implements llm.LLMProvider plus the
// llm.PromptCachingProvider capability.
type cachingCapableFake struct {
llmtest.Stub
}
func (*cachingCapableFake) SupportsPromptCaching() bool { return true }
// TestProviderSupportsCaching_CapabilityInterfaceWins: an Anthropic-shaped
// provider registered under a custom name (platformai, bedrock, any relay)
// must still get prompt caching. Gating on the config block's NAME meant
// every turn on a renamed provider re-processed the full history uncached.
func TestProviderSupportsCaching_CapabilityInterfaceWins(t *testing.T) {
r := &Runtime{Provider: "platformai", LLM: &cachingCapableFake{}}
assert.True(t, r.providerSupportsCaching(),
"capability interface must win over the provider name")
}
func TestProviderSupportsCaching_NameFallbackStillWorks(t *testing.T) {
r := &Runtime{Provider: "anthropic", LLM: &llmtest.Stub{}}
assert.True(t, r.providerSupportsCaching(),
"legacy name-based gate kept for providers without the capability interface")
}
func TestProviderSupportsCaching_NonCachingProviderFalse(t *testing.T) {
r := &Runtime{Provider: "local", LLM: &llmtest.Stub{}}
assert.False(t, r.providerSupportsCaching())
}
// TestAnthropicProviderDeclaresPromptCaching pins the wiring end-to-end:
// the real Anthropic provider must implement the capability interface.
func TestAnthropicProviderDeclaresPromptCaching(t *testing.T) {
p := anthropicprovider.NewAnthropicProvider("k", "")
pc, ok := any(p).(llm.PromptCachingProvider)
assert.True(t, ok, "AnthropicProvider must implement llm.PromptCachingProvider")
if ok {
assert.True(t, pc.SupportsPromptCaching())
}
}
// Mid-loop compaction was gated on the same name list; an Anthropic-shaped
// provider under a custom name must support it too.
func TestProviderSupportsMidLoopCompaction_CapabilityInterfaceWins(t *testing.T) {
r := &Runtime{Provider: "platformai", LLM: &cachingCapableFake{}}
assert.True(t, r.providerSupportsMidLoopCompaction())
}
+24 -18
View File
@@ -11,9 +11,15 @@ import (
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
)
const maxToolResultLen = 4000 // truncate tool results longer than this
// defaultMaxToolResultLen is the fallback cap used when LoopConfig.MaxToolResultLen
// is unset and the HARNESS_MAX_TOOL_RESULT_LEN env var is unset/invalid. Tool
// results longer than this get truncated (or spilled to disk + truncated-with-
// marker when spillConfig is supplied). 4000 chars (~1000 tokens) is conservative
// so behaviour is unchanged for callers that don't opt into a larger budget.
const defaultMaxToolResultLen = 4000
// detectImageMIME returns the actual MIME type based on magic bytes.
// Falls back to the provided hint if the format is unrecognized.
@@ -162,17 +168,6 @@ func buildDynamicSystemPromptSuffix(dateLine, cortexContext string) string {
// corresponding tool_result in the next user message. Orphaned tool calls
// (e.g. from interrupted sessions) get synthetic error results injected.
func assembleMessages(history []session.SessionEntry) []llm.Message {
// First pass: collect tool result IDs so we can detect orphaned tool calls.
resultIDs := make(map[string]bool)
for _, entry := range history {
if entry.Type == session.EntryTypeToolResult {
var tr session.ToolResultData
if err := json.Unmarshal(entry.Data, &tr); err == nil {
resultIDs[tr.ToolCallID] = true
}
}
}
var msgs []llm.Message
for _, entry := range history {
@@ -213,9 +208,6 @@ func assembleMessages(history []session.SessionEntry) []llm.Message {
if err := json.Unmarshal(entry.Data, &md); err != nil {
continue
}
// Before appending a new message, check if the last assistant
// message has orphaned tool calls that need synthetic results.
msgs = injectMissingToolResults(msgs)
msg := llm.Message{
Role: entry.Role,
Content: md.Text,
@@ -428,7 +420,7 @@ func spillToolResult(cfg spillConfig, toolCallID, content string) (string, error
return "", fmt.Errorf("spill mkdir: %w", err)
}
path := filepath.Join(dir, toolCallID+".txt")
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
if err := tool.WriteFileAtomic(path, []byte(content), 0o600); err != nil {
return "", fmt.Errorf("spill write: %w", err)
}
return path, nil
@@ -455,7 +447,7 @@ func spillToolResult(cfg spillConfig, toolCallID, content string) (string, error
// nearest newline boundary — most tool outputs (file reads, command
// output) are front-loaded with the most relevant info, so the head
// preview is usually enough on its own.
func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig) {
func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig, spilled map[string]bool) {
for i := range msgs {
if msgs[i].ToolCallID == "" || len(msgs[i].Content) <= maxLen {
continue
@@ -475,11 +467,25 @@ func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig) {
// Try spill first if configured. On any failure, fall through to
// legacy truncation so the prefill stays bounded either way.
if cfg.Workspace != "" && cfg.SessionKey != "" {
if path, err := spillToolResult(cfg, msgs[i].ToolCallID, msgs[i].Content); err == nil {
id := msgs[i].ToolCallID
// Spill content is immutable per ToolCallID and lands at a
// deterministic path. If this Run already spilled this ID,
// skip the (multi-MB) disk re-write and just rebuild the
// in-memory marker pointing at the same path.
if spilled != nil && spilled[id] {
path := filepath.Join(cfg.Workspace, ".harness", "spill", cfg.SessionKey, id+".txt")
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars saved to %s; use read_file to access the full output]",
head, spillMarker, len(head), originalLen, path)
continue
}
if writtenPath, err := spillToolResult(cfg, id, msgs[i].Content); err == nil {
if spilled != nil {
spilled[id] = true
}
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars saved to %s; use read_file to access the full output]",
head, spillMarker, len(head), originalLen, writtenPath)
continue
}
}
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars; re-run the tool with offset/limit to see more]",
+27
View File
@@ -1,12 +1,14 @@
package runtime
import (
jsonpkg "encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/sausheong/harness/session"
"github.com/stretchr/testify/require"
)
@@ -123,3 +125,28 @@ func TestFormatDateLine(t *testing.T) {
})
}
}
func mustJSON(t *testing.T, v any) jsonpkg.RawMessage {
t.Helper()
b, err := jsonpkg.Marshal(v)
require.NoError(t, err)
return b
}
func TestAssembleMessagesInjectsOrphanedToolResult(t *testing.T) {
history := []session.SessionEntry{
{Type: session.EntryTypeMessage, Role: "user", Data: mustJSON(t, session.MessageData{Text: "hi"})},
{Type: session.EntryTypeToolCall, Role: "assistant", Data: mustJSON(t, session.ToolCallData{
ID: "call_1", Tool: "bash", Input: jsonpkg.RawMessage(`{}`),
})},
{Type: session.EntryTypeMessage, Role: "user", Data: mustJSON(t, session.MessageData{Text: "still there?"})},
}
msgs := assembleMessages(history)
var found bool
for _, m := range msgs {
if m.ToolCallID == "call_1" {
found = true
}
}
require.True(t, found, "orphaned tool call must get a synthetic tool result from the terminal pass")
}
+107
View File
@@ -266,3 +266,110 @@ func TestBuildRuntimeRejectsCrossProviderFallback(t *testing.T) {
func decodeMessage(e session.SessionEntry, dst *session.MessageData) error {
return json.Unmarshal(e.Data, dst)
}
// refusalThenSuccessProvider returns a classifier-refusal stream (HTTP
// 200, EventDone with StopReason=refusal, no content) on the first call
// and a normal text stream on the second. Mirrors Claude Fable 5 safety
// classifier behavior: refusals are NOT transport errors, so the
// existing IsRetryableModelError path never sees them.
type refusalThenSuccessProvider struct {
llmtest.Base
calls int
modelsSeen []string
finalText string
}
func (p *refusalThenSuccessProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.calls++
p.modelsSeen = append(p.modelsSeen, req.Model)
ch := make(chan llm.ChatEvent, 4)
if p.calls == 1 {
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: llm.StopReasonRefusal, StopCategory: "bio"}
} else {
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: p.finalText}
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: "end_turn"}
}
close(ch)
return ch, nil
}
// TestRuntimeRefusalRetriesOnFallbackModel: a refusal turn with a
// configured fallback must transparently re-run the turn on the
// fallback model instead of surfacing an empty response.
func TestRuntimeRefusalRetriesOnFallbackModel(t *testing.T) {
prov := &refusalThenSuccessProvider{finalText: "fallback answered"}
rt := &Runtime{
LLM: prov,
Tools: tool.NewRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "claude-fable-5",
FallbackModel: "claude-opus-4-8",
Provider: "anthropic",
MaxTurns: 3,
Workspace: t.TempDir(),
}
out, err := rt.RunSync(context.Background(), "summarise the biology article", nil)
require.NoError(t, err)
assert.Equal(t, "fallback answered", out)
require.Equal(t, 2, prov.calls, "refusal + fallback retry = 2 calls")
assert.Equal(t, "claude-fable-5", prov.modelsSeen[0])
assert.Equal(t, "claude-opus-4-8", prov.modelsSeen[1])
}
// alwaysRefusalProvider refuses every call — covers the no-fallback and
// fallback-also-refused paths.
type alwaysRefusalProvider struct {
llmtest.Base
calls int
}
func (p *alwaysRefusalProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.calls++
ch := make(chan llm.ChatEvent, 2)
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: llm.StopReasonRefusal, StopCategory: "cyber"}
close(ch)
return ch, nil
}
// TestRuntimeRefusalWithoutFallbackSurfacesVisibleText: with no fallback
// the user must see an explanation, not an empty response.
func TestRuntimeRefusalWithoutFallbackSurfacesVisibleText(t *testing.T) {
prov := &alwaysRefusalProvider{}
rt := &Runtime{
LLM: prov,
Tools: tool.NewRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "claude-fable-5",
Provider: "anthropic",
MaxTurns: 3,
Workspace: t.TempDir(),
}
out, err := rt.RunSync(context.Background(), "do something", nil)
require.NoError(t, err, "a refusal is a model decision, not a transport error")
assert.Contains(t, out, "declined", "refusal must produce visible explanation text")
assert.Contains(t, out, "cyber", "category should be included when present")
assert.Equal(t, 1, prov.calls, "no fallback configured → no retry")
}
// TestRuntimeRefusalFallbackAlsoRefusesSurfacesText: when the fallback
// refuses too, stop (no infinite retry) and surface the explanation.
func TestRuntimeRefusalFallbackAlsoRefusesSurfacesText(t *testing.T) {
prov := &alwaysRefusalProvider{}
rt := &Runtime{
LLM: prov,
Tools: tool.NewRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "claude-fable-5",
FallbackModel: "claude-opus-4-8",
Provider: "anthropic",
MaxTurns: 3,
Workspace: t.TempDir(),
}
out, err := rt.RunSync(context.Background(), "do something", nil)
require.NoError(t, err)
assert.Contains(t, out, "declined")
assert.Equal(t, 2, prov.calls, "primary + one fallback attempt, then stop")
}
+125
View File
@@ -0,0 +1,125 @@
package runtime
import (
"context"
"encoding/json"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// twoTurnUsageLLM: turn 1 emits a noop tool call + EventDone{Usage:u1};
// turn 2 (after the tool result) emits text + EventDone{Usage:u2} and stops.
type twoTurnUsageLLM struct {
llmtest.Base
u1, u2 *llm.Usage
calls int
}
func (f *twoTurnUsageLLM) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
ch := make(chan llm.ChatEvent, 8)
first := f.calls == 0
f.calls++
go func() {
defer close(ch)
if first {
tc := llm.ToolCall{ID: "tc_0", Name: "noop", Input: json.RawMessage(`{}`)}
ch <- llm.ChatEvent{Type: llm.EventToolCallStart, ToolCall: &tc}
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &tc}
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: f.u1}
return
}
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "done"}
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: f.u2}
}()
return ch, nil
}
// usageNoopExecutor returns "ok" for a "noop" tool. (Distinct from the
// error-returning noopExecutor in agent_test.go, which has no tool defs.)
type usageNoopExecutor struct{}
func (usageNoopExecutor) Execute(_ context.Context, _ string, _ json.RawMessage) (tool.ToolResult, error) {
return tool.ToolResult{Output: "ok"}, nil
}
func (usageNoopExecutor) ToolDefs() []llm.ToolDef { return []llm.ToolDef{{Name: "noop"}} }
func (usageNoopExecutor) Names() []string { return []string{"noop"} }
func (usageNoopExecutor) Get(string) (tool.Tool, bool) { return nil, false }
func drainUsage(t *testing.T, events <-chan AgentEvent) *llm.Usage {
t.Helper()
var done *llm.Usage
var sawDone bool
for ev := range events {
if ev.Type == EventDone {
done = ev.Usage
sawDone = true
}
}
require.True(t, sawDone, "expected a terminal EventDone")
return done
}
func TestRun_UsageAccumulatesAcrossTurns(t *testing.T) {
r := &Runtime{
LLM: &twoTurnUsageLLM{
u1: &llm.Usage{InputTokens: 100, OutputTokens: 40, CacheCreationInputTokens: 10, CacheReadInputTokens: 6},
u2: &llm.Usage{InputTokens: 10, OutputTokens: 5, CacheCreationInputTokens: 1, CacheReadInputTokens: 2},
},
Tools: usageNoopExecutor{},
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test-model",
MaxTurns: 5,
}
events, err := r.Run(context.Background(), "go", nil)
require.NoError(t, err)
got := drainUsage(t, events)
require.NotNil(t, got)
assert.Equal(t, 110, got.InputTokens)
assert.Equal(t, 45, got.OutputTokens)
assert.Equal(t, 11, got.CacheCreationInputTokens)
assert.Equal(t, 8, got.CacheReadInputTokens)
}
func TestRun_UsageSingleTurn(t *testing.T) {
r := &Runtime{
LLM: &twoTurnUsageLLM{
u2: &llm.Usage{InputTokens: 7, OutputTokens: 3},
},
Tools: usageNoopExecutor{},
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test-model",
MaxTurns: 5,
}
// calls=0 path emits a tool call; to get a pure single turn, mark calls so
// the first ChatStream takes the text+stop branch.
r.LLM.(*twoTurnUsageLLM).calls = 1
events, err := r.Run(context.Background(), "go", nil)
require.NoError(t, err)
got := drainUsage(t, events)
require.NotNil(t, got)
assert.Equal(t, 7, got.InputTokens)
assert.Equal(t, 3, got.OutputTokens)
}
func TestRun_UsageNilWhenProviderSilent(t *testing.T) {
r := &Runtime{
LLM: &twoTurnUsageLLM{calls: 1}, // single turn, u2 nil → EventDone with nil usage
Tools: usageNoopExecutor{},
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test-model",
MaxTurns: 5,
}
events, err := r.Run(context.Background(), "go", nil)
require.NoError(t, err)
got := drainUsage(t, events)
assert.Nil(t, got, "usage must stay nil when the provider never reports it")
}
+189 -29
View File
@@ -45,7 +45,7 @@ type AgentEvent struct {
Result *tool.ToolResult
Error error
Compaction *compaction.Result // populated for EventCompaction* events
Usage *llm.Usage // populated for EventDone when the provider reported it
Usage *llm.Usage // on the terminal EventDone, the token total accumulated across all turns of the run (nil if the provider never reported usage); per-turn figures are available via RunTurn's TurnResult.Usage
}
// Runtime is the agent think-act loop.
@@ -105,6 +105,14 @@ type Runtime struct {
touchedMu sync.Mutex
touchedFiles []string
// spilledIDs records ToolCallIDs whose oversized results have already
// been written to the deterministic spill path during this Runtime's
// lifetime. Content is immutable per ToolCallID, so once spilled we
// skip the (multi-MB) disk re-write on subsequent turns and only
// rebuild the in-memory marker.
spilledMu sync.Mutex
spilledIDs map[string]bool
// IngestSource controls whether this run's thread is ingested into the KG.
// "chat" (or empty) ingests; any other value skips ingest.
IngestSource string
@@ -114,6 +122,12 @@ type Runtime struct {
calibrator *tokens.Calibrator
// calibratorDirty records that the calibrator was updated during this
// Run and must be flushed to CalibratorStore once at Run end. Accessed
// only on the Run goroutine (EventDone handling + deferred flush), so no
// lock is needed.
calibratorDirty bool
// mcpClients holds the MCP client sessions resolved from
// AgentSpec.MCPServers. Released by Close. Untouched when MCP is
// not used.
@@ -181,14 +195,26 @@ func (r *Runtime) maybeKickoffAsyncCompaction(msgs []llm.Message, parts []llm.Sy
}
// providerSupportsCaching returns true when the runtime's provider implements
// Anthropic-style explicit prompt caching.
// Anthropic-style explicit prompt caching. The capability interface wins:
// a provider block named "platformai" (or "bedrock", or anything else)
// wrapping the Anthropic implementation still caches. The name check is
// the legacy fallback for custom LLMProvider impls that predate the
// capability interface.
func (r *Runtime) providerSupportsCaching() bool {
if pc, ok := r.LLM.(llm.PromptCachingProvider); ok {
return pc.SupportsPromptCaching()
}
return r.Provider == "anthropic"
}
// providerSupportsMidLoopCompaction returns true for hosted frontier
// providers that handle mid-loop summary injection cleanly.
// providers that handle mid-loop summary injection cleanly. Same
// capability-over-name rule as providerSupportsCaching: an
// Anthropic-shaped provider under a custom name qualifies.
func (r *Runtime) providerSupportsMidLoopCompaction() bool {
if pc, ok := r.LLM.(llm.PromptCachingProvider); ok && pc.SupportsPromptCaching() {
return true
}
switch r.Provider {
case "anthropic", "openai", "gemini":
return true
@@ -223,6 +249,18 @@ func (r *Runtime) snapshotTouchedFiles() []string {
return out
}
// prune shortens oversized tool results in msgs, spilling to disk where
// configured. It carries the Runtime's per-Run spilled-ID set so a result
// already spilled this Run is not re-written to disk on subsequent turns.
func (r *Runtime) prune(msgs []llm.Message, spillCfg spillConfig) {
r.spilledMu.Lock()
if r.spilledIDs == nil {
r.spilledIDs = map[string]bool{}
}
pruneToolResults(msgs, r.maxToolResultLen(), spillCfg, r.spilledIDs)
r.spilledMu.Unlock()
}
// isFileTool reports whether a tool name's input contains a "path" field.
func isFileTool(name string) bool {
switch name {
@@ -242,6 +280,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
defer close(r.events)
defer tr.Summary()
// Flush the per-session calibrator once at Run end (all exit paths:
// normal, error, abort) instead of writing to disk on every LLM
// round. EventDone sets calibratorDirty when it folds in a usage
// sample; this defer persists the final state. Registered here so it
// runs regardless of which return below fires.
defer func() {
if r.calibratorDirty && r.CalibratorStore != nil && r.Session != nil && r.calibrator != nil {
ratio, count := r.calibrator.Snapshot()
r.CalibratorStore.Save(r.AgentID, r.Session.Key, ratio, count)
}
}()
// stopReason is read by the OnStop deferred hook below. Each early
// return path reassigns it before returning. Default is "max_turns"
// so the natural fall-through (loop exhausted MaxTurns) records the
@@ -326,6 +376,26 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
// Computed once per Run so the date stays stable across turns.
dateLine := FormatDateLine(time.Now())
// Tool defs are invariant for the whole Run (tools and permission don't
// change mid-Run), so normalize once instead of per turn (P3).
toolDefs := r.Tools.ToolDefs()
if r.Permission != nil {
toolDefs = r.Permission.FilterToolDefs(toolDefs, r.AgentID)
}
sort.SliceStable(toolDefs, func(i, j int) bool {
return toolDefs[i].Name < toolDefs[j].Name
})
toolDefs, diags := r.LLM.NormalizeToolSchema(toolDefs)
for _, d := range diags {
slog.Info("tool schema normalized",
"tool", d.ToolName,
"field", d.Field,
"action", d.Action,
"reason", d.Reason)
}
var runUsage *llm.Usage // accumulated across all turns; nil until first reported
for turn := 0; turn < maxTurns; turn++ {
if ctx.Err() != nil {
stopReason = "aborted"
@@ -364,23 +434,8 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
msgs := assembleMessages(history)
spillCfg := spillConfig{Workspace: r.Workspace, SessionKey: r.Session.Key}
pruneToolResults(msgs, maxToolResultLen, spillCfg)
r.prune(msgs, spillCfg)
toolDefs := r.Tools.ToolDefs()
if r.Permission != nil {
toolDefs = r.Permission.FilterToolDefs(toolDefs, r.AgentID)
}
sort.SliceStable(toolDefs, func(i, j int) bool {
return toolDefs[i].Name < toolDefs[j].Name
})
toolDefs, diags := r.LLM.NormalizeToolSchema(toolDefs)
for _, d := range diags {
slog.Info("tool schema normalized",
"tool", d.ToolName,
"field", d.Field,
"action", d.Action,
"reason", d.Reason)
}
tr.Mark("context.assemble", "turn", turn, "msgs", len(msgs), "tools", len(toolDefs), "sysprompt_chars", len(staticText)+len(dynamicSuffix), "dur_ms_local", time.Since(phaseStart).Milliseconds())
// Wait briefly on any in-flight async compaction kicked off by
@@ -390,7 +445,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
history = r.Session.View()
msgs = assembleMessages(history)
pruneToolResults(msgs, maxToolResultLen, spillCfg)
r.prune(msgs, spillCfg)
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
}
}
@@ -416,7 +471,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
history = r.Session.View()
msgs = assembleMessages(history)
pruneToolResults(msgs, maxToolResultLen, spillCfg)
r.prune(msgs, spillCfg)
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
} else {
r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res})
@@ -449,7 +504,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
history = r.Session.View()
msgs = assembleMessages(history)
pruneToolResults(msgs, maxToolResultLen, spillCfg)
r.prune(msgs, spillCfg)
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
req.Messages = msgs
stream, err = r.LLM.ChatStream(ctx, req)
@@ -475,7 +530,6 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
var textContent strings.Builder
var lastUsage *llm.Usage
var toolCalls []llm.ToolCall
gotFirstToken := false
@@ -485,6 +539,10 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
streamSource := stream
retriedNonStreaming := false
preTokenRetried := false
retriedRefusal := false
var refused bool
var refusalCategory string
streamLoop:
for {
for event := range streamSource {
@@ -527,18 +585,35 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}()
case llm.EventDone:
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
if event.Usage != nil {
lastUsage = event.Usage
runUsage = addUsage(runUsage, event.Usage)
}
if event.Usage != nil && r.calibrator != nil {
// Recompute the estimate on the CURRENT msgs (which may
// have been reassembled by mid-turn compaction) so the
// calibration ratio matches event.Usage.InputTokens, as
// the pre-debounce code did. The P8 change only debounces
// the disk write (calibratorDirty + deferred flush), not
// the estimate computation.
r.calibrator.Update(event.Usage.InputTokens, tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs))
if r.CalibratorStore != nil && r.Session != nil {
ratio, count := r.calibrator.Snapshot()
r.CalibratorStore.Save(r.AgentID, r.Session.Key, ratio, count)
}
r.calibratorDirty = true
}
case llm.EventError:
if !gotFirstToken && !preTokenRetried {
if newStream, ok := r.recoverFromPreTokenError(ctx, event.Error, &req, &msgs, spillCfg); ok {
preTokenRetried = true
drainKickoffs(kickoffs)
kickoffs = map[string]chan kickoffResult{}
textContent.Reset()
toolCalls = nil
kickoffStopped = false
streamSource = newStream
continue streamLoop
}
}
if gotFirstToken && !retriedNonStreaming {
if ns, ok := r.LLM.(llm.NonStreamingProvider); ok {
slog.Warn("stream died mid-flight; retrying as non-streaming",
@@ -567,6 +642,53 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
return
}
}
// Classifier/model refusal (Claude Fable 5+): HTTP 200,
// stop_reason=refusal, usually no content. Without handling,
// the turn ends as a silent empty success. Retry once on the
// fallback model (refusals are model-specific — Opus-tier
// has no bio/cyber classifiers); otherwise synthesize a
// visible explanation. Mid-stream refusals discard partial
// output per the API contract.
if refused {
if !retriedRefusal && r.FallbackModel != "" && r.FallbackModel != req.Model {
slog.Warn("model refused; retrying on fallback model",
"agent", r.AgentID,
"primary", req.Model,
"fallback", r.FallbackModel,
"category", refusalCategory)
tr.Mark("llm.refusal_fallback", "turn", turn,
"primary", req.Model, "fallback", r.FallbackModel,
"category", refusalCategory)
textContent.Reset()
toolCalls = nil
drainKickoffs(kickoffs)
kickoffs = map[string]chan kickoffResult{}
gotFirstToken = false
kickoffStopped = false
refused = false
retriedRefusal = true
req.Model = r.FallbackModel
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
if retryErr != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: retryErr})
return
}
streamSource = retryStream
continue streamLoop
}
textContent.Reset()
toolCalls = nil
drainKickoffs(kickoffs)
note := "The model declined this request (safety classifier"
if refusalCategory != "" {
note += ", category: " + refusalCategory
}
note += "). Try rephrasing, or switch this agent to a model without these classifiers."
textContent.WriteString(note)
r.emit(AgentEvent{Type: EventTextDelta, Text: note})
}
break streamLoop
}
tr.Mark("llm.stream_end", "turn", turn,
@@ -592,7 +714,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
tr.Mark("agent.done", "turn", turn, "reason", "no_tool_calls")
stopReason = "completed"
r.emit(AgentEvent{Type: EventDone, Usage: lastUsage})
r.emit(AgentEvent{Type: EventDone, Usage: runUsage})
r.maybeKickoffAsyncCompaction(msgs, parts, toolDefs)
return
}
@@ -679,6 +801,42 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
return r.events, nil
}
// recoverFromPreTokenError attempts the same recovery the synchronous
// ChatStream-error path performs, for an error delivered via EventError
// before any token arrived (Anthropic/Gemini deliver HTTP errors this way).
// Returns a fresh stream to resume from and true if recovered; false if the
// error is not recoverable (caller should abort). May mutate *req (model
// swap) and the session (compaction), and reassigns *msgs on compaction.
func (r *Runtime) recoverFromPreTokenError(ctx context.Context, err error, req *llm.ChatRequest, msgs *[]llm.Message, spillCfg spillConfig) (<-chan llm.ChatEvent, bool) {
if compaction.IsContextOverflow(err) && r.Compaction != nil {
r.emit(AgentEvent{Type: EventCompactionStart})
res, _ := r.Compaction.MaybeCompact(ctx, r.Session, compaction.ReasonReactive, "")
if res.Compacted {
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
history := r.Session.View()
newMsgs := assembleMessages(history)
r.prune(newMsgs, spillCfg)
newMsgs = prependPostCompactRestore(newMsgs, r.snapshotTouchedFiles())
*msgs = newMsgs
req.Messages = newMsgs
if s, e := r.LLM.ChatStream(ctx, *req); e == nil {
return s, true
}
} else {
r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res})
}
}
if r.FallbackModel != "" && r.FallbackModel != req.Model && llm.IsRetryableModelError(err) {
slog.Info("llm fallback model engaged (stream error)",
"agent", r.AgentID, "primary", req.Model, "fallback", r.FallbackModel, "err", err.Error())
req.Model = r.FallbackModel
if s, e := r.LLM.ChatStream(ctx, *req); e == nil {
return s, true
}
}
return nil, false
}
// RunSync is a convenience method that runs the agent and collects the
// full text response.
func (r *Runtime) RunSync(ctx context.Context, userMsg string, images []llm.ImageContent) (string, error) {
@@ -692,6 +850,8 @@ func (r *Runtime) RunSync(ctx context.Context, userMsg string, images []llm.Imag
switch event.Type {
case EventTextDelta:
response.WriteString(event.Text)
case EventAborted:
return response.String(), context.Canceled
case EventError:
return response.String(), event.Error
}
+265
View File
@@ -0,0 +1,265 @@
package runtime
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
// TurnResult describes the outcome of a single RunTurn call.
type TurnResult struct {
Done bool // true when no tool calls were produced (loop should stop)
StopReason string // "continue" | "completed" | "error" | "aborted"
Entries []session.SessionEntry // entries appended during THIS turn, in order
Err error
Usage *llm.Usage
}
// TurnEmit is an optional live-streaming callback. Pass nil for headless
// execution (e.g. durable replay, where live emission must be suppressed).
type TurnEmit func(AgentEvent)
// RunTurn executes exactly one turn of the agent loop against the current
// session and returns the entries it produced. The first call of a session
// passes the user message; continuation calls pass "".
//
// RunTurn is the durable unit for a per-turn driver: each call can be wrapped
// as a checkpointed step whose return value (TurnResult.Entries) rebuilds
// session state on replay. It differs from Run by design: it is headless
// (live events go only through the emit callback, never an internal channel),
// it dispatches tool calls serially (Run parallelizes concurrency-safe
// batches), and it does NOT perform compaction, streaming-tool kickoff, or the
// trace/slog emissions that Run's emitToolResult produces (those remain Run's
// responsibility). It DOES perform bounded-synchronous knowledge-graph recall on
// the first round of an exchange (folding the hint into the system prompt) and
// async knowledge-graph ingest on the completing round.
func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.ImageContent, emit TurnEmit) (TurnResult, error) {
if emit == nil {
emit = func(AgentEvent) {}
}
startLen := len(r.Session.Entries())
if userMsg != "" || len(images) > 0 {
if len(images) > 0 {
var imgData []session.ImageData
for _, img := range images {
imgData = append(imgData, session.ImageData{
MimeType: img.MimeType,
Data: base64.StdEncoding.EncodeToString(img.Data),
})
}
r.Session.Append(session.UserMessageWithImagesEntry(userMsg, imgData))
} else {
r.Session.Append(session.UserMessageEntry(userMsg))
}
}
if ctx.Err() != nil {
return r.turnSlice(startLen, true, "aborted", nil, ctx.Err()), nil
}
history := r.Session.View()
msgs := assembleMessages(history)
toolDefs := r.Tools.ToolDefs()
if r.Permission != nil {
toolDefs = r.Permission.FilterToolDefs(toolDefs, r.AgentID)
}
sort.SliceStable(toolDefs, func(i, j int) bool { return toolDefs[i].Name < toolDefs[j].Name })
toolDefs, _ = r.LLM.NormalizeToolSchema(toolDefs)
// KG recall (first round of the exchange only): bounded-synchronous so a
// slow embedder cannot stall the turn. The hint is a non-cached suffix —
// it varies per query, so caching it would poison the static prefix cache.
var kgHint string
if r.KG != nil && (userMsg != "" || len(images) > 0) && r.KG.ShouldRecall(userMsg) {
rctx, cancel := context.WithTimeout(ctx, 800*time.Millisecond)
kgHint = r.KG.Recall(rctx, userMsg)
cancel()
}
parts := []llm.SystemPromptPart{{Text: r.StaticSystemPrompt, Cache: true}}
if kgHint != "" {
parts = append(parts, llm.SystemPromptPart{Text: kgHint, Cache: false})
}
req := llm.ChatRequest{
Model: r.Model,
Messages: msgs,
Tools: toolDefs,
MaxTokens: 8192,
SystemPromptParts: parts,
CacheLastMessage: r.providerSupportsCaching(),
Reasoning: r.Reasoning,
}
stream, err := r.LLM.ChatStream(ctx, req)
if err != nil {
if r.FallbackModel != "" && r.FallbackModel != req.Model && llm.IsRetryableModelError(err) {
req.Model = r.FallbackModel
stream, err = r.LLM.ChatStream(ctx, req)
}
if err != nil {
emit(AgentEvent{Type: EventError, Error: fmt.Errorf("llm error: %w", err)})
return r.turnSlice(startLen, true, "error", nil, err), nil
}
}
var textContent strings.Builder
var toolCalls []llm.ToolCall
var lastUsage *llm.Usage
retriedRefusal := false
streamLoop:
for {
var refused bool
var refusalCategory string
for event := range stream {
switch event.Type {
case llm.EventTextDelta:
textContent.WriteString(event.Text)
emit(AgentEvent{Type: EventTextDelta, Text: event.Text})
case llm.EventToolCallStart:
emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall})
case llm.EventToolCallDone:
if event.ToolCall != nil {
toolCalls = append(toolCalls, *event.ToolCall)
}
case llm.EventDone:
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
if event.Usage != nil {
lastUsage = event.Usage
}
case llm.EventError:
emit(AgentEvent{Type: EventError, Error: event.Error})
return r.turnSlice(startLen, true, "error", lastUsage, event.Error), nil
}
}
// Same refusal contract as Run: retry once on the fallback model,
// else surface a visible explanation instead of empty silence.
if refused {
if !retriedRefusal && r.FallbackModel != "" && r.FallbackModel != req.Model {
retriedRefusal = true
textContent.Reset()
toolCalls = nil
req.Model = r.FallbackModel
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
if retryErr != nil {
emit(AgentEvent{Type: EventError, Error: retryErr})
return r.turnSlice(startLen, true, "error", lastUsage, retryErr), nil
}
stream = retryStream
continue streamLoop
}
textContent.Reset()
toolCalls = nil
note := "The model declined this request (safety classifier"
if refusalCategory != "" {
note += ", category: " + refusalCategory
}
note += "). Try rephrasing, or switch this agent to a model without these classifiers."
textContent.WriteString(note)
emit(AgentEvent{Type: EventTextDelta, Text: note})
}
break streamLoop
}
if textContent.Len() > 0 {
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
}
if len(toolCalls) == 0 {
// Exchange complete: ingest the full thread once. Background + best-effort
// (the KG spawns its own bounded goroutine), so it never delays the turn.
// context.Background() because the request ctx may be cancelling and the
// ingest goroutine deliberately outlives the turn. Unlike Run, RunTurn does
// not pre-filter trivial threads or gate on IngestSource: the KG impl owns
// its own growth gate (so single-message threads are skipped there), and the
// only RunTurn caller today is the chat serve loop. TODO: if a reviewer or
// subagent path is ever migrated to RunTurn, add an IngestSource-style gate
// here so non-chat transcripts are not ingested.
if r.KG != nil {
r.KG.Ingest(context.Background(), sessionThread(r.Session.View()))
}
emit(AgentEvent{Type: EventDone, Usage: lastUsage})
return r.turnSlice(startLen, true, "completed", lastUsage, nil), nil
}
// RunTurn dispatches tool calls serially by design: deterministic
// ordering keeps durable replay simple, and parallel/concurrency-safe
// batching deliberately stays in Run (see the doc comment). dispatchTool
// appends the tool_call and tool_result entries to the session.
for _, tc := range toolCalls {
result, aborted := r.dispatchTool(ctx, tc, nil)
emit(AgentEvent{Type: EventToolResult, ToolCall: &tc, Result: &result})
if aborted {
return r.turnSlice(startLen, true, "aborted", lastUsage, ctx.Err()), nil
}
}
return r.turnSlice(startLen, false, "continue", lastUsage, nil), nil
}
// turnSlice builds a TurnResult from the entries appended since startLen.
// It assumes a single active turn per session: the delta entries[startLen:]
// is correct only because no other goroutine appends to this session
// concurrently during the turn.
func (r *Runtime) turnSlice(startLen int, done bool, reason string, usage *llm.Usage, err error) TurnResult {
all := r.Session.Entries()
var delta []session.SessionEntry
if startLen <= len(all) {
delta = append(delta, all[startLen:]...)
}
return TurnResult{Done: done, StopReason: reason, Entries: delta, Usage: usage, Err: err}
}
// sessionThread converts session history into the minimal []Message the
// KnowledgeGraph ingests, mirroring how Run accumulates its thread: user and
// assistant messages by role+text, tool calls as "[tool: name]\n<input>"
// (assistant), tool results as their output or "[error] <err>" (user).
// Compaction/meta and non-user/assistant message entries are skipped — the
// thread carries only conversation turns and tool exchanges.
// On the runtime's per-turn serve path each call sees one turn's fresh session,
// so a compaction summary's absence here is intentional, not a gap.
func sessionThread(history []session.SessionEntry) []Message {
var thread []Message
for _, e := range history {
switch e.Type {
case session.EntryTypeMessage:
if e.Role != "user" && e.Role != "assistant" {
continue // skip system/summary messages
}
var d session.MessageData
if json.Unmarshal(e.Data, &d) != nil {
continue
}
thread = append(thread, Message{Role: e.Role, Content: d.Text})
case session.EntryTypeToolCall:
var d session.ToolCallData
if json.Unmarshal(e.Data, &d) != nil {
continue
}
thread = append(thread, Message{
Role: "assistant",
Content: fmt.Sprintf("[tool: %s]\n%s", d.Tool, string(d.Input)),
})
case session.EntryTypeToolResult:
var d session.ToolResultData
if json.Unmarshal(e.Data, &d) != nil {
continue
}
content := d.Output
if d.Error != "" {
content = "[error] " + d.Error
}
thread = append(thread, Message{Role: "user", Content: content})
}
}
return thread
}
+216
View File
@@ -0,0 +1,216 @@
package runtime
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/stretchr/testify/require"
)
func TestSessionThread_RendersEntries(t *testing.T) {
sess := session.NewSession("a", "k")
sess.Append(session.UserMessageEntry("hello"))
sess.Append(session.AssistantMessageEntry("hi there"))
sess.Append(session.ToolCallEntry("tc1", "echo", json.RawMessage(`{"x":1}`)))
sess.Append(session.ToolResultEntry("tc1", "echoed", "", nil))
sess.Append(session.ToolResultEntry("tc2", "", "boom", nil))
thread := sessionThread(sess.View())
require.Equal(t, []Message{
{Role: "user", Content: "hello"},
{Role: "assistant", Content: "hi there"},
{Role: "assistant", Content: "[tool: echo]\n{\"x\":1}"},
{Role: "user", Content: "echoed"},
{Role: "user", Content: "[error] boom"},
}, thread)
}
func TestSessionThread_SkipsCompaction(t *testing.T) {
sess := session.NewSession("a", "k")
// Compaction is appended FIRST so the entries that follow remain on the
// View() walk-back path. View() stops its back-walk at the most recent
// compaction (inclusive), so appending user/assistant AFTER it yields
// View() == [compaction, user, assistant] — the compaction is genuinely
// present in the slice handed to sessionThread, exercising the skip path.
// (Appending compaction last would make it the leaf, and View() would
// return only [compaction], never reaching the messages.)
sess.Append(session.CompactionEntry("summary", "", "", "m", 0, 0, 0))
sess.Append(session.UserMessageEntry("hello"))
sess.Append(session.AssistantMessageEntry("hi"))
view := sess.View()
require.Equal(t, session.EntryTypeCompaction, view[0].Type, "View() must include the compaction entry to exercise the skip")
got := sessionThread(view)
require.Equal(t, []Message{
{Role: "user", Content: "hello"},
{Role: "assistant", Content: "hi"},
}, got)
}
func TestSessionThread_SkipsUndecodableEntry(t *testing.T) {
history := []session.SessionEntry{
{Type: session.EntryTypeToolCall, Data: []byte("not json")},
session.UserMessageEntry("after"),
}
got := sessionThread(history)
require.Equal(t, []Message{{Role: "user", Content: "after"}}, got)
}
func TestSessionThread_Empty(t *testing.T) {
require.Nil(t, sessionThread(nil))
}
// fakeKG is a controllable KnowledgeGraph for RunTurn wiring tests.
type fakeKG struct {
shouldRecall bool
recallReturn string
recallDelay time.Duration
recallCalls int
recallQuery string
ingestCalls int
ingestThreads [][]Message
}
func (f *fakeKG) ShouldRecall(q string) bool { return f.shouldRecall }
func (f *fakeKG) Recall(ctx context.Context, q string) string {
f.recallCalls++
f.recallQuery = q
if f.recallDelay > 0 {
select {
case <-time.After(f.recallDelay):
case <-ctx.Done():
return ""
}
}
return f.recallReturn
}
func (f *fakeKG) Ingest(_ context.Context, thread []Message) {
f.ingestCalls++
f.ingestThreads = append(f.ingestThreads, thread)
}
func TestRunTurn_RecallInjectedIntoPrompt(t *testing.T) {
var captured []llm.SystemPromptPart
cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }}
kg := &fakeKG{shouldRecall: true, recallReturn: "Relevant memories:\n- the user likes tea\n"}
rt := &Runtime{
LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg,
}
_, err := rt.RunTurn(context.Background(), "what do I like?", nil, nil)
require.NoError(t, err)
require.Equal(t, 1, kg.recallCalls)
require.Equal(t, "what do I like?", kg.recallQuery)
require.GreaterOrEqual(t, len(captured), 2, "expected static + recall parts")
require.Equal(t, "STATIC", captured[0].Text)
require.True(t, captured[0].Cache)
require.Equal(t, "Relevant memories:\n- the user likes tea\n", captured[len(captured)-1].Text)
require.False(t, captured[len(captured)-1].Cache, "recall hint must NOT be cached")
}
func TestRunTurn_NoRecallWhenShouldRecallFalse(t *testing.T) {
var captured []llm.SystemPromptPart
cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }}
kg := &fakeKG{shouldRecall: false, recallReturn: "should not appear"}
rt := &Runtime{
LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg,
}
_, err := rt.RunTurn(context.Background(), "hi", nil, nil)
require.NoError(t, err)
require.Equal(t, 0, kg.recallCalls, "ShouldRecall false ⇒ Recall not called")
require.Len(t, captured, 1, "only the static part")
require.Equal(t, "STATIC", captured[0].Text)
}
func TestRunTurn_NoRecallOnContinuationRound(t *testing.T) {
var captured []llm.SystemPromptPart
cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }}
kg := &fakeKG{shouldRecall: true, recallReturn: "hint"}
rt := &Runtime{
LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg,
}
_, err := rt.RunTurn(context.Background(), "", nil, nil)
require.NoError(t, err)
require.Equal(t, 0, kg.recallCalls, "continuation round must not recall")
require.Len(t, captured, 1)
}
func TestRunTurn_RecallTimeoutInjectsNothing(t *testing.T) {
var captured []llm.SystemPromptPart
cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }}
kg := &fakeKG{shouldRecall: true, recallReturn: "late", recallDelay: 2 * time.Second}
rt := &Runtime{
LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg,
}
start := time.Now()
_, err := rt.RunTurn(context.Background(), "slow?", nil, nil)
require.NoError(t, err)
require.Less(t, time.Since(start), 1500*time.Millisecond, "recall must be bounded ~800ms")
require.Len(t, captured, 1, "timed-out recall injects nothing")
}
func TestRunTurn_IngestOnCompletion(t *testing.T) {
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
{typ: llm.EventTextDelta, text: "done"},
{typ: llm.EventDone},
}}
kg := &fakeKG{}
rt := &Runtime{
LLM: llmProvider, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "S", KG: kg,
}
res, err := rt.RunTurn(context.Background(), "remember I like tea", nil, nil)
require.NoError(t, err)
require.True(t, res.Done)
require.Equal(t, 1, kg.ingestCalls, "ingest fires once on the completing round")
require.NotEmpty(t, kg.ingestThreads[0], "ingest gets a non-empty thread")
require.Equal(t, "user", kg.ingestThreads[0][0].Role)
require.Equal(t, "remember I like tea", kg.ingestThreads[0][0].Content)
}
func TestRunTurn_NoIngestOnToolRound(t *testing.T) {
tc := &llm.ToolCall{ID: "tc_1", Name: "echo", Input: json.RawMessage(`{"x":1}`)}
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
{typ: llm.EventToolCallStart, toolCall: tc},
{typ: llm.EventToolCallDone, toolCall: tc},
{typ: llm.EventDone},
}}
kg := &fakeKG{}
rt := &Runtime{
LLM: llmProvider, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "S", KG: kg,
}
res, err := rt.RunTurn(context.Background(), "use echo", nil, nil)
require.NoError(t, err)
require.False(t, res.Done, "tool round is not terminal")
require.Equal(t, 0, kg.ingestCalls, "no ingest on a round that produced tool calls")
}
func TestRunTurn_NoIngestWhenKGNil(t *testing.T) {
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
{typ: llm.EventTextDelta, text: "done"},
{typ: llm.EventDone},
}}
rt := &Runtime{
LLM: llmProvider, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "S", KG: nil,
}
res, err := rt.RunTurn(context.Background(), "hi", nil, nil)
require.NoError(t, err)
require.True(t, res.Done)
}
+165
View File
@@ -0,0 +1,165 @@
package runtime
import (
"context"
"encoding/json"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/stretchr/testify/require"
)
// echoTool is a minimal tool.Tool implementation for RunTurn tests. It
// satisfies the real tool.Tool interface (Name/Description/Parameters/
// Execute/IsConcurrencySafe) and echoes its raw input back as output.
type echoTool struct{}
func (echoTool) Name() string { return "echo" }
func (echoTool) Description() string { return "echoes its input" }
func (echoTool) Parameters() json.RawMessage { return json.RawMessage(`{"type":"object"}`) }
func (echoTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
return tool.ToolResult{Output: string(input)}, nil
}
func (echoTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
// newEchoRegistry returns a tool.Registry containing only echoTool.
func newEchoRegistry() *tool.Registry {
reg := tool.NewRegistry()
reg.Register(echoTool{})
return reg
}
// TestRunTurn_TextOnly_IsDone: provider emits a text delta then EventDone
// with NO tool calls. The turn must be terminal (Done=true, StopReason
// "completed") and append exactly two entries: the user message and the
// assistant message.
func TestRunTurn_TextOnly_IsDone(t *testing.T) {
// scriptedStreamLLM emits its scripted events only on the FIRST call;
// subsequent calls emit a bare EventDone. For a text-only first turn we
// script text + done directly.
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
{typ: llm.EventTextDelta, text: "hello world"},
{typ: llm.EventDone},
}}
rt := &Runtime{
LLM: llmProvider,
Tools: newEchoRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test",
}
res, err := rt.RunTurn(context.Background(), "hi", nil, nil)
require.NoError(t, err)
require.True(t, res.Done, "text-only turn should be terminal")
require.Equal(t, "completed", res.StopReason)
require.Len(t, res.Entries, 2, "expected user + assistant entries")
require.Equal(t, session.EntryTypeMessage, res.Entries[0].Type)
require.Equal(t, "user", res.Entries[0].Role)
require.Equal(t, session.EntryTypeMessage, res.Entries[1].Type)
require.Equal(t, "assistant", res.Entries[1].Role)
}
// TestRunTurn_ToolCall_NotDone_ThenDone: turn 1 the model calls echo ⇒ the
// turn is NOT done and the entries include a tool_result entry. Turn 2
// (continuation, empty userMsg) the model emits text only ⇒ the turn is done.
func TestRunTurn_ToolCall_NotDone_ThenDone(t *testing.T) {
tc := &llm.ToolCall{ID: "tc_1", Name: "echo", Input: json.RawMessage(`{"x":1}`)}
// scriptedStreamLLM emits the scripted events on call 1 and a bare
// EventDone on every subsequent call — which is exactly the turn-2
// text-only/no-tool-calls behavior we need.
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
{typ: llm.EventToolCallStart, toolCall: tc},
{typ: llm.EventToolCallDone, toolCall: tc},
{typ: llm.EventDone},
}}
rt := &Runtime{
LLM: llmProvider,
Tools: newEchoRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test",
}
// Turn 1: tool call ⇒ not done, has a tool_result entry.
res1, err := rt.RunTurn(context.Background(), "use echo", nil, nil)
require.NoError(t, err)
require.False(t, res1.Done, "a turn that produced tool calls must not be terminal")
require.Equal(t, "continue", res1.StopReason)
var sawToolResult bool
for _, e := range res1.Entries {
if e.Type == session.EntryTypeToolResult {
sawToolResult = true
}
}
require.True(t, sawToolResult, "turn 1 entries should include a tool_result")
// Turn 2: continuation with empty userMsg ⇒ model emits no tool calls
// (bare EventDone) ⇒ terminal.
res2, err := rt.RunTurn(context.Background(), "", nil, nil)
require.NoError(t, err)
require.True(t, res2.Done, "second turn (no tool calls) should be terminal")
require.Equal(t, "completed", res2.StopReason)
}
// TestRunTurn_LLMError: the provider emits a mid-stream EventError. RunTurn
// does NOT use Run's stream-fallback path, so the error surfaces directly:
// the turn is terminal with StopReason "error" and a non-nil Err.
//
// Note on the fake: scriptedStreamLLM's scriptedStreamEvent cannot carry an
// error value (it has no error field), so it cannot emit a meaningful
// EventError. We reuse streamingOnlyProvider from streamfallback_test.go —
// the same-package fake the streaming tests use to simulate a mid-stream
// error (text delta then EventError with a real error).
func TestRunTurn_LLMError(t *testing.T) {
llmProvider := &streamingOnlyProvider{}
rt := &Runtime{
LLM: llmProvider,
Tools: newEchoRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test",
}
res, err := rt.RunTurn(context.Background(), "do it", nil, nil)
require.NoError(t, err, "RunTurn surfaces stream errors via TurnResult.Err, not its own error return")
require.True(t, res.Done, "an errored turn must be terminal")
require.Equal(t, "error", res.StopReason)
require.Error(t, res.Err)
require.EqualValues(t, 1, llmProvider.streamCalls.Load(), "stream hit exactly once (no fallback in RunTurn)")
}
// TestRunTurn_PreCancelledContext: a context cancelled before RunTurn runs
// must short-circuit to an aborted turn with a non-nil Err, and the LLM must
// never be called. scriptedStreamLLM exposes a `calls` counter, so we assert
// the provider was never invoked.
func TestRunTurn_PreCancelledContext(t *testing.T) {
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
{typ: llm.EventTextDelta, text: "should never run"},
{typ: llm.EventDone},
}}
rt := &Runtime{
LLM: llmProvider,
Tools: newEchoRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test",
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
res, err := rt.RunTurn(ctx, "hi", nil, nil)
require.NoError(t, err)
require.Equal(t, "aborted", res.StopReason)
require.Error(t, res.Err)
require.EqualValues(t, 0, llmProvider.calls.Load(), "LLM must not be called when context is pre-cancelled")
}
+79
View File
@@ -0,0 +1,79 @@
package runtime
import (
"context"
"errors"
"sync/atomic"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// streamErrThenOKProvider emits EventError (no token) on the first stream
// call, then clean text on the second.
type streamErrThenOKProvider struct {
llmtest.Base
calls atomic.Int64
streamErr error
finalText string
}
func (p *streamErrThenOKProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
n := p.calls.Add(1)
ch := make(chan llm.ChatEvent, 4)
if n == 1 {
ch <- llm.ChatEvent{Type: llm.EventError, Error: p.streamErr}
} else {
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: p.finalText}
ch <- llm.ChatEvent{Type: llm.EventDone}
}
close(ch)
return ch, nil
}
func TestStreamErrorRetryableEngagesFallback(t *testing.T) {
prov := &streamErrThenOKProvider{
streamErr: errors.New("429 rate limit exceeded"),
finalText: "RECOVERED_VIA_FALLBACK",
}
rt := &Runtime{
LLM: prov,
Tools: tool.NewRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "claude-opus-4-8",
FallbackModel: "claude-sonnet-4-5",
Provider: "anthropic",
MaxTurns: 2,
Workspace: t.TempDir(),
}
out, err := rt.RunSync(context.Background(), "do it", nil)
require.NoError(t, err)
assert.Contains(t, out, "RECOVERED_VIA_FALLBACK")
assert.EqualValues(t, 2, prov.calls.Load(), "must retry once after the pre-first-token 429")
}
func TestStreamErrorNonRetryableStillAborts(t *testing.T) {
prov := &streamErrThenOKProvider{
streamErr: errors.New("400 invalid input"),
finalText: "SHOULD_NOT_BE_REACHED",
}
rt := &Runtime{
LLM: prov,
Tools: tool.NewRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "claude-opus-4-8",
Provider: "anthropic",
MaxTurns: 2,
Workspace: t.TempDir(),
}
_, err := rt.RunSync(context.Background(), "do it", nil)
require.Error(t, err)
assert.EqualValues(t, 1, prov.calls.Load(), "non-retryable pre-first-token error must abort, not retry")
}
+8
View File
@@ -71,6 +71,14 @@ type LoopConfig struct {
// StreamingTools enables mid-stream concurrency-safe tool kickoff.
// false ⇒ env fallback (HARNESS_STREAMING_TOOLS=1) then off.
StreamingTools bool
// MaxToolResultLen caps the in-context length of any single tool
// result; longer results are truncated to their first MaxToolResultLen
// chars (cut at a newline boundary) with the remainder either spilled
// to disk via spillConfig or simply dropped. 0 ⇒ env fallback
// (HARNESS_MAX_TOOL_RESULT_LEN) then default 4000. Common pick for
// engineering-style agents (reading source files, running tests) is
// 16000-25000.
MaxToolResultLen int
// Hooks are optional callbacks the runtime fires at well-known
// points in the loop. Zero value (all nil fields) disables every
// hook with no overhead.
+25
View File
@@ -0,0 +1,25 @@
package runtime
import "github.com/sausheong/harness/llm"
// addUsage returns the field-wise sum of two usage snapshots. A nil operand is
// treated as zero. It returns a fresh pointer and never mutates its arguments,
// so callers may safely pass a pointer that aliases a provider stream event.
// Returns nil only when BOTH operands are nil, preserving the contract that
// EventDone.Usage stays nil for providers that never report usage.
func addUsage(acc, turn *llm.Usage) *llm.Usage {
if acc == nil && turn == nil {
return nil
}
var out llm.Usage
if acc != nil {
out = *acc
}
if turn != nil {
out.InputTokens += turn.InputTokens
out.OutputTokens += turn.OutputTokens
out.CacheCreationInputTokens += turn.CacheCreationInputTokens
out.CacheReadInputTokens += turn.CacheReadInputTokens
}
return &out
}
+45
View File
@@ -0,0 +1,45 @@
package runtime
import (
"testing"
"github.com/sausheong/harness/llm"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAddUsage_BothNil(t *testing.T) {
assert.Nil(t, addUsage(nil, nil))
}
func TestAddUsage_AccNil(t *testing.T) {
turn := &llm.Usage{InputTokens: 7, OutputTokens: 3, CacheCreationInputTokens: 2, CacheReadInputTokens: 1}
got := addUsage(nil, turn)
require.NotNil(t, got)
assert.Equal(t, llm.Usage{InputTokens: 7, OutputTokens: 3, CacheCreationInputTokens: 2, CacheReadInputTokens: 1}, *got)
// input not mutated, and the result must be a distinct pointer (the
// non-mutating/aliasing-safety contract the accumulator relies on).
assert.NotSame(t, turn, got)
assert.Equal(t, 7, turn.InputTokens)
}
func TestAddUsage_TurnNil(t *testing.T) {
acc := &llm.Usage{InputTokens: 5}
got := addUsage(acc, nil)
require.NotNil(t, got)
assert.Equal(t, 5, got.InputTokens)
}
func TestAddUsage_SumsAllFourFields(t *testing.T) {
acc := &llm.Usage{InputTokens: 100, OutputTokens: 40, CacheCreationInputTokens: 10, CacheReadInputTokens: 6}
turn := &llm.Usage{InputTokens: 10, OutputTokens: 5, CacheCreationInputTokens: 1, CacheReadInputTokens: 2}
got := addUsage(acc, turn)
require.NotNil(t, got)
assert.Equal(t, 110, got.InputTokens)
assert.Equal(t, 45, got.OutputTokens)
assert.Equal(t, 11, got.CacheCreationInputTokens)
assert.Equal(t, 8, got.CacheReadInputTokens)
// neither input mutated
assert.Equal(t, 100, acc.InputTokens)
assert.Equal(t, 10, turn.InputTokens)
}
+19 -4
View File
@@ -85,6 +85,12 @@ type Session struct {
entryMap map[string]*SessionEntry
leafID string // current leaf for history traversal
store *Store
// writeMu serializes store writes and preserves their order. Acquired in
// Append while s.mu is still held (lock-coupling), then s.mu is released
// before the disk write — so disk latency stays off s.mu while on-disk
// order still matches in-memory append order under concurrent callers. (P5)
writeMu sync.Mutex
}
// NewSession creates a new empty session.
@@ -100,7 +106,6 @@ func NewSession(agentID, key string) *Session {
// Append adds an entry to the session.
func (s *Session) Append(entry SessionEntry) {
s.mu.Lock()
defer s.mu.Unlock()
if entry.ID == "" {
entry.ID = generateID("e")
}
@@ -115,9 +120,19 @@ func (s *Session) Append(entry SessionEntry) {
s.entryMap[entry.ID] = &s.entries[len(s.entries)-1]
s.leafID = entry.ID
// Persist if store is set
if s.store != nil {
s.store.AppendEntry(s, entry)
finalized := entry // value copy with all fields set
store := s.store
// Lock-coupling: take writeMu BEFORE releasing s.mu so the disk-write
// order matches the in-memory append order even under concurrent callers,
// then release s.mu so disk latency doesn't block concurrent View()/append.
if store != nil {
s.writeMu.Lock()
s.mu.Unlock()
store.AppendEntry(s, finalized)
s.writeMu.Unlock()
} else {
s.mu.Unlock()
}
}
+57
View File
@@ -350,3 +350,60 @@ func TestSession_ViewReturnsCopy(t *testing.T) {
require.Len(t, v2, 1)
require.Equal(t, "e_1", v2[0].ID, "internal state must not be mutated by caller's slice modification")
}
func TestConcurrentAppendAndViewNoRace(t *testing.T) {
dir := t.TempDir()
store := NewStore(dir)
require.NoError(t, store.Create("a", "k"))
sess := NewSession("a", "k")
sess.SetStore(store)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 500; i++ {
sess.Append(SessionEntry{Type: EntryTypeMessage, Role: "user", Data: []byte(`{"text":"x"}`)})
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 500; i++ {
_ = sess.View()
}
}()
wg.Wait()
require.Len(t, sess.Entries(), 500)
}
// TestAppendPreservesDiskOrder verifies that the P5 lock-coupling keeps the
// on-disk JSONL order identical to the in-memory append order: sequential
// appends must persist in order, and reloading from disk must round-trip them
// in the same sequence.
func TestAppendPreservesDiskOrder(t *testing.T) {
dir := t.TempDir()
store := NewStore(dir)
require.NoError(t, store.Create("a", "k"))
sess := NewSession("a", "k")
sess.SetStore(store)
const n = 200
for i := 0; i < n; i++ {
sess.Append(SessionEntry{
Type: EntryTypeMessage,
Role: "user",
Data: json.RawMessage(fmt.Sprintf(`{"text":"%d"}`, i)),
})
}
reloaded, err := store.Load("a", "k")
require.NoError(t, err)
got := reloaded.Entries()
require.Len(t, got, n)
for i := 0; i < n; i++ {
require.JSONEq(t, fmt.Sprintf(`{"text":"%d"}`, i), string(got[i].Data),
"on-disk entry %d out of order", i)
}
}
+20 -2
View File
@@ -9,6 +9,7 @@ import (
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
)
@@ -22,8 +23,19 @@ type SessionInfo struct {
// Store handles JSONL file I/O for sessions.
type Store struct {
baseDir string
mu sync.Mutex
baseDir string
mu sync.Mutex
degraded atomic.Bool
}
// markDegraded emits a single warning the first time session persistence
// fails, so a user notices that in-memory state may not survive a restart.
// Subsequent failures stay at their existing Error level to avoid log spam.
func (s *Store) markDegraded(reason string, err error) {
if s.degraded.CompareAndSwap(false, true) {
slog.Warn("session persistence degraded; in-memory state may not survive restart",
"reason", reason, "error", err)
}
}
// NewStore creates a new session store.
@@ -94,6 +106,7 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
dir := s.sessionDir(sess.AgentID)
if err := os.MkdirAll(dir, 0o755); err != nil {
s.markDegraded("create session dir", err)
slog.Error("failed to create session dir", "error", err)
return
}
@@ -101,6 +114,7 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
path := s.sessionPath(sess.AgentID, sess.Key)
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
s.markDegraded("open session file", err)
slog.Error("failed to open session file", "error", err)
return
}
@@ -114,6 +128,7 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
data = append(data, '\n')
if _, err := f.Write(data); err != nil {
s.markDegraded("write session entry", err)
slog.Error("failed to write session entry", "error", err)
}
}
@@ -252,6 +267,7 @@ func (s *Store) Rewrite(sess *Session) {
dir := s.sessionDir(sess.AgentID)
if err := os.MkdirAll(dir, 0o755); err != nil {
s.markDegraded("create session dir", err)
slog.Error("failed to create session dir", "error", err)
return
}
@@ -260,6 +276,7 @@ func (s *Store) Rewrite(sess *Session) {
f, err := os.Create(path)
if err != nil {
s.markDegraded("create session file for rewrite", err)
slog.Error("failed to create session file for rewrite", "error", err)
return
}
@@ -277,6 +294,7 @@ func (s *Store) Rewrite(sess *Session) {
}
if err := w.Flush(); err != nil {
s.markDegraded("flush session file", err)
slog.Error("failed to flush session file", "error", err)
}
}
+52
View File
@@ -0,0 +1,52 @@
package session
import (
"bytes"
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestStore_DegradedPersistenceWarnsOnce(t *testing.T) {
var buf bytes.Buffer
prev := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})))
defer slog.SetDefault(prev)
// Make a path where the agent dir cannot be created: a regular FILE used
// as baseDir means sessionDir(agentID) = <file>/<agentID> and MkdirAll fails.
tmp := t.TempDir()
blocker := filepath.Join(tmp, "blocker")
require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600))
s := NewStore(blocker)
sess := &Session{AgentID: "a", Key: "k"}
s.AppendEntry(sess, SessionEntry{})
s.AppendEntry(sess, SessionEntry{})
s.AppendEntry(sess, SessionEntry{})
require.Equal(t, 1, strings.Count(buf.String(), "session persistence degraded"),
"degraded warning must fire exactly once across multiple failures")
}
func TestStore_RewriteDegradedWarns(t *testing.T) {
var buf bytes.Buffer
prev := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})))
defer slog.SetDefault(prev)
tmp := t.TempDir()
blocker := filepath.Join(tmp, "blocker")
require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600))
s := NewStore(blocker)
sess := &Session{AgentID: "a", Key: "k"}
s.Rewrite(sess)
require.Equal(t, 1, strings.Count(buf.String(), "session persistence degraded"),
"Rewrite failure must emit the degraded warning")
}
+23 -1
View File
@@ -21,6 +21,10 @@ func Estimate(msgs []llm.Message, systemPrompt string, tools []llm.ToolDef) int
for _, tc := range m.ToolCalls {
total += len(tc.ID) + len(tc.Name) + len(tc.Input)
}
// Images are not part of Content (Images is json:"-"); approximate
// each attached image's token cost. perImageTokens is expressed in
// tokens, so multiply by 4 to survive the final divide-by-4.
total += len(m.Images) * perImageTokens * 4
}
for _, t := range tools {
total += len(t.Name) + len(t.Description) + len(t.Parameters)
@@ -33,6 +37,12 @@ func Estimate(msgs []llm.Message, systemPrompt string, tools []llm.ToolDef) int
// since the final divide-by-4 maps it back to tokens.
const perMessageOverhead = 3
// perImageTokens approximates the token cost of one attached image. Vision
// models bill images by tiles/resolution; ~1500 tokens is a deliberately
// conservative flat estimate so image-heavy sessions trigger preventive
// compaction rather than hitting a reactive overflow.
const perImageTokens = 1500
// ContextWindow returns the maximum input tokens for the given
// "provider/model" identifier.
//
@@ -110,8 +120,20 @@ func windowByModelFamily(modelID string) int {
leaf = leaf[i+1:]
}
switch {
case strings.Contains(id, "claude-fable"),
strings.Contains(id, "claude-mythos"),
strings.Contains(id, "claude-opus-4-6"),
strings.Contains(id, "claude-opus-4-7"),
strings.Contains(id, "claude-opus-4-8"),
strings.Contains(id, "claude-opus-4-9"),
strings.Contains(id, "claude-sonnet-4-6"):
// The 1M-window Claude generation: Fable 5, Mythos 5,
// Opus 4.6+, Sonnet 4.6. Matching the 200k blanket rule below
// would make preventive compaction fire ~5x too early.
return 1000000
case strings.Contains(id, "claude"):
// All current Claude chat models share a 200k window.
// Older Claude chat models (3.x through the 4.5 era, Haiku 4.5)
// share a 200k window.
return 200000
case strings.HasPrefix(leaf, "gpt-4o"), strings.HasPrefix(leaf, "gpt-4-turbo"):
return 128000
+42 -1
View File
@@ -4,6 +4,7 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
@@ -84,7 +85,7 @@ func TestContextWindowProxyProviderDetectedByModelFamily(t *testing.T) {
model string
want int
}{
{"platformai/claude-sonnet-4-6-asia-southeast1", 200000},
{"platformai/claude-sonnet-4-6-asia-southeast1", 1000000},
{"openrouter/anthropic/claude-3-opus", 200000},
{"bedrock/anthropic.claude-3-haiku", 200000},
{"vertex/gemini-1.5-pro-001", 2000000},
@@ -97,6 +98,17 @@ func TestContextWindowProxyProviderDetectedByModelFamily(t *testing.T) {
}
}
func TestEstimate_CountsImages(t *testing.T) {
textOnly := []llm.Message{{Role: "user", Content: "hello"}}
withImg := []llm.Message{{Role: "user", Content: "hello", Images: []llm.ImageContent{
{MimeType: "image/png", Data: []byte("x")},
{MimeType: "image/png", Data: []byte("y")},
}}}
base := Estimate(textOnly, "", nil)
withImages := Estimate(withImg, "", nil)
require.GreaterOrEqual(t, withImages-base, 2*perImageTokens)
}
func TestContextWindowOllamaDefault(t *testing.T) {
// Without RegisterOllamaContext call, ollama models fall back to a sane default
assert.Equal(t, 32000, ContextWindow("local/qwen2.5:3b-instruct"))
@@ -135,3 +147,32 @@ func TestCalibratorIgnoresZeroOrNegative(t *testing.T) {
c.Update(-5, 100)
assert.Equal(t, 100, c.Adjust(100), "bad samples must be ignored")
}
// TestContextWindow1MClaudeFamily pins the 1M-window Claude generation:
// Fable 5, Mythos 5, Opus 4.6+, and Sonnet 4.6 all ship a 1M context
// window. The old blanket claude→200k rule made compaction fire ~5x too
// early on these models. Older Claude (3.x, 4.0-4.5 era) stays 200k.
func TestContextWindow1MClaudeFamily(t *testing.T) {
tests := []struct {
model string
want int
}{
{"anthropic/claude-fable-5", 1000000},
{"platformai/claude-fable-5-global", 1000000},
{"anthropic/claude-mythos-5", 1000000},
{"anthropic/claude-opus-4-6", 1000000},
{"anthropic/claude-opus-4-7", 1000000},
{"anthropic/claude-opus-4-8", 1000000},
{"platformai/claude-sonnet-4-6-asia-southeast1", 1000000},
// Older generations keep 200k.
{"anthropic/claude-haiku-4-5-20251001", 200000},
{"anthropic/claude-sonnet-4-5", 200000},
{"anthropic/claude-3-5-sonnet-20241022", 200000},
{"anthropic/claude-opus-4-0-20250514", 200000},
}
for _, tc := range tests {
t.Run(tc.model, func(t *testing.T) {
assert.Equal(t, tc.want, ContextWindow(tc.model))
})
}
}
+40
View File
@@ -0,0 +1,40 @@
package tool
import (
"fmt"
"os"
"path/filepath"
)
// WriteFileAtomic writes data to path atomically: it writes to a temp file in
// the same directory, fsyncs, sets perm, then renames over path. A crash
// mid-write leaves either the old file or the complete new file, never a
// truncated one. The rename is atomic on POSIX within a single filesystem.
func WriteFileAtomic(path string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".tmp-"+filepath.Base(path)+"-*")
if err != nil {
return fmt.Errorf("create temp: %w", err)
}
tmpName := tmp.Name()
defer func() { _ = os.Remove(tmpName) }()
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return fmt.Errorf("write temp: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return fmt.Errorf("sync temp: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close temp: %w", err)
}
if err := os.Chmod(tmpName, perm); err != nil {
return fmt.Errorf("chmod temp: %w", err)
}
if err := os.Rename(tmpName, path); err != nil {
return fmt.Errorf("rename temp: %w", err)
}
return nil
}
+33
View File
@@ -0,0 +1,33 @@
package tool
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestWriteFileAtomic(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "out.txt")
require.NoError(t, WriteFileAtomic(path, []byte("hello"), 0o600))
data, err := os.ReadFile(path)
require.NoError(t, err)
require.Equal(t, "hello", string(data))
info, err := os.Stat(path)
require.NoError(t, err)
require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
require.NoError(t, WriteFileAtomic(path, []byte("world"), 0o644))
data, _ = os.ReadFile(path)
require.Equal(t, "world", string(data))
entries, err := os.ReadDir(dir)
require.NoError(t, err)
require.Len(t, entries, 1)
require.Equal(t, "out.txt", entries[0].Name())
}
+14 -7
View File
@@ -132,10 +132,12 @@ func extractCommands(cmd string) []string {
// Find the earliest operator
minIdx := len(remaining)
opLen := 0
for _, op := range []string{"&&", "||", "|", ";"} {
if idx := strings.Index(remaining, op); idx != -1 && idx < minIdx {
minIdx = idx
opLen = len(op)
for _, op := range []string{"&&", "||", "|", ";", "&"} {
if idx := strings.Index(remaining, op); idx != -1 {
if idx < minIdx || (idx == minIdx && len(op) > opLen) {
minIdx = idx
opLen = len(op)
}
}
}
@@ -190,9 +192,14 @@ func (t *BashTool) Execute(ctx context.Context, input json.RawMessage) (tool.Too
case "deny":
return tool.ToolResult{Error: "bash execution is disabled by policy"}, nil
case "allowlist":
// Block shell metacharacters that can execute arbitrary code
// inside an otherwise-allowed command (e.g. ls $(curl evil.com))
for _, meta := range []string{"$(", "`", "<(", ">(", "${", "\\n"} {
// Block shell metacharacters that can execute arbitrary code or
// write files inside an otherwise-allowed command. Covers command
// substitution (e.g. ls $(curl evil.com)), real newline/CR bytes
// (bash -c treats them as command separators, so trailing lines
// would run unvalidated), and output redirection (">" matches ">",
// ">>", "2>", "&>", "2>&1" — all write/overwrite primitives).
// Input redirection "<" is intentionally allowed (not a write/exec bypass).
for _, meta := range []string{"$(", "`", "<(", ">(", "${", "\n", "\r", ">"} {
if strings.Contains(in.Command, meta) {
return tool.ToolResult{Error: "command contains shell metacharacters not allowed in allowlist mode"}, nil
}
+70
View File
@@ -1,13 +1,48 @@
package bash
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/sausheong/harness/tool"
)
// runAllowlist executes cmd under an allowlist policy and returns the
// ToolResult.Error (empty string = the command was permitted by policy).
func runAllowlist(t *testing.T, allow []string, command string) string {
t.Helper()
bt := &BashTool{ExecPolicy: &ExecPolicy{Level: "allowlist", Allowlist: allow}}
in, err := json.Marshal(bashInput{Command: command})
if err != nil {
t.Fatalf("marshal: %v", err)
}
res, err := bt.Execute(context.Background(), in)
if err != nil {
t.Fatalf("Execute returned a Go error (should use ToolResult.Error): %v", err)
}
return res.Error
}
func TestExtractCommands_BackgroundAmpersand(t *testing.T) {
// "ls & curl ..." must validate BOTH sides; curl is not allowed →
// rejected by policy BEFORE any command executes. Asserting the policy
// rejection message (not just a non-empty Error) is essential: without
// the fix, curl actually runs and its own runtime stderr lands in
// res.Error, which would mask the bypass.
got := runAllowlist(t, []string{"ls"}, "ls & curl http://evil")
if !strings.Contains(got, "not in the exec allowlist") {
t.Fatalf("background-& bypass: expected allowlist rejection of curl, got %q", got)
}
// "ls && echo hi" must still split on && (both allowed) → permitted.
if got := runAllowlist(t, []string{"ls", "echo"}, "ls && echo hi"); got != "" {
t.Fatalf("&& chain wrongly rejected: %q", got)
}
}
func TestSanitizeLLMText(t *testing.T) {
tests := []struct {
name string
@@ -142,3 +177,38 @@ func TestResolveExistingPath(t *testing.T) {
})
}
}
func TestAllowlist_RejectsNewlineCRAndRedirection(t *testing.T) {
allow := []string{"ls", "echo", "cat"}
const metaMsg = "shell metacharacters not allowed"
// The live exploit: a real newline runs a second, unvalidated line.
if got := runAllowlist(t, allow, "ls\ncurl http://evil"); !strings.Contains(got, metaMsg) {
t.Fatalf("newline bypass: expected metacharacter rejection, got %q", got)
}
// Carriage return likewise.
if got := runAllowlist(t, allow, "ls\rcurl http://evil"); !strings.Contains(got, metaMsg) {
t.Fatalf("CR bypass: expected metacharacter rejection, got %q", got)
}
// Redirection write-primitive (allowed cmd overwriting a file).
if got := runAllowlist(t, allow, "echo hi > /tmp/s1_x"); !strings.Contains(got, metaMsg) {
t.Fatalf("redirection > not rejected, got %q", got)
}
if got := runAllowlist(t, allow, "echo hi >> /tmp/s1_x"); !strings.Contains(got, metaMsg) {
t.Fatalf("append redirection >> not rejected, got %q", got)
}
// fd redirection also contains '>' so it is caught too.
if got := runAllowlist(t, allow, "cat a 2>&1"); !strings.Contains(got, metaMsg) {
t.Fatalf("fd redirection 2>&1 not rejected, got %q", got)
}
// Sanity: a plain allowed command still passes the policy gate.
if got := runAllowlist(t, allow, "ls -l"); got != "" {
t.Fatalf("plain allowed command wrongly rejected: %q", got)
}
// Sanity: input redirection '<' is NOT blocked (deliberate scope boundary);
// cat is allowed so policy permits it (it may still fail at runtime if the
// file is missing, but it must NOT be a policy rejection).
if got := runAllowlist(t, allow, "cat < /etc/hostname"); strings.Contains(got, "metacharacters") || strings.Contains(got, "not in the exec allowlist") {
t.Fatalf("input redirection wrongly rejected by policy: %q", got)
}
}
+19
View File
@@ -36,6 +36,24 @@ const (
janitorInterval = 1 * time.Minute
)
// hostResolverRules forces Chrome to fail DNS resolution for private/internal
// IP ranges and localhost, so in-page fetch() and evaluate()'d JS cannot reach
// cloud-metadata endpoints or localhost services — the Go-side
// ValidateURLNotInternal check only sees the top-level URL, so this covers
// sub-resource and script-initiated requests. (S3)
//
// Residual gap: name-based rules do not stop a page that dials a *literal*
// private IP URL in some Chrome builds; the complete fix is an allowlisting
// proxy (deferred). See the security-deeper spec's limitations section.
const hostResolverRules = "MAP localhost ~NOTFOUND," +
"MAP *.localhost ~NOTFOUND," +
"MAP 127.0.0.0/8 ~NOTFOUND," +
"MAP 10.0.0.0/8 ~NOTFOUND," +
"MAP 172.16.0.0/12 ~NOTFOUND," +
"MAP 169.254.0.0/16 ~NOTFOUND," +
"MAP 192.168.0.0/16 ~NOTFOUND," +
"MAP [::1] ~NOTFOUND"
// stealthScript runs before any page script on every new document. It hides the
// most common headless/automation tells that JS-heavy sites use to refuse to
// render content (Cloudflare, Akamai, anti-bot scripts, "please enable JS"
@@ -474,6 +492,7 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc,
chromedp.UserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"),
chromedp.Flag("disable-blink-features", "AutomationControlled"),
chromedp.Flag("lang", "en-US"),
chromedp.Flag("host-resolver-rules", hostResolverRules),
chromedp.UserDataDir(udd),
)...,
)
+44
View File
@@ -0,0 +1,44 @@
//go:build live
package browser
import (
"context"
"testing"
"time"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
"github.com/stretchr/testify/require"
)
// TestInPageFetchPrivateIPBlocked_Live verifies host-resolver-rules stops an
// in-page fetch to a metadata IP. Requires a real Chrome. Run:
// go test -tags live ./tools/browser/ -run TestInPageFetchPrivateIPBlocked_Live
func TestInPageFetchPrivateIPBlocked_Live(t *testing.T) {
tool := NewBrowserTool()
defer tool.Shutdown()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
taskCtx, ccancel, err := launchBrowser(ctx)
require.NoError(t, err)
defer ccancel()
require.NoError(t, chromedp.Run(taskCtx, chromedp.Navigate("https://example.com")))
var result string
script := `(async () => {
try {
await fetch('http://169.254.169.254/latest/meta-data/', {mode:'no-cors'});
return 'REACHED';
} catch (e) {
return 'BLOCKED';
}
})()`
err = chromedp.Run(taskCtx, chromedp.Evaluate(script, &result, func(p *runtime.EvaluateParams) *runtime.EvaluateParams {
return p.WithAwaitPromise(true)
}))
require.NoError(t, err)
require.Equal(t, "BLOCKED", result, "in-page fetch to metadata IP must be blocked by host-resolver-rules")
}
+11
View File
@@ -4,12 +4,23 @@ import (
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHostResolverRules_BlocksPrivateRanges(t *testing.T) {
require.Contains(t, hostResolverRules, "127.0.0.0/8")
require.Contains(t, hostResolverRules, "169.254.0.0/16")
require.Contains(t, hostResolverRules, "10.0.0.0/8")
require.Contains(t, hostResolverRules, "192.168.0.0/16")
require.Contains(t, hostResolverRules, "172.16.0.0/12")
require.Contains(t, hostResolverRules, "localhost")
require.True(t, strings.Contains(hostResolverRules, "~NOTFOUND"))
}
func TestBrowserToolName(t *testing.T) {
tool := &BrowserTool{}
assert.Equal(t, "browser", tool.Name())
+14 -2
View File
@@ -52,7 +52,7 @@ func (t *EditFileTool) Parameters() json.RawMessage {
// IsConcurrencySafe returns false — edit_file mutates the filesystem.
func (t *EditFileTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
func (t *EditFileTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
var in editFileInput
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
@@ -74,6 +74,14 @@ func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
}
}
if err := ctx.Err(); err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
if msg := checkFileSize(in.Path, int64(maxTextFileSize), "text"); msg != "" {
return tool.ToolResult{Error: msg}, nil
}
data, err := os.ReadFile(in.Path)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil
@@ -91,7 +99,11 @@ func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
newContent := strings.Replace(content, in.OldString, in.NewString, 1)
if err := os.WriteFile(in.Path, []byte(newContent), 0o644); err != nil {
mode := os.FileMode(0o600)
if info, statErr := os.Stat(in.Path); statErr == nil {
mode = info.Mode().Perm()
}
if err := tool.WriteFileAtomic(in.Path, []byte(newContent), mode); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to write file: %v", err)}, nil
}
+34
View File
@@ -0,0 +1,34 @@
package file
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestEditFilePreservesMode(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "code.txt")
require.NoError(t, os.WriteFile(path, []byte("alpha beta"), 0o640))
tool := &EditFileTool{WorkDir: dir}
in, _ := json.Marshal(map[string]string{
"path": path,
"old_string": "alpha",
"new_string": "gamma",
})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Empty(t, res.Error)
data, _ := os.ReadFile(path)
require.Equal(t, "gamma beta", string(data))
info, err := os.Stat(path)
require.NoError(t, err)
require.Equal(t, os.FileMode(0o640), info.Mode().Perm())
}
+27
View File
@@ -0,0 +1,27 @@
package file
import (
"fmt"
"os"
)
const (
maxTextFileSize = 10 * 1024 * 1024 // 10 MB
maxImageFileSize = 5 * 1024 * 1024 // 5 MB
)
// checkFileSize stats path and returns a non-empty error string if the file
// exceeds limit. kind is "text" or "image" for the message. Empty return means
// within bounds (or stat failed, in which case the caller's read surfaces the
// real error).
func checkFileSize(path string, limit int64, kind string) string {
fi, err := os.Stat(path)
if err != nil {
return ""
}
if fi.Size() > limit {
return fmt.Sprintf("file too large: %d bytes exceeds the %d byte limit for %s files; read a specific range or use a different tool",
fi.Size(), limit, kind)
}
return ""
}
+26 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
@@ -71,7 +72,7 @@ func detectImageMIMEFromBytes(data []byte, hint string) string {
// IsConcurrencySafe returns true — read_file is a pure read.
func (t *ReadFileTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
func (t *ReadFileTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
func (t *ReadFileTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
var in readFileInput
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
@@ -93,13 +94,35 @@ func (t *ReadFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
}
}
data, err := os.ReadFile(in.Path)
if err := ctx.Err(); err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
ext := strings.ToLower(filepath.Ext(in.Path))
limit := int64(maxTextFileSize)
kind := "text"
if _, isImg := imageExtMap[ext]; isImg {
limit = int64(maxImageFileSize)
kind = "image"
}
if msg := checkFileSize(in.Path, limit, kind); msg != "" {
return tool.ToolResult{Error: msg}, nil
}
f, err := os.Open(in.Path)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil
}
defer f.Close()
data, err := io.ReadAll(io.LimitReader(f, limit+1))
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil
}
if int64(len(data)) > limit {
return tool.ToolResult{Error: fmt.Sprintf("file too large: exceeds the %d byte limit for %s files; read a specific range or use a different tool", limit, kind)}, nil
}
// Check if this is an image file
ext := strings.ToLower(filepath.Ext(in.Path))
if mimeType, ok := imageExtMap[ext]; ok {
mimeType = detectImageMIMEFromBytes(data, mimeType)
return tool.ToolResult{
+86
View File
@@ -0,0 +1,86 @@
package file
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func writeSized(t *testing.T, dir, name string, n int) string {
t.Helper()
p := filepath.Join(dir, name)
require.NoError(t, os.WriteFile(p, make([]byte, n), 0o600))
return p
}
func TestReadFile_RejectsOversizedText(t *testing.T) {
dir := t.TempDir()
p := writeSized(t, dir, "big.txt", maxTextFileSize+1)
tool := &ReadFileTool{}
in, _ := json.Marshal(map[string]string{"path": p})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Contains(t, res.Error, "too large")
}
func TestReadFile_AllowsNormalText(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "ok.txt")
require.NoError(t, os.WriteFile(p, []byte("hello"), 0o600))
tool := &ReadFileTool{}
in, _ := json.Marshal(map[string]string{"path": p})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Empty(t, res.Error)
require.Equal(t, "hello", res.Output)
}
func TestReadFile_RejectsOversizedImage(t *testing.T) {
dir := t.TempDir()
p := writeSized(t, dir, "big.png", maxImageFileSize+1)
tool := &ReadFileTool{}
in, _ := json.Marshal(map[string]string{"path": p})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Contains(t, res.Error, "too large")
}
func TestEditFile_RejectsOversized(t *testing.T) {
dir := t.TempDir()
p := writeSized(t, dir, "big.txt", maxTextFileSize+1)
tool := &EditFileTool{}
in, _ := json.Marshal(map[string]string{"path": p, "old_string": "a", "new_string": "b"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Contains(t, res.Error, "too large")
}
func TestReadFile_HonorsCancelledContext(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "f.txt")
require.NoError(t, os.WriteFile(p, []byte("hello"), 0o600))
ctx, cancel := context.WithCancel(context.Background())
cancel()
tool := &ReadFileTool{}
in, _ := json.Marshal(map[string]string{"path": p})
res, err := tool.Execute(ctx, in)
require.NoError(t, err)
require.NotEmpty(t, res.Error, "cancelled ctx must short-circuit")
}
func TestEditFile_HonorsCancelledContext(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "f.txt")
require.NoError(t, os.WriteFile(p, []byte("hello"), 0o600))
ctx, cancel := context.WithCancel(context.Background())
cancel()
tool := &EditFileTool{}
in, _ := json.Marshal(map[string]string{"path": p, "old_string": "h", "new_string": "H"})
res, err := tool.Execute(ctx, in)
require.NoError(t, err)
require.NotEmpty(t, res.Error, "cancelled ctx must short-circuit")
}
+1 -1
View File
@@ -72,7 +72,7 @@ func (t *WriteFileTool) Execute(_ context.Context, input json.RawMessage) (tool.
return tool.ToolResult{Error: fmt.Sprintf("failed to create directory: %v", err)}, nil
}
if err := os.WriteFile(in.Path, []byte(in.Content), 0o644); err != nil {
if err := tool.WriteFileAtomic(in.Path, []byte(in.Content), 0o600); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to write file: %v", err)}, nil
}
+26
View File
@@ -0,0 +1,26 @@
package file
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestWriteFileIsRestrictive(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "secret.txt")
tool := &WriteFileTool{WorkDir: dir}
in, _ := json.Marshal(map[string]string{"path": path, "content": "data"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Empty(t, res.Error)
info, err := os.Stat(path)
require.NoError(t, err)
require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
}
+7
View File
@@ -125,6 +125,13 @@ func (c *Client) Tools() []tool.Tool { return c.tools }
// Name returns the configured server name.
func (c *Client) Name() string { return c.name }
// Ping verifies the session is alive by sending an MCP ping. A non-nil
// error means the session (and for stdio servers, likely the child
// process) is no longer usable.
func (c *Client) Ping(ctx context.Context) error {
return c.session.Ping(ctx, nil)
}
// Close releases the underlying MCP session. Safe to call multiple
// times — subsequent calls are no-ops.
func (c *Client) Close() error {
+23
View File
@@ -150,6 +150,29 @@ func TestMCPClient_ConnectDiscovers(t *testing.T) {
assert.ElementsMatch(t, []string{"mcp__srv__a", "mcp__srv__b"}, got)
}
func TestMCPClient_PingLiveAndDead(t *testing.T) {
// Built inline (not via startInProcessServer) because the test needs the
// server session to kill the connection mid-life.
ctx := context.Background()
server := sdk.NewServer(&sdk.Implementation{Name: "test-server", Version: "v0"}, nil)
tf := stringArgTool("noop", "no-op", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: ""}}}, nil
})
server.AddTool(tf.Tool, tf.Handler)
clientTransport, serverTransport := sdk.NewInMemoryTransports()
serverSession, err := server.Connect(ctx, serverTransport, nil)
require.NoError(t, err)
cli, err := connectWithTransport(ctx, "srv", clientTransport, nil)
require.NoError(t, err)
t.Cleanup(func() { _ = cli.Close() })
require.NoError(t, cli.Ping(ctx), "ping against a live session must succeed")
require.NoError(t, serverSession.Close())
assert.Error(t, cli.Ping(ctx), "ping after the server side died must fail")
}
func TestMCPClient_CloseIsIdempotent(t *testing.T) {
cli := startInProcessServer(t, "srv", []sdkToolFixture{
stringArgTool("noop", "no-op", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
+66
View File
@@ -0,0 +1,66 @@
package web
import (
"context"
"fmt"
"net"
"net/http"
"time"
)
// SafeHTTPClient returns an *http.Client whose transport resolves and validates
// the destination host, then dials the exact validated IP — closing the
// TOCTOU/DNS-rebinding window where a stock http.Client would re-resolve the
// hostname independently of ValidateURLNotInternal. Redirects are re-validated.
func SafeHTTPClient(timeout time.Duration) *http.Client {
dialer := &net.Dialer{Timeout: timeout}
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
if err != nil {
return nil, fmt.Errorf("cannot resolve %q — blocking to prevent SSRF", host)
}
// Fail closed: if ANY resolved IP is private, refuse — this defeats
// DNS-rebinding where one A record is public and another is private.
for _, ip := range ips {
if isPrivateIP(ip) {
return nil, fmt.Errorf("access to internal address %s (%s) is blocked", host, ip)
}
}
if len(ips) == 0 {
return nil, fmt.Errorf("no usable address for %q", host)
}
// Try each validated public IP in order, falling back on dial
// failure so dual-stack hosts still connect on IPv4-only or
// IPv6-broken networks (stock happy-eyeballs is bypassed because we
// dial literal IPs to pin the validated address).
var lastErr error
for _, ip := range ips {
conn, derr := dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
if derr == nil {
return conn, nil
}
lastErr = derr
}
return nil, lastErr
},
}
return &http.Client{
Timeout: timeout,
Transport: transport,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return fmt.Errorf("too many redirects (max 10)")
}
if err := ValidateURLNotInternal(req.URL.String()); err != nil {
return fmt.Errorf("redirect blocked: %w", err)
}
return nil
},
}
}
+54
View File
@@ -0,0 +1,54 @@
package web
import (
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestSafeHTTPClient_BlocksPrivateAtDial(t *testing.T) {
client := SafeHTTPClient(5 * time.Second)
// 127.0.0.1 is itself private, so dialing it directly must be refused.
_, err := client.Get("http://127.0.0.1:9/")
require.Error(t, err)
require.Contains(t, err.Error(), "internal address")
}
func TestSafeHTTPClient_AllowsPublic(t *testing.T) {
client := SafeHTTPClient(5 * time.Second)
tr, ok := client.Transport.(*http.Transport)
require.True(t, ok)
require.NotNil(t, tr.DialContext)
require.NotNil(t, client.CheckRedirect)
require.Equal(t, 5*time.Second, client.Timeout)
}
func TestSafeHTTPClient_RedirectToPrivateBlocked(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://169.254.169.254/latest/meta-data/", http.StatusFound)
}))
defer srv.Close()
client := SafeHTTPClient(5 * time.Second)
// The httptest server binds loopback (private), so the FIRST dial is already blocked.
_, err := client.Get(srv.URL)
require.Error(t, err)
}
func TestSafeHTTPClient_PublicUnreachableReturnsDialError(t *testing.T) {
// 192.0.2.1 is RFC5737 TEST-NET-1 (public, unrouteable). It is NOT in the
// private blocklist, so validation passes and we should get a DIAL error
// (timeout/unreachable), not a "blocked" validation error — proving the
// path dials rather than rejecting.
client := SafeHTTPClient(2 * time.Second)
_, err := client.Get("http://192.0.2.1/")
require.Error(t, err)
require.NotContains(t, err.Error(), "internal address")
}
var _ = isPrivateIP(net.IPv4(127, 0, 0, 1))
var _ = strings.TrimSpace
+4
View File
@@ -14,9 +14,13 @@ var privateNetworks = []string{
"172.16.0.0/12", // RFC 1918
"192.168.0.0/16", // RFC 1918
"169.254.0.0/16", // link-local
"0.0.0.0/8", // "this" network / unspecified; routes to loopback on Linux
"100.64.0.0/10", // CGNAT (RFC 6598)
"192.0.0.0/24", // IETF protocol assignments (RFC 6890)
"::1/128", // IPv6 loopback
"fc00::/7", // IPv6 unique local
"fe80::/10", // IPv6 link-local
"::/128", // IPv6 unspecified
}
var parsedPrivateNets []*net.IPNet
+27
View File
@@ -1,10 +1,12 @@
package web
import (
"net"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidateURLNotInternal_BlocksLoopback(t *testing.T) {
@@ -45,3 +47,28 @@ func TestValidateURLNotInternal_RejectsBadScheme(t *testing.T) {
assert.Error(t, err, "non-http schemes must be rejected")
_ = strings.TrimSpace(err.Error())
}
func TestIsPrivateIP_BlocksReservedRanges(t *testing.T) {
blocked := []string{
"0.0.0.0", // unspecified / routes to loopback on Linux
"0.0.0.1", // 0.0.0.0/8
"100.64.0.0", // CGNAT 100.64.0.0/10
"100.127.255.255", // CGNAT upper
"192.0.0.1", // 192.0.0.0/24 IETF protocol assignments
"::", // IPv6 unspecified ::/128
}
for _, s := range blocked {
ip := net.ParseIP(s)
require.NotNil(t, ip, "parse %s", s)
require.True(t, isPrivateIP(ip), "%s must be treated as private/blocked", s)
}
}
func TestIsPrivateIP_AllowsPublic(t *testing.T) {
pub := []string{"8.8.8.8", "1.1.1.1", "93.184.216.34", "2606:2800:220:1:248:1893:25c8:1946"}
for _, s := range pub {
ip := net.ParseIP(s)
require.NotNil(t, ip, "parse %s", s)
require.False(t, isPrivateIP(ip), "%s must be allowed (public)", s)
}
}
+1 -13
View File
@@ -85,19 +85,7 @@ func (t *WebFetchTool) Execute(ctx context.Context, input json.RawMessage) (tool
req.Header.Set(k, v)
}
client := &http.Client{
Timeout: fetchTimeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return fmt.Errorf("too many redirects (max 10)")
}
// Re-validate each redirect destination against SSRF blocklist
if err := ValidateURLNotInternal(req.URL.String()); err != nil {
return fmt.Errorf("redirect blocked: %w", err)
}
return nil
},
}
client := SafeHTTPClient(fetchTimeout)
resp, err := client.Do(req)
if err != nil {
+16
View File
@@ -0,0 +1,16 @@
package web
import (
"context"
"testing"
"github.com/stretchr/testify/require"
)
func TestWebFetch_BlocksPrivateHost(t *testing.T) {
tool := &WebFetchTool{}
res, err := tool.Execute(context.Background(),
[]byte(`{"url":"http://169.254.169.254/latest/meta-data/"}`))
require.NoError(t, err)
require.NotEmpty(t, res.Error, "private metadata IP must be rejected")
}
+8 -7
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"html"
"io"
"net/http"
"net/url"
@@ -14,6 +15,11 @@ import (
const searchTimeout = 15 * time.Second
// searchClient is the shared SSRF-safe HTTP client for all web_search
// backends. It pins the validated IP and re-validates redirects, bringing
// web_search to parity with web_fetch. (N4)
var searchClient = SafeHTTPClient(searchTimeout)
// WebSearchTool searches the web and returns results via a configurable
// backend. The default backend (when Backend is nil) scrapes DuckDuckGo's
// HTML interface — no API key required, but fragile to upstream HTML
@@ -131,7 +137,7 @@ func duckDuckGoSearch(ctx context.Context, query string, maxResults int) ([]sear
}
req.Header.Set("User-Agent", "harness/1.0 (Go agent framework)")
resp, err := http.DefaultClient.Do(req)
resp, err := searchClient.Do(req)
if err != nil {
return nil, err
}
@@ -266,11 +272,6 @@ func cleanHTMLText(s string) string {
}
}
result := out.String()
result = strings.ReplaceAll(result, "&amp;", "&")
result = strings.ReplaceAll(result, "&lt;", "<")
result = strings.ReplaceAll(result, "&gt;", ">")
result = strings.ReplaceAll(result, "&quot;", `"`)
result = strings.ReplaceAll(result, "&#x27;", "'")
result = strings.ReplaceAll(result, "&nbsp;", " ")
result = html.UnescapeString(result)
return strings.TrimSpace(result)
}
+7 -3
View File
@@ -17,6 +17,10 @@ import (
// are constructed with their config (API key, base URL, etc.) at
// registration time and remain immutable thereafter. This keeps the tool
// dispatch path zero-allocation in the hot loop.
//
// Implementations that make outbound HTTP calls MUST use the package
// searchClient (SafeHTTPClient) so a configured/typo'd internal base URL
// cannot be used for SSRF. (N4)
type WebSearchBackend interface {
Name() string
Search(ctx context.Context, query string, maxResults int) ([]searchResult, error)
@@ -58,7 +62,7 @@ func (b *braveBackend) Search(ctx context.Context, q string, n int) ([]searchRes
}
req.Header.Set("Accept", "application/json")
req.Header.Set("X-Subscription-Token", b.apiKey)
resp, err := http.DefaultClient.Do(req)
resp, err := searchClient.Do(req)
if err != nil {
return nil, err
}
@@ -119,7 +123,7 @@ func (b *tavilyBackend) Search(ctx context.Context, q string, n int) ([]searchRe
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
resp, err := searchClient.Do(req)
if err != nil {
return nil, err
}
@@ -169,7 +173,7 @@ func (b *searxngBackend) Search(ctx context.Context, q string, n int) ([]searchR
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
resp, err := searchClient.Do(req)
if err != nil {
return nil, err
}
+37
View File
@@ -0,0 +1,37 @@
package web
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func testCtx(t *testing.T) context.Context {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
t.Cleanup(cancel)
return ctx
}
func TestSearchClient_IsSafe(t *testing.T) {
require.NotNil(t, searchClient)
require.NotNil(t, searchClient.Transport)
require.NotNil(t, searchClient.CheckRedirect)
require.Equal(t, searchTimeout, searchClient.Timeout)
}
func TestSearxng_BlocksPrivateBaseURL(t *testing.T) {
b := newSearxngBackend("http://127.0.0.1:8080")
_, err := b.Search(testCtx(t), "hello", 3)
require.Error(t, err)
}
func TestCleanHTMLText_DecodesNumericEntities(t *testing.T) {
out := cleanHTMLText("<b>caf&#233;</b> &amp; t&#8217;is &nbsp;done")
require.Contains(t, out, "café")
require.Contains(t, out, "&", "amp must decode")
require.Contains(t, out, "t’is", "numeric entity must decode")
require.NotContains(t, out, "&#", "no raw numeric entities remain")
}