2 Commits
Author SHA1 Message Date
Chang Sau Sheong 8c84ed6180 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
sausheongandClaude Opus 4.7 cbb40e239d 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.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-21 07:55:16 +08:00
245 changed files with 1178 additions and 23690 deletions

No files matched your search

-76
View File
@@ -1,76 +0,0 @@
name: Qualify Harness
on:
pull_request:
push:
branches: [main, 'codex/**']
workflow_dispatch:
permissions:
contents: read
jobs:
native:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-15-intel]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Record candidate identity
run: |
mkdir evidence
git rev-parse HEAD > evidence/commit.txt
git status --porcelain > evidence/status.txt
go version > evidence/toolchain.txt
go env -json GOOS GOARCH GOVERSION > evidence/platform.json
- name: Start Docker on hosted macOS
if: runner.os == 'macOS'
run: |
brew install colima docker
colima start --runtime docker --cpu 2 --memory 4
docker info
mkdir -p "$HOME/harness-test-tmp"
echo "TMPDIR=$HOME/harness-test-tmp" >> "$GITHUB_ENV"
- name: Prepare required Docker fixtures
shell: bash
run: |
set -euo pipefail
docker_bin="$(command -v docker)"
if [ ! -x /usr/local/bin/docker ]; then
sudo ln -s "$docker_bin" /usr/local/bin/docker
fi
docker version > evidence/docker-version.txt
endpoint="$(docker context inspect --format '{{.Endpoints.docker.Host}}')"
case "$endpoint" in
unix://*) socket="${endpoint#unix://}" ;;
*) echo 'Qualification requires a local Unix Docker socket' >&2; exit 1 ;;
esac
docker pull alpine:3.22 > evidence/alpine-pull.txt
docker pull debian:bookworm-slim > evidence/debian-pull.txt
image="$(docker image inspect --format '{{.Id}}' alpine:3.22)"
bash_image="$(docker image inspect --format '{{.Id}}' debian:bookworm-slim)"
python3 scripts/prepare_container_fixtures.py --docker /usr/local/bin/docker \
--socket "$socket" --image "$image" --bash-image "$bash_image" \
--output "$RUNNER_TEMP/harness-fixtures"
cp "$RUNNER_TEMP/harness-fixtures/fixtures.json" evidence/fixtures.json
cat "$RUNNER_TEMP/harness-fixtures/fixtures.env" >> "$GITHUB_ENV"
- name: Build and vet
run: |
go build ./... > evidence/build.txt 2>&1
go vet ./... > evidence/vet.txt 2>&1
- name: Uncached race and coverage suite
run: go test -count=1 -timeout=10m -race -json -covermode=atomic -coverprofile=evidence/coverage.out ./... > evidence/tests.jsonl 2> evidence/tests.stderr
- name: Reject skipped or incomplete qualification
run: python3 scripts/check_test_events.py evidence/tests.jsonl > evidence/test-gate.json
- name: Repeat lifecycle regressions
run: go test -count=20 -race -timeout=10m -json ./process ./tools/bash ./runtime -run 'TestCancellationStopsShellDescendant|TestNormalExitStopsShellDescendant|TestArtifactCrossProcessReservation|TestRun_StreamingAbortMidKickoffPairsAllEntries' > evidence/critical-repeat.jsonl 2> evidence/critical-repeat.stderr
- name: Reject skipped or incomplete lifecycle repetitions
run: python3 scripts/check_test_events.py evidence/critical-repeat.jsonl > evidence/repeat-gate.json
- name: Preserve raw results
if: always()
uses: actions/upload-artifact@v4
with:
name: harness-${{ matrix.os }}-${{ github.sha }}
path: evidence/
-4
View File
@@ -4,7 +4,6 @@
!/developer.md
!/examples/*/kb/
!/examples/*/kb/*.md
/docs/
# Other prose/document formats
*.txt
@@ -43,6 +42,3 @@ support-agent-audit.jsonl
# Env
.env
.env.local
# Keep native qualification setup with its runner.
!scripts/QUALIFICATION.md
+32 -203
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.6.3.** Latest tagged release. The `runtime` API
> **Status: v0.1.0.** First tagged release. The `runtime` API
> surface may still shift in the v0.x line — pin your version.
## Why Harness
@@ -26,112 +26,6 @@ opinions about how your agents should be deployed. There is no
`harness` binary. You import packages, compose a `Runtime`, and call
`rt.Run(ctx, msg, nil)`.
## What's in v0.6.3
[v0.6.3](https://github.com/sausheong/harness/releases/tag/v0.6.3) is a
security fix for the browser tools, plus dependency updates:
- **Browser SSRF containment.** `tools/browser` and Stagehand's local-Chrome
mode used Chrome's `--host-resolver-rules` to keep pages away from private
addresses, but Chrome only glob-matches those rules, so the CIDR entries
never matched. A page could fetch `169.254.169.254`, RFC 1918 addresses, or
names that resolve to them. Chrome now runs behind `web.EgressProxy`, an
in-process proxy that resolves each destination, refuses private
addresses, and connects to the address it checked. This covers redirects,
sub-resources, in-page `fetch`/XHR and WebSockets, and WebRTC is limited to
proxied traffic. You can also use `web.StartEgressProxy` with your own
browser.
- **Stricter private-address checks.** The shared SSRF guard now also blocks
multicast, reserved and benchmark ranges, Teredo, and IPv6 addresses that
embed a private IPv4 address (NAT64, 6to4). `SafeHTTPClient` races IPv4
and IPv6 addresses so hosts with broken IPv6 no longer stall.
- **Dependencies.** chromedp v0.16.0, go-openai v1.43.0, html-to-markdown
v2.5.2, otel v1.47.0, testify v1.12.1, x/sys v0.48.0.
## What's in v0.6.2
[v0.6.2](https://github.com/sausheong/harness/releases/tag/v0.6.2) and
[v0.6.1](https://github.com/sausheong/harness/releases/tag/v0.6.1) are
patch releases with no API changes:
- **Updated provider and MCP SDKs.** `anthropic-sdk-go` moves to v1.78.0,
`google.golang.org/genai` to v1.72.0 and the MCP Go SDK to v1.8.0.
Applications that also import these modules will be raised to at least
these versions by Go's minimum version selection.
- **MCP structured results.** When an MCP tool returns its result only as
`structuredContent`, with no text block, the adapter passes the JSON to
the agent instead of an empty result. Text still wins when present.
## What's in v0.6.0
[v0.6.0](https://github.com/sausheong/harness/releases/tag/v0.6.0) and
[v0.5.0](https://github.com/sausheong/harness/releases/tag/v0.5.0) add two
tools and raise the minimum Go version:
- **Go 1.26 required.** The module declares `go 1.26.0`, needed by the
Stagehand SDK. With the default `GOTOOLCHAIN=auto`, older toolchains
download 1.26 automatically; pinned CI images must be updated.
- **Natural-language browser.** `tools/stagehand` drives a browser with
instructions such as "click the Sign in button" instead of CSS selectors
(`act`, `observe`, `extract`, plus `navigate`, `get_text`, `screenshot`).
It runs on local Chrome or Browserbase, and Stagehand's inference goes
through your own `LLMProvider`.
- **Exa search.** `web.ExaSearchTool` (`exa_search`) returns ranked results
with query-relevant highlights, with category, domain and date filters.
- **Smaller changes.** PDF attachments are sent to Anthropic as document
blocks, Opus 5.5 uses adaptive low-effort thinking when reasoning is off,
and `WebFetchTool`'s output cap is raised to about 1M tokens.
## What's in v0.4.2
[v0.4.2](https://github.com/sausheong/harness/releases/tag/v0.4.2)
improves response handling and tool visibility for applications such as Hand:
- **Empty answers fail clearly.** `Runtime.Run` retries a response with no text
or tool calls once, subject to existing budgets and cancellation. It keeps
the same output allowance and does not replay tools. If no answer arrives,
the run reports an error. `RunTurn` reports the error directly; its caller
controls retries.
- **Output limits remain visible.** Answers stopped by `length` or `max_tokens`
are reported as incomplete rather than successful. The OpenAI-compatible
provider preserves finish reasons and trailing usage records, and does not
dispatch partial tool arguments from an output-truncated response.
- **Truncated summaries preserve history.** Compaction rejects a summary that
reaches its output limit, retaining the original conversation.
- **Complete tool arguments before execution.** `EventToolCallReady` carries
the complete tool call so a host can preview a command before it runs.
This includes the v0.4.1 fixes for repeated stream finishes and preservation
of cancellation causes. See [releases](https://github.com/sausheong/harness/releases)
for version-by-version notes.
## What's in v0.4.0
v0.4.0 adds the operational controls needed by a production coding
agent while keeping Harness a composable Go library:
- **Explicit execution boundaries.** `execution.Host` labels commands
as unrestricted host execution. `execution.Container` uses an
immutable image ID, explicit mounts and environment, resource limits,
and fail-closed startup with no host fallback.
- **Request, token, cost, run, and time budgets.** Provider calls can be
admitted before dispatch and settled against reported usage. Unknown
usage remains unknown rather than being counted as zero.
- **Request-level usage accounting.** The ledger records main,
compaction, and other provider calls without double-counting cache
token subsets. See [`USAGE.md`](./USAGE.md).
- **Durable session evolution.** Versioned JSONL records, writer leases,
attachments, branches, annotations, crash recovery, and explicit,
backed-up migration from legacy sessions. See
[`SESSION_FORMAT.md`](./SESSION_FORMAT.md).
- **Steering and inspectable context.** Hosts can queue corrections at
joined tool boundaries, pin context, inspect composed state, and
retain stable tool-call identity. See
[`runtime/STEERING.md`](./runtime/STEERING.md).
- **Bounded process output and joined cleanup.** Commands and stdio MCP
servers use managed process groups on Unix, bounded inline output,
and optional private spill artifacts.
## What Harness is for
Harness is well-suited to:
@@ -188,13 +82,13 @@ a lot. The package is optimized for the use cases above, not these.
## Requirements
- **Go 1.26 or newer.** The module declares `go 1.26.0`, required by
the Stagehand SDK that `tools/stagehand` depends on. With the default
`GOTOOLCHAIN=auto`, an older local Go downloads 1.26 automatically.
- **Go 1.25.1 or newer.** The module declares `go 1.25.1` and uses
`iter.Seq` from `iter` (Go 1.23+) plus a few stdlib calls that
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
LiteLLM/OpenRouter key for those aggregators. For local models
(Ollama, LM Studio, etc.), `local.NewLocalProvider` needs no key at all.
Qwen DashScope key. 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.).
@@ -213,11 +107,7 @@ in only what you need (e.g. `tools/file` without `tools/browser`).
```
github.com/sausheong/harness/
├── attachment/ # Bounded private attachment storage
├── budget/ # Token, cost, run and deadline budgets
├── execution/ # Explicit host/container execution backends
├── llm/ # LLMProvider interface, Message/ToolDef/ChatRequest types
├── process/ # Managed subprocesses and bounded output capture
├── session/ # Append-only session DAG (Session, SessionEntry, Store)
├── tokens/ # char/4 estimator + Calibrator + CalibratorStore
├── compaction/ # Three-stage summarize-and-splice manager
@@ -229,18 +119,14 @@ github.com/sausheong/harness/
│ # MemoryProvider/SkillProvider/KnowledgeGraph interfaces
├── providers/
│ ├── anthropic/ # Anthropic LLMProvider (with prompt caching)
│ ├── openai/ # OpenAI / OpenAI-compatible
│ ├── openai/ # OpenAI / OpenAI-compatible / local Ollama
│ ├── gemini/ # Google Gemini via google.golang.org/genai
│ ├── litellm/ # Self-hosted LiteLLM proxy (OpenAI-compatible)
│ ├── openrouter/ # OpenRouter aggregator (OpenAI-compatible)
│ └── local/ # Local model server — Ollama, LM Studio, etc. (OpenAI-compatible, no API key)
│ └── qwen/ # Alibaba Qwen (OpenAI-compatible endpoint)
└── tools/ # Batteries-included concrete tools (each importable separately)
├── file/ # read_file (with vision), write_file, edit_file
├── bash/ # bash (with ExecPolicy: deny | allowlist | full)
├── web/ # web_fetch, web_search, exa_search, ssrf guard, egress proxy
├── web/ # web_fetch, web_search, ssrf guard
├── browser/ # chromedp wrapper with per-session reuse
├── stagehand/ # natural-language browser (Stagehand: act/observe/extract),
│ # local Chrome or Browserbase; inference via your LLMProvider
├── mcp/ # Connect to external MCP servers; adapt their tools
└── todo/ # todo_write
```
@@ -304,7 +190,7 @@ how to plug in hooks, MCP servers, skills, permissions, and more.
## Examples
Five end-to-end agents ship in [`examples/`](./examples). Each is a
Four end-to-end agents ship in [`examples/`](./examples). Each is a
self-contained `main.go` you can `go run`:
| Example | What it shows | API surface |
@@ -343,9 +229,6 @@ 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
@@ -353,14 +236,13 @@ none of it.
## Components
A general agent harness spans the loop, the model invocation layer,
the tool registry, permission gating,
A general agent harness has ~16 conceptual components: the loop, the
model invocation layer, the tool registry, permission gating,
context/compaction, the system prompt, sub-agents, hooks, MCP, skills,
session persistence, writable memory, writable skills, a
self-improvement reviewer, budgets, execution boundaries, attachments,
UI, and entrypoints. Harness implements the in-process, library-shaped
subset of those. The rest is left to the caller — you own the binary,
you own the UI, you own the channel.
self-improvement reviewer, UI, and entrypoints. harness implements the
in-process, library-shaped subset of those. The rest is left to the
caller — you own the binary, you own the UI, you own the channel.
| # | Component | Where it lives in harness |
|---|---|---|
@@ -369,7 +251,7 @@ you own the UI, you own the channel.
| 3 | **Tool registry & schemas** | `tool.Registry`; `ToolDefs()` is sorted by name so the request prefix is stable across turns (cache hit) |
| 4 | **Tool execution & permissions** | `tool.PermissionChecker` (`Check` + `FilterToolDefs`); concurrency-safe partitioning via `Tool.IsConcurrencySafe` + `LoopConfig.MaxToolConcurrency` (default 10) |
| 5 | **Context & compaction** | `compaction.Manager` — summarize-and-splice at a clean user-message boundary; tool-result pruning at request time |
| 6 | **System prompt assembly** | `llm.SystemPromptPart` — splits the static cacheable prefix (`Runtime.StaticSystemPrompt`, built once) from the per-turn dynamic suffix (date line, KG hint, and `Runtime.DynamicIdentityHint` for any caller-mutable fact — e.g. the active model name after a live switch — that needs fresher recency than the cached prefix gives it); provider-side `cache_control` placement is automatic |
| 6 | **System prompt assembly** | `llm.SystemPromptPart` — splits the static cacheable prefix from the per-turn dynamic suffix; provider-side `cache_control` placement is automatic |
| 7 | **Sub-agents / delegation** | `runtime.SubagentResolver` interface + `MaxAgentDepth=3` cap; subagents run as in-process goroutines with their own `Runtime` |
| 8 | **Hooks** | `runtime.LifecycleHooks` (on `LoopConfig.Hooks`): `OnUserPromptSubmit`, `OnSessionStart`, `BeforeToolUse`, `AfterToolUse`, `OnStop`. Go callbacks — type-safe, in-process, nil-friendly |
| 9 | **MCP** | `tools/mcp` package: `mcp.Connect(ctx, ServerConfig)` adapts an external MCP server's tools as `tool.Tool`s. Declare `AgentSpec.MCPServers` for auto-wiring; `Runtime.Close()` releases sessions |
@@ -378,24 +260,19 @@ you own the UI, you own the channel.
| 12 | **Writable memory** | `tool/memory` package: `MemoryStore` interface, `MemoryTool` (action-discriminated), JSONL on-disk default. Wraps any backend; `*jsonl.Store` doubles as a `runtime.MemoryProvider`. |
| 13 | **Writable skills** | `tool/skills` package: `SkillStore` interface, `SkillTool` (six actions: create/patch/replace/remove/list/get), directory-on-disk default. Patch supports surgical string-match with three error categories. |
| 14 | **Self-improvement reviewer** | `runtime.Review` — one-shot reviewer Runtime against a finished session. Designed to be called from `LifecycleHooks.OnStop` in a goroutine. Snapshots parent's session; shares Memory/Skills writes; recursion guard via `AgentID = "__review__"`. |
| 15 | **Budgets and usage** | `budget` + `llm.WithCallAdmission` / `WithUsageObserver` — pre-dispatch admission, request settlement, durable run/token/cost limits, deadlines, and reported-only accounting |
| 16 | **Execution boundary** | `execution.Backend` — explicitly labelled host execution or a fail-closed Docker container with an immutable image, allowlisted environment, mounts, limits, and joined cleanup |
| 17 | **Attachments and artifacts** | `attachment.Store`, session attachment records, and bounded process output artifacts with integrity checks and private storage |
Deliberately not in scope:
Deliberately not in scope (numbers from the same conceptual list):
- **UI**: harness emits events; the caller renders.
- **Entrypoints**: harness is a library. There is no `harness`
- **15 — UI**: harness emits events; the caller renders.
- **16 — Entrypoints**: harness is a library. There is no `harness`
binary. The example agents in `examples/` show how a binary is
assembled.
## Design notes
- **Streaming-first.** The loop yields `EventTextDelta`,
`EventToolCallStart`, `EventToolCallReady`, `EventToolResult`,
`EventDone`, and friends through a `<-chan AgentEvent`.
Use `EventToolCallReady` for complete arguments; the start event may arrive
before arguments are available. There is no buffered "give me the
`EventToolCallStart`, `EventToolResult`, `EventDone`, and friends
through a `<-chan ChatEvent`. There is no buffered "give me the
whole response" path — even the non-streaming fallback re-emits
through the same channel.
- **Prompt-cache discipline.** Tool definitions are sorted, system
@@ -433,19 +310,9 @@ Deliberately not in scope:
`clientcredentials.Config.Client(ctx)`) as `HTTPClient` —
auto-refresh comes for free. Call `Runtime.Close()` to release
sessions.
- **Execution mode is an explicit trust decision.** `execution.Host`
has access to the caller's host authority and says so through
`Boundary()`. `execution.Container` requires a real Docker socket,
immutable `sha256:` image, explicit workspace and resources, and
never falls back to host execution. Network and workspace writes are
disabled unless enabled. MCP servers, hooks, and other in-process host
integrations remain outside that container boundary unless the caller
separately isolates them.
- **Six providers, one interface.** Anthropic, OpenAI, Gemini, LiteLLM,
OpenRouter, and local (Ollama, LM Studio, etc.) ship built-in — LiteLLM,
OpenRouter, and local cost none of that ~300 LOC each, since all three
are thin constructors over the existing OpenAI-compatible path. Adding
a genuinely new wire format is implementing `llm.Provider` (~300 LOC).
- **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).
See [`developer.md`](./developer.md) for a step-by-step guide to
building agents on top of Harness, including diagrams of the
@@ -477,10 +344,9 @@ these, you'll need to bring them yourself or layer them on top:
- **A skill / plugin marketplace.** Skills are `//go:embed` markdown
in your binary, or whatever your `SkillProvider` resolves at
runtime. There is no central registry.
- **Authentication and multi-tenant infrastructure.** Per-agent policy
lives in `PermissionChecker`. Harness supplies accounting and budget
primitives, but the caller owns identity, tenancy, provider billing
reconciliation, and the durable policy service.
- **Auth / billing / multi-tenant infrastructure.** Per-agent
policy lives in `PermissionChecker`; everything else is your
problem.
- **Shell-command hooks.** Hooks are typed Go callbacks on
`LifecycleHooks`, not subprocess invocations driven by a config
file.
@@ -501,19 +367,18 @@ hermetic:
LTA_DATAMALL_KEY=... go test -tags live ./examples/lta-agent/...
```
The release qualification workflow runs uncached race-enabled tests on
hosted Linux and macOS, reconciles the complete test inventory, rejects
skips and incomplete packages, and repeats critical process-lifecycle
tests. See [`scripts/QUALIFICATION.md`](./scripts/QUALIFICATION.md).
The runtime test suite includes some rare timing-sensitive cases —
if a streaming-tools test flakes once, re-run before treating it as
a real failure.
## Status
`v0.6.3` is the latest tagged release. The v0.x line follows Go
`v0.1.0` is the first 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.6.3
go get github.com/sausheong/harness@v0.1.0
```
Likely sources of v0.x churn before a v1.0.0:
@@ -532,39 +397,3 @@ for the changelog of each tagged version.
## License
MIT — see [`LICENSE`](./LICENSE).
## Usage accounting
See [USAGE.md](USAGE.md) for request-level records, reported versus unknown usage,
retry/compaction accounting and the cache-counter migration from v0.3.9.
### Managed subprocess lifecycle and output
The `process` package creates a private Unix process group for a command and
kills that group on context cancellation. `process.Run` joins the command and
removes descendants after normal exit too. Callers using `Start`/`Wait` directly
must call `process.KillGroup` when their protocol closes. Bash and stdio MCP use
this lifecycle; non-Unix platforms currently provide direct-child cleanup only.
A child that deliberately starts a new session can escape a process group: this
is lifecycle management, not isolation. Use a containment backend for isolation.
`process.Capture` drains output while retaining a bounded prefix. Bash retains
at most 64 KiB per stdout/stderr stream and includes explicit truncation notices,
observed byte counts, truncation flags, cancellation/timeout flags and an exit
code when available in result metadata. Cancellation and timeout reasons remain
visible even if stderr has content. Output exceeding the memory prefix is spooled into private 0600 artifacts. The
metadata and inline notice identify their paths, captured bytes, disk truncation
and any capture error. The default store is `harness-output-<uid>` under the OS
temporary directory; callers may provide BashTool.OutputStore to choose a
private directory. Treat output as potentially sensitive.
Each artifact is capped at 8 MiB and the store reserves at most 64 MiB across
active and completed captures. Cooperating processes use advisory locks so
active files cannot be evicted; completed files are evicted oldest first.
Allocation also removes completed files older than 24 hours. Time-based cleanup
is lazy, so files can remain until the next allocation; storage remains bounded.
Artifacts are ephemeral and paths can expire after eviction. A full active quota
or write failure is explicitly reported while output continues to drain.
Artifact locking is supported on Unix; other platforms report unavailable disk
capture and retain the bounded inline prefix. These locks do not defend against
malicious programs running as the same user.
-120
View File
@@ -1,120 +0,0 @@
# Session JSONL format, version 1
New sessions begin with one `session_header` record. Its nonempty `id` is the
session identity, `schemaVersion` is 1, and `timestamp` records creation time.
The header has no parent. It is independent of agent/key names and survives
renaming the file. Copying a file preserves identity; a product-level fork must
assign a new identity explicitly rather than pretending the copy is a new session.
```json
{"id":"ses_example","type":"session_header","schemaVersion":1,"timestamp":1788796800,"data":null}
{"id":"e_example","type":"message","role":"user","timestamp":1788796801,"data":{"text":"Hello"}}
```
The header must be the first nonblank record and cannot occur again. Unsupported
header versions, a version field on a conversation record, and graph links to
headers or selection controls are errors. No loader, recovery or migration path
silently accepts an unsupported version. Entry IDs are unique within the log;
parents precede children. Selection controls use `type: selection`, their target
in `parentId`, and `data: {"version":1}`. They select a conversation node without
becoming part of its history. Ordinary appends subsequently select the new node.
`Session.Entries` contains graph entries and selection controls, excluding the
format header. `History` and `View` exclude both kinds of control record. A raw
file export must retain the header; serialising `Entries` alone is not a complete
identity-preserving session export. Store.List exposes the stored session ID and
excludes the header from EntryCount.
Store.Create commits a complete synced header file without overwriting an
existing key. First append to a new/empty file writes the header before the entry.
Rewrite retains the same header. Use an exclusive session lease and Flush/Close
according to their documented producer-joining contract. A failed append may
leave an incomplete final record and must be treated as degraded persistence.
Legacy headerless files remain readable without implicit modification. Their
historical format has no persisted session ID, so ordinary Load still assigns
an ephemeral ID. Use MigrateLegacy before exposing durable session identity:
it adds the version-1 header, corrects supported old compaction duplicate IDs,
and retains a synced complete-original backup before atomic replacement. The
report distinguishes format upgrade from duplicate-ID remapping. Repeating the
migration on a valid version-1 file preserves its exact bytes and ID.
Recovery repairs only incomplete final JSON objects and retains its own backup.
A future-version or structurally invalid complete record is never a recoverable
tail. Truncated first-header recovery yields an empty log; without a complete
header there was no recoverable durable identity. Unsupported versions require
an explicit future migration implementation.
Payload-specific schemas, application session catalogues, attachment/export
policies and cross-platform release qualification remain separate work. Unknown
JSON fields are retained by the legacy converter; generic typed rewrites do not
promise lossless preservation of arbitrary unknown fields.
## Application annotations
`annotation` records contain `data: {"version":1,"kind":"app.name","payload":{...}}`.
They are durable application metadata, exposed by Entries and Annotations but
excluded from History and View. They do not move the selected leaf, even in an
empty session. Their optional parent attaches them to the current conversation
node; conversation nodes cannot use annotations as parents or branch targets.
Kinds contain ASCII letters, digits, dots, underscores or hyphens (1–128 bytes).
The encoded annotation data is limited to 64 KiB. Unsupported annotation versions
are rejected. Annotate flushes before committing the in-memory record; invalid
input returns an error without degrading persistence. Stored metadata is retained
by full graph rewrites and raw exports. Applications define payload schemas,
request deduplication and inherited-versus-new accounting semantics for forks.
This extension is part of the unpublished session format candidate. The older
5cc93a3 development snapshot does not implement annotation control semantics and
must not be used to load files created by this candidate.
## Attachment references (unpublished development format)
New persistent message/tool-result images store `attachment: {sha256, size}`
instead of base64 `data`. Blobs live in the agent session directory's private
`.attachments` directory. Legacy inline data remains readable. Image MIME type
and unknown payload fields remain in JSONL. AppendContext publishes and syncs
blobs before the referring record; ResolveImages verifies and hydrates them for
model replay. Missing/corrupt references are errors. In-memory sessions retain
inline data. This extension requires the corresponding runtime; older loaders
must not be used for image replay on these unpublished candidates.
CopyAttachments publishes only referenced blobs into a target store before its
session JSONL is published. Portable JSONL copies must travel together with their
sibling `.attachments` directory. Copying JSONL alone is insufficient when it
contains references. Blob quotas do not evict existing session data.
MigrateLegacy also externalizes legacy inline images, including image records
larger than the normal reader limit. Its migration-only record cap is 64 MiB,
within the existing 128 MiB total import cap. Each blob must fit the attachment
store's 32 MiB limit. Normalized output still passes the unchanged 10 MiB record
reader and strict graph/duplicate-ID validation before replacement. The backup
and reported source digest refer to the original unmodified bytes. The report's
ExternalizedImages count describes transformed image occurrences. Repeated
migration of reference-backed records leaves bytes and identity unchanged.
Invalid image data and oversized non-image records remain errors. A failed
conversion can leave unreferenced immutable blobs; it never rewrites the source.
Combined recovery is available through the explicit MigrateRecovering API.
## Combined recovery and migration
MigrateLegacy remains strict about unfinished tails. MigrateRecovering may
remove only a syntactically unfinished final JSON object, preserving a full
original backup. It converts and validates the complete retained prefix under
one lifetime writer lease, including oversized inline images and recognised
historical compaction clones. Interior corruption, terminated malformed records
and invalid retained graphs remain errors with no source replacement.
TailRecovered and DiscardedTailBytes are set only after replacement; Migrated
still indicates replacement when a later directory sync fails. The source hash
covers the full original including the discarded tail. Restart is idempotent.
### Listing metadata
`Store.List` scans records up to the legacy image import record limit and checks
scan/read errors. Each `SessionInfo.MetadataError` is empty only when that file's
metadata scan completed. On failure the key stays discoverable for explicit
recovery, but ID and entry count are cleared; timestamps use file modification
time when available. Non-regular files are reported without opening them.
Listing extracts syntactic metadata; it does not validate the session graph or
replace leased loading/migration. Callers must not interpret a metadata error as
an empty, valid session.
-63
View File
@@ -1,63 +0,0 @@
# Usage accounting
`llm.Usage.InputTokens` is total input, including cached input. Cache-read and
cache-creation counters are subsets used for pricing and analysis. Do not add
them to InputTokens when calculating context occupancy or total input. The
Anthropic adapter normalizes its separate wire counters to this contract;
OpenAI-style prompt-token totals already include all input.
This changes Anthropic InputTokens from its old uncached-only value. Consumers
upgrading from v0.3.9 must remove their extra addition of cache counters. For
example, 10 uncached + 42 cache creation + 17 cache read becomes InputTokens=69,
not 10 and not 128 after adding cache twice.
`runtime.EventRequestUsage` carries one `llm.RequestUsage` per provider attempt:
request ID, model, category (`generation`, `retry`, `compaction`), status,
source (`reported` or `unavailable`) and optional usage. A nil usage value is
unknown, including on potentially billable failures. It must never be priced
as zero or replaced by the preceding request's usage. No estimated figure is
labelled reported by this layer.
Use the newest applicable generation/retry record for the active model when
showing context occupancy. Use the sum of records for consumption. Ten
20,000-input requests consume 200,000 reported input tokens while the newest
request occupies approximately 20,000 input tokens. An unavailable newest
record makes current occupancy unknown; model/session changes also require
resetting a consumer's gauge.
`EventDone.Usage` is a reported-only aggregate for the run, including observed
retries and run-owned background and synchronous compaction. It is incomplete whenever any request
record has unavailable usage. RunTurn returns the aggregate for that call,
including refusal retries, rather than only the last attempt. Request records
are available on error paths even when no EventDone is emitted.
Compaction returns its attempt records in `compaction.Result.Requests`.
`Manager.OnUsage` optionally observes all compaction attempts, including
background compaction. The observer must be concurrency-safe. Background work
started with `MaybeCompactAsyncContext` retains the caller's cancellation and
usage observer. Runtime joins its background producer and flushes the session
before emitting EventDone or closing the event stream. Cancellation during
that join produces EventAborted instead of a successful EventDone. This may
add summarisation latency at the end of a run; consume the stream until it
closes, including after cancellation.
The legacy `MaybeCompactAsync` API still creates detached work. Applications
using it must own that producer separately and collect its session accounting.
`JoinInFlight` cancels on caller cancellation and still waits for the producer
to exit; prevent new launches while joining or releasing session ownership.
Providers must honour cancellation for bounded shutdown. When combining event and
callback streams, deduplicate by request ID.
`llm.WithUsageObserver` can be used by other adapters with `llm.ObserveChat`.
Observers are invoked before the terminal event is forwarded; providers must
honour cancellation and end their streams after EventDone/EventError.
`RunTurn` preserves serial delivery of its TurnEmit callbacks. UsageLedger is
intended for a bounded operation, not an unbounded global history. Persistence,
price schedules and budget admission remain application responsibilities.
Context-owned compaction retains its completed result until `JoinInFlight` (or
`ForgetSession`) consumes it. Always join, even when `HasInFlight` is false:
that method reports active execution, not an unread result. Repeated launches
return the existing handle until consumption, preventing an unread failure
from being overwritten. `WaitForInFlight` observes without consuming. This
retains at most one result per owned session; release it when ownership ends.
-26
View File
@@ -1,26 +0,0 @@
# Session attachment storage
`Open(directory, quotaBytes)` opens a private (0700) content store. Its parent directory must already exist;
the store directory and its parent publication are synced before use. Use
`DefaultStoreBytes` for a 1 GiB quota. `Put(ctx, data)` publishes a synced 0600
blob and returns a `Ref` containing its lowercase SHA-256 digest and exact byte
length. `Read(ctx, ref)` verifies regular-file identity, size and digest. Blobs
are limited to 32 MiB; MIME type belongs in the referring session record.
Publication uses a synced temporary file, exclusive hard link and directory
sync. A cross-process lock serialises deduplication, quota admission and
publication on Linux/macOS. Interrupted pending files are removed under that
lock on a later new-content put. Existing published attachments are never
evicted. A full store fails admission. Directory scanning is bounded to 8192
entries, including control files; oversized stores require explicit maintenance.
References contain no caller-chosen filesystem path. File operations use
`os.Root`; external symlinks cannot escape that root. The caller owns the
configured private root and must not replace it with an untrusted directory.
Do not close the store until its operations have joined. Cancellation interrupts
lock waits and chunked I/O; the caller still owns its input byte slice until Put
returns. Other platforms reject writer locking explicitly.
This package is the storage foundation. Session image references, runtime
hydration, legacy inline-image conversion, fork copying and portable export
packaging must be integrated before claiming attachment workflow completion.
-14
View File
@@ -1,14 +0,0 @@
//go:build !darwin && !linux
package attachment
import (
"context"
"errors"
"os"
)
func lock(context.Context, *os.File) error {
return errors.New("attachment writer locking unsupported on this platform")
}
func unlock(*os.File) {}
-34
View File
@@ -1,34 +0,0 @@
//go:build darwin || linux
package attachment
import (
"context"
"errors"
"golang.org/x/sys/unix"
"os"
"time"
)
func lock(ctx context.Context, f *os.File) error {
for {
if err := ctx.Err(); err != nil {
return err
}
err := unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB)
if err == nil {
return nil
}
if !errors.Is(err, unix.EWOULDBLOCK) && !errors.Is(err, unix.EAGAIN) {
return err
}
timer := time.NewTimer(10 * time.Millisecond)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
}
}
func unlock(f *os.File) { _ = unix.Flock(int(f.Fd()), unix.LOCK_UN) }
-267
View File
@@ -1,267 +0,0 @@
// Package attachment stores immutable session attachments by their content hash.
package attachment
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
const MaxBlobBytes int64 = 32 << 20
const DefaultStoreBytes int64 = 1 << 30
const maxEntries = 8192
// Ref has no path chosen by a caller. MIME type belongs to the referring entry.
type Ref struct {
SHA256 string `json:"sha256"`
Size int64 `json:"size"`
}
func (r Ref) Validate() error {
if len(r.SHA256) != 64 || r.Size < 0 || r.Size > MaxBlobBytes {
return errors.New("invalid attachment reference")
}
for _, c := range r.SHA256 {
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
return errors.New("invalid attachment digest")
}
}
return nil
}
type Store struct {
root *os.Root
limit int64
}
// Open opens a private directory. Close after all operations join. A full store
// rejects new content; existing session attachments are never evicted.
func Open(dir string, limit int64) (*Store, error) {
if limit <= 0 {
return nil, errors.New("attachment quota must be positive")
}
if err := os.Mkdir(dir, 0700); err != nil && !errors.Is(err, os.ErrExist) {
return nil, err
}
info, err := os.Lstat(dir)
if err != nil {
return nil, err
}
if !info.IsDir() || info.Mode().Perm()&0077 != 0 {
return nil, errors.New("attachment directory must be private (0700)")
}
root, err := os.OpenRoot(dir)
if err != nil {
return nil, err
}
// A durable blob directory also needs its name synced in the parent before
// any session record can refer to a blob inside it. The parent must exist.
parent, err := os.Open(filepath.Dir(dir))
if err != nil {
root.Close()
return nil, err
}
if err = errors.Join(parent.Sync(), parent.Close()); err != nil {
root.Close()
return nil, err
}
return &Store{root: root, limit: limit}, nil
}
func (s *Store) Close() error { return s.root.Close() }
func (s *Store) Put(ctx context.Context, data []byte) (Ref, error) {
if err := ctx.Err(); err != nil {
return Ref{}, err
}
if int64(len(data)) > MaxBlobBytes {
return Ref{}, errors.New("attachment exceeds blob limit")
}
digest := sha256.Sum256(data)
ref := Ref{SHA256: hex.EncodeToString(digest[:]), Size: int64(len(data))}
guard, err := s.root.OpenFile(".lock", os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return Ref{}, err
}
defer guard.Close()
if err := lock(ctx, guard); err != nil {
return Ref{}, err
}
defer unlock(guard)
if _, err := s.root.Lstat(ref.SHA256); err == nil {
if _, err := s.Read(ctx, ref); err != nil {
return Ref{}, err
}
// Reestablish a durability fence when reusing a prior publication.
f, err := s.root.Open(ref.SHA256)
if err != nil {
return Ref{}, err
}
err = f.Sync()
closeErr := f.Close()
if err = errors.Join(err, closeErr, s.sync()); err != nil {
return Ref{}, err
}
return ref, nil
} else if !errors.Is(err, os.ErrNotExist) {
return Ref{}, err
}
used, err := s.usage(ctx)
if err != nil {
return Ref{}, err
}
if ref.Size > s.limit-used {
return Ref{}, errors.New("attachment store quota exceeded")
}
name := ".pending-" + rand.Text()
f, err := s.root.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
return Ref{}, err
}
defer s.root.Remove(name)
for offset := 0; offset < len(data); {
if err = ctx.Err(); err != nil {
f.Close()
return Ref{}, err
}
end := min(offset+64*1024, len(data))
n, writeErr := f.Write(data[offset:end])
offset += n
if writeErr != nil {
f.Close()
return Ref{}, writeErr
}
if n == 0 {
f.Close()
return Ref{}, io.ErrShortWrite
}
}
err = f.Sync()
err = errors.Join(err, f.Close())
if err != nil {
return Ref{}, err
}
if err = ctx.Err(); err != nil {
return Ref{}, err
}
if err = s.root.Link(name, ref.SHA256); err != nil {
return Ref{}, err
}
if err = s.sync(); err != nil {
return Ref{}, fmt.Errorf("attachment published but directory sync failed: %w", err)
}
return ref, nil
}
func (s *Store) Read(ctx context.Context, ref Ref) ([]byte, error) {
if err := ref.Validate(); err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
info, err := s.root.Lstat(ref.SHA256)
if err != nil {
return nil, err
}
if !info.Mode().IsRegular() || info.Size() != ref.Size {
return nil, errors.New("attachment is not a regular file of the declared size")
}
f, err := s.root.Open(ref.SHA256)
if err != nil {
return nil, err
}
defer f.Close()
actual, err := f.Stat()
if err != nil {
return nil, err
}
if !actual.Mode().IsRegular() || !os.SameFile(info, actual) || actual.Size() != ref.Size {
return nil, errors.New("attachment changed while opening")
}
data := make([]byte, 0, int(ref.Size))
buffer := make([]byte, 64*1024)
for {
if err := ctx.Err(); err != nil {
return nil, err
}
n, err := f.Read(buffer)
if int64(len(data)+n) > ref.Size {
return nil, errors.New("attachment grew past declared size")
}
data = append(data, buffer[:n]...)
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, err
}
}
digest := sha256.Sum256(data)
if int64(len(data)) != ref.Size || hex.EncodeToString(digest[:]) != ref.SHA256 {
return nil, errors.New("attachment integrity check failed")
}
return data, nil
}
func (s *Store) sync() error {
dir, err := s.root.Open(".")
if err != nil {
return err
}
return errors.Join(dir.Sync(), dir.Close())
}
// Called under the cross-process writer lock. Pending files are leftovers of
// interrupted puts; published blobs are never removed by this cleanup.
func (s *Store) usage(ctx context.Context) (int64, error) {
dir, err := s.root.Open(".")
if err != nil {
return 0, err
}
defer dir.Close()
entries, err := dir.ReadDir(maxEntries + 1)
if err != nil && !errors.Is(err, io.EOF) {
return 0, err
}
if len(entries) > maxEntries {
return 0, errors.New("attachment directory entry limit exceeded")
}
var used int64
for _, entry := range entries {
if err := ctx.Err(); err != nil {
return 0, err
}
name := entry.Name()
if name == ".lock" {
continue
}
info, err := entry.Info()
if err != nil {
return 0, err
}
if !info.Mode().IsRegular() {
return 0, errors.New("non-regular attachment store entry")
}
if strings.HasPrefix(name, ".pending-") {
if err := s.root.Remove(name); err != nil {
return 0, err
}
continue
}
if err := (Ref{SHA256: name, Size: info.Size()}).Validate(); err != nil {
return 0, err
}
if info.Size() > s.limit-used {
return 0, errors.New("attachment store exceeds quota")
}
used += info.Size()
}
return used, nil
}
-185
View File
@@ -1,185 +0,0 @@
package attachment
import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"sync"
"testing"
"time"
)
func openTest(t *testing.T, dir string, quota int64) *Store {
t.Helper()
if err := os.Chmod(dir, 0700); err != nil {
t.Fatal(err)
}
s, err := Open(dir, quota)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { s.Close() })
return s
}
func TestLargeAttachmentRoundTripAndDeduplication(t *testing.T) {
dir := t.TempDir()
s := openTest(t, dir, DefaultStoreBytes)
data := bytes.Repeat([]byte{0x42}, 12<<20)
ref, err := s.Put(context.Background(), data)
if err != nil {
t.Fatal(err)
}
duplicate, err := s.Put(context.Background(), data)
if err != nil || duplicate != ref {
t.Fatal(duplicate, err)
}
other := openTest(t, dir, DefaultStoreBytes)
got, err := other.Read(context.Background(), ref)
if err != nil || !bytes.Equal(got, data) {
t.Fatal("reopened blob changed", err)
}
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
if len(entries) != 2 {
t.Fatal("deduplication left extra files", entries)
}
info, err := os.Stat(filepath.Join(dir, ref.SHA256))
if err != nil || info.Mode().Perm() != 0600 {
t.Fatal(info, err)
}
}
func TestAttachmentIntegrityAndTraversal(t *testing.T) {
dir := t.TempDir()
s := openTest(t, dir, 100)
ref, err := s.Put(context.Background(), []byte("original"))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, ref.SHA256), []byte("modified"), 0600); err != nil {
t.Fatal(err)
}
if _, err := s.Read(context.Background(), ref); err == nil {
t.Fatal("tampering accepted")
}
if _, err := s.Put(context.Background(), []byte("original")); err == nil {
t.Fatal("corrupt existing blob reused")
}
if _, err := s.Read(context.Background(), Ref{SHA256: "../outside", Size: 1}); err == nil {
t.Fatal("path accepted as digest")
}
if err := os.Remove(filepath.Join(dir, ref.SHA256)); err != nil {
t.Fatal(err)
}
outside := filepath.Join(t.TempDir(), "secret")
if err := os.WriteFile(outside, []byte("original"), 0600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(outside, filepath.Join(dir, ref.SHA256)); err != nil {
t.Fatal(err)
}
if _, err := s.Read(context.Background(), ref); err == nil {
t.Fatal("symlink accepted")
}
}
func TestAttachmentQuotaSerialisesIndependentStores(t *testing.T) {
dir := t.TempDir()
stores := []*Store{openTest(t, dir, 10), openTest(t, dir, 10)}
var wg sync.WaitGroup
errs := make([]error, 2)
refs := make([]Ref, 2)
for i := range stores {
wg.Add(1)
go func(i int) {
defer wg.Done()
refs[i], errs[i] = stores[i].Put(context.Background(), bytes.Repeat([]byte{byte(i)}, 8))
}(i)
}
wg.Wait()
success := 0
for i, err := range errs {
if err == nil {
success++
if _, err := stores[i].Read(context.Background(), refs[i]); err != nil {
t.Fatal(err)
}
}
}
if success != 1 {
t.Fatalf("quota accepted %d independent writes: %v", success, errs)
}
}
func TestAttachmentCancellationAndPendingCleanup(t *testing.T) {
dir := t.TempDir()
s := openTest(t, dir, 100)
guard, err := s.root.OpenFile(".lock", os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
t.Fatal(err)
}
defer guard.Close()
if err := lock(context.Background(), guard); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
_, err = s.Put(ctx, []byte("cancelled"))
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatal(err)
}
unlock(guard)
if err := os.WriteFile(filepath.Join(dir, ".pending-orphan"), []byte("unfinished"), 0600); err != nil {
t.Fatal(err)
}
ref, err := s.Put(context.Background(), []byte("complete"))
if err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(dir, ".pending-orphan")); !errors.Is(err, os.ErrNotExist) {
t.Fatal("orphan retained", err)
}
cancelled, stop := context.WithCancel(context.Background())
stop()
if _, err := s.Read(cancelled, ref); !errors.Is(err, context.Canceled) {
t.Fatal(err)
}
if _, err := s.Read(context.Background(), ref); err != nil {
t.Fatal("cancellation damaged content", err)
}
}
func TestAttachmentLimitsAndPrivateDirectory(t *testing.T) {
dir := t.TempDir()
s := openTest(t, dir, 100)
if _, err := s.Put(context.Background(), make([]byte, MaxBlobBytes+1)); err == nil {
t.Fatal("oversized blob accepted")
}
if _, err := s.Put(context.Background(), make([]byte, 101)); err == nil {
t.Fatal("quota exceeded")
}
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
for _, entry := range entries {
if entry.Name() != ".lock" {
t.Fatal("failed put published file", entry.Name())
}
}
if _, err := Open(t.TempDir(), 0); err == nil {
t.Fatal("invalid quota accepted")
}
public := t.TempDir()
if err := os.Chmod(public, 0755); err != nil {
t.Fatal(err)
}
if _, err := Open(public, 100); err == nil {
t.Fatal("public directory accepted")
}
}
-349
View File
@@ -1,349 +0,0 @@
package budget
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"sync"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
var ErrCostExhausted = fmt.Errorf("session cost budget: %w", ErrExhausted)
const costKind = "harness.budget.cost.v1"
type CostAttempt struct {
ID string `json:"id"`
Category llm.CallCategory `json:"category"`
Model string `json:"model"`
Quote PriceQuote `json:"quote"`
ChargedNano int64 `json:"charged_nano"`
Status string `json:"status"`
}
type CostState struct {
Currency string `json:"currency"`
LimitNano int64 `json:"limit_nano"`
CommittedNano int64 `json:"committed_nano"`
Strict bool `json:"strict"`
Exhausted bool `json:"exhausted"`
Unknown int `json:"unknown_attempts"`
Attempts []CostAttempt `json:"attempts"`
}
type costEvent struct {
Version int `json:"version"`
Kind string `json:"kind"`
Currency string `json:"currency,omitempty"`
LimitNano int64 `json:"limit_nano,omitempty"`
Strict bool `json:"strict,omitempty"`
Attempt *CostAttempt `json:"attempt,omitempty"`
ID string `json:"id,omitempty"`
ChargedNano int64 `json:"charged_nano,omitempty"`
Status string `json:"status,omitempty"`
}
// CostLedger records session-wide attempt costs in nano-units of one currency.
// Use an exclusively loaded disk Session for cross-process ownership. Unknown
// advisory charges remain visible and prevent silently enabling strict mode.
// Interrupted attempts retain their reservation and exact pricing snapshot.
type CostLedger struct {
session *session.Session
kind string
}
func OpenCostLedger(s *session.Session) (*CostLedger, error) {
return openCostLedger(s, costKind)
}
func openCostLedger(s *session.Session, kind string) (*CostLedger, error) {
if s == nil {
return nil, errors.New("cost budget requires a session")
}
l := &CostLedger{session: s, kind: kind}
_, _, err := l.read()
return l, err
}
func currencyValid(s string) bool {
return len(s) == 3 && strings.IndexFunc(s, func(r rune) bool { return r < 'A' || r > 'Z' }) < 0
}
func (l *CostLedger) read() (CostState, int, error) {
var state CostState
records := l.session.Annotations(l.kind)
if len(records) > maxRecords {
return state, 0, errors.New("cost journal exceeds record limit")
}
index := map[string]int{}
for _, record := range records {
var e costEvent
if err := decodeBudgetJSON(record.Payload, &e); err != nil {
return state, 0, err
}
if e.Version != 1 {
return state, 0, errors.New("invalid cost record")
}
switch e.Kind {
case "decision":
if !currencyValid(e.Currency) || (state.Currency != "" && state.Currency != e.Currency) || e.LimitNano <= state.CommittedNano || e.LimitNano > maxTokens || (e.Strict && state.Unknown > 0) {
return state, 0, errors.New("invalid cost decision")
}
state.Currency = e.Currency
state.LimitNano = e.LimitNano
state.Strict = e.Strict
state.Exhausted = false
case "reserve":
a := e.Attempt
if a == nil || a.ID == "" || len(a.ID) > 128 || len(a.Model) > 1024 || a.Status != "reserved" || state.LimitNano == 0 || state.Exhausted {
return state, 0, errors.New("invalid cost reservation")
}
if _, ok := index[a.ID]; ok {
return state, 0, errors.New("duplicate cost attempt")
}
q := a.Quote
if q.Nano < 0 || q.Nano > maxTokens || a.ChargedNano != q.Nano || (q.Currency != "" && q.Currency != state.Currency) || (!q.Known && (q.Nano != 0 || q.Reason == "" || state.Strict)) {
return state, 0, errors.New("invalid reservation quote")
}
if q.Snapshot != nil {
if err := q.Snapshot.Validate(); err != nil {
return state, 0, err
}
}
if q.Known && (q.Snapshot == nil || !q.Snapshot.AllChargesBounded || q.Currency != q.Snapshot.Currency || a.Model != q.Snapshot.Model) {
return state, 0, errors.New("known quote lacks matching tariff")
}
if q.Nano > state.LimitNano-state.CommittedNano {
return state, 0, errors.New("reservation exceeds balance")
}
index[a.ID] = len(state.Attempts)
state.Attempts = append(state.Attempts, *a)
state.CommittedNano += q.Nano
if !q.Known {
state.Unknown++
}
case "settle":
i, ok := index[e.ID]
if !ok || state.Attempts[i].Status != "reserved" {
return state, 0, errors.New("invalid cost settlement")
}
a := &state.Attempts[i]
if e.ChargedNano < 0 || e.ChargedNano > maxTokens {
return state, 0, errors.New("invalid settled amount")
}
switch e.Status {
case "not_dispatched":
if e.ChargedNano != 0 {
return state, 0, errors.New("undispatched charge is nonzero")
}
if !a.Quote.Known {
state.Unknown--
}
case "reported":
if !a.Quote.Known {
return state, 0, errors.New("reported charge lacks tariff")
}
case "uncertain":
if e.ChargedNano < a.Quote.Nano {
return state, 0, errors.New("uncertain charge released reservation")
}
default:
return state, 0, errors.New("invalid cost status")
}
state.CommittedNano -= a.ChargedNano
if e.ChargedNano > maxTokens-state.CommittedNano {
return state, 0, errors.New("cost total overflow")
}
state.CommittedNano += e.ChargedNano
a.ChargedNano = e.ChargedNano
a.Status = e.Status
if state.CommittedNano >= state.LimitNano {
state.Exhausted = true
}
case "exhausted":
state.Exhausted = true
default:
return state, 0, errors.New("unknown cost event")
}
}
return state, len(records), nil
}
func (l *CostLedger) State() (CostState, error) { s, _, err := l.read(); return s, err }
func (l *CostLedger) append(e costEvent, n int) error {
s, current, err := l.read()
if err != nil {
return err
}
if current != n {
return session.ErrAnnotationConflict
}
pending := 0
for _, a := range s.Attempts {
if a.Status == "reserved" {
pending++
}
}
if e.Kind == "reserve" {
pending++
}
if e.Kind == "settle" {
pending--
}
if n+1+pending > maxRecords {
return errors.New("cost journal lacks settlement capacity")
}
e.Version = 1
raw, err := json.Marshal(e)
if err != nil {
return err
}
return l.session.AnnotateIfCount(l.kind, raw, n)
}
// Decide records an explicitly approved absolute ceiling. It does not authorize
// spending by itself: callers must obtain the user's decision first. Currency
// cannot change within a ledger and no charges are erased by a new decision.
func (l *CostLedger) Decide(ctx context.Context, currency string, limit int64, strict bool) error {
if !currencyValid(currency) || limit <= 0 || limit > maxTokens {
return errors.New("invalid cost ceiling or currency")
}
for {
if err := ctx.Err(); err != nil {
return err
}
s, n, err := l.read()
if err != nil {
return err
}
if s.Currency != "" && s.Currency != currency {
return errors.New("cost ledger currency cannot change")
}
if limit <= s.CommittedNano {
return errors.New("cost ceiling must exceed committed reservations and charges")
}
if strict && s.Unknown > 0 {
return errors.New("unpriced prior attempts prevent a strict cost guarantee")
}
err = l.append(costEvent{Kind: "decision", Currency: currency, LimitNano: limit, Strict: strict}, n)
if errors.Is(err, session.ErrAnnotationConflict) {
continue
}
return err
}
}
// CostResolver must return the tariff for the actual provider route and a full
// input estimate. A nil tariff means unknown. Callers must bind provider and
// destination to their constructed client; model equality alone is not enough.
type CostResolver func(llm.ChatRequest, llm.CallCategory) (*PriceSnapshot, int64, error)
func (l *CostLedger) Admission(resolve CostResolver) llm.CallAdmission {
return func(ctx context.Context, req llm.ChatRequest, category llm.CallCategory, id string) (func(llm.RequestUsage) error, error) {
if resolve == nil || id == "" || len(id) > 128 || len(req.Model) > 1024 {
return nil, errors.New("invalid cost resolver or attempt")
}
price, input, err := resolve(req, category)
if err != nil {
return nil, err
}
if price != nil {
copy := *price
price = &copy
if price.Provider != req.Route.Provider || price.Destination != req.Route.Destination {
return nil, errors.New("price route differs from dispatched provider destination")
}
if price.Model != req.Model {
return nil, errors.New("price model differs from dispatched model")
}
}
var quote PriceQuote
for {
if err := ctx.Err(); err != nil {
return nil, err
}
s, n, err := l.read()
if err != nil {
return nil, err
}
if s.LimitNano == 0 || s.Exhausted {
return nil, ErrCostExhausted
}
for _, a := range s.Attempts {
if a.ID == id {
return nil, errors.New("duplicate cost attempt")
}
}
if price != nil && price.Currency != s.Currency {
return nil, errors.New("tariff currency differs from budget")
}
quote, err = ReservePrice(price, input, int64(req.MaxTokens), time.Now(), s.Strict)
if err != nil {
return nil, err
}
if quote.Nano > s.LimitNano-s.CommittedNano {
err = l.append(costEvent{Kind: "exhausted"}, n)
if errors.Is(err, session.ErrAnnotationConflict) {
continue
}
return nil, errors.Join(ErrCostExhausted, err)
}
err = l.append(costEvent{Kind: "reserve", Attempt: &CostAttempt{ID: id, Model: req.Model, Category: category, Quote: quote, ChargedNano: quote.Nano, Status: "reserved"}}, n)
if errors.Is(err, session.ErrAnnotationConflict) {
continue
}
if err != nil {
return nil, err
}
break
}
var once sync.Once
var result error
return func(r llm.RequestUsage) error { once.Do(func() { result = l.settle(id, quote, r) }); return result }, nil
}
}
func (l *CostLedger) settle(id string, q PriceQuote, r llm.RequestUsage) error {
if r.ID != id {
return errors.New("cost settlement identity mismatch")
}
charge, status := q.Nano, "uncertain"
if r.Status == "not_dispatched" {
charge, status = 0, "not_dispatched"
} else if q.Known && q.Snapshot != nil {
actual, err := ReportedPrice(*q.Snapshot, r.Usage)
if err != nil {
return err
}
if actual.Known {
if r.Status == "completed" {
charge, status = actual.Nano, "reported"
} else {
charge = max(charge, actual.Nano)
}
}
}
for {
state, n, err := l.read()
if err != nil {
return err
}
if charge > maxTokens || charge > maxTokens-(state.CommittedNano-q.Nano) {
return errors.New("settled cost exceeds representable ledger balance; reservation retained")
}
err = l.append(costEvent{Kind: "settle", ID: id, ChargedNano: charge, Status: status}, n)
if errors.Is(err, session.ErrAnnotationConflict) {
continue
}
if err != nil {
return err
}
s, err := l.State()
if err != nil {
return err
}
if s.Exhausted {
return ErrCostExhausted
}
return nil
}
}
-232
View File
@@ -1,232 +0,0 @@
package budget
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
func currentFixturePrice() PriceSnapshot {
p := fixturePrice()
p.EffectiveAt = time.Now().Add(-time.Hour)
p.ExpiresAt = time.Now().Add(time.Hour)
return p
}
func priceResolver(p *PriceSnapshot) CostResolver {
return func(llm.ChatRequest, llm.CallCategory) (*PriceSnapshot, int64, error) { return p, 10, nil }
}
func TestCostLedgerRestartAndPricingProvenance(t *testing.T) {
ctx := context.Background()
store := session.NewStore(t.TempDir())
if err := store.Create("a", "cost"); err != nil {
t.Fatal(err)
}
s, err := store.LoadExclusive("a", "cost")
if err != nil {
t.Fatal(err)
}
l, _ := OpenCostLedger(s)
if err = l.Decide(ctx, "USD", 1000000, true); err != nil {
t.Fatal(err)
}
p := currentFixturePrice()
_, err = l.Admission(priceResolver(&p))(ctx, llm.ChatRequest{Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, Model: p.Model, MaxTokens: 20}, llm.CallRetry, "interrupted")
if err != nil {
t.Fatal(err)
}
if err = s.Close(); err != nil {
t.Fatal(err)
}
s, err = store.LoadExclusive("a", "cost")
if err != nil {
t.Fatal(err)
}
defer s.Close()
l, err = OpenCostLedger(s)
if err != nil {
t.Fatal(err)
}
state, err := l.State()
if err != nil || state.CommittedNano != 337507 || len(state.Attempts) != 1 || state.Attempts[0].Status != "reserved" {
t.Fatalf("state %+v err %v", state, err)
}
if state.Attempts[0].Quote.Snapshot.Source != p.Source || state.Attempts[0].Category != llm.CallRetry {
t.Fatal("provenance lost")
}
state.Attempts[0].Quote.Snapshot.Source = "caller mutation"
state, _ = l.State()
if state.Attempts[0].Quote.Snapshot.Source != p.Source {
t.Fatal("mutable state shared")
}
done, err := l.Admission(priceResolver(&p))(ctx, llm.ChatRequest{Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, Model: p.Model, MaxTokens: 20}, llm.CallCompaction, "summary")
if err != nil {
t.Fatal(err)
}
if err = done(llm.RequestUsage{ID: "summary", Status: "completed", Usage: &llm.Usage{InputTokens: 10, OutputTokens: 5}}); err != nil {
t.Fatal(err)
}
state, _ = l.State()
if state.CommittedNano != 442514 || state.Attempts[1].Status != "reported" {
t.Fatalf("state %+v", state)
}
}
func TestStrictCostBlocksUnknownAndAdvisoryPersistsUncertainty(t *testing.T) {
ctx := context.Background()
l, _ := OpenCostLedger(session.NewSession("a", "cost"))
if err := l.Decide(ctx, "USD", 1000000, true); err != nil {
t.Fatal(err)
}
observed := llm.WithCallAdmission(ctx, l.Admission(priceResolver(nil)))
_, err := llm.ObserveChat(observed, llm.ChatRequest{Model: "m", MaxTokens: 20}, llm.CallGeneration, func(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
t.Fatal("strict unknown price dispatched")
return nil, nil
})
if !errors.Is(err, ErrUnknownPrice) {
t.Fatal(err)
}
if err = l.Decide(ctx, "USD", 1000000, false); err != nil {
t.Fatal(err)
}
done, err := l.Admission(priceResolver(nil))(ctx, llm.ChatRequest{Model: "m", MaxTokens: 20}, llm.CallGeneration, "unknown")
if err != nil {
t.Fatal(err)
}
if err = done(llm.RequestUsage{ID: "unknown", Status: "completed", Usage: &llm.Usage{InputTokens: 10}}); err != nil {
t.Fatal(err)
}
state, _ := l.State()
if state.Unknown != 1 || state.Attempts[0].Quote.Known || state.Attempts[0].Status != "uncertain" {
t.Fatalf("state %+v", state)
}
if err = l.Decide(ctx, "USD", 2000000, true); err == nil {
t.Fatal("unknown historic charge disappeared in strict mode")
}
if err = l.Decide(ctx, "EUR", 2000000, false); err == nil {
t.Fatal("implicit currency conversion accepted")
}
}
func TestCostConcurrentOwnersAndExplicitResume(t *testing.T) {
ctx := context.Background()
s := session.NewSession("a", "cost")
a, _ := OpenCostLedger(s)
b, _ := OpenCostLedger(s)
if err := a.Decide(ctx, "USD", 500000, true); err != nil {
t.Fatal(err)
}
p := currentFixturePrice()
var wg sync.WaitGroup
results := make(chan error, 2)
for i, l := range []*CostLedger{a, b} {
wg.Add(1)
go func(i int, l *CostLedger) {
defer wg.Done()
_, err := l.Admission(priceResolver(&p))(ctx, llm.ChatRequest{Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, Model: p.Model, MaxTokens: 20}, llm.CallRetry, string(rune('a'+i)))
results <- err
}(i, l)
}
wg.Wait()
close(results)
success := 0
for err := range results {
if err == nil {
success++
} else if !errors.Is(err, ErrExhausted) {
t.Fatal(err)
}
}
state, _ := a.State()
if success != 1 || state.CommittedNano != 337507 || !state.Exhausted {
t.Fatalf("state %+v success %d", state, success)
}
if err := a.Decide(ctx, "USD", 1000000, true); err != nil {
t.Fatal(err)
}
state, _ = a.State()
if state.Exhausted || state.CommittedNano != 337507 {
t.Fatal("resume erased charges")
}
}
func TestCostFailedUsageRetainsReservationAndOverrunExhausts(t *testing.T) {
ctx := context.Background()
l, _ := OpenCostLedger(session.NewSession("a", "cost"))
p := currentFixturePrice()
if err := l.Decide(ctx, "USD", 500000, true); err != nil {
t.Fatal(err)
}
done, err := l.Admission(priceResolver(&p))(ctx, llm.ChatRequest{Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, Model: p.Model, MaxTokens: 20}, llm.CallGeneration, "partial")
if err != nil {
t.Fatal(err)
}
if err = done(llm.RequestUsage{ID: "partial", Status: "cancelled", Usage: &llm.Usage{InputTokens: 1}}); err != nil {
t.Fatal(err)
}
state, _ := l.State()
if state.CommittedNano != 337507 {
t.Fatal("partial usage released uncertain cost")
}
if err = l.Decide(ctx, "USD", 1000000, true); err != nil {
t.Fatal(err)
}
done, err = l.Admission(priceResolver(&p))(ctx, llm.ChatRequest{Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, Model: p.Model, MaxTokens: 20}, llm.CallGeneration, "overrun")
if err != nil {
t.Fatal(err)
}
err = done(llm.RequestUsage{ID: "overrun", Status: "completed", Usage: &llm.Usage{OutputTokens: 100}})
if !errors.Is(err, ErrExhausted) {
t.Fatal("overrun did not stop admission")
}
state, _ = l.State()
if state.CommittedNano != 1837514 || !state.Exhausted {
t.Fatalf("state %+v", state)
}
}
func TestCostOversizedSettlementPreservesReadableJournal(t *testing.T) {
ctx := context.Background()
l, _ := OpenCostLedger(session.NewSession("a", "cost"))
p := currentFixturePrice()
p.OutputNanoPerMillion = 1000000000000000
if err := l.Decide(ctx, "USD", 1000000000000, true); err != nil {
t.Fatal(err)
}
done, err := l.Admission(priceResolver(&p))(ctx, llm.ChatRequest{Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, Model: p.Model, MaxTokens: 20}, llm.CallGeneration, "oversized")
if err != nil {
t.Fatal(err)
}
before, _ := l.State()
if err = done(llm.RequestUsage{ID: "oversized", Status: "completed", Usage: &llm.Usage{OutputTokens: 2000000}}); err == nil {
t.Fatal("oversized settlement accepted")
}
after, err := l.State()
if err != nil || after.CommittedNano != before.CommittedNano || after.Attempts[0].Status != "reserved" {
t.Fatalf("journal corrupted: %+v %v", after, err)
}
}
func TestCostAdmissionRejectsSameModelAtDifferentDestination(t *testing.T) {
ctx := context.Background()
l, _ := OpenCostLedger(session.NewSession("a", "route"))
p := currentFixturePrice()
if err := l.Decide(ctx, "USD", 1000000, true); err != nil {
t.Fatal(err)
}
for _, route := range []llm.CallRoute{{}, {Provider: p.Provider, Destination: "http://other.example/v1"}, {Provider: "other", Destination: p.Destination}} {
request := llm.ChatRequest{Route: route, Model: p.Model, MaxTokens: 20}
_, err := llm.ObserveChat(llm.WithCallAdmission(ctx, l.Admission(priceResolver(&p))), request, llm.CallGeneration, func(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
t.Fatal("mismatched tariff dispatched")
return nil, nil
})
if err == nil {
t.Fatal("route mismatch accepted")
}
}
state, err := l.State()
if err != nil || len(state.Attempts) != 0 {
t.Fatalf("mismatch reserved funds: %+v %v", state, err)
}
}
-87
View File
@@ -1,87 +0,0 @@
package budget
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/sausheong/harness/session"
)
var ErrTimeExhausted = fmt.Errorf("session time budget: %w", ErrExhausted)
const deadlineKind = "harness.budget.deadline.v1"
type DeadlineState struct {
Version int `json:"version"`
DecidedAt time.Time `json:"decided_at"`
Deadline time.Time `json:"deadline"`
}
// DecideDeadline starts a new explicitly approved wall-clock allowance. Idle
// time counts, and restarting does not reset the deadline. No prior cost/token
// charges are changed. There is deliberately no implicit disable or renewal.
func DecideDeadline(ctx context.Context, s *session.Session, allowance time.Duration) error {
return decideDeadline(ctx, s, deadlineKind, allowance)
}
func decideDeadline(ctx context.Context, s *session.Session, kind string, allowance time.Duration) error {
if err := ctx.Err(); err != nil {
return err
}
if s == nil || allowance <= 0 || allowance > 30*24*time.Hour {
return errors.New("time allowance must be positive and at most 30 days")
}
now := time.Now().UTC()
raw, err := json.Marshal(DeadlineState{Version: 1, DecidedAt: now, Deadline: now.Add(allowance)})
if err != nil {
return err
}
return s.Annotate(kind, raw)
}
func ReadDeadline(s *session.Session) (DeadlineState, error) {
return readDeadline(s, deadlineKind)
}
func readDeadline(s *session.Session, kind string) (DeadlineState, error) {
var state DeadlineState
if s == nil {
return state, nil
}
records := s.Annotations(kind)
if len(records) == 0 {
return state, nil
}
if err := decodeBudgetJSON(records[len(records)-1].Payload, &state); err != nil {
return state, err
}
if state.Version != 1 || state.DecidedAt.IsZero() || !state.Deadline.After(state.DecidedAt) || state.Deadline.Sub(state.DecidedAt) > 30*24*time.Hour {
return state, errors.New("invalid session time budget record")
}
return state, nil
}
// WithDeadline binds owned work to the stored session deadline. The caller must
// cancel after all child work joins. Expired sessions fail before dispatch;
// active work is cancelled with ErrTimeExhausted as its context cause.
func WithDeadline(ctx context.Context, s *session.Session) (context.Context, context.CancelFunc, error) {
return withDeadline(ctx, s, deadlineKind, ErrTimeExhausted)
}
func withDeadline(ctx context.Context, s *session.Session, kind string, cause error) (context.Context, context.CancelFunc, error) {
noop := func() {}
state, err := readDeadline(s, kind)
if err != nil {
return ctx, noop, err
}
if state.Version == 0 {
return ctx, noop, nil
}
if err := ctx.Err(); err != nil {
return ctx, noop, err
}
if !time.Now().Before(state.Deadline) {
return ctx, noop, cause
}
child, cancel := context.WithDeadlineCause(ctx, state.Deadline, cause)
return child, cancel, nil
}
-89
View File
@@ -1,89 +0,0 @@
package budget
import (
"context"
"errors"
"github.com/sausheong/harness/session"
"testing"
"time"
)
func TestDeadlineExpiresAcrossRestartAndExplicitResume(t *testing.T) {
ctx := context.Background()
store := session.NewStore(t.TempDir())
if err := store.Create("a", "time"); err != nil {
t.Fatal(err)
}
s, err := store.LoadExclusive("a", "time")
if err != nil {
t.Fatal(err)
}
if err = DecideDeadline(ctx, s, time.Second); err != nil {
t.Fatal(err)
}
bound, cancel, err := WithDeadline(ctx, s)
if err != nil {
t.Fatal(err)
}
defer cancel()
select {
case <-bound.Done():
case <-time.After(3 * time.Second):
t.Fatal("deadline did not cancel")
}
if !errors.Is(context.Cause(bound), ErrTimeExhausted) {
t.Fatal(context.Cause(bound))
}
before, err := ReadDeadline(s)
if err != nil {
t.Fatal(err)
}
if err = s.Close(); err != nil {
t.Fatal(err)
}
s, err = store.LoadExclusive("a", "time")
if err != nil {
t.Fatal(err)
}
defer s.Close()
after, err := ReadDeadline(s)
if err != nil || !after.Deadline.Equal(before.Deadline) {
t.Fatal("restart reset deadline")
}
_, cleanup, err := WithDeadline(ctx, s)
cleanup()
if !errors.Is(err, ErrTimeExhausted) {
t.Fatal("expired restart accepted")
}
if err = DecideDeadline(ctx, s, time.Hour); err != nil {
t.Fatal(err)
}
resumed, cleanup, err := WithDeadline(ctx, s)
defer cleanup()
if err != nil || resumed.Err() != nil {
t.Fatal("explicit resume failed")
}
}
func TestDeadlineValidationAndParentCancellation(t *testing.T) {
s := session.NewSession("a", "time")
ctx := context.Background()
for _, d := range []time.Duration{0, -1, 31 * 24 * time.Hour} {
if err := DecideDeadline(ctx, s, d); err == nil {
t.Fatal("invalid allowance accepted")
}
}
if err := DecideDeadline(ctx, s, time.Hour); err != nil {
t.Fatal(err)
}
parent, cancel := context.WithCancel(ctx)
bound, cleanup, err := WithDeadline(parent, s)
if err != nil {
t.Fatal(err)
}
defer cleanup()
cancel()
<-bound.Done()
if !errors.Is(context.Cause(bound), context.Canceled) || errors.Is(context.Cause(bound), ErrTimeExhausted) {
t.Fatal("user cancellation relabelled as budget exhaustion")
}
}
-135
View File
@@ -1,135 +0,0 @@
package budget
import (
"bytes"
"encoding/json"
"errors"
"io"
"reflect"
"strings"
"time"
"unicode/utf8"
)
// All version-1 budget schema names are lowercase. Validate the complete JSON
// structure before typed decoding can accept aliases, duplicates or null scalar
// values. The existing typed decoder still enforces the per-object field set.
func decodeBudgetJSON(raw json.RawMessage, destination any) error {
trimmed := bytes.TrimSpace(raw)
if !utf8.Valid(raw) || len(trimmed) == 0 || trimmed[0] != '{' {
return errors.New("budget record requires a UTF-8 object")
}
scanner := json.NewDecoder(bytes.NewReader(raw))
if err := scanBudgetJSON(scanner, "", 0); err != nil {
return err
}
if scanner.Decode(new(any)) != io.EOF {
return errors.New("trailing budget JSON")
}
if err := requireBudgetFields(raw, reflect.TypeOf(destination)); err != nil {
return err
}
d := json.NewDecoder(bytes.NewReader(raw))
d.DisallowUnknownFields()
return d.Decode(destination)
}
func scanBudgetJSON(d *json.Decoder, field string, depth int) error {
if depth > 16 {
return errors.New("budget JSON nesting exceeds schema limit")
}
token, err := d.Token()
if err != nil {
return err
}
if token == nil && field != "snapshot" && field != "attempt" {
return errors.New("budget scalar field cannot be null")
}
delimiter, compound := token.(json.Delim)
if !compound {
return nil
}
switch delimiter {
case '{':
seen := map[string]bool{}
for d.More() {
token, err := d.Token()
if err != nil {
return err
}
key, ok := token.(string)
if !ok || key != strings.ToLower(key) || seen[key] {
return errors.New("duplicate or noncanonical budget field")
}
seen[key] = true
if err := scanBudgetJSON(d, key, depth+1); err != nil {
return err
}
}
if token, err := d.Token(); err != nil || token != json.Delim('}') {
return errors.New("invalid budget object")
}
case '[':
for d.More() {
if err := scanBudgetJSON(d, "", depth+1); err != nil {
return err
}
}
if token, err := d.Token(); err != nil || token != json.Delim(']') {
return errors.New("invalid budget array")
}
default:
return errors.New("unexpected budget delimiter")
}
return nil
}
// The on-disk contract matches the writer: fields without omitempty must be
// present even when their value is zero. This keeps omitted settlement charges
// or price counters from being silently manufactured by typed unmarshalling.
func requireBudgetFields(raw json.RawMessage, typ reflect.Type) error {
if typ == nil {
return errors.New("budget destination type missing")
}
for typ.Kind() == reflect.Pointer {
typ = typ.Elem()
}
if typ.Kind() != reflect.Struct || typ == reflect.TypeOf(time.Time{}) || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
return nil
}
var fields map[string]json.RawMessage
if err := json.Unmarshal(raw, &fields); err != nil {
return err
}
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
if field.PkgPath != "" {
continue
}
tag := strings.Split(field.Tag.Get("json"), ",")
name := tag[0]
if name == "-" {
continue
}
if name == "" {
name = field.Name
}
optional := false
for _, option := range tag[1:] {
if option == "omitempty" {
optional = true
}
}
value, exists := fields[name]
if !exists {
if optional {
continue
}
return errors.New("missing required budget field: " + name)
}
if err := requireBudgetFields(value, field.Type); err != nil {
return err
}
}
return nil
}
-46
View File
@@ -1,46 +0,0 @@
package budget
import (
"bytes"
"encoding/json"
"testing"
)
func FuzzBudgetRecordJSON(f *testing.F) {
f.Add(byte(0), []byte(`{"version":1,"kind":"limit","tokens":100}`))
f.Add(byte(0), []byte(`{"version":1,"kind":"settle","id":"one","status":"reported","tokens":0}`))
f.Add(byte(0), []byte(`{"version":1,"kind":"limit","tokens":1,"to\u006bens":1000}`))
f.Add(byte(1), []byte(`{"version":1,"kind":"decision","currency":"USD","limit_nano":100,"strict":true}`))
f.Add(byte(2), []byte(`{"version":1,"decided_at":"2026-09-09T00:00:00Z","deadline":"2026-09-09T01:00:00Z"}`))
f.Add(byte(2), []byte(`{"version":1,"decided_at":"2026-09-09T00:00:00+00:00","deadline":"2026-09-09T01:00:00+00:00"}`))
f.Fuzz(func(t *testing.T, kind byte, raw []byte) {
if len(raw) > 128<<10 {
return
}
var first, second any
switch kind % 3 {
case 0:
first, second = new(tokenEvent), new(tokenEvent)
case 1:
first, second = new(costEvent), new(costEvent)
default:
first, second = new(DeadlineState), new(DeadlineState)
}
if err := decodeBudgetJSON(raw, first); err != nil {
return
}
canonical, err := json.Marshal(first)
if err != nil {
t.Fatal(err)
}
if err := decodeBudgetJSON(canonical, second); err != nil {
t.Fatalf("accepted record cannot round trip: %v", err)
}
// Compare persisted semantics, not time.Time's internal Location
// pointer, which may normalise a zero offset to UTC on encoding.
repeated, err := json.Marshal(second)
if err != nil || !bytes.Equal(canonical, repeated) {
t.Fatal("canonical round trip changed budget record", err)
}
})
}
-247
View File
@@ -1,247 +0,0 @@
package budget
import (
"bytes"
"context"
"encoding/json"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
func TestBudgetJSONAmbiguityRefusesReopenedAdmission(t *testing.T) {
cases := []struct{ name, kind, payload string }{
{"token-duplicate", tokenKind, `{"version":1,"kind":"limit","tokens":1,"tokens":1000}`},
{"token-escaped", tokenKind, `{"version":1,"kind":"limit","tokens":1,"to\u006bens":1000}`},
{"token-alias", tokenKind, `{"version":1,"kind":"limit","tokens":1,"TOKENS":1000}`},
{"cost-duplicate", costKind, `{"version":1,"kind":"decision","currency":"USD","limit_nano":1,"limit_nano":1000}`},
{"cost-alias", costKind, `{"version":1,"kind":"decision","currency":"USD","limit_nano":1,"LIMIT_NANO":1000}`},
{"cost-null-strict", costKind, `{"version":1,"kind":"decision","currency":"USD","limit_nano":1000,"strict":null}`},
{"deadline-duplicate", deadlineKind, `{"version":1,"decided_at":"2026-09-09T00:00:00Z","deadline":"2026-09-09T00:00:01Z","deadline":"2026-09-10T00:00:00Z"}`},
{"deadline-alias", deadlineKind, `{"version":1,"decided_at":"2026-09-09T00:00:00Z","deadline":"2026-09-09T00:00:01Z","DEADLINE":"2026-09-10T00:00:00Z"}`},
}
for _, tc := range cases {
for _, run := range []bool{false, true} {
name := tc.name
if run {
name += "-run"
}
t.Run(name, func(t *testing.T) {
kind := tc.kind
if run {
var err error
kind, err = runKind(kind, "logical")
if err != nil {
t.Fatal(err)
}
}
root := t.TempDir()
store := session.NewStore(root)
sess, err := store.LoadExclusive("hand", "key")
if err != nil {
t.Fatal(err)
}
if err := sess.Annotate(kind, json.RawMessage(tc.payload)); err != nil {
t.Fatal(err)
}
if err := sess.Close(); err != nil {
t.Fatal(err)
}
path := filepath.Join(root, "hand", "key.jsonl")
before, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
sess, err = store.LoadExclusive("hand", "key")
if err != nil {
t.Fatal(err)
}
defer sess.Close()
switch tc.kind {
case tokenKind:
ledger, err := openTokenLedger(sess, kind)
if err == nil {
t.Fatal("ambiguous token ceiling accepted")
}
if finish, err := ledger.Admission(func(llm.ChatRequest) (int64, error) { return 1, nil })(context.Background(), llm.ChatRequest{Model: "m", MaxTokens: 2}, llm.CallGeneration, "attempt"); err == nil || finish != nil {
t.Fatal("admitted corrupt token state")
}
case costKind:
ledger, err := openCostLedger(sess, kind)
if err == nil {
t.Fatal("ambiguous cost ceiling accepted")
}
if err := ledger.Decide(context.Background(), "USD", 2000, false); err == nil {
t.Fatal("appended over corrupt cost state")
}
case deadlineKind:
if _, err := readDeadline(sess, kind); err == nil {
t.Fatal("ambiguous deadline accepted")
}
}
if err := sess.Close(); err != nil {
t.Fatal(err)
}
after, err := os.ReadFile(path)
if err != nil || !bytes.Equal(before, after) {
t.Fatal("corrupt budget changed", err)
}
})
}
}
}
func TestBudgetNestedQuoteIntegrity(t *testing.T) {
price := currentFixturePrice()
event := costEvent{Version: 1, Kind: "reserve", Attempt: &CostAttempt{ID: "one", Model: price.Model, Category: llm.CallGeneration, Quote: PriceQuote{Known: true, Nano: 1, Currency: "USD", Snapshot: &price}, ChargedNano: 1, Status: "reserved"}}
raw, err := json.Marshal(event)
if err != nil {
t.Fatal(err)
}
for _, name := range []string{"valid", "duplicate-price", "alias-price", "null-price", "duplicate-quote"} {
t.Run(name, func(t *testing.T) {
payload := string(raw)
switch name {
case "duplicate-price":
payload = strings.Replace(payload, `"fixed_nano":`, `"fixed_nano":999,"fixed_nano":`, 1)
case "alias-price":
payload = strings.Replace(payload, `"fixed_nano":`, `"FIXED_NANO":999,"fixed_nano":`, 1)
case "null-price":
payload = strings.Replace(payload, `"fixed_nano":`+strconv.FormatInt(price.FixedNano, 10), `"fixed_nano":null`, 1)
case "duplicate-quote":
payload = strings.Replace(payload, `"nano":1`, `"nano":999,"nano":1`, 1)
}
sess := session.NewSession("a", "nested")
ledger, err := OpenCostLedger(sess)
if err != nil {
t.Fatal(err)
}
if err := ledger.Decide(context.Background(), "USD", 1000000, true); err != nil {
t.Fatal(err)
}
if err := sess.Annotate(costKind, json.RawMessage(payload)); err != nil {
t.Fatal(err)
}
state, err := ledger.State()
if name == "valid" {
if err != nil || state.CommittedNano != 1 {
t.Fatalf("valid nested record failed: %+v %v", state, err)
}
} else if err == nil {
t.Fatal("ambiguous nested price accepted")
}
})
}
}
func TestMissingTokenSettlementChargeDoesNotReleaseReservation(t *testing.T) {
root := t.TempDir()
store := session.NewStore(root)
sess, err := store.LoadExclusive("a", "key")
if err != nil {
t.Fatal(err)
}
ledger, err := OpenTokenLedger(sess)
if err != nil {
t.Fatal(err)
}
if err := ledger.Decide(context.Background(), 100); err != nil {
t.Fatal(err)
}
if _, err := ledger.Admission(func(llm.ChatRequest) (int64, error) { return 10, nil })(context.Background(), llm.ChatRequest{Model: "m", MaxTokens: 10}, llm.CallGeneration, "one"); err != nil {
t.Fatal(err)
}
if err := sess.Annotate(tokenKind, json.RawMessage(`{"version":1,"kind":"settle","id":"one","status":"reported"}`)); err != nil {
t.Fatal(err)
}
if err := sess.Close(); err != nil {
t.Fatal(err)
}
path := filepath.Join(root, "a", "key.jsonl")
before, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
sess, err = store.LoadExclusive("a", "key")
if err != nil {
t.Fatal(err)
}
defer sess.Close()
ledger, err = OpenTokenLedger(sess)
if err == nil {
state, _ := ledger.State()
t.Fatalf("missing charge released reserved tokens: %+v", state)
}
if finish, err := ledger.Admission(func(llm.ChatRequest) (int64, error) { return 1, nil })(context.Background(), llm.ChatRequest{Model: "m", MaxTokens: 1}, llm.CallGeneration, "next"); err == nil || finish != nil {
t.Fatal("corrupt settlement admitted request")
}
if err := sess.Close(); err != nil {
t.Fatal(err)
}
after, err := os.ReadFile(path)
if err != nil || !bytes.Equal(before, after) {
t.Fatal("corrupt journal changed", err)
}
}
func TestBudgetRequiredNestedFieldsAndExplicitZero(t *testing.T) {
price := currentFixturePrice()
event := costEvent{Version: 1, Kind: "reserve", Attempt: &CostAttempt{ID: "one", Model: price.Model, Category: llm.CallGeneration, Quote: PriceQuote{Known: true, Nano: 0, Currency: "USD", Snapshot: &price}, ChargedNano: 0, Status: "reserved"}}
raw, err := json.Marshal(event)
if err != nil {
t.Fatal(err)
}
for _, path := range [][]string{
{"attempt", "charged_nano"},
{"attempt", "quote", "nano"},
{"attempt", "quote", "known"},
{"attempt", "quote", "snapshot", "fixed_nano"},
{"attempt", "quote", "snapshot", "input_nano_per_million"},
{"attempt", "quote", "snapshot", "all_charges_bounded"},
} {
t.Run(strings.Join(path, "/"), func(t *testing.T) {
var object map[string]any
if err := json.Unmarshal(raw, &object); err != nil {
t.Fatal(err)
}
current := object
for _, key := range path[:len(path)-1] {
current = current[key].(map[string]any)
}
delete(current, path[len(path)-1])
corrupted, err := json.Marshal(object)
if err != nil {
t.Fatal(err)
}
var decoded costEvent
if err := decodeBudgetJSON(corrupted, &decoded); err == nil {
t.Fatal("missing required pricing field accepted")
}
})
}
// Explicit zero is still meaningful; optional false/empty fields emitted
// with omitempty remain compatible with the existing writer contract.
for _, value := range []any{event, costEvent{Version: 1, Kind: "decision", Currency: "USD", LimitNano: 100}, tokenEvent{Version: 1, Kind: "settle", ID: "one", Status: "reported", Tokens: 0}} {
encoded, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
switch value.(type) {
case costEvent:
var decoded costEvent
if err := decodeBudgetJSON(encoded, &decoded); err != nil {
t.Fatal("writer output rejected", err)
}
case tokenEvent:
var decoded tokenEvent
if err := decodeBudgetJSON(encoded, &decoded); err != nil {
t.Fatal("explicit zero rejected", err)
}
}
}
}
-159
View File
@@ -1,159 +0,0 @@
package budget
import (
"errors"
"fmt"
"math/big"
"strings"
"time"
"unicode/utf8"
"github.com/sausheong/harness/llm"
)
var ErrUnknownPrice = errors.New("request price is unknown or unbounded")
// PriceSnapshot is an immutable, caller-reviewed tariff for a specific route.
// Rates are billionths of Currency per million tokens; FixedNano is charged
// once per provider attempt. No implicit currency conversion is performed.
// AllChargesBounded must be false when tool, reasoning, image, tiered-cache or
// other provider charges are not fully represented by these counters/rates.
// Input, cache creation and cache read counters must be disjoint subsets of
// total input under the provider adapter's usage contract.
type PriceSnapshot struct {
Provider string `json:"provider"`
Model string `json:"model"`
Destination string `json:"destination"`
Currency string `json:"currency"`
Source string `json:"source"`
Version string `json:"version"`
EffectiveAt time.Time `json:"effective_at"`
ExpiresAt time.Time `json:"expires_at"`
InputNanoPerMillion int64 `json:"input_nano_per_million"`
OutputNanoPerMillion int64 `json:"output_nano_per_million"`
CacheWriteNanoPerMillion int64 `json:"cache_write_nano_per_million"`
CacheReadNanoPerMillion int64 `json:"cache_read_nano_per_million"`
FixedNano int64 `json:"fixed_nano"`
AllChargesBounded bool `json:"all_charges_bounded"`
}
func (p PriceSnapshot) Validate() error {
for _, s := range []string{p.Provider, p.Model, p.Destination, p.Source, p.Version} {
if strings.TrimSpace(s) == "" || len(s) > 2048 || !utf8.ValidString(s) || strings.ContainsAny(s, "\x00\r\n") {
return errors.New("pricing requires bounded route, source and version metadata")
}
}
if len(p.Currency) != 3 || strings.IndexFunc(p.Currency, func(r rune) bool { return r < 'A' || r > 'Z' }) >= 0 {
return errors.New("pricing currency requires three uppercase letters")
}
if p.EffectiveAt.IsZero() || p.ExpiresAt.IsZero() || !p.ExpiresAt.After(p.EffectiveAt) {
return errors.New("pricing requires an explicit validity interval")
}
for _, rate := range []int64{p.InputNanoPerMillion, p.OutputNanoPerMillion, p.CacheWriteNanoPerMillion, p.CacheReadNanoPerMillion, p.FixedNano} {
if rate < 0 {
return errors.New("negative price")
}
}
return nil
}
// PriceQuote separates a known amount from unknown cost. Nano must never be
// interpreted as a free request when Known is false. Snapshot is copied into
// the quote for durable request accounting by the caller.
type PriceQuote struct {
Known bool `json:"known"`
Nano int64 `json:"nano"`
Currency string `json:"currency,omitempty"`
Reason string `json:"reason,omitempty"`
Snapshot *PriceSnapshot `json:"snapshot,omitempty"`
}
// ReservePrice prices an estimated input bound plus a finite output cap. The
// maximum input/cache rate prevents optimistic cache-hit assumptions. Strict
// mode refuses missing, expired or unbounded pricing. Advisory mode returns an
// explicitly unknown quote. Invalid metadata/negative values always fail.
func ReservePrice(p *PriceSnapshot, input, output int64, now time.Time, strict bool) (PriceQuote, error) {
if input < 0 || output <= 0 {
return PriceQuote{}, errors.New("reservation requires nonnegative input and a positive output cap")
}
unknown := func(reason string) (PriceQuote, error) {
q := PriceQuote{Reason: reason}
if p != nil {
copy := *p
q.Snapshot = &copy
q.Currency = p.Currency
}
if strict {
return q, fmt.Errorf("%w: %s", ErrUnknownPrice, reason)
}
return q, nil
}
if p == nil {
return unknown("no route price supplied")
}
if err := p.Validate(); err != nil {
return PriceQuote{}, err
}
if now.IsZero() || now.Before(p.EffectiveAt) || !now.Before(p.ExpiresAt) {
return unknown("price is outside its validity interval")
}
if !p.AllChargesBounded {
return unknown("tariff does not bound all provider charges")
}
rate := max(p.InputNanoPerMillion, p.CacheWriteNanoPerMillion, p.CacheReadNanoPerMillion)
amount, err := priceSum(p.FixedNano, [][2]int64{{input, rate}, {output, p.OutputNanoPerMillion}})
if err != nil {
return PriceQuote{}, err
}
copy := *p
return PriceQuote{Known: true, Nano: amount, Currency: p.Currency, Snapshot: &copy}, nil
}
// ReportedPrice uses the admission-time snapshot, even if its validity interval
// has since expired. Nil usage remains unknown. Cache tokens are subsets of
// InputTokens, not extra input charges. Invalid/inconsistent counters fail so
// callers retain their conservative reservation instead of undercharging.
func ReportedPrice(p PriceSnapshot, u *llm.Usage) (PriceQuote, error) {
if err := p.Validate(); err != nil {
return PriceQuote{}, err
}
q := PriceQuote{Currency: p.Currency, Snapshot: &p}
if u == nil {
q.Reason = "provider usage unavailable"
return q, nil
}
if !p.AllChargesBounded {
q.Reason = "tariff does not bound all provider charges"
return q, nil
}
input, output, write, read := int64(u.InputTokens), int64(u.OutputTokens), int64(u.CacheCreationInputTokens), int64(u.CacheReadInputTokens)
if input < 0 || output < 0 || write < 0 || read < 0 || write > input || read > input-write {
return q, errors.New("inconsistent provider token counters")
}
amount, err := priceSum(p.FixedNano, [][2]int64{{input - write - read, p.InputNanoPerMillion}, {write, p.CacheWriteNanoPerMillion}, {read, p.CacheReadNanoPerMillion}, {output, p.OutputNanoPerMillion}})
if err != nil {
return q, err
}
q.Known = true
q.Nano = amount
return q, nil
}
// Integer accumulation rounds the final token charge up once to a nano-unit.
// big.Int avoids multiplication overflow before checking the representable sum.
func priceSum(fixed int64, terms [][2]int64) (int64, error) {
total := new(big.Int)
for _, term := range terms {
if term[0] < 0 || term[1] < 0 || fixed < 0 {
return 0, errors.New("negative pricing operand")
}
total.Add(total, new(big.Int).Mul(big.NewInt(term[0]), big.NewInt(term[1])))
}
total.Add(total, big.NewInt(999999))
total.Quo(total, big.NewInt(1000000))
total.Add(total, big.NewInt(fixed))
if !total.IsInt64() {
return 0, errors.New("request price exceeds representable amount")
}
return total.Int64(), nil
}
-94
View File
@@ -1,94 +0,0 @@
package budget
import (
"errors"
"github.com/sausheong/harness/llm"
"math"
"testing"
"time"
)
func fixturePrice() PriceSnapshot {
return PriceSnapshot{Provider: "fixture", Model: "scripted", Destination: "http://127.0.0.1/v1", Currency: "USD", Source: "test fixture, not a market tariff", Version: "fixture-1", EffectiveAt: time.Unix(1000, 0), ExpiresAt: time.Unix(2000, 0), InputNanoPerMillion: 3000000000, OutputNanoPerMillion: 15000000000, CacheWriteNanoPerMillion: 3750000000, CacheReadNanoPerMillion: 300000000, FixedNano: 7, AllChargesBounded: true}
}
func TestPriceReservationAndCacheReconciliation(t *testing.T) {
p := fixturePrice()
q, err := ReservePrice(&p, 100, 20, time.Unix(1500, 0), true)
if err != nil || !q.Known || q.Nano != 675007 || q.Currency != "USD" {
t.Fatalf("quote %+v err %v", q, err)
}
actual, err := ReportedPrice(p, &llm.Usage{InputTokens: 100, OutputTokens: 20, CacheCreationInputTokens: 20, CacheReadInputTokens: 30})
// 50 regular + 20 cache write + 30 cache read; no double-counted cache.
if err != nil || actual.Nano != 534007 || !actual.Known {
t.Fatalf("actual %+v err %v", actual, err)
}
p.Source = "changed"
if q.Snapshot.Source == p.Source {
t.Fatal("quote retained caller-owned snapshot")
}
}
func TestUnknownPricesAreNotFree(t *testing.T) {
for _, name := range []string{"missing", "expired", "future", "unbounded"} {
t.Run(name, func(t *testing.T) {
p := fixturePrice()
ptr := &p
now := time.Unix(1500, 0)
switch name {
case "missing":
ptr = nil
case "expired":
now = p.ExpiresAt
case "future":
now = p.EffectiveAt.Add(-time.Second)
case "unbounded":
p.AllChargesBounded = false
}
advisory, err := ReservePrice(ptr, 1, 1, now, false)
if err != nil || advisory.Known || advisory.Reason == "" {
t.Fatalf("advisory %+v %v", advisory, err)
}
strict, err := ReservePrice(ptr, 1, 1, now, true)
if !errors.Is(err, ErrUnknownPrice) || strict.Known {
t.Fatalf("strict %+v %v", strict, err)
}
})
}
p := fixturePrice()
q, err := ReportedPrice(p, nil)
if err != nil || q.Known || q.Reason == "" {
t.Fatal("missing usage charged as free")
}
}
func TestPricingRefusesInvalidCountersAndOverflow(t *testing.T) {
p := fixturePrice()
for _, u := range []llm.Usage{{InputTokens: -1}, {OutputTokens: -1}, {InputTokens: 10, CacheCreationInputTokens: 8, CacheReadInputTokens: 3}, {InputTokens: 10, CacheReadInputTokens: -1}} {
if _, err := ReportedPrice(p, &u); err == nil {
t.Fatalf("accepted %+v", u)
}
}
p.OutputNanoPerMillion = math.MaxInt64
if _, err := ReservePrice(&p, 0, math.MaxInt64, time.Unix(1500, 0), true); err == nil {
t.Fatal("overflow accepted")
}
p = fixturePrice()
p.InputNanoPerMillion = -1
if _, err := ReservePrice(&p, 1, 1, time.Unix(1500, 0), false); err == nil {
t.Fatal("advisory accepted negative tariff")
}
}
func TestPriceRoundingAndExplicitZeroTariff(t *testing.T) {
amount, err := priceSum(0, [][2]int64{{1, 1}, {1, 1}})
if err != nil || amount != 1 {
t.Fatalf("rounding %d %v", amount, err)
}
p := fixturePrice()
p.InputNanoPerMillion = 0
p.OutputNanoPerMillion = 0
p.CacheReadNanoPerMillion = 0
p.CacheWriteNanoPerMillion = 0
p.FixedNano = 0
q, err := ReservePrice(&p, 10, 10, time.Unix(1500, 0), true)
if err != nil || !q.Known || q.Nano != 0 {
t.Fatalf("explicit free tariff %+v %v", q, err)
}
}
-64
View File
@@ -1,64 +0,0 @@
package budget
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/sausheong/harness/session"
)
var ErrRunTimeExhausted = fmt.Errorf("run time budget: %w", ErrExhausted)
// Run IDs are stable logical-operation identities, not process-local counters.
// Reusing an ID reopens its existing charges and deadline. A caller must bind
// the same ID to retries, summaries, continuation and recovery of that run.
func runKind(base, id string) (string, error) {
if len(id) == 0 || len(id) > 64 || strings.IndexFunc(id, func(r rune) bool {
return !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_' || r == '-')
}) >= 0 {
return "", errors.New("run budget ID must contain 1-64 ASCII letters, digits, underscores or hyphens")
}
return base + ".run." + id, nil
}
// OpenRunTokenLedger opens a durable per-run ledger. Attach its admission guard
// alongside the session guard; opening this ledger does not replace either
// scope or grant a new allowance.
func OpenRunTokenLedger(s *session.Session, id string) (*TokenLedger, error) {
kind, err := runKind(tokenKind, id)
if err != nil {
return nil, err
}
return openTokenLedger(s, kind)
}
func OpenRunCostLedger(s *session.Session, id string) (*CostLedger, error) {
kind, err := runKind(costKind, id)
if err != nil {
return nil, err
}
return openCostLedger(s, kind)
}
func DecideRunDeadline(ctx context.Context, s *session.Session, id string, allowance time.Duration) error {
kind, err := runKind(deadlineKind, id)
if err != nil {
return err
}
return decideDeadline(ctx, s, kind, allowance)
}
func ReadRunDeadline(s *session.Session, id string) (DeadlineState, error) {
kind, err := runKind(deadlineKind, id)
if err != nil {
return DeadlineState{}, err
}
return readDeadline(s, kind)
}
func WithRunDeadline(ctx context.Context, s *session.Session, id string) (context.Context, context.CancelFunc, error) {
kind, err := runKind(deadlineKind, id)
if err != nil {
return ctx, func() {}, err
}
return withDeadline(ctx, s, kind, ErrRunTimeExhausted)
}
-206
View File
@@ -1,206 +0,0 @@
package budget
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
func TestRunLedgersComposeWithSessionAndSurviveRestart(t *testing.T) {
ctx := context.Background()
store := session.NewStore(t.TempDir())
if err := store.Create("a", "runs"); err != nil {
t.Fatal(err)
}
s, err := store.LoadExclusive("a", "runs")
if err != nil {
t.Fatal(err)
}
defer func() {
if s != nil {
s.Close()
}
}()
total, _ := OpenTokenLedger(s)
run, _ := OpenRunTokenLedger(s, "job-1")
if err = total.Decide(ctx, 100); err != nil {
t.Fatal(err)
}
if err = run.Decide(ctx, 1); err != nil {
t.Fatal(err)
}
guarded := llm.WithCallAdmission(llm.WithCallAdmission(ctx, total.Admission(estimate)), run.Admission(estimate))
calls := 0
provider := func(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
calls++
out := make(chan llm.ChatEvent, 1)
out <- llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 8, OutputTokens: 2}}
close(out)
return out, nil
}
req := llm.ChatRequest{Model: "m", MaxTokens: 20}
if _, err = llm.ObserveChat(guarded, req, llm.CallGeneration, provider); !errors.Is(err, ErrExhausted) {
t.Fatal(err)
}
state, err := total.State()
if err != nil || state.Committed != 0 || calls != 0 {
t.Fatalf("denied run charged session: %+v %v calls=%d", state, err, calls)
}
if err = run.Decide(ctx, 80); err != nil {
t.Fatal(err)
}
for _, category := range []llm.CallCategory{llm.CallGeneration, llm.CallRetry, llm.CallCompaction} {
events, e := llm.ObserveChat(guarded, req, category, provider)
if e != nil {
t.Fatal(e)
}
for ev := range events {
if ev.Error != nil {
t.Fatal(ev.Error)
}
}
}
if err = s.Close(); err != nil {
t.Fatal(err)
}
s = nil
s, err = store.LoadExclusive("a", "runs")
if err != nil {
t.Fatal(err)
}
total, _ = OpenTokenLedger(s)
run, _ = OpenRunTokenLedger(s, "job-1")
other, _ := OpenRunTokenLedger(s, "job-2")
for _, l := range []*TokenLedger{total, run} {
state, e := l.State()
if e != nil || state.Committed != 30 {
t.Fatalf("lost charge: %+v %v", state, e)
}
}
untouched, e := other.State()
if e != nil || untouched.Limit != 0 || untouched.Committed != 0 {
t.Fatalf("scope collision: %+v %v", untouched, e)
}
}
func TestRunCostAndDeadlinePersistWithoutSessionReset(t *testing.T) {
ctx := context.Background()
store := session.NewStore(t.TempDir())
if err := store.Create("a", "run-cost"); err != nil {
t.Fatal(err)
}
s, err := store.LoadExclusive("a", "run-cost")
if err != nil {
t.Fatal(err)
}
defer func() {
if s != nil {
s.Close()
}
}()
run, _ := OpenRunCostLedger(s, "operation")
if err = run.Decide(ctx, "USD", 1000000, true); err != nil {
t.Fatal(err)
}
p := currentFixturePrice()
req := llm.ChatRequest{Model: p.Model, Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, MaxTokens: 20}
// An interrupted attempt remains reserved under the same run after reopen.
if _, err = run.Admission(priceResolver(&p))(ctx, req, llm.CallRetry, "attempt"); err != nil {
t.Fatal(err)
}
if err = DecideRunDeadline(ctx, s, "operation", time.Hour); err != nil {
t.Fatal(err)
}
before, err := ReadRunDeadline(s, "operation")
if err != nil {
t.Fatal(err)
}
if err = s.Close(); err != nil {
t.Fatal(err)
}
s = nil
s, err = store.LoadExclusive("a", "run-cost")
if err != nil {
t.Fatal(err)
}
run, _ = OpenRunCostLedger(s, "operation")
state, err := run.State()
if err != nil || state.CommittedNano != 337507 || state.Attempts[0].Status != "reserved" {
t.Fatalf("lost run cost: %+v %v", state, err)
}
after, err := ReadRunDeadline(s, "operation")
if err != nil || !after.Deadline.Equal(before.Deadline) {
t.Fatalf("deadline renewed: %+v %v", after, err)
}
sessionCost, _ := OpenCostLedger(s)
total, err := sessionCost.State()
if err != nil || total.CommittedNano != 0 || total.LimitNano != 0 {
t.Fatalf("scope contaminated session: %+v %v", total, err)
}
sessionDeadline, err := ReadDeadline(s)
if err != nil || sessionDeadline.Version != 0 {
t.Fatal("run set session deadline")
}
parent, cancel := context.WithCancel(ctx)
child, stop, err := WithRunDeadline(parent, s, "operation")
if err != nil {
t.Fatal(err)
}
defer stop()
cancel()
<-child.Done()
if !errors.Is(context.Cause(child), context.Canceled) {
t.Fatal("parent cancellation lost")
}
}
func TestRunBudgetIDsRejectAmbiguousNamespaces(t *testing.T) {
s := session.NewSession("a", "ids")
for _, id := range []string{"", "x.y", "../session", "with space", "a/b", strings.Repeat("a", 65), "日本"} {
if _, err := OpenRunTokenLedger(s, id); err == nil {
t.Fatalf("accepted %q", id)
}
if _, err := OpenRunCostLedger(s, id); err == nil {
t.Fatalf("accepted %q", id)
}
if err := DecideRunDeadline(context.Background(), s, id, time.Hour); err == nil {
t.Fatalf("accepted %q", id)
}
}
}
func TestRunDeadlineExpiryDoesNotRenewOnRebind(t *testing.T) {
s := session.NewSession("a", "expiry")
ctx := context.Background()
if err := DecideRunDeadline(ctx, s, "run", 20*time.Millisecond); err != nil {
t.Fatal(err)
}
child, cancel, err := WithRunDeadline(ctx, s, "run")
if err != nil {
t.Fatal(err)
}
defer cancel()
select {
case <-child.Done():
case <-time.After(time.Second):
t.Fatal("run deadline did not expire")
}
if !errors.Is(context.Cause(child), ErrRunTimeExhausted) {
t.Fatal(context.Cause(child))
}
if _, stop, err := WithRunDeadline(ctx, s, "run"); !errors.Is(err, ErrRunTimeExhausted) {
stop()
t.Fatal("expired run implicitly renewed", err)
}
if err := DecideRunDeadline(ctx, s, "run", time.Hour); err != nil {
t.Fatal(err)
}
_, stop, err := WithRunDeadline(ctx, s, "run")
defer stop()
if err != nil {
t.Fatal(err)
}
}
-302
View File
@@ -1,302 +0,0 @@
// Package budget provides durable provider-attempt admission policies.
package budget
import (
"context"
"encoding/json"
"errors"
"fmt"
"sync"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
var ErrExhausted = errors.New("budget_exhausted")
const tokenKind = "harness.budget.tokens.v1"
const maxRecords = 10000
const maxTokens int64 = 1 << 50
type tokenEvent struct {
Version int `json:"version"`
Kind string `json:"kind"`
ID string `json:"id,omitempty"`
Model string `json:"model,omitempty"`
Category llm.CallCategory `json:"category,omitempty"`
Tokens int64 `json:"tokens"`
Status string `json:"status,omitempty"`
}
type TokenAttempt struct {
ID string `json:"id"`
Model string `json:"model"`
Category llm.CallCategory `json:"category"`
Reserved int64 `json:"reserved"`
Charged int64 `json:"charged"`
Status string `json:"status"`
}
type TokenState struct {
Limit int64 `json:"limit"`
Committed int64 `json:"committed"`
Exhausted bool `json:"exhausted"`
Attempts []TokenAttempt `json:"attempts"`
}
// TokenLedger shares a session-wide limit across every attached operation and
// branch. Use a disk session loaded exclusively for durability across processes.
// Reopening never changes limits or releases interrupted reservations. Multiple
// ledgers over the same Session coordinate through conditional durable appends.
// This is token admission, not a financial billing cap.
type TokenLedger struct {
session *session.Session
kind string
}
func OpenTokenLedger(s *session.Session) (*TokenLedger, error) {
return openTokenLedger(s, tokenKind)
}
func openTokenLedger(s *session.Session, kind string) (*TokenLedger, error) {
if s == nil {
return nil, errors.New("budget requires a session")
}
l := &TokenLedger{session: s, kind: kind}
_, _, err := l.read()
return l, err
}
func (l *TokenLedger) read() (TokenState, int, error) {
var state TokenState
records := l.session.Annotations(l.kind)
if len(records) > maxRecords {
return state, 0, errors.New("budget journal exceeds record limit")
}
index := map[string]int{}
for _, record := range records {
var e tokenEvent
if err := decodeBudgetJSON(record.Payload, &e); err != nil {
return state, 0, err
}
if e.Version != 1 || e.Tokens < 0 || e.Tokens > maxTokens {
return state, 0, errors.New("invalid budget record")
}
switch e.Kind {
case "limit":
if e.Tokens <= state.Committed {
return state, 0, errors.New("budget decision leaves no available capacity")
}
state.Limit = e.Tokens
state.Exhausted = false
case "reserve":
if _, exists := index[e.ID]; exists || e.ID == "" || state.Limit == 0 || state.Exhausted || e.Tokens <= 0 || e.Tokens > state.Limit-state.Committed {
return state, 0, errors.New("invalid budget reservation")
}
index[e.ID] = len(state.Attempts)
state.Attempts = append(state.Attempts, TokenAttempt{ID: e.ID, Model: e.Model, Category: e.Category, Reserved: e.Tokens, Charged: e.Tokens, Status: "reserved"})
state.Committed += e.Tokens
case "settle":
i, ok := index[e.ID]
if !ok || state.Attempts[i].Status != "reserved" {
return state, 0, errors.New("invalid budget settlement")
}
a := &state.Attempts[i]
if e.Status != "reported" && e.Status != "unknown" && e.Status != "not_dispatched" {
return state, 0, errors.New("invalid settlement status")
}
if (e.Status == "unknown" && e.Tokens < a.Reserved) || (e.Status == "not_dispatched" && e.Tokens != 0) {
return state, 0, errors.New("invalid settlement charge")
}
state.Committed -= a.Charged
if e.Tokens > maxTokens-state.Committed {
return state, 0, errors.New("budget total overflow")
}
state.Committed += e.Tokens
a.Charged = e.Tokens
a.Status = e.Status
if state.Committed >= state.Limit {
state.Exhausted = true
}
case "exhausted":
state.Exhausted = true
default:
return state, 0, errors.New("unknown budget event")
}
}
return state, len(records), nil
}
func (l *TokenLedger) append(e tokenEvent, revision int) error {
state, current, err := l.read()
if err != nil {
return err
}
if current != revision {
return session.ErrAnnotationConflict
}
pending := 0
for _, a := range state.Attempts {
if a.Status == "reserved" {
pending++
}
}
if e.Kind == "reserve" {
pending++
}
if e.Kind == "settle" {
pending--
}
if revision+1+pending > maxRecords {
return errors.New("budget journal lacks settlement capacity")
}
if revision >= maxRecords {
return errors.New("budget journal full")
}
e.Version = 1
raw, err := json.Marshal(e)
if err != nil {
return err
}
return l.session.AnnotateIfCount(l.kind, raw, revision)
}
func (l *TokenLedger) State() (TokenState, error) { s, _, err := l.read(); return s, err }
// Decide explicitly sets an absolute session token ceiling above all committed
// and uncertain usage. It resumes a previously exhausted ledger without erasing
// charges. Callers must obtain the user's budget decision before invoking it.
func (l *TokenLedger) Decide(ctx context.Context, limit int64) error {
if limit <= 0 || limit > maxTokens {
return errors.New("invalid token ceiling")
}
for {
if err := ctx.Err(); err != nil {
return err
}
s, n, err := l.read()
if err != nil {
return err
}
if limit <= s.Committed {
return errors.New("ceiling must exceed committed and reserved tokens")
}
err = l.append(tokenEvent{Kind: "limit", Tokens: limit}, n)
if errors.Is(err, session.ErrAnnotationConflict) {
continue
}
return err
}
}
// Admission reserves inputEstimate(req)+MaxTokens before dispatch. The supplied
// estimator must include system text, tool schemas, framing and multimodal
// input; its provenance must be disclosed by the application. Estimation error
// and provider output overruns can exceed the limit and latch exhaustion.
func (l *TokenLedger) Admission(inputEstimate func(llm.ChatRequest) (int64, error)) llm.CallAdmission {
return func(ctx context.Context, req llm.ChatRequest, category llm.CallCategory, id string) (func(llm.RequestUsage) error, error) {
if inputEstimate == nil || id == "" || len(id) > 128 || len(req.Model) > 1024 || req.MaxTokens <= 0 {
return nil, errors.New("bounded request and estimator required")
}
input, err := inputEstimate(req)
if err != nil {
return nil, err
}
if input < 0 || input > maxTokens-int64(req.MaxTokens) {
return nil, errors.New("invalid token estimate")
}
reserved := input + int64(req.MaxTokens)
for {
if err := ctx.Err(); err != nil {
return nil, err
}
s, n, err := l.read()
if err != nil {
return nil, err
}
for _, a := range s.Attempts {
if a.ID == id {
return nil, errors.New("duplicate budget attempt")
}
}
if s.Limit == 0 || s.Exhausted {
return nil, ErrExhausted
}
if reserved > s.Limit-s.Committed {
err = l.append(tokenEvent{Kind: "exhausted"}, n)
if errors.Is(err, session.ErrAnnotationConflict) {
continue
}
return nil, errors.Join(ErrExhausted, err)
}
// Leave one record for each outstanding settlement. Journal exhaustion
// must not admit a request whose terminal record cannot fit.
pending := 0
for _, a := range s.Attempts {
if a.Status == "reserved" {
pending++
}
}
if n+pending+2 > maxRecords {
return nil, errors.New("budget journal lacks settlement capacity")
}
err = l.append(tokenEvent{Kind: "reserve", ID: id, Model: req.Model, Category: category, Tokens: reserved}, n)
if errors.Is(err, session.ErrAnnotationConflict) {
continue
}
if err != nil {
return nil, err
}
break
}
var once sync.Once
var settledErr error
return func(r llm.RequestUsage) error {
once.Do(func() { settledErr = l.settle(id, reserved, r) })
return settledErr
}, nil
}
}
func (l *TokenLedger) settle(id string, reserved int64, r llm.RequestUsage) error {
if r.ID != id {
return errors.New("settlement identity mismatch")
}
charge, status := reserved, "unknown"
if r.Status == "not_dispatched" {
charge, status = 0, "not_dispatched"
} else if r.Usage != nil {
u := r.Usage
if u.InputTokens < 0 || u.OutputTokens < 0 || int64(u.InputTokens) > maxTokens-int64(u.OutputTokens) {
return errors.New("invalid reported tokens")
}
charge = int64(u.InputTokens) + int64(u.OutputTokens)
if r.Status == "completed" {
status = "reported"
} else if charge < reserved {
charge = reserved
}
}
for {
state, n, err := l.read()
if err != nil {
return err
}
if charge > maxTokens || charge > maxTokens-(state.Committed-reserved) {
return errors.New("settled tokens exceed representable ledger balance; reservation retained")
}
err = l.append(tokenEvent{Kind: "settle", ID: id, Tokens: charge, Status: status}, n)
if errors.Is(err, session.ErrAnnotationConflict) {
continue
}
if err != nil {
return fmt.Errorf("persist token settlement: %w", err)
}
state, err = l.State()
if err != nil {
return err
}
if state.Exhausted {
return ErrExhausted
}
return nil
}
}
-177
View File
@@ -1,177 +0,0 @@
package budget
import (
"context"
"errors"
"sync"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
func estimate(llm.ChatRequest) (int64, error) { return 10, nil }
func reserve(t *testing.T, l *TokenLedger, id string) func(llm.RequestUsage) error {
t.Helper()
done, err := l.Admission(estimate)(context.Background(), llm.ChatRequest{Model: "m", MaxTokens: 20}, llm.CallCompaction, id)
if err != nil {
t.Fatal(err)
}
return done
}
func TestTokenLedgerRestartRetainsUncertainAndRequiresDecision(t *testing.T) {
ctx := context.Background()
store := session.NewStore(t.TempDir())
if err := store.Create("a", "s"); err != nil {
t.Fatal(err)
}
s, err := store.LoadExclusive("a", "s")
if err != nil {
t.Fatal(err)
}
l, err := OpenTokenLedger(s)
if err != nil {
t.Fatal(err)
}
if err = l.Decide(ctx, 50); err != nil {
t.Fatal(err)
}
reserve(t, l, "interrupted")
if err = s.Close(); err != nil {
t.Fatal(err)
}
s, err = store.LoadExclusive("a", "s")
if err != nil {
t.Fatal(err)
}
defer s.Close()
l, err = OpenTokenLedger(s)
if err != nil {
t.Fatal(err)
}
state, err := l.State()
if err != nil || state.Committed != 30 || state.Attempts[0].Status != "reserved" {
t.Fatalf("restart %+v %v", state, err)
}
_, err = l.Admission(estimate)(ctx, llm.ChatRequest{MaxTokens: 20}, llm.CallRetry, "next")
if !errors.Is(err, ErrExhausted) {
t.Fatal(err)
}
// Even a smaller request cannot implicitly resume an exhausted decision.
_, err = l.Admission(estimate)(ctx, llm.ChatRequest{MaxTokens: 1}, llm.CallRetry, "small")
if !errors.Is(err, ErrExhausted) {
t.Fatal("exhaustion not latched")
}
if err = l.Decide(ctx, 80); err != nil {
t.Fatal(err)
}
done := reserve(t, l, "resumed")
if err = done(llm.RequestUsage{ID: "resumed", Status: "completed", Usage: &llm.Usage{InputTokens: 8, OutputTokens: 2}}); err != nil {
t.Fatal(err)
}
state, _ = l.State()
if state.Committed != 40 || state.Limit != 80 || state.Exhausted {
t.Fatalf("state %+v", state)
}
s.Compact("summary", 0)
if err = s.Flush(); err != nil {
t.Fatal(err)
}
l, err = OpenTokenLedger(s)
if err != nil {
t.Fatal(err)
}
state, _ = l.State()
if state.Committed != 40 {
t.Fatal("compaction erased ledger")
}
}
func TestTokenLedgerOwnersCannotDoubleReserve(t *testing.T) {
s := session.NewSession("a", "s")
first, _ := OpenTokenLedger(s)
second, _ := OpenTokenLedger(s)
if err := first.Decide(context.Background(), 30); err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
results := make(chan error, 2)
for i, l := range []*TokenLedger{first, second} {
wg.Add(1)
go func(i int, l *TokenLedger) {
defer wg.Done()
_, err := l.Admission(estimate)(context.Background(), llm.ChatRequest{MaxTokens: 20}, llm.CallGeneration, string(rune('a'+i)))
results <- err
}(i, l)
}
wg.Wait()
close(results)
ok := 0
for err := range results {
if err == nil {
ok++
} else if !errors.Is(err, ErrExhausted) {
t.Fatal(err)
}
}
state, err := first.State()
if err != nil || ok != 1 || state.Committed != 30 || len(state.Attempts) != 1 {
t.Fatalf("state %+v success %d err %v", state, ok, err)
}
}
func TestTokenLedgerSettlementUncertaintyAndOverrun(t *testing.T) {
for _, tc := range []struct {
name, status string
usage *llm.Usage
want int64
exhausted bool
}{
{"missing", "completed", nil, 30, false},
{"partial", "cancelled", &llm.Usage{InputTokens: 1}, 30, false},
{"not_sent", "not_dispatched", nil, 0, false},
{"overrun", "completed", &llm.Usage{InputTokens: 80, OutputTokens: 40}, 120, true},
} {
t.Run(tc.name, func(t *testing.T) {
l, _ := OpenTokenLedger(session.NewSession("a", "s"))
if err := l.Decide(context.Background(), 100); err != nil {
t.Fatal(err)
}
done := reserve(t, l, "attempt")
r := llm.RequestUsage{ID: "attempt", Status: tc.status, Usage: tc.usage}
if err := done(r); (err != nil) != tc.exhausted || (err != nil && !errors.Is(err, ErrExhausted)) {
t.Fatal(err)
}
if err := done(r); (err != nil) != tc.exhausted || (err != nil && !errors.Is(err, ErrExhausted)) {
t.Fatal(err)
}
state, err := l.State()
if err != nil || state.Committed != tc.want || state.Exhausted != tc.exhausted {
t.Fatalf("state %+v err %v", state, err)
}
})
}
}
func TestTokenLedgerPersistenceFailurePreventsDispatch(t *testing.T) {
store := session.NewStore(t.TempDir())
if err := store.Create("a", "s"); err != nil {
t.Fatal(err)
}
s, err := store.LoadExclusive("a", "s")
if err != nil {
t.Fatal(err)
}
l, _ := OpenTokenLedger(s)
if err = l.Decide(context.Background(), 100); err != nil {
t.Fatal(err)
}
if err = s.Close(); err != nil {
t.Fatal(err)
}
ctx := llm.WithCallAdmission(context.Background(), l.Admission(estimate))
_, err = llm.ObserveChat(ctx, llm.ChatRequest{MaxTokens: 20}, llm.CallGeneration, func(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
t.Fatal("failed reservation dispatched")
return nil, nil
})
if err == nil {
t.Fatal("closed journal accepted reservation")
}
}
-46
View File
@@ -1,46 +0,0 @@
package compaction
import (
"context"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"strings"
"testing"
)
type budgetProvider struct {
fakeProvider
requests []llm.ChatRequest
}
func (p *budgetProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.requests = append(p.requests, req)
return p.fakeProvider.ChatStream(ctx, req)
}
func TestSummariserOutputBudgetAndResponseBound(t *testing.T) {
entries := []session.SessionEntry{session.UserMessageEntry("task")}
for _, limit := range []int{0, 1, 2048, 32768, -1, 32769} {
provider := &budgetProvider{fakeProvider: fakeProvider{text: "summary"}}
s := &Summarizer{Provider: provider, MaxOutputTokens: limit}
_, err := s.Summarize(context.Background(), entries, "")
if limit < 0 || limit > 32768 {
if err == nil || len(provider.requests) != 0 {
t.Fatal("invalid budget dispatched")
}
continue
}
want := limit
if want == 0 {
want = 4096
}
if err != nil || len(provider.requests) != 1 || provider.requests[0].MaxTokens != want {
t.Fatalf("budget %d: %v %+v", limit, err, provider.requests)
}
}
provider := &budgetProvider{fakeProvider: fakeProvider{text: strings.Repeat("x", (256<<10)+1)}}
s := &Summarizer{Provider: provider}
out, err := s.Summarize(context.Background(), entries, "")
if err == nil || out != "" || len(provider.requests) != 1 {
t.Fatal("oversized summary accepted or retried")
}
}
+48 -122
View File
@@ -4,15 +4,16 @@ import (
"context"
"errors"
"log/slog"
"strings"
"sync"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
// MaxConsecutiveFailures is the per-session circuit-breaker threshold.
// After this many consecutive failed autocompact attempts, MaybeCompact stops attempting compaction
// After this many consecutive autocompact attempts that drop to the
// placeholder stage (stage 3), MaybeCompact stops attempting compaction
// for the session and returns Skipped="circuit_breaker".
//
// The breaker resets on any genuine summarizer success (stage 1 or 2
@@ -33,8 +34,6 @@ const (
// false, Skipped names the reason ("too_short", "empty_summary",
// "ollama_down", "model_missing", "timeout", "summarizer_error").
type Result struct {
Requests []llm.RequestUsage
Compacted bool
Reason Reason
Skipped string
@@ -47,23 +46,7 @@ type Result struct {
// Manager orchestrates compaction for sessions. One Manager is shared across
// the whole agent runtime; it tracks per-session mutexes internally.
type CommitNotification struct {
SessionID string
Reason Reason
TurnsCompacted int
TokensBefore int
TokensAfter int
}
type Manager struct {
// OnCommitted observes a successfully committed compaction after its lock is released.
// Configure while idle; callbacks must honour their bounded context. Panics are contained.
OnCommitted func(context.Context, CommitNotification)
// OnUsage receives compaction attempt records, including background work.
// The callback must be concurrency-safe and must not mutate records.
OnUsage func(llm.RequestUsage)
Summarizer *Summarizer
PreserveTurns int // K; default 4 if zero
Threshold float64 // fraction of context window that triggers preventive compaction (e.g. 0.6); 0 means use caller default
@@ -82,14 +65,13 @@ type Manager struct {
// mutexes so awaiting an in-flight compaction (WaitForInFlight)
// never serializes on the per-session lock-map or failure-counter.
inFlightMu sync.Mutex
inFlight map[string]*inFlightCompaction // stable session key → active or unconsumed handle
inFlight map[string]*inFlightCompaction // session.ID → in-flight handle
}
// inFlightCompaction tracks a background compaction goroutine spawned
// via MaybeCompactAsync. The done channel is closed when the goroutine
// returns; result holds the outcome for any waiter that wants it.
type inFlightCompaction struct {
cancel context.CancelFunc
done chan struct{}
result Result
err error
@@ -108,32 +90,11 @@ type inFlightCompaction struct {
// will block until the first completes. This is intentional — it prevents
// two compactions from racing on session.Append — but callers triggering
// manual compactions while a preventive one is in flight should expect a wait.
func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reason Reason, instructions string) (result Result, resultErr error) {
ledger := &llm.UsageLedger{}
ctx = llm.WithUsageObserver(ctx, func(record llm.RequestUsage) {
ledger.Record(record)
if m != nil && m.OnUsage != nil {
m.OnUsage(record)
}
})
defer func() { result.Requests = ledger.Records() }()
func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reason Reason, instructions string) (Result, error) {
if m == nil || m.Summarizer == nil {
return Result{Reason: reason, Skipped: "no_summarizer"}, nil
}
defer func() {
if resultErr == nil && result.Compacted && m.OnCommitted != nil {
observerCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
defer cancel()
defer func() {
if recovered := recover(); recovered != nil {
slog.Warn("compaction observer panicked")
}
}()
m.OnCommitted(observerCtx, CommitNotification{sess.ID, result.Reason, result.TurnsCompacted, result.TokensBefore, result.TokensAfter})
}
}()
key := stableKey(sess)
if fc := m.failureCount(key); fc >= MaxConsecutiveFailures {
slog.Info("compaction skipped",
@@ -163,20 +124,27 @@ func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reaso
slog.Info("compaction triggered", "session_id", sess.ID, "reason", string(reason))
combined, err := guidanceFor(ctx, instructions)
if err != nil {
return Result{Reason: reason, Skipped: "invalid_guidance"}, err
}
summary, err := m.Summarizer.Summarize(ctx, toCompact, combined)
summary, err := m.Summarizer.Summarize(ctx, toCompact, instructions)
if err != nil {
skipReason := classifySummarizerError(err)
slog.Warn("compaction skipped", "session_id", sess.ID, "reason", string(reason), "skipped", skipReason, "detail", err.Error())
// Leave both raw and effective history unchanged on summarizer failure.
// A hard error from Summarize means even stage 3 didn't run.
// Count it as a failure for breaker accounting.
m.incrementFailure(key)
return Result{Reason: reason, Skipped: skipReason}, nil
}
m.resetFailures(key)
// summarizeWithFallback's stage 3 returns a placeholder summary
// (no error) when both stage 1 and stage 2 failed. We detect
// placeholders by their stable marker phrase and treat them as
// failures for breaker accounting; real (stage-1 or stage-2)
// summaries reset the counter.
isPlaceholder := strings.Contains(summary, "compaction failed and the summary could not be generated")
if isPlaceholder {
m.incrementFailure(key)
} else {
m.resetFailures(key)
}
first := toCompact[0]
last := toCompact[len(toCompact)-1]
@@ -188,8 +156,14 @@ func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reaso
// compaction at the leaf and View() would terminate on it immediately,
// silently dropping every preserved turn.
entry.ParentID = toPreserve[0].ParentID
if err := sess.CommitCompaction(view[len(view)-1].ID, entry, toPreserve); err != nil {
return Result{}, err
sess.Append(entry)
for i, e := range toPreserve {
if i == 0 {
e.ParentID = entry.ID
}
// Re-append with same ID — Session.Append's entryMap overwrite and
// the loader's last-write-wins behaviour both make this safe.
sess.Append(e)
}
dur := time.Since(start).Milliseconds()
@@ -223,18 +197,6 @@ func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reaso
// enough for the three-stage fallback path) so that a returning
// caller's cancellation can't kill the in-flight summary.
func (m *Manager) MaybeCompactAsync(sess *session.Session, reason Reason) <-chan struct{} {
return m.maybeCompactAsync(context.Background(), sess, reason, false)
}
// MaybeCompactAsyncContext retains caller cancellation and usage observation.
// Its completed result remains available until JoinInFlight or ForgetSession;
// another launch for this session returns the existing handle until then.
// Callers must join before releasing ownership, including on error paths.
func (m *Manager) MaybeCompactAsyncContext(parent context.Context, sess *session.Session, reason Reason) <-chan struct{} {
return m.maybeCompactAsync(parent, sess, reason, true)
}
func (m *Manager) maybeCompactAsync(parent context.Context, sess *session.Session, reason Reason, retainResult bool) <-chan struct{} {
if m == nil || m.Summarizer == nil || sess == nil {
ch := make(chan struct{})
close(ch)
@@ -249,26 +211,27 @@ func (m *Manager) maybeCompactAsync(parent context.Context, sess *session.Sessio
if m.inFlight == nil {
m.inFlight = make(map[string]*inFlightCompaction)
}
fl := &inFlightCompaction{done: make(chan struct{})}
m.inFlight[key] = fl
m.inFlightMu.Unlock()
timeout := m.Summarizer.Timeout
if timeout == 0 {
timeout = 60 * time.Second
}
ctx, cancel := context.WithTimeout(parent, 2*timeout)
fl := &inFlightCompaction{done: make(chan struct{}), cancel: cancel}
m.inFlight[key] = fl
m.inFlightMu.Unlock()
go func() {
defer func() {
cancel()
m.inFlightMu.Lock()
close(fl.done)
if !retainResult && m.inFlight[key] == fl {
delete(m.inFlight, key)
}
m.inFlightMu.Unlock()
}()
fl.result, fl.err = m.MaybeCompact(ctx, sess, reason, "")
defer close(fl.done)
ctx, cancel := context.WithTimeout(context.Background(), 2*timeout)
defer cancel()
res, err := m.MaybeCompact(ctx, sess, reason, "")
fl.result = res
fl.err = err
// Drop our entry from the map so a subsequent burst can fire a
// fresh compaction (the next turn's WaitForInFlight will see no
// entry and proceed straight to its own threshold check).
m.inFlightMu.Lock()
delete(m.inFlight, key)
m.inFlightMu.Unlock()
}()
return fl.done
}
@@ -318,16 +281,8 @@ func (m *Manager) HasInFlight(sess *session.Session) bool {
key := stableKey(sess)
m.inFlightMu.Lock()
defer m.inFlightMu.Unlock()
fl, ok := m.inFlight[key]
if !ok {
return false
}
select {
case <-fl.done:
return false
default:
return true
}
_, ok := m.inFlight[key]
return ok
}
// ForgetSession removes the per-session lock, failure counter, and
@@ -345,9 +300,6 @@ func (m *Manager) ForgetSession(sess *session.Session) {
if m == nil || sess == nil {
return
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
m.JoinInFlight(ctx, sess)
key := stableKey(sess)
m.mu.Lock()
delete(m.locks, key)
@@ -355,7 +307,9 @@ func (m *Manager) ForgetSession(sess *session.Session) {
m.failMu.Lock()
delete(m.failures, key)
m.failMu.Unlock()
// Clear tracking after joining; the owner must prevent concurrent launches.
// Drop any in-flight tracking entry too. The goroutine itself
// already deletes its entry on completion; this covers the rare
// case of a session being forgotten mid-compaction.
m.inFlightMu.Lock()
delete(m.inFlight, key)
m.inFlightMu.Unlock()
@@ -435,31 +389,3 @@ func classifySummarizerError(err error) string {
return "summarizer_error"
}
}
// JoinInFlight waits for and consumes the current background producer, returning its result
// and error. Cancellation cancels that producer, then still waits for it to
// finish; it never reports a join while session writes can continue. Callers
// must prevent concurrent new launches while ending session ownership.
func (m *Manager) JoinInFlight(ctx context.Context, sess *session.Session) (Result, bool, error) {
if m == nil || sess == nil {
return Result{}, false, nil
}
m.inFlightMu.Lock()
fl, ok := m.inFlight[stableKey(sess)]
m.inFlightMu.Unlock()
if !ok {
return Result{}, false, nil
}
select {
case <-fl.done:
case <-ctx.Done():
fl.cancel()
<-fl.done
}
m.inFlightMu.Lock()
if m.inFlight[stableKey(sess)] == fl {
delete(m.inFlight, stableKey(sess))
}
m.inFlightMu.Unlock()
return fl.result, true, fl.err
}
+24 -84
View File
@@ -93,7 +93,12 @@ func TestManagerRefusesShortSession(t *testing.T) {
assert.Equal(t, "too_short", res.Skipped)
}
func TestManagerSummarizerErrorSkipsWithoutSummary(t *testing.T) {
func TestManagerSummarizerErrorFallsBackToPlaceholder(t *testing.T) {
// With the three-stage fallback chain, an empty model response no
// longer surfaces ErrEmptySummary to the Manager — stage 3 emits a
// placeholder summary so compaction "succeeds" with a stub. The
// circuit breaker (Task 5) detects the stub by string match for
// breaker accounting.
mgr := &Manager{
Summarizer: &Summarizer{
Provider: &fakeProvider{text: ""},
@@ -105,9 +110,9 @@ func TestManagerSummarizerErrorSkipsWithoutSummary(t *testing.T) {
sess := longSession()
res, err := mgr.MaybeCompact(context.Background(), sess, ReasonManual, "")
require.NoError(t, err)
assert.False(t, res.Compacted)
assert.Empty(t, res.Summary)
assert.NotEmpty(t, res.Skipped)
assert.True(t, res.Compacted, "stage-3 placeholder counts as a successful compaction")
assert.Contains(t, res.Summary, "compaction failed",
"summary must contain the placeholder marker so Task 5's breaker can detect it")
}
func TestManagerSerializesPerSession(t *testing.T) {
@@ -337,11 +342,24 @@ func TestCircuitBreakerTripsAfterMaxFailures(t *testing.T) {
}
sess := longSession()
// Failed attempts leave history available and increment the breaker.
// First N-1 attempts run the summarizer; the alwaysFailingProvider
// makes every call drop to stage 3 (placeholder). The breaker treats
// hitting stage 3 as failure for circuit-breaker accounting.
//
// After each placeholder compaction, View() walks back to the new
// compaction entry and Split sees only the preserved K turns — too
// short to compact again. To keep the loop reaching the summarizer
// (so the failure counter can increment) we add a new user/assistant
// pair between iterations, simulating real conversation continuing
// through repeated compaction failures.
//
// First MaxConsecutiveFailures calls: Compacted=true (placeholder)
// — each increments the failure counter. The next call sees
// counter >= MaxConsecutiveFailures and is blocked by the breaker.
for i := range MaxConsecutiveFailures {
res, err := mgr.MaybeCompact(context.Background(), sess, ReasonPreventive, "")
require.NoError(t, err, "iteration %d", i)
assert.False(t, res.Compacted, "iteration %d must preserve history", i)
assert.True(t, res.Compacted, "iteration %d should still attempt", i)
// Add new turns so the next iteration has something to compact.
sess.Append(session.UserMessageEntry("follow-up"))
sess.Append(session.AssistantMessageEntry("more reply"))
@@ -411,81 +429,3 @@ func longSessionWith(agentID, key string) *session.Session {
}
return sess
}
func TestCommittedObserverSeesCommittedHistoryAndCannotChangeResult(t *testing.T) {
for _, mode := range []string{"success", "panic", "skip", "failure"} {
t.Run(mode, func(t *testing.T) {
sess := longSession()
defer sess.Close()
mgr := &Manager{Summarizer: &Summarizer{Provider: &fakeProvider{text: "summary"}, Model: "m", Timeout: time.Second}, PreserveTurns: 4}
if mode == "skip" {
mgr.Summarizer = nil
}
if mode == "failure" {
mgr.Summarizer.Provider = &fakeProvider{err: errors.New("unavailable")}
}
calls := 0
mgr.OnCommitted = func(ctx context.Context, event CommitNotification) {
calls++
if event.SessionID != sess.ID || event.TurnsCompacted == 0 || sess.View()[0].Type != session.EntryTypeCompaction {
t.Fatal(event, sess.View())
}
deadline, ok := ctx.Deadline()
if !ok || time.Until(deadline) > 2*time.Second {
t.Fatal("observer not bounded")
}
lock := mgr.lockFor(stableKey(sess))
if !lock.TryLock() {
t.Fatal("observer called under compaction lock")
}
lock.Unlock()
if mode == "panic" {
panic("observer failure")
}
}
result, err := mgr.MaybeCompact(context.Background(), sess, ReasonManual, "")
if err != nil {
t.Fatal(err)
}
expected := mode == "success" || mode == "panic"
if result.Compacted != expected || (calls == 1) != expected {
t.Fatal(result, calls)
}
})
}
}
func TestBackgroundCompactionJoinsCommittedObserver(t *testing.T) {
sess := longSession()
defer sess.Close()
entered, release := make(chan struct{}), make(chan struct{})
manager := &Manager{Summarizer: &Summarizer{Provider: &fakeProvider{text: "summary"}, Model: "m", Timeout: time.Second}, PreserveTurns: 4}
manager.OnCommitted = func(ctx context.Context, event CommitNotification) {
close(entered)
select {
case <-release:
case <-ctx.Done():
}
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
done := manager.MaybeCompactAsyncContext(ctx, sess, ReasonPreventive)
select {
case <-entered:
case <-ctx.Done():
t.Fatal("observer never entered")
}
select {
case <-done:
t.Fatal("background finished before observer joined")
default:
}
if !manager.HasInFlight(sess) {
t.Fatal("active observer not tracked")
}
close(release)
result, joined, err := manager.JoinInFlight(ctx, sess)
if err != nil || !joined || !result.Compacted || manager.HasInFlight(sess) {
t.Fatal(result, joined, err)
}
}
-29
View File
@@ -1,29 +0,0 @@
package compaction
import (
"context"
"errors"
"strings"
"unicode/utf8"
)
type guidanceKey struct{}
// WithGuidance binds immutable caller guidance to synchronous and asynchronous
// compaction derived from this context. It does not modify shared managers.
func WithGuidance(ctx context.Context, guidance string) (context.Context, error) {
if len(guidance) > 48<<10 || !utf8.ValidString(guidance) || strings.ContainsRune(guidance, 0) {
return ctx, errors.New("compaction guidance exceeds 48 KiB or is invalid UTF-8")
}
return context.WithValue(ctx, guidanceKey{}, guidance), nil
}
func guidanceFor(ctx context.Context, focus string) (string, error) {
guidance, _ := ctx.Value(guidanceKey{}).(string)
if len(focus) > 16<<10 || !utf8.ValidString(focus) || strings.ContainsRune(focus, 0) {
return "", errors.New("compaction focus exceeds 16 KiB or is invalid UTF-8")
}
if guidance == "" {
return focus, nil
}
return guidance + "\n\nCurrent compaction focus:\n" + focus, nil
}
-36
View File
@@ -1,36 +0,0 @@
package compaction
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestJoinRetainsCompletedResultUntilConsumed(t *testing.T) {
mgr := &Manager{Summarizer: &Summarizer{Provider: usageSummaryProvider{}, Model: "summary"}, PreserveTurns: 1}
sess := longSession()
done := mgr.MaybeCompactAsyncContext(context.Background(), sess, ReasonManual)
<-done
require.False(t, mgr.HasInFlight(sess), "completed producer is not running")
// Neither a legacy waiter nor another launch may erase an unconsumed result.
res, found := mgr.WaitForInFlight(sess, time.Second)
require.True(t, found)
require.True(t, res.Compacted)
require.Equal(t, done, mgr.MaybeCompactAsyncContext(context.Background(), sess, ReasonPreventive))
res, found, err := mgr.JoinInFlight(context.Background(), sess)
require.NoError(t, err)
require.True(t, found)
require.True(t, res.Compacted)
require.Len(t, res.Requests, 1)
_, found, err = mgr.JoinInFlight(context.Background(), sess)
require.NoError(t, err)
require.False(t, found)
next := mgr.MaybeCompactAsyncContext(context.Background(), sess, ReasonPreventive)
require.NotEqual(t, done, next)
<-next
_, found, err = mgr.JoinInFlight(context.Background(), sess)
require.NoError(t, err)
require.True(t, found)
}
-22
View File
@@ -1,22 +0,0 @@
package compaction
import (
"context"
"github.com/stretchr/testify/require"
"testing"
)
func TestFailedSummarisationPreservesEffectiveAndRawHistory(t *testing.T) {
sess := longSession()
before := sess.View()
raw := sess.Entries()
leaf := sess.LeafID()
manager := &Manager{Summarizer: &Summarizer{Provider: &fakeProvider{text: ""}, Model: "test"}, PreserveTurns: 4}
result, err := manager.MaybeCompact(context.Background(), sess, ReasonManual, "")
require.NoError(t, err)
require.False(t, result.Compacted)
require.NotEmpty(t, result.Skipped)
require.Equal(t, before, sess.View())
require.Equal(t, raw, sess.Entries())
require.Equal(t, leaf, sess.LeafID())
}
+43 -41
View File
@@ -18,21 +18,25 @@ var ErrEmptySummary = errors.New("compaction: empty summary returned")
// for compaction. The provider is expected to be the bundled Ollama in
// production but any LLMProvider works (used for tests).
type Summarizer struct {
Route llm.CallRoute // identifies the independently selected provider client
Provider llm.LLMProvider
MaxOutputTokens int // 0 defaults to 4096; otherwise 1-32768
Model string // bare model id, e.g. "qwen2.5:3b-instruct"
Timeout time.Duration // per-call deadline; 0 → 60s
Provider llm.LLMProvider
Model string // bare model id, e.g. "qwen2.5:3b-instruct"
Timeout time.Duration // per-call deadline; 0 → 60s
}
// Summarize sends entries through the configured provider and returns the
// trimmed, formatted summary text. additionalInstructions is appended to
// the prompt when non-empty (used by manual /compact <focus...>).
//
// A full transcript is attempted first. Overflow/stream failures may retry
// with oversized messages explicitly elided. If neither attempt produces a
// summary, return the error so the manager preserves effective history.
// The call wraps three fallback stages:
// 1. Full transcript — preferred; preserves all detail.
// 2. Small-only — drops oversized messages, keeps a note that they were
// elided. Triggered when stage 1 returns a context-overflow error
// or a stream error.
// 3. Placeholder — a static stub indicating compaction failed; never
// returns an error to the caller so the agent loop can continue.
//
// Each stage applies FormatCompactSummary to strip the analysis scratchpad
// and unwrap the summary block.
func (s *Summarizer) Summarize(ctx context.Context, entries []session.SessionEntry, additionalInstructions string) (string, error) {
return s.summarizeWithFallback(ctx, entries, additionalInstructions)
}
@@ -45,8 +49,16 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
}
stage1Err := err
// Cancellation and per-call deadlines stop retries and retain their
// classification for the manager.
// Context cancellation/deadline propagates up — the caller asked us to
// stop, so don't burn an extra provider call on stage 2 or paper over
// the cancel with a placeholder. This preserves the Manager's ability
// to classify cancellation/timeout distinctly from "compaction is
// genuinely broken; degrade gracefully".
//
// We also propagate a per-call deadline (Summarizer.Timeout firing while
// the parent ctx is still alive) — otherwise a per-call timeout would
// flow into stage 2/3, masking timeout as a placeholder. Manager
// classifies the wrapped DeadlineExceeded as Skipped: "timeout".
if ctxErr := ctx.Err(); ctxErr != nil || errors.Is(stage1Err, context.DeadlineExceeded) {
return "", stage1Err
}
@@ -55,7 +67,7 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
// buildSmallOnlyTranscript actually elides something — otherwise we'd
// be re-sending the same transcript with the same prompt against the
// same provider (predictable failure, wasted call). Fall through to
// the final error in that case.
// stage 3 in that case.
if isOverflowError(stage1Err) || isStreamError(stage1Err) {
small, droppedCount := buildSmallOnlyTranscript(entries)
if droppedCount > 0 {
@@ -67,10 +79,9 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
}
}
if failure := errors.Join(stage1Err, err); failure != nil {
return "", failure
}
return "", ErrEmptySummary
// Stage 3: placeholder. Never returns an error — the agent loop must
// be able to continue even if compaction is wholly broken.
return placeholderSummary(len(entries)), nil
}
// callOnce performs a single summarizer invocation against a pre-built
@@ -83,16 +94,6 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
// 5-minute TTL window hits cache_read for the prefix, dropping a few
// seconds off TTFT.
func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstructions string) (string, error) {
maxTokens := s.MaxOutputTokens
if maxTokens == 0 {
maxTokens = 4096
}
if maxTokens < 1 || maxTokens > 32768 {
return "", errors.New("summariser output token limit must be 1-32768")
}
if s.Provider == nil {
return "", errors.New("summariser provider unavailable")
}
systemPrompt, userMessage := BuildPromptParts(transcript, additionalInstructions)
timeout := s.Timeout
if timeout == 0 {
@@ -102,7 +103,6 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
defer cancel()
req := llm.ChatRequest{
Route: s.Route,
Model: s.Model,
Messages: []llm.Message{{Role: "user", Content: userMessage}},
// One cache-marked system part: providers that support caching
@@ -111,34 +111,22 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
SystemPromptParts: []llm.SystemPromptPart{
{Text: systemPrompt, Cache: true},
},
MaxTokens: maxTokens,
MaxTokens: 4096,
}
stream, err := llm.ObserveChat(callCtx, req, llm.CallCompaction, s.Provider.ChatStream)
stream, err := s.Provider.ChatStream(callCtx, req)
if err != nil {
return "", fmt.Errorf("compaction: chat stream: %w", err)
}
var sb strings.Builder
var terminalReason string
for ev := range stream {
switch ev.Type {
case llm.EventTextDelta:
if len(ev.Text) > 256<<10-sb.Len() {
return "", errors.New("summariser response exceeds 256 KiB")
}
sb.WriteString(ev.Text)
case llm.EventDone:
terminalReason = ev.StopReason
case llm.EventError:
return "", fmt.Errorf("compaction: stream error: %w", ev.Error)
}
}
if err := callCtx.Err(); err != nil {
return "", err
}
if terminalReason == "length" || terminalReason == "max_tokens" {
return "", errors.New("summariser reached its output limit; original history retained")
}
out := strings.TrimSpace(sb.String())
if out == "" {
return "", ErrEmptySummary
@@ -173,6 +161,20 @@ func buildSmallOnlyTranscript(entries []session.SessionEntry) (string, int) {
return BuildTranscript(kept), dropped
}
// placeholderSummary is the stage-3 fallback. It must be a valid summary
// the model can pick up from — minimally describing what was elided so
// the next turn doesn't act as if the conversation was empty. The
// "compaction failed and the summary could not be generated" phrase is
// stable: Task 5's circuit breaker detects placeholders by string match
// on this fragment to count them as failures for breaker accounting.
func placeholderSummary(entryCount int) string {
return fmt.Sprintf(
"Summary:\nConversation history (%d entries) — compaction failed and the summary could not be generated. "+
"The conversation continues; refer to the recent preserved turns and ask the user for any context you need.",
entryCount,
)
}
// isOverflowError reports whether err looks like a "your prompt is too big"
// signal from any provider. Re-uses the overflow signature list rather
// than depending on package-level state.
+24 -9
View File
@@ -58,26 +58,37 @@ func TestSummarizerTrimsWhitespace(t *testing.T) {
assert.Equal(t, "summary text", got)
}
func TestSummarizerEmptyResponseReturnsError(t *testing.T) {
func TestSummarizerEmptyResponseFallsBackToPlaceholder(t *testing.T) {
// An empty model response is no longer surfaced as ErrEmptySummary —
// the three-stage fallback chain catches it: stage 1 returns
// ErrEmptySummary internally, stage 2 is skipped (not an overflow or
// stream error), stage 3 emits the placeholder. The underlying
// ErrEmptySummary remains the failure mode that callOnce reports
// inside the chain; the user-facing contract is "always returns a
// usable summary string, never an error".
s := &Summarizer{
Provider: &fakeProvider{text: " \n "},
Model: "qwen2.5:3b-instruct",
Timeout: 5 * time.Second,
}
got, err := s.Summarize(context.Background(), []session.SessionEntry{session.UserMessageEntry("hi")}, "")
require.Error(t, err)
assert.Empty(t, got)
require.NoError(t, err)
assert.Contains(t, got, "compaction failed")
}
func TestSummarizerProviderErrorReturnsError(t *testing.T) {
func TestSummarizerProviderErrorFallsBackToPlaceholder(t *testing.T) {
// A provider-level ChatStream error is wrapped as
// "compaction: chat stream: <err>" — neither an overflow nor a
// stream-event error, so stage 2 is skipped and we fall straight
// through to the placeholder. The agent loop sees no error.
s := &Summarizer{
Provider: &fakeProvider{err: errors.New("ollama down")},
Model: "qwen2.5:3b-instruct",
Timeout: 5 * time.Second,
}
got, err := s.Summarize(context.Background(), []session.SessionEntry{session.UserMessageEntry("hi")}, "")
require.Error(t, err)
assert.Empty(t, got)
require.NoError(t, err)
assert.Contains(t, got, "compaction failed")
}
// flakyProvider returns ChatStream errors a configured number of times,
@@ -142,7 +153,7 @@ func TestSummarizeFallbackToSmallOnlyOnOverflow(t *testing.T) {
"second-stage success must produce the summary")
}
func TestSummarizeReturnsErrorWhenAllStagesFail(t *testing.T) {
func TestSummarizeFallbackToPlaceholderWhenAllStagesFail(t *testing.T) {
entries := []session.SessionEntry{session.UserMessageEntry("hi")}
s := &Summarizer{
Provider: &flakyProvider{failsRemaining: 99, successText: ""},
@@ -150,8 +161,12 @@ func TestSummarizeReturnsErrorWhenAllStagesFail(t *testing.T) {
Timeout: time.Second,
}
got, err := s.Summarize(context.Background(), entries, "")
require.Error(t, err)
assert.Empty(t, got)
require.NoError(t, err,
"placeholder stage must not surface the underlying error to caller")
assert.Contains(t, got, "Conversation history",
"placeholder must be a usable summary stub")
assert.Contains(t, got, "compaction failed",
"placeholder must indicate the failure so the next turn can adapt")
}
func TestSummarizePerCallTimeoutPropagates(t *testing.T) {
-26
View File
@@ -1,26 +0,0 @@
package compaction
import (
"context"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"strings"
"testing"
)
type truncatedSummaryProvider struct{ llmtest.Base }
func (truncatedSummaryProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
ch := make(chan llm.ChatEvent, 2)
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Incomplete summary"}
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: "length"}
close(ch)
return ch, nil
}
func TestRejectTruncatedSummary(t *testing.T) {
s := Summarizer{Provider: truncatedSummaryProvider{}, Model: "fixture"}
out, err := s.callOnce(context.Background(), "history", "")
if err == nil || out != "" || !strings.Contains(err.Error(), "output limit") {
t.Fatalf("%q %v", out, err)
}
}
-33
View File
@@ -1,33 +0,0 @@
package compaction
import (
"context"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/stretchr/testify/require"
)
type usageSummaryProvider struct{ llmtest.Base }
func (usageSummaryProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
ch := make(chan llm.ChatEvent, 2)
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Summary of prior work."}
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 1200, OutputTokens: 20}}
close(ch)
return ch, nil
}
func TestCompactionUsageRecordsAndBackgroundObserver(t *testing.T) {
ledger := &llm.UsageLedger{}
manager := &Manager{Summarizer: &Summarizer{Provider: usageSummaryProvider{}, Model: "summary-model"}, OnUsage: ledger.Record, PreserveTurns: 4}
result, err := manager.MaybeCompact(context.Background(), longSession(), ReasonManual, "")
require.NoError(t, err)
require.True(t, result.Compacted)
require.Len(t, result.Requests, 1)
require.Equal(t, llm.CallCompaction, result.Requests[0].Category)
require.Equal(t, "summary-model", result.Requests[0].Model)
<-manager.MaybeCompactAsync(longSession(), ReasonPreventive)
require.Len(t, ledger.Records(), 2)
require.Equal(t, 2400, ledger.Total().InputTokens)
}
+4 -7
View File
@@ -1,7 +1,7 @@
# Writing agents with harness
This guide walks you through building agents on top of `harness`. It assumes
you've read [`README.md`](./README.md) and have a Go 1.26+ project that depends
you've read [`README.md`](./README.md) and have a Go 1.25+ project that depends
on `github.com/sausheong/harness`.
> Two complete examples ship in [`examples/`](./examples) — `minimal/` (file +
@@ -59,8 +59,7 @@ 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 / LiteLLM / OpenRouter /
local (Ollama, LM Studio, etc.), or your own).
chat client (Anthropic / OpenAI / Gemini / Qwen, 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
@@ -388,11 +387,9 @@ 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, "local"\|"openai-compatible")` | for local Ollama, etc. |
| OpenAI-compat| `openai.NewOpenAIProviderWithKind(apiKey, baseURL, "ollama"\|"compat")` | for local Ollama, etc. |
| Gemini | `gemini.NewGeminiProvider(ctx, apiKey)` | takes `context.Context` |
| LiteLLM | `litellm.NewLiteLLMProvider(apiKey, baseURL)` | `baseURL` required (self-hosted) |
| OpenRouter | `openrouter.NewOpenRouterProvider(apiKey, baseURL)` | `baseURL == ""` → OpenRouter's public endpoint |
| Local | `local.NewLocalProvider(baseURL)` | `baseURL == ""` → `http://localhost:11434/v1` (Ollama's default; override for LM Studio, llama.cpp, vLLM, etc.); no API key |
| Qwen | `qwen.NewQwenProvider(apiKey, baseURL)` | OpenAI-compatible endpoint |
The provider you pass on `RuntimeInputs.Provider` only needs to match the
provider prefix in `AgentSpec.Model` — `runtime.BuildRuntime` parses
+1 -2
View File
@@ -82,8 +82,6 @@ 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")
@@ -117,4 +115,5 @@ func main() {
}
}
}
_ = llm.ReasoningOff // keep llm import live for clarity in the demo
}
-293
View File
@@ -1,293 +0,0 @@
// Package execution provides explicit host and container command boundaries.
// Admission belongs to the caller; choosing a backend never grants permission.
package execution
import (
"bytes"
"context"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/sausheong/harness/process"
)
type Request struct {
CaptureLimit int // zero uses 64 KiB; bounded protocol callers may request up to 16 MiB
OutputStore *process.ArtifactStore // caller-owned trusted capture store
Argv []string
Env map[string]string
Stdin []byte
}
type Result struct {
StdoutTruncated, StderrTruncated bool
StdoutBytes, StderrBytes int64
StdoutArtifact, StderrArtifact process.ArtifactInfo
Stdout, Stderr string
ExitCode int
Truncated bool
}
type Backend interface {
Run(context.Context, Request) (Result, error)
Boundary() string
}
type Host struct{ Workspace string }
func (Host) Boundary() string { return "unrestricted host; commands can access host resources" }
func (h Host) Run(ctx context.Context, r Request) (Result, error) {
if err := validate(r); err != nil {
return Result{}, err
}
return runCaptured(ctx, r.OutputStore, r.CaptureLimit, h.Workspace, environment(r.Env), r.Stdin, r.Argv[0], r.Argv[1:]...)
}
var imageID = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
type Container struct {
Resources []ReadOnlyResource // explicit pinned files mounted read-only at /harness-resources
WorkerSHA256 string // required when WorkerPath is configured
WorkerPath string // optional trusted executable mounted read-only at /hand-worker
Docker, Socket, Image, Workspace string
Writable, Network bool
}
func (c Container) Boundary() string {
return fmt.Sprintf("container: workspace writable=%t; network=%t; other host paths unmounted", c.Writable, c.Network)
}
func validate(r Request) error {
if r.CaptureLimit < 0 || r.CaptureLimit > 16<<20 {
return errors.New("invalid capture limit")
}
if len(r.Argv) == 0 || r.Argv[0] == "" || len(r.Argv) > 1024 || len(r.Stdin) > 1<<20 {
return errors.New("invalid or oversized execution request")
}
size := 0
for _, a := range r.Argv {
size += len(a)
if strings.ContainsRune(a, 0) {
return errors.New("NUL in argument")
}
}
for k, v := range r.Env {
size += len(k) + len(v)
if !envName.MatchString(k) || strings.ContainsRune(v, 0) {
return errors.New("invalid environment entry")
}
}
if size > 1<<20 {
return errors.New("execution arguments exceed 1 MiB")
}
return nil
}
func environment(values map[string]string) []string {
env := []string{"PATH=/usr/local/bin:/usr/bin:/bin"}
keys := make([]string, 0, len(values))
for k := range values {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
env = append(env, k+"="+values[k])
}
return env
}
func run(ctx context.Context, dir string, env []string, input []byte, name string, args ...string) (Result, error) {
return runCaptured(ctx, nil, 0, dir, env, input, name, args...)
}
func runCaptured(ctx context.Context, store *process.ArtifactStore, limit int, dir string, env []string, input []byte, name string, args ...string) (Result, error) {
cmd := process.Command(ctx, name, args...)
cmd.Dir = dir
cmd.Env = env
cmd.Stdin = bytes.NewReader(input)
type capture interface {
Write([]byte) (int, error)
Snapshot() (string, int64, bool)
}
if limit == 0 {
limit = 64 << 10
}
var out, stderr capture = process.NewCapture(limit), process.NewCapture(limit)
var diskOut, diskErr *process.OutputCapture
if store != nil {
diskOut, diskErr = store.Capture(limit), store.Capture(limit)
out, stderr = diskOut, diskErr
}
cmd.Stdout = out
cmd.Stderr = stderr
err := process.Run(cmd)
result := Result{ExitCode: -1}
if diskOut != nil {
diskOut.Close()
diskErr.Close()
result.StdoutArtifact = diskOut.Info()
result.StderrArtifact = diskErr.Info()
}
a, ab, at := out.Snapshot()
b, bb, bt := stderr.Snapshot()
result.Stdout = a
result.Stderr = b
result.StdoutBytes = ab
result.StderrBytes = bb
result.Truncated = at || bt
result.StdoutTruncated = at
result.StderrTruncated = bt
if cmd.ProcessState != nil {
result.ExitCode = cmd.ProcessState.ExitCode()
}
return result, err
}
type containerCommand struct {
docker string
args []string
cleanup func() error
}
func (c Container) Run(ctx context.Context, r Request) (result Result, err error) {
plan, err := c.prepare(ctx, r)
if err != nil {
return result, err
}
defer func() { err = errors.Join(err, plan.cleanup()) }()
return runCaptured(ctx, r.OutputStore, r.CaptureLimit, "", environment(nil), r.Stdin, plan.docker, plan.args...)
}
func (c Container) prepare(ctx context.Context, r Request) (plan *containerCommand, err error) {
if err = ctx.Err(); err != nil {
return
}
if err = validate(r); err != nil {
return
}
if !filepath.IsAbs(c.Docker) || !filepath.IsAbs(c.Socket) || !imageID.MatchString(c.Image) {
return nil, errors.New("container requires absolute Docker executable/socket and immutable sha256 image ID")
}
info, e := os.Stat(c.Socket)
if e != nil || info.Mode()&os.ModeSocket == 0 {
return nil, errors.New("local container socket unavailable; no host fallback")
}
workspace, e := filepath.EvalSymlinks(c.Workspace)
if e != nil {
return nil, e
}
workspace, e = filepath.Abs(workspace)
if e != nil {
return nil, e
}
info, e = os.Stat(workspace)
if e != nil || !info.IsDir() || strings.ContainsAny(workspace, ",\n\r") {
return nil, errors.New("invalid workspace mount")
}
// A separate config directory prevents ambient Docker auth/context inheritance.
config, e := os.MkdirTemp("", "harness-docker-config-")
if e != nil {
return nil, e
}
defer func() {
if plan == nil {
os.RemoveAll(config)
}
}()
configCanonical, e := filepath.EvalSymlinks(config)
if e != nil {
return nil, e
}
relative, e := filepath.Rel(workspace, configCanonical)
if e != nil || (relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator)) && !filepath.IsAbs(relative)) {
return nil, errors.New("container state must be outside the mounted workspace")
}
if strings.ContainsAny(configCanonical, ",\n\r") {
return nil, errors.New("container state path cannot be mounted safely")
}
base := []string{"--config", config, "--host", "unix://" + c.Socket}
inspectCtx, inspectCancel := context.WithTimeout(ctx, 5*time.Second)
inspected, inspectErr := run(inspectCtx, "", environment(nil), nil, c.Docker, append(append([]string{}, base...), "image", "inspect", "--format", `{{json (index .Config "Volumes")}}`, c.Image)...)
inspectCancel()
if inspectErr != nil {
return nil, fmt.Errorf("inspect container image: %w: %s", inspectErr, inspected.Stderr)
}
if inspected.Truncated {
return nil, errors.New("container image volume metadata exceeds limit")
}
if err = validateImageVolumes(inspected.Stdout); err != nil {
return
}
name := "harness-exec-" + strings.ToLower(rand.Text())
cleanup := func() error {
defer os.RemoveAll(config)
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
res, e := run(cleanupCtx, "", environment(nil), nil, c.Docker, append(append([]string{}, base...), "rm", "--force", name)...)
if e != nil {
return fmt.Errorf("container cleanup failed for %s: %w: %s", name, e, res.Stderr)
}
return nil
}
network := "none"
if c.Network {
network = "bridge"
}
mount := "type=bind,src=" + workspace + ",dst=/workspace,bind-propagation=rprivate,bind-recursive=disabled"
if !c.Writable {
mount += ",readonly"
}
uid, gid := os.Getuid(), os.Getgid()
if uid < 1 {
uid, gid = 65534, 65534
}
args := append(append([]string{}, base...), "create", "--name", name, "--pull=never", "--read-only", "--cap-drop=ALL", "--security-opt=no-new-privileges", "--network", network, "--pids-limit=128", "--memory=512m", "--memory-swap=512m", "--cpus=2", "--init", "--no-healthcheck", "--log-driver=none", "--user", strconv.Itoa(uid)+":"+strconv.Itoa(gid), "--mount", mount, "--tmpfs", "/tmp:rw,nosuid,nodev,size=64m,mode=1777", "--workdir", "/workspace", "--interactive", "--entrypoint", r.Argv[0])
if c.WorkerPath != "" {
worker, e := snapshotWorker(ctx, c.WorkerPath, c.WorkerSHA256, config)
if e != nil {
return nil, e
}
args = append(args, "--mount", "type=bind,src="+worker+",dst=/hand-worker,readonly")
}
if len(c.Resources) > 0 {
resources, e := snapshotResources(ctx, c.Resources, config)
if e != nil {
return nil, e
}
args = append(args, "--mount", "type=bind,src="+resources+",dst=/harness-resources,readonly,bind-recursive=disabled")
}
for _, entry := range environment(r.Env) {
args = append(args, "--env", entry)
}
args = append(args, c.Image)
args = append(args, r.Argv[1:]...)
// Join creation independently of caller cancellation before removing its name.
// A daemon/transport failure is surfaced and cannot be treated as clean exit.
createCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
created, createErr := run(createCtx, "", environment(nil), nil, c.Docker, args...)
cancel()
if createErr != nil {
return nil, errors.Join(fmt.Errorf("container create failed: %w: %s", createErr, created.Stderr), cleanup())
}
if err = ctx.Err(); err != nil {
return nil, errors.Join(err, cleanup())
}
return &containerCommand{docker: c.Docker, args: append(append([]string{}, base...), "start", "--attach", "--interactive", name), cleanup: cleanup}, nil
}
// Image-declared volumes otherwise create implicit writable disk mounts even
// with a read-only root filesystem. Require explicit workspace/scratch only.
func validateImageVolumes(raw string) error {
var volumes map[string]json.RawMessage
if err := json.Unmarshal([]byte(raw), &volumes); err != nil {
return errors.New("invalid container image volume metadata")
}
if len(volumes) != 0 {
return errors.New("container image declares implicit volumes; use an image without VOLUME declarations")
}
return nil
}
-164
View File
@@ -1,164 +0,0 @@
package execution
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestHostExplicitEnvironmentAndExactArguments(t *testing.T) {
t.Setenv("EXECUTION_TEST_SECRET", "must-not-inherit")
h := Host{Workspace: t.TempDir()}
result, err := h.Run(context.Background(), Request{Argv: []string{"/bin/sh", "-c", `test -z "$EXECUTION_TEST_SECRET"; printf '%s' "$1"`, "sh", "a; echo injected"}})
if err != nil || result.Stdout != "a; echo injected" {
t.Fatalf("%+v %v", result, err)
}
if !strings.Contains(h.Boundary(), "unrestricted host") {
t.Fatal("host boundary hidden")
}
}
func TestMissingContainerNeverExecutesHostCommand(t *testing.T) {
path := filepath.Join(t.TempDir(), "must-not-exist")
c := Container{Docker: "/missing/docker", Socket: "/missing/socket", Image: "sha256:" + strings.Repeat("a", 64), Workspace: t.TempDir()}
if _, err := c.Run(context.Background(), Request{Argv: []string{"/bin/sh", "-c", "touch " + path}}); err == nil {
t.Fatal("missing backend accepted")
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatal("host fallback ran")
}
}
// This is an opt-in real-container suite. Its skip never qualifies isolation.
func TestNativeContainerBoundary(t *testing.T) {
image, socket := os.Getenv("HARNESS_TEST_CONTAINER_IMAGE"), os.Getenv("HARNESS_TEST_CONTAINER_SOCKET")
if image == "" || socket == "" {
t.Skip("native container fixture not configured")
}
workspace := t.TempDir()
if err := os.Chmod(workspace, 0777); err != nil {
t.Fatal(err)
}
secret := filepath.Join(t.TempDir(), "outside")
if err := os.WriteFile(secret, []byte("outside"), 0600); err != nil {
t.Fatal(err)
}
if err := os.Symlink(secret, filepath.Join(workspace, "escape")); err != nil {
t.Fatal(err)
}
c := Container{Docker: "/usr/local/bin/docker", Socket: socket, Image: image, Workspace: workspace}
script := `set -eu; command -v /sbin/ip >/dev/null; command -v nc >/dev/null; test -z "${EXECUTION_TEST_SECRET-}"; test "$EXPLICIT_VALUE" = allowed; test ! -e /var/run/docker.sock; test ! -e /workspace/escape; ! touch /workspace/denied; ! touch /etc/denied; printf scratch >/tmp/allowed; sh -c 'test ! -e /workspace/escape; ! touch /etc/child-denied'; test -z "$(/sbin/ip route)"; ! nc -z -w 1 192.0.2.1 80; printf bounded`
t.Setenv("EXECUTION_TEST_SECRET", "must-not-inherit")
result, err := c.Run(context.Background(), Request{Argv: []string{"/bin/sh", "-c", script}, Env: map[string]string{"EXPLICIT_VALUE": "allowed"}})
if err != nil || result.Stdout != "bounded" {
t.Fatalf("boundary: %+v %v", result, err)
}
c.Writable = true
result, err = c.Run(context.Background(), Request{Argv: []string{"/bin/sh", "-c", "cat > /workspace/allowed"}, Stdin: []byte("explicit write")})
if err != nil {
t.Fatalf("write: %+v %v", result, err)
}
raw, err := os.ReadFile(filepath.Join(workspace, "allowed"))
if err != nil || string(raw) != "explicit write" {
t.Fatalf("write missing: %q %v", raw, err)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
start := time.Now()
_, err = c.Run(ctx, Request{Argv: []string{"/bin/sh", "-c", "sleep 60 & wait"}})
if err == nil || time.Since(start) > 6*time.Second {
t.Fatalf("cancel not bounded: %v %s", err, time.Since(start))
}
}
func TestImageImplicitVolumesRejected(t *testing.T) {
for _, raw := range []string{`{"/data":{}}`, `{"/tmp":{}}`, `[]`, `"unknown"`, `{} garbage`} {
if err := validateImageVolumes(raw); err == nil {
t.Fatalf("accepted implicit or malformed volumes: %s", raw)
}
}
for _, raw := range []string{`null`, `{}`} {
if err := validateImageVolumes(raw); err != nil {
t.Fatal(err)
}
}
}
func TestNativeImageVolumeRejection(t *testing.T) {
image, socket := os.Getenv("HARNESS_TEST_VOLUME_IMAGE"), os.Getenv("HARNESS_TEST_CONTAINER_SOCKET")
if image == "" || socket == "" {
t.Skip("native volume image fixture not configured")
}
c := Container{Docker: "/usr/local/bin/docker", Socket: socket, Image: image, Workspace: t.TempDir()}
_, err := c.Run(context.Background(), Request{Argv: []string{"/bin/sh", "-c", "exit 99"}})
if err == nil || !strings.Contains(err.Error(), "implicit volumes") {
t.Fatalf("image volume declarations were not rejected: %v", err)
}
}
func TestNativeCancellationStopsChildWrites(t *testing.T) {
image, socket := os.Getenv("HARNESS_TEST_CONTAINER_IMAGE"), os.Getenv("HARNESS_TEST_CONTAINER_SOCKET")
if image == "" || socket == "" {
t.Skip("native container fixture not configured")
}
workspace := t.TempDir()
if err := os.Chmod(workspace, 0777); err != nil {
t.Fatal(err)
}
c := Container{Docker: "/usr/local/bin/docker", Socket: socket, Image: image, Workspace: workspace, Writable: true}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
done := make(chan error, 1)
joined := false
defer func() {
cancel()
if !joined {
select {
case <-done:
case <-time.After(6 * time.Second):
t.Error("container invocation did not join during test cleanup")
}
}
}()
go func() {
_, err := c.Run(ctx, Request{Argv: []string{"/bin/sh", "-c", `sh -c 'while :; do printf tick >> /workspace/heartbeat; sleep 0.05; done' & wait`}})
done <- err
}()
heartbeat := filepath.Join(workspace, "heartbeat")
for {
if b, err := os.ReadFile(heartbeat); err == nil && len(b) > 0 {
break
}
select {
case err := <-done:
joined = true
t.Fatalf("container exited before child became active: %v", err)
case <-ctx.Done():
t.Fatal("child did not become active before deadline")
case <-time.After(20 * time.Millisecond):
}
}
start := time.Now()
cancel()
select {
case err := <-done:
joined = true
if err == nil {
t.Fatal("cancelled invocation reported success")
}
case <-time.After(5 * time.Second):
t.Fatal("container cleanup exceeded five seconds")
}
if time.Since(start) > 5*time.Second {
t.Fatal("child cleanup exceeded five seconds")
}
before, err := os.ReadFile(heartbeat)
if err != nil {
t.Fatal(err)
}
time.Sleep(250 * time.Millisecond)
after, err := os.ReadFile(heartbeat)
if err != nil || string(before) != string(after) {
t.Fatalf("child continued writing after cancellation: before=%d after=%d err=%v", len(before), len(after), err)
}
}
-90
View File
@@ -1,90 +0,0 @@
package execution
import (
"context"
"errors"
"github.com/sausheong/harness/process"
)
// Starter is optional: backends that cannot own interactive processes must fail
// explicitly instead of routing those operations to the host.
type Starter interface {
Start(context.Context, Request) (*Handle, error)
}
// Handle remains running until both the process and backend cleanup have joined.
type Handle struct {
*process.Handle
done chan struct{}
err error
}
func ownedHandle(handle *process.Handle, cleanup func() error) *Handle {
h := &Handle{Handle: handle, done: make(chan struct{})}
go func() { defer close(h.done); h.err = errors.Join(handle.Wait(), cleanup()) }()
return h
}
func (h *Handle) Wait() error { <-h.done; return h.err }
func (h *Handle) Close() error { h.Cancel(); return h.Wait() }
func (h *Handle) Snapshot() process.HandleSnapshot {
s := h.Handle.Snapshot()
select {
case <-h.done:
s.Running = false
if h.err != nil {
s.Error = h.err.Error()
}
default:
s.Running = true
}
return s
}
func validateStart(r Request) error {
if err := validate(r); err != nil {
return err
}
if r.OutputStore == nil {
return errors.New("asynchronous execution requires an output store")
}
if len(r.Stdin) != 0 {
return errors.New("asynchronous input must use the owned handle")
}
if r.CaptureLimit != 0 {
return errors.New("asynchronous execution uses standard bounded captures")
}
return nil
}
func (h Host) Start(ctx context.Context, r Request) (*Handle, error) {
if err := validateStart(r); err != nil {
return nil, err
}
handle, err := process.StartHandleWithEnv(ctx, r.OutputStore, environment(r.Env), h.Workspace, r.Argv[0], r.Argv[1:]...)
if err != nil {
return nil, err
}
return ownedHandle(handle, func() error { return nil }), nil
}
func (c Container) Start(ctx context.Context, r Request) (*Handle, error) {
if err := validateStart(r); err != nil {
return nil, err
}
plan, err := c.prepare(ctx, r)
if err != nil {
return nil, err
}
handle, err := process.StartHandleWithEnv(ctx, r.OutputStore, environment(nil), "", plan.docker, plan.args...)
if err != nil {
return nil, errors.Join(err, plan.cleanup())
}
return ownedHandle(handle, plan.cleanup), nil
}
func (h *Handle) Send(ctx context.Context, data []byte) error {
err := h.Handle.Send(ctx, data)
if ctx.Err() != nil {
h.Cancel()
<-h.done
}
return err
}
-33
View File
@@ -1,33 +0,0 @@
package execution
import (
"context"
"path/filepath"
"testing"
"github.com/sausheong/harness/process"
)
func TestHandleCompletionIncludesBackendCleanup(t *testing.T) {
store, err := process.NewArtifactStore(filepath.Join(t.TempDir(), "capture"))
if err != nil {
t.Fatal(err)
}
raw, err := process.StartHandle(context.Background(), store, t.TempDir(), "/bin/sh", "-c", "exit 0")
if err != nil {
t.Fatal(err)
}
entered, release := make(chan struct{}), make(chan struct{})
h := ownedHandle(raw, func() error { close(entered); <-release; return nil })
<-entered
if !h.Snapshot().Running {
t.Fatal("terminal visible before cleanup")
}
close(release)
if err = h.Wait(); err != nil {
t.Fatal(err)
}
if h.Snapshot().Running {
t.Fatal("joined handle remains running")
}
}
-145
View File
@@ -1,145 +0,0 @@
package execution
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
)
// ReadOnlyResource is an explicitly pinned file exposed under
// /harness-resources/<Relative>. Only a verified private copy is mounted.
type ReadOnlyResource struct {
Path string
Relative string
SHA256 string
Executable bool
}
func snapshotResources(ctx context.Context, files []ReadOnlyResource, directory string) (string, error) {
if len(files) == 0 || len(files) > 65 {
return "", errors.New("resource bundle requires 1 to 65 files")
}
seen := map[string]bool{}
for _, f := range files {
digest, err := hex.DecodeString(f.SHA256)
if !filepath.IsAbs(f.Path) || !fs.ValidPath(f.Relative) || f.Relative == "." || strings.ContainsAny(f.Relative, "\\,:\r\n\x00") || err != nil || len(digest) != 32 || hex.EncodeToString(digest) != f.SHA256 {
return "", errors.New("invalid pinned resource")
}
key := strings.ToLower(f.Relative)
if seen[key] {
return "", errors.New("duplicate resource path")
}
seen[key] = true
}
for key := range seen {
for parent := filepath.ToSlash(filepath.Dir(key)); parent != "."; parent = filepath.ToSlash(filepath.Dir(parent)) {
if seen[parent] {
return "", errors.New("resource path overlaps a directory")
}
}
}
root, err := os.MkdirTemp(directory, "verified-resources-")
if err != nil {
return "", err
}
complete := false
defer func() {
if !complete {
os.RemoveAll(root)
}
}()
var total int64
for _, f := range files {
if err = ctx.Err(); err != nil {
return "", err
}
n, e := copyResource(ctx, f, filepath.Join(root, filepath.FromSlash(f.Relative)), 160<<20-total)
if e != nil {
return "", e
}
total += n
}
// Files are immutable to the container UID and the entire bind mount is read-only.
err = filepath.WalkDir(root, func(path string, d fs.DirEntry, e error) error {
if e != nil {
return e
}
if d.IsDir() {
return os.Chmod(path, 0755)
}
return nil
})
if err != nil {
return "", err
}
complete = true
return root, nil
}
func copyResource(ctx context.Context, f ReadOnlyResource, target string, remaining int64) (int64, error) {
input, err := openWorkerSource(f.Path)
if err != nil {
return 0, err
}
defer input.Close()
info, err := input.Stat()
if err != nil {
return 0, err
}
if !info.Mode().IsRegular() || info.Size() > MaxWorkerBytes || info.Size() > remaining {
return 0, errors.New("resource size or file type invalid")
}
if err = os.MkdirAll(filepath.Dir(target), 0700); err != nil {
return 0, err
}
output, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
return 0, err
}
defer output.Close()
hash := sha256.New()
buffer := make([]byte, 32<<10)
reader := io.LimitReader(input, info.Size()+1)
var total int64
for {
if err = ctx.Err(); err != nil {
return 0, err
}
n, e := reader.Read(buffer)
if n > 0 {
total += int64(n)
if total > info.Size() {
return 0, errors.New("resource changed size")
}
if _, err = output.Write(buffer[:n]); err != nil {
return 0, err
}
hash.Write(buffer[:n])
}
if e == io.EOF {
break
}
if e != nil {
return 0, e
}
}
if total != info.Size() || hex.EncodeToString(hash.Sum(nil)) != f.SHA256 {
return 0, errors.New("resource digest mismatch")
}
mode := os.FileMode(0444)
if f.Executable {
mode = 0555
}
if err = output.Chmod(mode); err != nil {
return 0, err
}
if err = output.Sync(); err != nil {
return 0, err
}
return total, output.Close()
}
-58
View File
@@ -1,58 +0,0 @@
package execution
import (
"context"
"crypto/sha256"
"fmt"
"os"
"path/filepath"
"testing"
)
func TestPinnedResourceSnapshotIntegrity(t *testing.T) {
source := filepath.Join(t.TempDir(), "asset")
if err := os.WriteFile(source, []byte("reviewed"), 0600); err != nil {
t.Fatal(err)
}
pin := fmt.Sprintf("%x", sha256.Sum256([]byte("reviewed")))
root := t.TempDir()
files := []ReadOnlyResource{{Path: source, Relative: "package/asset.txt", SHA256: pin}}
frozen, err := snapshotResources(context.Background(), files, root)
if err != nil {
t.Fatal(err)
}
if err = os.WriteFile(source, []byte("changed"), 0600); err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(filepath.Join(frozen, "package/asset.txt"))
if err != nil || string(b) != "reviewed" {
t.Fatal(string(b), err)
}
if err = os.RemoveAll(frozen); err != nil {
t.Fatal("snapshot not removable", err)
}
if _, err = snapshotResources(context.Background(), files, root); err == nil {
t.Fatal("changed source accepted")
}
entries, err := os.ReadDir(root)
if err != nil || len(entries) != 0 {
t.Fatal("partial snapshot retained", entries, err)
}
for _, paths := range [][]string{{"../escape"}, {"a", "a/b"}, {"A", "a"}, {"bad,path"}} {
var invalid []ReadOnlyResource
for _, path := range paths {
invalid = append(invalid, ReadOnlyResource{Path: source, Relative: path, SHA256: pin})
}
if _, err = snapshotResources(context.Background(), invalid, root); err == nil {
t.Fatal("invalid layout accepted", paths)
}
}
link := filepath.Join(t.TempDir(), "link")
if err = os.Symlink(source, link); err != nil {
t.Fatal(err)
}
files[0].Path = link
if _, err = snapshotResources(context.Background(), files, root); err == nil {
t.Fatal("symlink source accepted")
}
}
-129
View File
@@ -1,129 +0,0 @@
package execution
import (
"context"
"errors"
"io"
"os"
"sync"
"github.com/sausheong/harness/process"
)
// StreamStarter opens a raw protocol stream inside the selected boundary.
// Consumers must bound framing and drain both output streams. No capture or
// implicit fallback is applied to protocol traffic.
type StreamStarter interface {
OpenStream(context.Context, Request) (*Stream, error)
}
type Stream struct {
Stdin io.WriteCloser
Stdout io.ReadCloser
Stderr io.ReadCloser
cancel context.CancelFunc
stop func()
done chan struct{}
err error
closeOnce sync.Once
}
// Wait joins the child and boundary cleanup. Readers remain usable until Close.
func (s *Stream) Wait() error { <-s.done; return s.err }
// Close stops the child, joins boundary cleanup and releases all owned pipes.
func (s *Stream) Close() error {
s.closeOnce.Do(func() {
s.cancel()
s.stop()
s.Stdin.Close()
s.Wait()
s.Stdout.Close()
s.Stderr.Close()
})
return s.Wait()
}
func validateStream(r Request) error {
if err := validate(r); err != nil {
return err
}
if len(r.Stdin) != 0 || r.OutputStore != nil || r.CaptureLimit != 0 {
return errors.New("protocol streams require pipe input and consumer-owned output bounds")
}
return nil
}
func (h Host) OpenStream(ctx context.Context, r Request) (*Stream, error) {
if err := validateStream(r); err != nil {
return nil, err
}
return openStream(ctx, h.Workspace, environment(r.Env), r.Argv[0], r.Argv[1:], func() error { return nil })
}
func (c Container) OpenStream(ctx context.Context, r Request) (*Stream, error) {
if err := validateStream(r); err != nil {
return nil, err
}
plan, err := c.prepare(ctx, r)
if err != nil {
return nil, err
}
return openStream(ctx, "", environment(nil), plan.docker, plan.args, plan.cleanup)
}
func openStream(ctx context.Context, dir string, env []string, name string, args []string, cleanup func() error) (stream *Stream, err error) {
owned, cancel := context.WithCancel(ctx)
cmd := process.Command(owned, name, args...)
cmd.Dir = dir
cmd.Env = env
var pipes []*os.File
retained := false
defer func() {
if !retained {
cancel()
for _, p := range pipes {
p.Close()
}
err = errors.Join(err, cleanup())
}
}()
input, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
defer func() {
if !retained {
input.Close()
}
}()
output, outWriter, err := os.Pipe()
if err != nil {
return nil, err
}
pipes = append(pipes, output, outWriter)
diagnostic, errWriter, err := os.Pipe()
if err != nil {
return nil, err
}
pipes = append(pipes, diagnostic, errWriter)
cmd.Stdout = outWriter
cmd.Stderr = errWriter
if err = ctx.Err(); err != nil {
return nil, err
}
if err = cmd.Start(); err != nil {
return nil, err
}
outWriter.Close()
errWriter.Close()
s := &Stream{Stdin: input, Stdout: output, Stderr: diagnostic, cancel: cancel, stop: func() { process.KillGroup(cmd) }, done: make(chan struct{})}
retained = true
go func() {
defer close(s.done)
defer cancel()
runErr := cmd.Wait()
if owned.Err() != nil {
runErr = nil
}
s.err = errors.Join(runErr, process.KillGroup(cmd), cleanup())
}()
return s, nil
}
-138
View File
@@ -1,138 +0,0 @@
package execution
import (
"context"
"crypto/sha256"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestHostProtocolStreamRoundTrip(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
s, err := (Host{Workspace: t.TempDir()}).OpenStream(ctx, Request{Argv: []string{"/bin/sh", "-c", "cat; printf diagnostic >&2"}})
if err != nil {
t.Fatal(err)
}
defer s.Close()
errout := make(chan string, 1)
go func() { b, _ := io.ReadAll(s.Stderr); errout <- string(b) }()
if _, err = s.Stdin.Write([]byte("protocol\n")); err != nil {
t.Fatal(err)
}
if err = s.Stdin.Close(); err != nil {
t.Fatal(err)
}
b, err := io.ReadAll(s.Stdout)
if err != nil || string(b) != "protocol\n" {
t.Fatal(string(b), err)
}
if err = s.Wait(); err != nil {
t.Fatal(err)
}
if got := <-errout; got != "diagnostic" {
t.Fatal(got)
}
if err = s.Close(); err != nil {
t.Fatal(err)
}
}
func TestHostProtocolStreamCancellationAndValidation(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
s, err := (Host{Workspace: t.TempDir()}).OpenStream(ctx, Request{Argv: []string{"/bin/sh", "-c", "printf ready; sleep 20"}})
if err != nil {
t.Fatal(err)
}
defer s.Close()
b := make([]byte, 5)
if _, err = io.ReadFull(s.Stdout, b); err != nil || string(b) != "ready" {
t.Fatal(string(b), err)
}
start := time.Now()
cancel()
_ = s.Close()
if time.Since(start) > 5*time.Second {
t.Fatal("stream cleanup exceeded deadline")
}
if _, err = (Host{}).OpenStream(context.Background(), Request{Argv: []string{"/bin/sh"}, Stdin: []byte("x")}); err == nil {
t.Fatal("buffered input accepted")
}
_, err = (Container{}).OpenStream(context.Background(), Request{Argv: []string{"/bin/sh"}})
if err == nil || !strings.Contains(err.Error(), "container requires") {
t.Fatal("invalid container did not fail closed", err)
}
}
func TestContainerProtocolStreamRoundTrip(t *testing.T) {
image := os.Getenv("HARNESS_TEST_CONTAINER_IMAGE")
socket := os.Getenv("HARNESS_TEST_CONTAINER_SOCKET")
if image == "" || socket == "" {
t.Skip("native container fixture required")
}
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
defer cancel()
c := Container{Docker: "/usr/local/bin/docker", Socket: socket, Image: image, Workspace: t.TempDir()}
s, err := c.OpenStream(ctx, Request{Argv: []string{"/bin/sh", "-c", "cat; printf isolated >&2"}})
if err != nil {
t.Fatal(err)
}
defer s.Close()
diagnostic := make(chan string, 1)
go func() { b, _ := io.ReadAll(s.Stderr); diagnostic <- string(b) }()
if _, err = s.Stdin.Write([]byte("container protocol\n")); err != nil {
t.Fatal(err)
}
if err = s.Stdin.Close(); err != nil {
t.Fatal(err)
}
b, err := io.ReadAll(s.Stdout)
if err != nil || string(b) != "container protocol\n" {
t.Fatal(string(b), err)
}
if err = s.Wait(); err != nil {
t.Fatal(err)
}
if got := <-diagnostic; got != "isolated" {
t.Fatal(got)
}
if err = s.Close(); err != nil {
t.Fatal(err)
}
}
func TestContainerProtocolPinnedResources(t *testing.T) {
image, socket := os.Getenv("HARNESS_TEST_CONTAINER_IMAGE"), os.Getenv("HARNESS_TEST_CONTAINER_SOCKET")
if image == "" || socket == "" {
t.Skip("native container fixture required")
}
source := filepath.Join(t.TempDir(), "asset.txt")
if err := os.WriteFile(source, []byte("pinned-content"), 0600); err != nil {
t.Fatal(err)
}
c := Container{Docker: "/usr/local/bin/docker", Socket: socket, Image: image, Workspace: t.TempDir(), Resources: []ReadOnlyResource{{Path: source, Relative: "package/asset.txt", SHA256: fmt.Sprintf("%x", sha256.Sum256([]byte("pinned-content")))}}}
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
defer cancel()
s, err := c.OpenStream(ctx, Request{Argv: []string{"/bin/sh", "-c", "cat /harness-resources/package/asset.txt; if printf changed > /harness-resources/package/asset.txt 2>/dev/null; then exit 7; fi"}})
if err != nil {
t.Fatal(err)
}
defer s.Close()
go io.Copy(io.Discard, s.Stderr)
b, err := io.ReadAll(s.Stdout)
if err != nil || string(b) != "pinned-content" {
t.Fatal(string(b), err)
}
if err = s.Wait(); err != nil {
t.Fatal(err)
}
original, err := os.ReadFile(source)
if err != nil || string(original) != "pinned-content" {
t.Fatal(string(original), err)
}
}
-90
View File
@@ -1,90 +0,0 @@
package execution
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"os"
"path/filepath"
)
const MaxWorkerBytes int64 = 128 << 20
// snapshotWorker freezes verified bytes in a private directory outside the
// workspace. The daemon mounts this copy, never the mutable configured path.
func snapshotWorker(ctx context.Context, source, expected, directory string) (string, error) {
digest, err := hex.DecodeString(expected)
if err != nil || len(digest) != sha256.Size {
return "", errors.New("worker requires a SHA-256 digest")
}
canonical, err := filepath.EvalSymlinks(source)
if err != nil {
return "", err
}
input, err := openWorkerSource(canonical)
if err != nil {
return "", err
}
defer input.Close()
info, err := input.Stat()
if err != nil {
return "", err
}
if !info.Mode().IsRegular() || info.Mode().Perm()&0111 == 0 || info.Size() > MaxWorkerBytes {
return "", errors.New("worker must be a regular executable within 128 MiB")
}
destination := filepath.Join(directory, "verified-worker")
output, err := os.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0500)
if err != nil {
return "", err
}
complete := false
defer func() {
output.Close()
if !complete {
os.Remove(destination)
}
}()
hash := sha256.New()
reader := io.LimitReader(input, MaxWorkerBytes+1)
buffer := make([]byte, 32<<10)
var total int64
for {
if err = ctx.Err(); err != nil {
return "", err
}
n, readErr := reader.Read(buffer)
if n > 0 {
total += int64(n)
if total > MaxWorkerBytes {
return "", errors.New("worker exceeds 128 MiB")
}
if _, err = output.Write(buffer[:n]); err != nil {
return "", err
}
hash.Write(buffer[:n])
}
if readErr == io.EOF {
break
}
if readErr != nil {
return "", readErr
}
}
if hex.EncodeToString(hash.Sum(nil)) != expected {
return "", errors.New("worker SHA-256 mismatch; refusing execution")
}
if err = output.Chmod(0555); err != nil {
return "", err
}
if err = output.Sync(); err != nil {
return "", err
}
if err = output.Close(); err != nil {
return "", err
}
complete = true
return destination, nil
}
-54
View File
@@ -1,54 +0,0 @@
package execution
import (
"context"
"crypto/sha256"
"encoding/hex"
"os"
"path/filepath"
"testing"
)
func TestWorkerSnapshotPinsBytesAcrossSourceReplacement(t *testing.T) {
source := filepath.Join(t.TempDir(), "worker")
original := []byte("#!/bin/sh\nprintf original\n")
if err := os.WriteFile(source, original, 0700); err != nil {
t.Fatal(err)
}
hash := sha256.Sum256(original)
digest := hex.EncodeToString(hash[:])
frozen, err := snapshotWorker(context.Background(), source, digest, t.TempDir())
if err != nil {
t.Fatal(err)
}
if err = os.WriteFile(source, []byte("#!/bin/sh\nprintf replaced\n"), 0700); err != nil {
t.Fatal(err)
}
raw, err := os.ReadFile(frozen)
if err != nil || string(raw) != string(original) {
t.Fatal("snapshot changed with source")
}
dir := t.TempDir()
if _, err = snapshotWorker(context.Background(), source, digest, dir); err == nil {
t.Fatal("changed worker accepted")
}
entries, err := os.ReadDir(dir)
if err != nil || len(entries) != 0 {
t.Fatal("failed snapshot retained")
}
}
func TestWorkerSnapshotRejectsCancellationAndInvalidDigest(t *testing.T) {
source := filepath.Join(t.TempDir(), "worker")
if err := os.WriteFile(source, []byte("worker"), 0700); err != nil {
t.Fatal(err)
}
if _, err := snapshotWorker(context.Background(), source, "invalid", t.TempDir()); err == nil {
t.Fatal("invalid digest accepted")
}
hash := sha256.Sum256([]byte("worker"))
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := snapshotWorker(ctx, source, hex.EncodeToString(hash[:]), t.TempDir()); err != context.Canceled {
t.Fatal(err)
}
}
-12
View File
@@ -1,12 +0,0 @@
//go:build !unix
package execution
import (
"errors"
"os"
)
func openWorkerSource(string) (*os.File, error) {
return nil, errors.New("worker snapshot source validation is unavailable on this platform")
}
-16
View File
@@ -1,16 +0,0 @@
//go:build unix
package execution
import (
"golang.org/x/sys/unix"
"os"
)
func openWorkerSource(path string) (*os.File, error) {
fd, err := unix.Open(path, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK|unix.O_CLOEXEC, 0)
if err != nil {
return nil, err
}
return os.NewFile(uintptr(fd), path), nil
}
+21 -29
View File
@@ -1,47 +1,42 @@
module github.com/sausheong/harness
go 1.26.0
go 1.25.1
require (
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2
github.com/anthropics/anthropic-sdk-go v1.78.0
github.com/browserbase/stagehand/packages/sdk-go/v4 v4.1.0
github.com/chromedp/cdproto v0.0.0-20260714215040-dc233986426f
github.com/chromedp/chromedp v0.16.0
github.com/modelcontextprotocol/go-sdk v1.8.0
github.com/sashabaranov/go-openai v1.43.0
github.com/stretchr/testify v1.12.1
go.opentelemetry.io/otel v1.47.0
go.opentelemetry.io/otel/trace v1.47.0
golang.org/x/sys v0.48.0
google.golang.org/genai v1.72.0
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0
github.com/anthropics/anthropic-sdk-go v1.35.0
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327
github.com/chromedp/chromedp v0.14.2
github.com/modelcontextprotocol/go-sdk v1.5.0
github.com/sashabaranov/go-openai v1.41.2
github.com/stretchr/testify v1.11.1
go.opentelemetry.io/otel v1.43.0
go.opentelemetry.io/otel/trace v1.43.0
golang.org/x/sys v0.42.0
google.golang.org/genai v1.49.0
)
require (
cloud.google.com/go v0.116.0 // indirect
cloud.google.com/go/auth v0.9.3 // indirect
cloud.google.com/go/compute/metadata v0.9.0 // indirect
github.com/JohannesKaufmann/dom v0.3.1 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/buger/jsonparser v1.1.2 // indirect
github.com/JohannesKaufmann/dom v0.2.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/chromedp/sysutil v1.1.0 // indirect
github.com/coder/websocket v1.8.13 // indirect
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/google/jsonschema-go v0.4.2 // indirect
github.com/google/s2a-go v0.1.8 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/invopop/jsonschema v0.14.0 // indirect
github.com/pb33f/ordered-map/v2 v2.3.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect
github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
@@ -49,16 +44,13 @@ require (
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go.opencensus.io v0.24.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect
golang.org/x/crypto v0.51.0 // indirect
golang.org/x/mod v0.38.0 // indirect
golang.org/x/net v0.55.0 // indirect
golang.org/x/crypto v0.49.0 // indirect
golang.org/x/net v0.52.0 // indirect
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/text v0.37.0 // indirect
golang.org/x/time v0.15.0 // indirect
golang.org/x/text v0.35.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect
google.golang.org/grpc v1.80.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+45 -66
View File
@@ -6,32 +6,25 @@ cloud.google.com/go/auth v0.9.3/go.mod h1:7z6VY+7h3KUdRov5F1i8NDP5ZzWKYmEPO842Bg
cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/JohannesKaufmann/dom v0.3.1 h1:J16l9JAHWgkFPR3VIPbQ1gvS0cWab6laK1q7PFL3qh0=
github.com/JohannesKaufmann/dom v0.3.1/go.mod h1:BZPkf8ZeYrBgABjwJn9iiKt8aiCtkxpHkevms+Yp2DE=
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2 h1:XFJZFWESIWlUEHHjzBuv8RvrtCWnSGlimEX17ysSDb8=
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.2/go.mod h1:BHWO8lJzttJLqwuV8Rb1B3OG2OSzLbssZDI1FRg2eAA=
github.com/anthropics/anthropic-sdk-go v1.78.0 h1:8uluL7g84HtSSm347tMGtrUuCEBLmme7vOcFCMn7bnk=
github.com/anthropics/anthropic-sdk-go v1.78.0/go.mod h1:x+lPk/cCl48uRegeP0hlYYBN1b7bEBTveInIMgLicnY=
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
github.com/browserbase/stagehand/packages/sdk-go/v4 v4.1.0 h1:XELhAEkPJlyjirc1aWPhd0n+ZdFP0U+wRWamGRD05K0=
github.com/browserbase/stagehand/packages/sdk-go/v4 v4.1.0/go.mod h1:Z4qkSeN4whiyoYk+jqKbwYbUPu16JgmvEZWtiiaXyqY=
github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk=
github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/JohannesKaufmann/dom v0.2.0 h1:1bragmEb19K8lHAqgFgqCpiPCFEZMTXzOIEjuxkUfLQ=
github.com/JohannesKaufmann/dom v0.2.0/go.mod h1:57iSUl5RKric4bUkgos4zu6Xt5LMHUnw3TF1l5CbGZo=
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0 h1:mklaPbT4f/EiDr1Q+zPrEt9lgKAkVrIBtWf33d9GpVA=
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0/go.mod h1:D56Cl9r8M5i3UwAchE+LlLc5hPN3kJtdZNVJn06lSHU=
github.com/anthropics/anthropic-sdk-go v1.35.0 h1:W6K8mIkD1zIU0VUPMuokWONUvdlt2C//b11Zr6v5Oz4=
github.com/anthropics/anthropic-sdk-go v1.35.0/go.mod h1:dSIO7kSrOI7MA4fE6RRVaw8tyWP7HNQU5/H/KS4cax8=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chromedp/cdproto v0.0.0-20260714215040-dc233986426f h1:0Z1zcSLEmnj2c2CmJYBqewtS6pxhB39bNWUSEUAWjgk=
github.com/chromedp/cdproto v0.0.0-20260714215040-dc233986426f/go.mod h1:RwFsSODCtFExll+GhHM6R92SARHR3Z3oipaxLHj46C0=
github.com/chromedp/chromedp v0.16.0 h1:rOO4deOm4CbZgBCa8mD9g2rDyIoNs0BkgvNrlbp5ouk=
github.com/chromedp/chromedp v0.16.0/go.mod h1:rbuGKFT1vMcFcFqKfPIO1GpX/N+2s8onm2qMxZLbU5U=
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 h1:UQ4AU+BGti3Sy/aLU8KVseYKNALcX9UXY6DfpwQ6J8E=
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327/go.mod h1:NItd7aLkcfOA/dcMXvl8p1u+lQqioRMq/SqDp71Pb/k=
github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZSzM=
github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE=
github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
@@ -39,10 +32,10 @@ github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymF
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 h1:KZaTBSyshWX3MP5jukJcNSuXDQTO+rNpt0J564dX/eg=
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 h1:iizUGZ9pEquQS5jTGkh4AqeeHCMbfbjeb0zMt0aEFzs=
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
@@ -77,8 +70,8 @@ github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/s2a-go v0.1.8 h1:zZDs9gcbt9ZPLV0ndSyQk6Kacx2g/X+SKYovpnz3SMM=
github.com/google/s2a-go v0.1.8/go.mod h1:6iNWHTpQ+nfNRN5E00MSdfDwVesa8hhS32PhPO8deJA=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
@@ -88,21 +81,17 @@ github.com/googleapis/enterprise-certificate-proxy v0.3.4 h1:XYIDZApgAnrN1c855gT
github.com/googleapis/enterprise-certificate-proxy v0.3.4/go.mod h1:YKe7cfqYXjKGpGvmSg28/fFvhNzinZQm8DGnaburhGA=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg=
github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I=
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo=
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/modelcontextprotocol/go-sdk v1.5.0 h1:CHU0FIX9kpueNkxuYtfYQn1Z0slhFzBZuq+x6IiblIU=
github.com/modelcontextprotocol/go-sdk v1.5.0/go.mod h1:gggDIhoemhWs3BGkGwd1umzEXCEMMvAnhTrnbXJKKKA=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY=
github.com/pb33f/ordered-map/v2 v2.3.1/go.mod h1:qxFQgd0PkVUtOMCkTapqotNgzRhMPL7VvaHKbd1HnmQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/sashabaranov/go-openai v1.43.0 h1:HNRpO8TAQ01ssO7aPXO/68QRlcCCYQQ5GfHbFceRZcY=
github.com/sashabaranov/go-openai v1.43.0/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
github.com/sashabaranov/go-openai v1.41.2 h1:vfPRBZNMpnqu8ELsclWcAvF19lDNgh1t6TVfFFOPiSM=
github.com/sashabaranov/go-openai v1.41.2/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
github.com/sebdah/goldie/v2 v2.8.0 h1:dZb9wR8q5++oplmEiJT+U/5KyotVD+HNGCAc5gNr8rc=
github.com/sebdah/goldie/v2 v2.8.0/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
@@ -111,16 +100,14 @@ github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfv
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 h1:uOfcYT+3QungH6tIGSVCR/Y3KJmgJiHcojJbMTPDZAI=
github.com/standard-webhooks/standard-webhooks/libraries v0.0.1/go.mod h1:L1MQhA6x4dn9r007T033lsaZMv9EmBAdXyU/+EF40fo=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
@@ -133,46 +120,38 @@ github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yuin/goldmark v1.8.2 h1:kEGpgqJXdgbkhcOgBxkC0X0PmoPG1ZyoZ117rDVp4zE=
github.com/yuin/goldmark v1.8.2/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
github.com/yuin/goldmark v1.7.13 h1:GPddIs617DnBLFFVJFgpo1aBfe/4xcvMc3SB5t/D0pA=
github.com/yuin/goldmark v1.7.13/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s=
go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
@@ -186,28 +165,26 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genai v1.72.0 h1:sn3V1cHkHQhMcjtUrO2y1r54jprbFjmeokBU1IKfpZk=
google.golang.org/genai v1.72.0/go.mod h1:2j40fGpqPPIZNjaDKmjGGjYwCJi6Nm2ofmyP65GnqtY=
google.golang.org/genai v1.49.0 h1:Se+QJaH2GYK1aaR1o5S38mlU2GD5FnVvP76nfkV7LH0=
google.golang.org/genai v1.49.0/go.mod h1:A3kkl0nyBjyFlNjgxIwKq70julKbIxpSxqKO5gw/gmk=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
@@ -231,10 +208,12 @@ google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpAD
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
-57
View File
@@ -1,57 +0,0 @@
package llm
import (
"context"
"errors"
)
// CallAdmission reserves capacity before an individual provider attempt. A
// successful reservation returns a non-nil settlement callback, called exactly
// once before terminal delivery. Missing usage is unknown, never zero cost.
// Implementations must be concurrency safe and must not mutate the request.
// Settlement must retain uncertain in-flight charges after cancellation.
// A denial must leave no reservation behind. A settlement error must leave
// conservative durable state; it turns the attempt into a visible error.
type CallAdmission func(context.Context, ChatRequest, CallCategory, string) (func(RequestUsage) error, error)
type callAdmissionKey struct{}
// WithCallAdmission adds a guard; nested callers cannot remove earlier guards.
// Guards run in installation order. If a later guard denies admission, earlier
// reservations settle as not_dispatched, with no provider call made.
func WithCallAdmission(ctx context.Context, guard CallAdmission) context.Context {
previous, _ := ctx.Value(callAdmissionKey{}).([]CallAdmission)
guards := append([]CallAdmission(nil), previous...)
if guard != nil {
guards = append(guards, guard)
}
return context.WithValue(ctx, callAdmissionKey{}, guards)
}
func admitCall(ctx context.Context, req ChatRequest, record RequestUsage, guards []CallAdmission) (func(RequestUsage) error, error) {
var settlements []func(RequestUsage) error
settle := func(result RequestUsage) error {
var failures []error
for i := len(settlements) - 1; i >= 0; i-- {
detached := result
if result.Usage != nil {
u := *result.Usage
detached.Usage = &u
}
failures = append(failures, settlements[i](detached))
}
return errors.Join(failures...)
}
for _, guard := range guards {
finish, err := guard(ctx, req, record.Category, record.ID)
if err == nil && finish == nil {
err = errors.New("admission guard returned no settlement callback")
}
if err != nil {
record.Status = "not_dispatched"
return nil, errors.Join(err, settle(record))
}
settlements = append(settlements, finish)
}
return settle, nil
}
-138
View File
@@ -1,138 +0,0 @@
package llm
import (
"context"
"errors"
"sync"
"testing"
)
func TestAdmissionDenialUnwindsWithoutDispatch(t *testing.T) {
denied := errors.New("budget exhausted")
var records []RequestUsage
ctx := WithCallAdmission(context.Background(), func(_ context.Context, _ ChatRequest, category CallCategory, id string) (func(RequestUsage) error, error) {
if category != CallRetry || id == "" {
t.Fatal("missing attempt identity")
}
return func(r RequestUsage) error { records = append(records, r); return nil }, nil
})
ctx = WithCallAdmission(ctx, func(context.Context, ChatRequest, CallCategory, string) (func(RequestUsage) error, error) {
return nil, denied
})
_, err := ObserveChat(ctx, ChatRequest{Model: "m"}, CallRetry, func(context.Context, ChatRequest) (<-chan ChatEvent, error) {
t.Fatal("denied provider dispatched")
return nil, nil
})
if !errors.Is(err, denied) || len(records) != 1 || records[0].Status != "not_dispatched" || records[0].Usage != nil {
t.Fatalf("err %v records %+v", err, records)
}
}
func TestAdmissionSettlementPrecedesTerminalAndFailureIsVisible(t *testing.T) {
failure := errors.New("ledger persistence failed")
for _, category := range []CallCategory{CallGeneration, CallRetry, CallCompaction} {
t.Run(string(category), func(t *testing.T) {
settled := false
ctx := WithCallAdmission(context.Background(), func(_ context.Context, _ ChatRequest, actual CallCategory, id string) (func(RequestUsage) error, error) {
if actual != category {
t.Fatal("wrong category")
}
return func(r RequestUsage) error {
if r.ID != id || r.Usage == nil || r.Usage.OutputTokens != 7 || r.Status != "completed" {
t.Errorf("record %+v", r)
}
settled = true
return failure
}, nil
})
ch, err := ObserveChat(ctx, ChatRequest{Model: "m"}, category, func(context.Context, ChatRequest) (<-chan ChatEvent, error) {
ch := make(chan ChatEvent, 1)
ch <- ChatEvent{Type: EventDone, Usage: &Usage{OutputTokens: 7}}
close(ch)
return ch, nil
})
if err != nil {
t.Fatal(err)
}
count := 0
for event := range ch {
count++
if !settled || event.Type != EventError || !errors.Is(event.Error, failure) {
t.Fatalf("event %+v settled %v", event, settled)
}
}
if count != 1 {
t.Fatal("wrong terminal count")
}
})
}
}
func TestAdmissionConcurrentReservations(t *testing.T) {
var mu sync.Mutex
reserved, settlements := 0, 0
guard := func(context.Context, ChatRequest, CallCategory, string) (func(RequestUsage) error, error) {
mu.Lock()
defer mu.Unlock()
if reserved == 1 {
return nil, errors.New("budget exhausted")
}
reserved++
return func(r RequestUsage) error { mu.Lock(); defer mu.Unlock(); reserved--; settlements++; return nil }, nil
}
ctx := WithCallAdmission(context.Background(), guard)
source := make(chan ChatEvent)
first, err := ObserveChat(ctx, ChatRequest{}, CallGeneration, func(context.Context, ChatRequest) (<-chan ChatEvent, error) { return source, nil })
if err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_, err := ObserveChat(ctx, ChatRequest{}, CallCompaction, func(context.Context, ChatRequest) (<-chan ChatEvent, error) {
t.Error("oversubscribed provider dispatched")
return nil, nil
})
if err == nil {
t.Error("oversubscription accepted")
}
}()
}
wg.Wait()
source <- ChatEvent{Type: EventDone}
close(source)
for range first {
}
mu.Lock()
defer mu.Unlock()
if reserved != 0 || settlements != 1 {
t.Fatalf("reserved %d settlements %d", reserved, settlements)
}
}
func TestAdmissionCancellationSettlesUnknownOnce(t *testing.T) {
settled := make(chan RequestUsage, 2)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ctx = WithCallAdmission(ctx, func(context.Context, ChatRequest, CallCategory, string) (func(RequestUsage) error, error) {
return func(r RequestUsage) error { settled <- r; return nil }, nil
})
ch, err := ObserveChat(ctx, ChatRequest{}, CallGeneration, func(context.Context, ChatRequest) (<-chan ChatEvent, error) { return make(chan ChatEvent), nil })
if err != nil {
t.Fatal(err)
}
cancel()
for range ch {
}
r := <-settled
if r.Status != "cancelled" || r.Usage != nil {
t.Fatalf("record %+v", r)
}
select {
case <-settled:
t.Fatal("double settlement")
default:
}
}
+2 -13
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, Gemini) are thin wrappers over this helper — only the
// strip list differs. Anthropic doesn't use this (identity).
// methods (OpenAI, Qwen, 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,11 +93,6 @@ 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))
@@ -109,12 +104,6 @@ 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,16 +118,3 @@ 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")
}
+29 -133
View File
@@ -17,42 +17,22 @@ 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. MimeType
// "application/pdf" is carried as a PDF document (not an image) by
// providers that support it (e.g. Anthropic emits a `document` block);
// providers without PDF support report a clear error or placeholder
// instead of silently mishandling the bytes.
// ImageContent holds image data for multimodal messages.
type ImageContent struct {
MimeType string // "image/jpeg", "image/png", "application/pdf", etc.
Data []byte // raw bytes
MimeType string // "image/jpeg", "image/png", etc.
Data []byte // raw image bytes
}
// 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
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"`
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
}
// ToolCall represents a tool invocation requested by the LLM.
@@ -64,17 +44,9 @@ 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
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"`
Name string `json:"name"`
Description string `json:"description"`
Parameters json.RawMessage `json:"parameters"` // JSON Schema
}
// Diagnostic describes a single normalization or clamping event emitted
@@ -94,15 +66,14 @@ type SystemPromptPart struct {
Text string
// Cache requests that the prefix up to and including this part be cached.
// Anthropic-only; ignored elsewhere.
Cache bool
CacheControl *CacheControl
Cache bool
}
// 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).
// reasoning_effort, Gemini ThinkingConfig, Qwen enable_thinking).
type ReasoningMode string
const (
@@ -112,31 +83,6 @@ 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.
@@ -156,26 +102,13 @@ func ParseReasoningMode(s string) (ReasoningMode, error) {
}
// ChatRequest is the input to a streaming chat call.
// CallRoute identifies the constructed provider client for local admission and
// accounting. It is not sent to the provider. Destination must distinguish
// custom endpoints from explicitly named provider defaults.
type CallRoute struct {
Provider string `json:"provider"`
Destination string `json:"destination"`
}
type ChatRequest struct {
Route CallRoute `json:"-"`
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
Model string
Messages []Message
Tools []ToolDef
MaxTokens int
Temperature float64
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
@@ -184,19 +117,10 @@ type ChatRequest struct {
// CacheLastMessage requests that the final block of the final user
// message also be cache-marked. Anthropic-only; ignored elsewhere.
CacheLastMessage bool
// 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
Reasoning ReasoningMode // zero value = ReasoningOff; safe default
}
// Usage tracks token usage.
// InputTokens is total input including cached input. Cache counters are
// subsets used for pricing/analysis and must not be added again for context.
type Usage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
@@ -206,29 +130,13 @@ type Usage struct {
// ChatEvent is a single streaming event from the LLM.
type ChatEvent struct {
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
Type EventType
Text string
ToolCall *ToolCall
Usage *Usage
Error error
}
// 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
@@ -263,18 +171,6 @@ 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) {
@@ -311,10 +207,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,litellm,openrouter}). Each
// subpackage's New() takes the relevant fields directly.
// (harness/providers/{anthropic,openai,gemini,qwen}). Each subpackage's
// New() takes the relevant fields directly.
type ProviderOptions struct {
APIKey string
BaseURL string
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini"
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini" | "qwen"
}
+6 -26
View File
@@ -6,7 +6,6 @@ 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
@@ -15,17 +14,14 @@ 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.) 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.) 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.
func IsRetryableModelError(err error) bool {
if err == nil {
return false
@@ -51,29 +47,13 @@ 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())
// 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") {
if strings.Contains(msg, "429") || strings.Contains(msg, "529") ||
strings.Contains(msg, "rate limit") || strings.Contains(msg, "overloaded") {
return true
}
return false
-28
View File
@@ -8,26 +8,8 @@ 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))
@@ -107,13 +89,3 @@ 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))
}
-186
View File
@@ -1,186 +0,0 @@
package llm
import (
"context"
"crypto/rand"
"errors"
"fmt"
"sync"
)
type CallCategory string
const (
CallGeneration CallCategory = "generation"
CallRetry CallCategory = "retry"
CallCompaction CallCategory = "compaction"
)
// RequestUsage represents one attempted provider call. Nil Usage explicitly
// means unavailable, including potentially billable failures; it is not zero.
// InputTokens includes cached input. Cache fields are subsets, not additions.
type RequestUsage struct {
ID string `json:"request_id"`
Model string `json:"model"`
Category CallCategory `json:"category"`
Status string `json:"status"`
Source string `json:"source"`
Usage *Usage `json:"usage"`
}
type usageObserverKey struct{}
// WithUsageObserver chains observers. Callbacks can run concurrently and must
// not mutate their record. Each callback completes before its terminal event
// is forwarded to the consumer.
func WithUsageObserver(ctx context.Context, observer func(RequestUsage)) context.Context {
previous, _ := ctx.Value(usageObserverKey{}).(func(RequestUsage))
return context.WithValue(ctx, usageObserverKey{}, func(record RequestUsage) {
if previous != nil {
previous(record)
}
if observer != nil {
observer(record)
}
})
}
// ObserveChat observes streaming and non-streaming adapters using one contract.
// Providers must terminate after EventDone/EventError and honour cancellation.
func ObserveChat(ctx context.Context, req ChatRequest, category CallCategory, call func(context.Context, ChatRequest) (<-chan ChatEvent, error)) (<-chan ChatEvent, error) {
observer, _ := ctx.Value(usageObserverKey{}).(func(RequestUsage))
guards, _ := ctx.Value(callAdmissionKey{}).([]CallAdmission)
if observer == nil && len(guards) == 0 {
return call(ctx, req)
}
record := RequestUsage{ID: rand.Text(), Model: req.Model, Category: category, Source: "unavailable"}
settle, err := admitCall(ctx, req, record, guards)
if err != nil {
return nil, fmt.Errorf("provider admission: %w", err)
}
publish := func(status string, usage *Usage) error {
record.Status = status
if usage != nil {
copy := *usage
record.Usage = &copy
record.Source = "reported"
}
err := settle(record)
if observer != nil {
observer(record)
}
return err
}
if err := ctx.Err(); err != nil {
return nil, errors.Join(err, context.Cause(ctx), publish("not_dispatched", nil))
}
source, err := call(ctx, req)
if err != nil {
status := "failed"
if ctx.Err() != nil {
status = "cancelled"
}
return nil, errors.Join(err, context.Cause(ctx), publish(status, nil))
}
if source == nil {
return nil, errors.Join(fmt.Errorf("provider returned a nil event stream"), publish("failed", nil))
}
out := make(chan ChatEvent)
go func() {
defer close(out)
var usage *Usage
for {
select {
case <-ctx.Done():
publish("cancelled", usage)
return
case event, ok := <-source:
if !ok {
settlementErr := publish("failed", usage)
select {
case out <- ChatEvent{Type: EventError, Error: errors.Join(fmt.Errorf("provider stream closed without terminal event"), settlementErr, context.Cause(ctx))}:
case <-ctx.Done():
}
return
}
if event.Usage != nil {
copy := *event.Usage
usage = &copy
}
if event.Type == EventError && ctx.Err() != nil {
event.Error = errors.Join(event.Error, context.Cause(ctx))
}
terminal := event.Type == EventDone || event.Type == EventError
if terminal {
status := "completed"
if event.Type == EventError {
status = "failed"
}
if err := publish(status, usage); err != nil {
event.Type = EventError
event.Error = errors.Join(event.Error, fmt.Errorf("provider settlement: %w", err))
}
}
select {
case out <- event:
case <-ctx.Done():
if !terminal {
publish("cancelled", usage)
}
return
}
if terminal {
return
}
}
}
}()
return out, nil
}
// UsageLedger keeps immutable request records and a reported-only total.
// Unknown requests remain visible through Records rather than being priced as
// free. Create a ledger per bounded operation, not a process-global history.
type UsageLedger struct {
mu sync.Mutex
records []RequestUsage
total *Usage
}
func (l *UsageLedger) Record(record RequestUsage) {
l.mu.Lock()
defer l.mu.Unlock()
if record.Usage != nil {
u := *record.Usage
record.Usage = &u
if l.total == nil {
l.total = &Usage{}
}
l.total.InputTokens += u.InputTokens
l.total.OutputTokens += u.OutputTokens
l.total.CacheCreationInputTokens += u.CacheCreationInputTokens
l.total.CacheReadInputTokens += u.CacheReadInputTokens
}
l.records = append(l.records, record)
}
func (l *UsageLedger) Total() *Usage {
l.mu.Lock()
defer l.mu.Unlock()
if l.total == nil {
return nil
}
u := *l.total
return &u
}
func (l *UsageLedger) Records() []RequestUsage {
l.mu.Lock()
defer l.mu.Unlock()
out := append([]RequestUsage(nil), l.records...)
for i := range out {
if out[i].Usage != nil {
u := *out[i].Usage
out[i].Usage = &u
}
}
return out
}
-50
View File
@@ -1,50 +0,0 @@
package llm
import (
"context"
"errors"
"testing"
)
func TestUsageObserverFailedRequestCanCarryReportedUsage(t *testing.T) {
ledger := &UsageLedger{}
ctx := WithUsageObserver(context.Background(), ledger.Record)
ch, err := ObserveChat(ctx, ChatRequest{Model: "m"}, CallRetry, func(context.Context, ChatRequest) (<-chan ChatEvent, error) {
ch := make(chan ChatEvent, 1)
ch <- ChatEvent{Type: EventError, Error: errors.New("failed"), Usage: &Usage{InputTokens: 42}}
close(ch)
return ch, nil
})
if err != nil {
t.Fatal(err)
}
for range ch {
}
records := ledger.Records()
if len(records) != 1 || records[0].Status != "failed" || records[0].Source != "reported" || ledger.Total().InputTokens != 42 {
t.Fatalf("records %+v total %+v", records, ledger.Total())
}
records[0].Usage.InputTokens = 100
if ledger.Total().InputTokens != 42 {
t.Fatal("records alias total")
}
}
func TestUsageObserverReportsMissingTerminal(t *testing.T) {
ledger := &UsageLedger{}
ctx := WithUsageObserver(context.Background(), ledger.Record)
ch, err := ObserveChat(ctx, ChatRequest{Model: "m"}, CallGeneration, func(context.Context, ChatRequest) (<-chan ChatEvent, error) {
ch := make(chan ChatEvent)
close(ch)
return ch, nil
})
if err != nil {
t.Fatal(err)
}
var event ChatEvent
for e := range ch {
event = e
}
if event.Type != EventError || len(ledger.Records()) != 1 || ledger.Total() != nil {
t.Fatal("missing terminal treated as success")
}
}
-84
View File
@@ -1,84 +0,0 @@
package process
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// Read verifies a completed artifact within this store. It never follows paths
// supplied by output prose. Missing/expired, active, corrupt or legacy unverified
// artifacts fail explicitly. Truncated describes capture completeness separately
// from integrity: the verified captured prefix may still be read.
func (s *ArtifactStore) Read(ctx context.Context, info ArtifactInfo) ([]byte, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
digest, err := hex.DecodeString(info.SHA256)
if err != nil || len(digest) != sha256.Size || info.Bytes < 0 || info.Bytes > ArtifactFileLimit || info.Error != "" {
return nil, errors.New("artifact has no valid completed integrity record")
}
rel, err := filepath.Rel(s.dir, info.Path)
if err != nil || filepath.Base(rel) != rel || !strings.HasPrefix(rel, "output-") || !strings.HasSuffix(rel, ".log") {
return nil, errors.New("artifact is outside this store")
}
root, err := os.OpenRoot(s.dir)
if err != nil {
return nil, err
}
defer root.Close()
before, err := root.Lstat(rel)
if err != nil {
return nil, err
}
if !before.Mode().IsRegular() {
return nil, errors.New("artifact is not a regular file")
}
f, err := root.OpenFile(rel, artifactReadFlags(), 0)
if err != nil {
return nil, err
}
defer f.Close()
if err := lockArtifact(f, true); err != nil {
return nil, fmt.Errorf("artifact is active or unavailable: %w", err)
}
stat, err := f.Stat()
if err != nil {
return nil, err
}
if !stat.Mode().IsRegular() || stat.Mode().Perm()&0077 != 0 || stat.Size() != info.Bytes {
return nil, errors.New("artifact size or permissions changed")
}
data := make([]byte, 0, int(info.Bytes))
buf := make([]byte, 32<<10)
for {
if err := ctx.Err(); err != nil {
return nil, err
}
n, readErr := f.Read(buf)
if int64(len(data)+n) > info.Bytes {
return nil, errors.New("artifact grew during read")
}
data = append(data, buf[:n]...)
if readErr == io.EOF {
break
}
if readErr != nil {
return nil, readErr
}
}
if err := ctx.Err(); err != nil {
return nil, err
}
actual := sha256.Sum256(data)
if int64(len(data)) != info.Bytes || hex.EncodeToString(actual[:]) != strings.ToLower(info.SHA256) {
return nil, errors.New("artifact integrity mismatch")
}
return data, nil
}
-84
View File
@@ -1,84 +0,0 @@
//go:build unix
package process
import (
"bytes"
"context"
"os"
"path/filepath"
"testing"
)
func TestArtifactReadVerifiedAndTampered(t *testing.T) {
store := testStore(t)
capture := store.Capture(4)
data := bytes.Repeat([]byte("captured output\n"), 100)
capture.Write(data)
if _, err := store.Read(context.Background(), capture.Info()); err == nil {
t.Fatal("active unfinalised capture accepted")
}
if err := capture.Close(); err != nil {
t.Fatal(err)
}
info := capture.Info()
got, err := store.Read(context.Background(), info)
if err != nil || !bytes.Equal(got, data) || len(info.SHA256) != 64 {
t.Fatal("verified artifact unavailable", err)
}
tampered := bytes.Repeat([]byte("x"), len(data))
if err := os.WriteFile(info.Path, tampered, 0600); err != nil {
t.Fatal(err)
}
if _, err := store.Read(context.Background(), info); err == nil {
t.Fatal("same-size tampering accepted")
}
if err := os.Remove(info.Path); err != nil {
t.Fatal(err)
}
if _, err := store.Read(context.Background(), info); !os.IsNotExist(err) {
t.Fatal("missing artifact not reported", err)
}
}
func TestArtifactReadScopeLockAndCancellation(t *testing.T) {
store := testStore(t)
capture := store.Capture(1)
capture.Write([]byte("complete output"))
capture.Close()
info := capture.Info()
outside := info
outside.Path = filepath.Join(t.TempDir(), filepath.Base(info.Path))
if _, err := store.Read(context.Background(), outside); err == nil {
t.Fatal("outside path accepted")
}
link := filepath.Join(store.dir, "output-link.log")
if err := os.Symlink(info.Path, link); err != nil {
t.Fatal(err)
}
alias := info
alias.Path = link
if _, err := store.Read(context.Background(), alias); err == nil {
t.Fatal("symlink accepted")
}
file, err := os.OpenFile(info.Path, os.O_RDWR, 0)
if err != nil {
t.Fatal(err)
}
if err := lockArtifact(file, false); err != nil {
t.Fatal(err)
}
if _, err := store.Read(context.Background(), info); err == nil {
t.Fatal("locked artifact accepted")
}
file.Close()
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := store.Read(ctx, info); err != context.Canceled {
t.Fatal(err)
}
legacy := info
legacy.SHA256 = ""
if _, err := store.Read(context.Background(), legacy); err == nil {
t.Fatal("unverified legacy record accepted")
}
}
-216
View File
@@ -1,216 +0,0 @@
package process
import (
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"hash"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
const ArtifactFileLimit int64 = 8 << 20
const ArtifactStoreLimit int64 = 64 << 20
const ArtifactRetention = 24 * time.Hour
// ArtifactStore owns a private directory used only for command output. Each
// active capture reserves one full file allowance. Advisory file locks protect
// active files across cooperating processes; old completed files are evicted
// oldest first. Retention is enforced when a new artifact is allocated.
type ArtifactStore struct{ dir string }
func NewArtifactStore(dir string) (*ArtifactStore, error) {
abs, err := filepath.Abs(dir)
if err != nil {
return nil, err
}
if err = os.MkdirAll(abs, 0700); err != nil {
return nil, err
}
info, err := os.Lstat(abs)
if err != nil {
return nil, err
}
if !info.IsDir() || info.Mode().Perm()&0077 != 0 {
return nil, errors.New("artifact directory must be a private directory (0700)")
}
return &ArtifactStore{dir: abs}, nil
}
func (s *ArtifactStore) allocate() (*os.File, string, error) {
root, err := os.OpenRoot(s.dir)
if err != nil {
return nil, "", err
}
defer root.Close()
guard, err := root.OpenFile(".lock", os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return nil, "", err
}
defer guard.Close()
if err = lockArtifact(guard, false); err != nil {
return nil, "", err
}
names, err := fs.ReadDir(root.FS(), ".")
if err != nil {
return nil, "", err
}
type candidate struct {
name string
modified time.Time
}
var files []candidate
for _, e := range names {
if !strings.HasPrefix(e.Name(), "output-") {
continue
}
info, err := e.Info()
if err != nil {
return nil, "", err
}
if !info.Mode().IsRegular() || info.Size() > ArtifactFileLimit {
return nil, "", errors.New("invalid output artifact in store")
}
files = append(files, candidate{e.Name(), info.ModTime()})
}
sort.Slice(files, func(i, j int) bool { return files[i].modified.Before(files[j].modified) })
count := len(files)
for _, f := range files {
expired := time.Since(f.modified) > ArtifactRetention
if !expired && int64(count+1)*ArtifactFileLimit <= ArtifactStoreLimit {
continue
}
file, err := root.OpenFile(f.name, os.O_RDWR, 0)
if err != nil {
return nil, "", err
}
err = lockArtifact(file, true)
if artifactBusy(err) {
file.Close()
continue
}
if err != nil {
file.Close()
return nil, "", err
}
err = root.Remove(f.name)
file.Close()
if err != nil {
return nil, "", err
}
count--
}
if int64(count+1)*ArtifactFileLimit > ArtifactStoreLimit {
return nil, "", errors.New("output artifact quota occupied by active captures")
}
name := "output-" + rand.Text() + ".log"
file, err := root.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
if err != nil {
return nil, "", err
}
if err = lockArtifact(file, false); err != nil {
file.Close()
root.Remove(name)
return nil, "", err
}
return file, filepath.Join(s.dir, name), nil
}
// OutputCapture drains every byte, retains a bounded memory prefix, and spills
// output exceeding that prefix into an artifact with an independent disk cap.
// Call Close after the subprocess joins, before consuming Info. Write errors
// are recorded instead of stopping the drain and changing subprocess behaviour.
type OutputCapture struct {
mu sync.Mutex
prefix *Capture
store *ArtifactStore
file *os.File
info ArtifactInfo
closed bool
digest hash.Hash
}
type ArtifactInfo struct {
SHA256 string `json:"sha256,omitempty"`
Path string `json:"path,omitempty"`
Bytes int64 `json:"bytes"`
Truncated bool `json:"truncated"`
Error string `json:"error,omitempty"`
}
func (s *ArtifactStore) Capture(memoryLimit int) *OutputCapture {
return &OutputCapture{store: s, prefix: NewCapture(memoryLimit), digest: sha256.New()}
}
func (c *OutputCapture) Write(p []byte) (int, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return 0, os.ErrClosed
}
var before string
if c.file == nil && c.info.Error == "" {
_, retained, limit := c.prefix.stats()
if len(p) > limit-retained {
before, _, _ = c.prefix.Snapshot()
}
}
c.prefix.Write(p)
total, retained, _ := c.prefix.stats()
truncated := total > int64(retained)
if truncated && c.file == nil && c.info.Error == "" {
f, path, err := c.store.allocate()
if err != nil {
c.info.Error = err.Error()
} else {
c.file = f
c.info.Path = path
c.writeDisk([]byte(before))
}
}
if c.file != nil {
c.writeDisk(p)
}
c.info.Truncated = truncated && (c.info.Bytes < total)
return len(p), nil
}
func (c *OutputCapture) writeDisk(p []byte) {
if c.info.Error != "" {
return
}
keep := min(int64(len(p)), ArtifactFileLimit-c.info.Bytes)
n, err := c.file.Write(p[:int(keep)])
c.info.Bytes += int64(n)
c.digest.Write(p[:n])
if err == nil && int64(n) != keep {
err = errors.New("short artifact write")
}
if err != nil {
c.info.Error = fmt.Sprintf("capture output: %v", err)
}
}
func (c *OutputCapture) Snapshot() (string, int64, bool) { return c.prefix.Snapshot() }
func (c *OutputCapture) Info() ArtifactInfo { c.mu.Lock(); defer c.mu.Unlock(); return c.info }
func (c *OutputCapture) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return nil
}
c.closed = true
if c.file == nil {
return nil
}
err := errors.Join(c.file.Sync(), c.file.Close())
c.info.SHA256 = fmt.Sprintf("%x", c.digest.Sum(nil))
if err != nil {
c.info.Error = err.Error()
}
return err
}
-15
View File
@@ -1,15 +0,0 @@
//go:build !unix
package process
import (
"errors"
"os"
)
func lockArtifact(_ *os.File, _ bool) error {
return errors.New("output artifact locking is unsupported on this platform")
}
func artifactBusy(_ error) bool { return false }
func artifactReadFlags() int { return os.O_RDONLY }
-182
View File
@@ -1,182 +0,0 @@
//go:build unix
package process
import (
"bytes"
"context"
"os"
"path/filepath"
"testing"
"time"
)
func testStore(t *testing.T) *ArtifactStore {
t.Helper()
dir := filepath.Join(t.TempDir(), "output")
s, err := NewArtifactStore(dir)
if err != nil {
t.Fatal(err)
}
return s
}
func TestArtifactSpillExactAndCap(t *testing.T) {
s := testStore(t)
c := s.Capture(7)
for _, p := range []string{"abc", "def", "ghij", "klmnop"} {
c.Write([]byte(p))
}
c.Close()
info := c.Info()
raw, err := os.ReadFile(info.Path)
if err != nil || string(raw) != "abcdefghijklmnop" || info.Bytes != 16 || info.Truncated || info.Error != "" {
t.Fatalf("%q %+v %v", raw, info, err)
}
stat, _ := os.Stat(info.Path)
if stat.Mode().Perm() != 0600 {
t.Fatal(stat.Mode())
}
capped := s.Capture(4)
block := bytes.Repeat([]byte("z"), 1<<20)
for range 10 {
capped.Write(block)
}
capped.Close()
info = capped.Info()
stat, err = os.Stat(info.Path)
if err != nil || stat.Size() != ArtifactFileLimit || info.Bytes != ArtifactFileLimit || !info.Truncated {
t.Fatalf("%+v %v", info, err)
}
prefix, total, truncated := capped.Snapshot()
if prefix != "zzzz" || total != 10<<20 || !truncated {
t.Fatalf("%q %d %v", prefix, total, truncated)
}
}
func TestArtifactQuotaProtectsActiveAndEvictsCompleted(t *testing.T) {
s := testStore(t)
var active []*OutputCapture
for range 8 {
c := s.Capture(1)
c.Write([]byte("abc"))
if c.Info().Error != "" {
t.Fatal(c.Info())
}
active = append(active, c)
defer c.Close()
}
// A separate store instance must obey the same active-file reservations.
other, err := NewArtifactStore(s.dir)
if err != nil {
t.Fatal(err)
}
full := other.Capture(1)
full.Write([]byte("abc"))
full.Close()
if full.Info().Error == "" || !full.Info().Truncated || full.Info().Path != "" {
t.Fatal(full.Info())
}
old := active[0].Info().Path
active[0].Close()
next := other.Capture(1)
next.Write([]byte("abc"))
defer next.Close()
if next.Info().Error != "" {
t.Fatal(next.Info())
}
if _, err := os.Stat(old); !os.IsNotExist(err) {
t.Fatalf("completed artifact not evicted: %v", err)
}
for _, c := range active[1:] {
if _, err := os.Stat(c.Info().Path); err != nil {
t.Fatal("active artifact evicted", err)
}
}
}
func TestArtifactRetentionAndPrivateDirectory(t *testing.T) {
s := testStore(t)
c := s.Capture(1)
c.Write([]byte("abc"))
c.Close()
old := c.Info().Path
expired := time.Now().Add(-ArtifactRetention - time.Hour)
if err := os.Chtimes(old, expired, expired); err != nil {
t.Fatal(err)
}
next := s.Capture(1)
next.Write([]byte("abc"))
next.Close()
if _, err := os.Stat(old); !os.IsNotExist(err) {
t.Fatalf("expired artifact remains: %v", err)
}
small := s.Capture(10)
small.Write([]byte("abc"))
small.Close()
if small.Info().Path != "" || small.Info().Truncated {
t.Fatal(small.Info())
}
if _, err := small.Write([]byte("x")); err == nil {
t.Fatal("write after close succeeded")
}
if err := os.Chmod(s.dir, 0755); err != nil {
t.Fatal(err)
}
if _, err := NewArtifactStore(s.dir); err == nil {
t.Fatal("public directory accepted")
}
}
func TestArtifactCrossProcessReservation(t *testing.T) {
if dir := os.Getenv("HARNESS_ARTIFACT_QUOTA_FIXTURE"); dir != "" {
s, err := NewArtifactStore(dir)
if err != nil {
t.Fatal(err)
}
c := s.Capture(1)
c.Write([]byte("abc"))
c.Close()
if c.Info().Error == "" || c.Info().Path != "" {
t.Fatal("child bypassed active reservations", c.Info())
}
return
}
s := testStore(t)
for range 8 {
c := s.Capture(1)
c.Write([]byte("abc"))
defer c.Close()
if c.Info().Error != "" {
t.Fatal(c.Info())
}
}
exe, err := os.Executable()
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := Command(ctx, exe, "-test.run=^TestArtifactCrossProcessReservation$")
cmd.Env = append(os.Environ(), "HARNESS_ARTIFACT_QUOTA_FIXTURE="+s.dir, "GORACE=atexit_sleep_ms=0")
var output bytes.Buffer
cmd.Stdout = &output
cmd.Stderr = &output
if err := Run(cmd); err != nil {
t.Fatalf("child quota check: %v %s", err, output.String())
}
}
func TestArtifactAllocationFailureStillDrains(t *testing.T) {
s := testStore(t)
if err := os.Mkdir(filepath.Join(s.dir, ".lock"), 0700); err != nil {
t.Fatal(err)
}
c := s.Capture(2)
n, err := c.Write([]byte("abcdef"))
c.Close()
if n != 6 || err != nil {
t.Fatalf("drain: %d %v", n, err)
}
prefix, total, truncated := c.Snapshot()
if prefix != "ab" || total != 6 || !truncated || c.Info().Error == "" || !c.Info().Truncated {
t.Fatalf("%q %d %v %+v", prefix, total, truncated, c.Info())
}
}
-20
View File
@@ -1,20 +0,0 @@
//go:build unix
package process
import (
"errors"
"os"
"syscall"
)
func lockArtifact(f *os.File, nonblocking bool) error {
flags := syscall.LOCK_EX
if nonblocking {
flags |= syscall.LOCK_NB
}
return syscall.Flock(int(f.Fd()), flags)
}
func artifactBusy(err error) bool { return errors.Is(err, syscall.EWOULDBLOCK) }
func artifactReadFlags() int { return os.O_RDONLY | syscall.O_NONBLOCK | syscall.O_NOFOLLOW }
-44
View File
@@ -1,44 +0,0 @@
package process
import "sync"
// Capture retains a bounded prefix while draining all writes. It deliberately
// does not embed a buffer: io.Copy must not bypass Write through ReaderFrom.
// The zero value drains without retaining bytes.
type Capture struct {
mu sync.Mutex
limit int
data []byte
total int64
}
func NewCapture(limit int) *Capture {
if limit < 0 {
limit = 0
}
return &Capture{limit: limit}
}
func (c *Capture) Write(p []byte) (int, error) {
c.mu.Lock()
defer c.mu.Unlock()
n := len(p)
c.total += int64(n)
keep := min(n, c.limit-len(c.data))
c.data = append(c.data, p[:keep]...)
return n, nil
}
// Snapshot returns an independent prefix, observed byte count and truncation.
func (c *Capture) Snapshot() (string, int64, bool) {
c.mu.Lock()
defer c.mu.Unlock()
return string(c.data), c.total, c.total > int64(len(c.data))
}
// stats inspects accounting without allocating a copy of the retained bytes.
func (c *Capture) stats() (total int64, retained, limit int) {
c.mu.Lock()
defer c.mu.Unlock()
return c.total, len(c.data), c.limit
}
-41
View File
@@ -1,41 +0,0 @@
package process
import (
"bytes"
"path/filepath"
"testing"
)
func TestOutputCaptureFloodAllocationsPlateau(t *testing.T) {
store, err := NewArtifactStore(filepath.Join(t.TempDir(), "output"))
if err != nil {
t.Fatal(err)
}
capture := store.Capture(64 << 10)
defer capture.Close()
block := bytes.Repeat([]byte("x"), 32<<10)
for i := 0; i < 300; i++ {
if _, err = capture.Write(block); err != nil {
t.Fatal(err)
}
}
if info := capture.Info(); info.Bytes != ArtifactFileLimit || !info.Truncated {
t.Fatalf("disk not saturated: %+v", info)
}
allocations := testing.AllocsPerRun(100, func() {
if _, err := capture.Write(block); err != nil {
panic(err)
}
})
if allocations != 0 {
t.Fatalf("saturated capture allocates per write: %f", allocations)
}
prefix, total, truncated := capture.Snapshot()
if len(prefix) != 64<<10 || total <= 300*int64(len(block)) || !truncated {
t.Fatal("capture accounting changed")
}
t.Logf("saturated_write_allocations=%f retained_prefix_bytes=%d backing_capacity_bytes=%d", allocations, len(prefix), cap(capture.prefix.data))
if cap(capture.prefix.data) > 2*(64<<10)+8192 {
t.Fatal("capture backing storage exceeded allowance")
}
}
-40
View File
@@ -1,40 +0,0 @@
package process
import (
"io"
"strings"
"sync"
"testing"
)
func TestCaptureCopyBound(t *testing.T) {
c := NewCapture(17)
n, err := io.Copy(c, strings.NewReader(strings.Repeat("x", 1<<20)))
prefix, total, truncated := c.Snapshot()
if err != nil || n != 1<<20 || total != n || prefix != strings.Repeat("x", 17) || !truncated {
t.Fatalf("copy=%d err=%v prefix=%q total=%d truncated=%v", n, err, prefix, total, truncated)
}
}
func TestCaptureConcurrentAndEmpty(t *testing.T) {
var c Capture
var wg sync.WaitGroup
for range 10 {
wg.Go(func() {
for range 100 {
_, _ = c.Write([]byte("abc"))
c.Snapshot()
}
})
}
wg.Wait()
prefix, total, truncated := c.Snapshot()
if prefix != "" || total != 3000 || !truncated {
t.Fatalf("%q %d %v", prefix, total, truncated)
}
empty := NewCapture(10)
_, total, truncated = empty.Snapshot()
if total != 0 || truncated {
t.Fatal("empty capture marked truncated")
}
}
-28
View File
@@ -1,28 +0,0 @@
// Package process owns bounded subprocess shutdown. On Unix each command has
// its own process group. This is lifecycle management, not a security sandbox.
package process
import (
"context"
"os/exec"
"time"
)
// Command creates a command whose cancellation kills its owned process group.
// Run joins it and removes descendants left after normal exit. Callers using
// Start/Wait directly must call KillGroup when their protocol closes.
func Command(ctx context.Context, name string, args ...string) *exec.Cmd {
cmd := exec.CommandContext(ctx, name, args...)
configureGroup(cmd)
cmd.Cancel = func() error { return KillGroup(cmd) }
cmd.WaitDelay = 250 * time.Millisecond
return cmd
}
func Run(cmd *exec.Cmd) error {
err := cmd.Run()
cleanupErr := KillGroup(cmd)
if err != nil {
return err
}
return cleanupErr
}
-24
View File
@@ -1,24 +0,0 @@
//go:build !unix
package process
import (
"errors"
"os"
"os/exec"
)
func configureGroup(cmd *exec.Cmd) {}
// Other platforms stop the direct child only. Process-tree guarantees apply
// to the advertised Linux/macOS backends; isolation is a separate capability.
func KillGroup(cmd *exec.Cmd) error {
if cmd.Process == nil {
return nil
}
err := cmd.Process.Kill()
if errors.Is(err, os.ErrProcessDone) {
return nil
}
return err
}
-28
View File
@@ -1,28 +0,0 @@
//go:build unix
package process
import (
"errors"
"os/exec"
"syscall"
)
func configureGroup(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} }
// KillGroup only signals the group explicitly created for this command.
func KillGroup(cmd *exec.Cmd) error {
if cmd.Process == nil {
return nil
}
var err error
if cmd.SysProcAttr != nil && cmd.SysProcAttr.Setpgid {
err = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
} else {
err = cmd.Process.Kill()
}
if errors.Is(err, syscall.ESRCH) {
return nil
}
return err
}
-161
View File
@@ -1,161 +0,0 @@
package process
import (
"context"
"crypto/rand"
"errors"
"io"
"os/exec"
)
const HandleInputLimit = 64 << 10
type inputWrite struct {
data []byte
done chan error
}
// Handle owns one deliberately asynchronous process group. It does not survive
// its owner context or application shutdown; callers must Close or Wait.
type Handle struct {
ID string
ctx context.Context
cancel context.CancelFunc
command *exec.Cmd
stdin io.WriteCloser
stdout, stderr *OutputCapture
input chan inputWrite
inputDone, done chan struct{}
err error
}
type HandleSnapshot struct {
ID string
Running bool
ExitCode int
Error string
Stdout, Stderr string
StdoutBytes, StderrBytes int64
StdoutTruncated, StderrTruncated bool
StdoutArtifact, StderrArtifact ArtifactInfo
}
func StartHandle(parent context.Context, store *ArtifactStore, dir, name string, args ...string) (*Handle, error) {
return startHandle(parent, store, nil, dir, name, args...)
}
// StartHandleWithEnv uses only the supplied environment, without ambient inheritance.
func StartHandleWithEnv(parent context.Context, store *ArtifactStore, env []string, dir, name string, args ...string) (*Handle, error) {
return startHandle(parent, store, append([]string{}, env...), dir, name, args...)
}
func startHandle(parent context.Context, store *ArtifactStore, env []string, dir, name string, args ...string) (*Handle, error) {
if store == nil {
return nil, errors.New("background process requires an output store")
}
ctx, cancel := context.WithCancel(parent)
cmd := Command(ctx, name, args...)
cmd.Dir = dir
cmd.Env = env
stdin, err := cmd.StdinPipe()
if err != nil {
cancel()
return nil, err
}
h := &Handle{ID: rand.Text(), ctx: ctx, cancel: cancel, command: cmd, stdin: stdin, stdout: store.Capture(64 << 10), stderr: store.Capture(64 << 10), input: make(chan inputWrite, 1), inputDone: make(chan struct{}), done: make(chan struct{})}
cmd.Stdout = h.stdout
cmd.Stderr = h.stderr
if err := cmd.Start(); err != nil {
cancel()
stdin.Close()
h.stdout.Close()
h.stderr.Close()
return nil, err
}
go h.writeInput()
go func() {
defer close(h.done)
waitErr := cmd.Wait()
cleanupErr := KillGroup(cmd)
cancel()
stdin.Close()
<-h.inputDone
h.err = errors.Join(waitErr, cleanupErr, h.stdout.Close(), h.stderr.Close())
}()
return h, nil
}
func (h *Handle) writeInput() {
defer close(h.inputDone)
for {
select {
case <-h.ctx.Done():
return
case request := <-h.input:
if err := h.ctx.Err(); err != nil {
request.done <- err
continue
}
n, err := h.stdin.Write(request.data)
if err == nil && n != len(request.data) {
err = io.ErrShortWrite
}
request.done <- err
}
}
}
// Send waits for a bounded input write. If its context is cancelled after
// admission, the owned process is cancelled because a partial write cannot be
// withdrawn safely. Successful return means the pipe accepted all bytes.
func (h *Handle) Send(ctx context.Context, data []byte) error {
if err := ctx.Err(); err != nil {
return err
}
if len(data) > HandleInputLimit {
return errors.New("process input exceeds 64 KiB")
}
request := inputWrite{data: append([]byte(nil), data...), done: make(chan error, 1)}
select {
case <-ctx.Done():
return ctx.Err()
case <-h.done:
return errors.New("process already stopped")
case <-h.ctx.Done():
return h.ctx.Err()
case h.input <- request:
}
select {
case err := <-request.done:
return err
case <-h.done:
select {
case err := <-request.done:
return err
default:
return errors.New("process stopped before input delivery completed")
}
case <-ctx.Done():
h.cancel()
<-h.done
return ctx.Err()
}
}
func (h *Handle) Cancel() { h.cancel() }
func (h *Handle) Wait() error { <-h.done; return h.err }
func (h *Handle) Close() error { h.cancel(); return h.Wait() }
func (h *Handle) Snapshot() HandleSnapshot {
s := HandleSnapshot{ID: h.ID, Running: true, ExitCode: -1}
select {
case <-h.done:
s.Running = false
if h.command.ProcessState != nil {
s.ExitCode = h.command.ProcessState.ExitCode()
}
if h.err != nil {
s.Error = h.err.Error()
}
default:
}
s.Stdout, s.StdoutBytes, s.StdoutTruncated = h.stdout.Snapshot()
s.Stderr, s.StderrBytes, s.StderrTruncated = h.stderr.Snapshot()
s.StdoutArtifact, s.StderrArtifact = h.stdout.Info(), h.stderr.Info()
return s
}
-104
View File
@@ -1,104 +0,0 @@
//go:build unix
package process
import (
"context"
"strings"
"testing"
"time"
)
func TestHandleSendReadWait(t *testing.T) {
h, err := StartHandle(context.Background(), testStore(t), t.TempDir(), "sh", "-c", "read line; printf 'received:%s' \"$line\"")
if err != nil {
t.Fatal(err)
}
defer h.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := h.Send(ctx, []byte("hello\n")); err != nil {
t.Fatal(err)
}
if err := h.Wait(); err != nil {
t.Fatal(err)
}
result := h.Snapshot()
if result.Running || result.ExitCode != 0 || result.Stdout != "received:hello" {
t.Fatal(result)
}
if err := h.Send(ctx, []byte("late")); err == nil {
t.Fatal("input accepted after exit")
}
}
func TestHandleBoundedCaptureAndOwnerCancellation(t *testing.T) {
store := testStore(t)
h, err := StartHandle(context.Background(), store, t.TempDir(), "sh", "-c", "head -c 70000 /dev/zero")
if err != nil {
t.Fatal(err)
}
defer h.Close()
if err := h.Wait(); err != nil {
t.Fatal(err)
}
result := h.Snapshot()
if len(result.Stdout) != 64<<10 || result.StdoutBytes != 70000 || !result.StdoutTruncated {
t.Fatal("capture bound failed")
}
data, err := store.Read(context.Background(), result.StdoutArtifact)
if err != nil || len(data) != 70000 {
t.Fatal("full capture unavailable", err)
}
ctx, cancel := context.WithCancel(context.Background())
server, err := StartHandle(ctx, store, t.TempDir(), "sh", "-c", "sleep 30 & wait")
if err != nil {
t.Fatal(err)
}
defer server.Close()
cancel()
done := make(chan error, 1)
go func() { done <- server.Wait() }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("owned process did not stop")
}
if server.Snapshot().Running {
t.Fatal("cancelled process still running")
}
}
func TestHandleRejectsOversizedInput(t *testing.T) {
h, err := StartHandle(context.Background(), testStore(t), t.TempDir(), "sh", "-c", "sleep 30")
if err != nil {
t.Fatal(err)
}
defer h.Close()
if err := h.Send(context.Background(), []byte(strings.Repeat("x", HandleInputLimit+1))); err == nil {
t.Fatal("oversized input accepted")
}
}
func TestHandleCancelledInputStopsAndJoinsProcess(t *testing.T) {
h, err := StartHandle(context.Background(), testStore(t), t.TempDir(), "sh", "-c", "sleep 30")
if err != nil {
t.Fatal(err)
}
defer h.Close()
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
payload := []byte(strings.Repeat("x", HandleInputLimit))
// A process that never reads eventually fills its pipe; delivery cancellation
// must stop it rather than leave a queued or partially delivered write alive.
for i := 0; i < 32; i++ {
err = h.Send(ctx, payload)
if err != nil {
break
}
}
if err != context.DeadlineExceeded {
t.Fatal("blocked input did not observe deadline", err)
}
if h.Snapshot().Running {
t.Fatal("cancelled input returned before process joined")
}
}
+29 -317
View File
@@ -4,7 +4,6 @@ import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log/slog"
"strings"
@@ -29,21 +28,6 @@ func NewAnthropicProvider(apiKey, baseURL string) *AnthropicProvider {
return &AnthropicProvider{client: client}
}
// NewAnthropicProviderWithOptions creates a provider from Anthropic SDK request
// options, for endpoints NewAnthropicProvider can't express: gateways that want
// a bearer token (option.WithAuthToken) instead of X-Api-Key, or that reject the
// SDK's version header (option.WithHeaderDel("anthropic-version")). The SDK's
// environment defaults (ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN,
// ANTHROPIC_BASE_URL) still apply first; opts override them.
func NewAnthropicProviderWithOptions(opts ...option.RequestOption) *AnthropicProvider {
return &AnthropicProvider{client: anthropic.NewClient(opts...)}
}
// 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"},
@@ -71,18 +55,16 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
props = schema.Properties
required = schema.Required
}
tool := anthropic.ToolParam{
Name: t.Name,
Description: anthropic.String(t.Description),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: props,
Required: required,
tools = append(tools, anthropic.ToolUnionParam{
OfTool: &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)
@@ -99,111 +81,16 @@ 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.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.
if req.Temperature > 0 {
params.Temperature = anthropic.Float(req.Temperature)
}
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 anthropicThinksBetweenTools(model) {
// Sonnet 5.5 rejects {type:"disabled"}: its "off" is
// {type:"between_tools"} (no thinking before responding; the
// short updates between tool calls come back as thinking blocks).
params.Thinking = anthropic.ThinkingConfigParamUnion{
OfBetweenTools: &anthropic.ThinkingConfigBetweenToolsParam{},
}
} else if anthropicRejectsDisabledThinking(model) {
// Opus 5.5 can't turn thinking off: {type:"disabled"} is a 400
// ("use thinking.type.adaptive and output_config.effort").
// Adaptive at low effort is the closest accepted "off".
params.Thinking = anthropic.ThinkingConfigParamUnion{
OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{},
}
params.OutputConfig = anthropic.OutputConfigParam{
Effort: anthropic.OutputConfigEffortLow,
}
} 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 {
if cfg, ok := p.BuildThinkingConfig(model, req.Reasoning); ok {
required := cfg.BudgetTokens + 4096
if maxTokens < required {
maxTokens = required
@@ -254,14 +141,12 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
type pendingTC struct {
id string
name string
inputJSON strings.Builder // built from input_json_delta events
startInput string // captured from content_block_start (proxy fallback)
inputJSON string // 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()
@@ -278,10 +163,6 @@ 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{
@@ -314,38 +195,20 @@ 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.WriteString(delta.PartialJSON)
pendingTools[len(pendingTools)-1].inputJSON += 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 {
// 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]
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.String()
inp := tc.inputJSON
if inp == "" {
inp = tc.startInput
}
@@ -364,14 +227,7 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
currentBlockType = ""
case "message_delta":
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 != "" {
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 {
slog.Info("anthropic stream usage",
"input_tokens", inputTokens,
"output_tokens", event.Usage.OutputTokens,
@@ -381,13 +237,11 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
events <- llm.ChatEvent{
Type: llm.EventDone,
Usage: &llm.Usage{
InputTokens: int(inputTokens + cacheCreationTokens + cacheReadTokens),
InputTokens: int(inputTokens),
OutputTokens: int(event.Usage.OutputTokens),
CacheCreationInputTokens: int(cacheCreationTokens),
CacheReadInputTokens: int(cacheReadTokens),
},
StopReason: stopReason,
StopCategory: stopCategory,
}
}
@@ -395,14 +249,7 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
// Final event — nothing extra to emit
case "error":
// 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"),
}
slog.Error("anthropic stream error", "event", event.Type)
}
}
@@ -424,8 +271,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.
//
// Thinking blocks are surfaced as EventThinkingBlock events so the runtime
// can store and echo them back in subsequent turns.
// Note: thinking blocks (when reasoning is enabled) are NOT surfaced —
// matches the streaming path which also doesn't emit thinking deltas.
// 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)
@@ -439,16 +286,6 @@ 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}
@@ -484,13 +321,11 @@ func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRe
events <- llm.ChatEvent{
Type: llm.EventDone,
Usage: &llm.Usage{
InputTokens: int(msg.Usage.InputTokens + msg.Usage.CacheCreationInputTokens + msg.Usage.CacheReadInputTokens),
InputTokens: int(msg.Usage.InputTokens),
OutputTokens: int(msg.Usage.OutputTokens),
CacheCreationInputTokens: int(msg.Usage.CacheCreationInputTokens),
CacheReadInputTokens: int(msg.Usage.CacheReadInputTokens),
},
StopReason: string(msg.StopReason),
StopCategory: string(msg.StopDetails.Category),
}
}()
return events, nil
@@ -539,77 +374,6 @@ 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
}
// anthropicThinksBetweenTools reports models whose reasoning-off setting is
// {type:"between_tools"} rather than {type:"disabled"}.
func anthropicThinksBetweenTools(model string) bool {
return strings.Contains(model, "claude-sonnet-5-5")
}
// anthropicRejectsDisabledThinking reports whether the model returns a 400
// for thinking {type:"disabled"}. Checked before anthropicThinksByDefault,
// whose "claude-opus-5" marker also matches Opus 5.5 IDs.
func anthropicRejectsDisabledThinking(model string) bool {
return strings.Contains(model, "claude-opus-5-5")
}
// 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.
@@ -650,49 +414,24 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
i-- // un-consume; outer loop will re-process
break
}
block := buildToolResultBlock(cur)
if cacheRequested(cur.CacheControl) {
setCacheControlOnBlock(&block, cur.CacheControl)
}
blocks = append(blocks, block)
blocks = append(blocks, buildToolResultBlock(cur))
}
msgs = append(msgs, anthropic.NewUserMessage(blocks...))
} else if len(m.Images) > 0 {
var blocks []anthropic.ContentBlockParamUnion
for _, img := range m.Images {
encoded := base64.StdEncoding.EncodeToString(img.Data)
if img.MimeType == "application/pdf" {
blocks = append(blocks, anthropic.NewDocumentBlock(anthropic.Base64PDFSourceParam{Data: encoded}))
continue
}
blocks = append(blocks, anthropic.NewImageBlockBase64(img.MimeType, encoded))
}
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 {
block := anthropic.NewTextBlock(m.Content)
if cacheRequested(m.CacheControl) {
setCacheControlOnBlock(&block, m.CacheControl)
}
msgs = append(msgs, anthropic.NewUserMessage(block))
msgs = append(msgs, anthropic.NewUserMessage(anthropic.NewTextBlock(m.Content)))
}
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))
}
@@ -704,9 +443,6 @@ 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...))
}
}
@@ -717,7 +453,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], nil)
setCacheControlOnBlock(&tail.Content[len(tail.Content)-1])
}
}
return msgs
@@ -729,8 +465,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, cache *llm.CacheControl) {
cc := anthropicCacheControl(cache)
func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion) {
cc := anthropic.NewCacheControlEphemeralParam()
switch {
case block.OfText != nil:
block.OfText.CacheControl = cc
@@ -738,8 +474,6 @@ func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion, cache *llm.
block.OfToolResult.CacheControl = cc
case block.OfImage != nil:
block.OfImage.CacheControl = cc
case block.OfDocument != nil:
block.OfDocument.CacheControl = cc
case block.OfToolUse != nil:
block.OfToolUse.CacheControl = cc
}
@@ -755,16 +489,6 @@ func buildToolResultBlock(m llm.Message) anthropic.ContentBlockParamUnion {
var content []anthropic.ToolResultBlockParamContentUnion
for _, img := range m.Images {
encoded := base64.StdEncoding.EncodeToString(img.Data)
if img.MimeType == "application/pdf" {
content = append(content, anthropic.ToolResultBlockParamContentUnion{
OfDocument: &anthropic.DocumentBlockParam{
Source: anthropic.DocumentBlockParamSourceUnion{
OfBase64: &anthropic.Base64PDFSourceParam{Data: encoded},
},
},
})
continue
}
content = append(content, anthropic.ToolResultBlockParamContentUnion{
OfImage: &anthropic.ImageBlockParam{
Source: anthropic.ImageBlockParamSourceUnion{
@@ -804,8 +528,8 @@ func buildAnthropicSystem(req llm.ChatRequest) []anthropic.TextBlockParam {
continue
}
b := anthropic.TextBlockParam{Text: p.Text}
if p.Cache || cacheRequested(p.CacheControl) {
b.CacheControl = anthropicCacheControl(p.CacheControl)
if p.Cache {
b.CacheControl = anthropic.NewCacheControlEphemeralParam()
}
blocks = append(blocks, b)
}
@@ -819,15 +543,3 @@ 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
}
+2 -505
View File
@@ -6,14 +6,12 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
anthropic "github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
"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.
@@ -222,101 +220,6 @@ func TestAnthropic_ToolResultsWithImages(t *testing.T) {
assert.True(t, p3.IsError.Value)
}
// TestAnthropic_ToolResultWithPDFAttachment verifies that a tool result
// carrying a PDF attachment (MimeType "application/pdf") emits a
// document block with media_type application/pdf and the base64 data,
// alongside a separate image attachment's own image block.
func TestAnthropic_ToolResultWithPDFAttachment(t *testing.T) {
pngBytes := []byte{0x89, 0x50, 0x4E, 0x47}
pdfBytes := []byte("%PDF-1.4 fake pdf bytes")
in := []llm.Message{
{
Role: "assistant",
ToolCalls: []llm.ToolCall{
{ID: "R1", Name: "read_document", Input: []byte(`{}`)},
},
},
{
Role: "user",
ToolCallID: "R1",
Content: "here are the pages",
Images: []llm.ImageContent{
{MimeType: "image/png", Data: pngBytes},
{MimeType: "application/pdf", Data: pdfBytes},
},
},
}
got := buildAnthropicMessages(in, false)
require.Len(t, got, 2)
toolResult := got[1].Content[0].OfToolResult
require.NotNil(t, toolResult)
require.Len(t, toolResult.Content, 3, "image + document + text caption")
require.NotNil(t, toolResult.Content[0].OfImage)
assert.Equal(t, base64.StdEncoding.EncodeToString(pngBytes), toolResult.Content[0].OfImage.Source.OfBase64.Data)
doc := toolResult.Content[1].OfDocument
require.NotNil(t, doc, "expected a document block for the PDF attachment")
require.NotNil(t, doc.Source.OfBase64)
assert.Equal(t, base64.StdEncoding.EncodeToString(pdfBytes), doc.Source.OfBase64.Data)
require.NotNil(t, toolResult.Content[2].OfText)
assert.Equal(t, "here are the pages", toolResult.Content[2].OfText.Text)
// Confirm the wire format: media_type defaults to "application/pdf" only
// on marshal (it's a zero-value constant type until then).
raw, err := json.Marshal(toolResult.Content[1])
require.NoError(t, err)
assert.Contains(t, string(raw), `"media_type":"application/pdf"`)
assert.Contains(t, string(raw), `"type":"document"`)
}
// TestAnthropic_UserMessageWithPDFAttachment verifies that a PDF attachment
// on a plain user message (not a tool result) also produces a document
// block rather than an image block.
func TestAnthropic_UserMessageWithPDFAttachment(t *testing.T) {
pdfBytes := []byte("%PDF-1.4 fake pdf bytes")
in := []llm.Message{
{
Role: "user",
Content: "read this",
Images: []llm.ImageContent{
{MimeType: "application/pdf", Data: pdfBytes},
},
},
}
got := buildAnthropicMessages(in, false)
require.Len(t, got, 1)
require.Len(t, got[0].Content, 2, "document block + text")
doc := got[0].Content[0].OfDocument
require.NotNil(t, doc, "expected a document block for the PDF attachment")
require.NotNil(t, doc.Source.OfBase64)
assert.Equal(t, base64.StdEncoding.EncodeToString(pdfBytes), doc.Source.OfBase64.Data)
require.Nil(t, got[0].Content[0].OfImage)
require.NotNil(t, got[0].Content[1].OfText)
assert.Equal(t, "read this", got[0].Content[1].OfText.Text)
}
// TestAnthropic_ImageOnlyToolResultUnchanged pins the pre-PDF behavior: a
// tool result with only image attachments (no PDFs) is unaffected by the
// PDF branch added to buildToolResultBlock.
func TestAnthropic_ImageOnlyToolResultUnchanged(t *testing.T) {
pngBytes := []byte{0x89, 0x50, 0x4E, 0x47}
in := []llm.Message{
{Role: "assistant", ToolCalls: []llm.ToolCall{{ID: "I1", Name: "snap", Input: []byte(`{}`)}}},
{Role: "user", ToolCallID: "I1", Images: []llm.ImageContent{{MimeType: "image/png", Data: pngBytes}}},
}
got := buildAnthropicMessages(in, false)
require.Len(t, got, 2)
tr := got[1].Content[0].OfToolResult
require.NotNil(t, tr)
require.Len(t, tr.Content, 1)
require.NotNil(t, tr.Content[0].OfImage)
require.Nil(t, tr.Content[0].OfDocument)
}
func TestAnthropicSystemPromptPartsEmitCacheControl(t *testing.T) {
got := buildAnthropicSystem(llm.ChatRequest{
SystemPromptParts: []llm.SystemPromptPart{
@@ -331,65 +234,6 @@ 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)
@@ -520,35 +364,7 @@ data: {"type":"message_stop"}
require.Equal(t, 42, done.Usage.CacheCreationInputTokens)
require.Equal(t, 17, done.Usage.CacheReadInputTokens)
require.Equal(t, 5, done.Usage.OutputTokens)
require.Equal(t, 69, done.Usage.InputTokens) // 10 uncached + 42 cache creation + 17 cache read
}
// TestNewAnthropicProviderWithOptionsGatewayAuth checks the gateway shape:
// a bearer token instead of X-Api-Key, and no anthropic-version header.
func TestNewAnthropicProviderWithOptionsGatewayAuth(t *testing.T) {
t.Setenv("ANTHROPIC_API_KEY", "")
t.Setenv("ANTHROPIC_AUTH_TOKEN", "")
var got http.Header
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r.Header.Clone()
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"))
}))
t.Cleanup(srv.Close)
p := NewAnthropicProviderWithOptions(
option.WithAuthToken("gw-token"),
option.WithBaseURL(srv.URL),
option.WithHeaderDel("anthropic-version"),
)
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-test"})
require.NoError(t, err)
for range stream {
}
require.NotNil(t, got, "expected a request")
require.Equal(t, "Bearer gw-token", got.Get("Authorization"))
require.Empty(t, got.Get("X-Api-Key"))
require.Empty(t, got.Get("Anthropic-Version"))
require.Equal(t, 10, done.Usage.InputTokens)
}
// TestBuildMessageParamsIsPure protects the cache-prefix invariant
@@ -705,322 +521,3 @@ 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"`)
})
}
}
// TestOpus5_5_ReasoningOffSendsAdaptiveLow guards against a 400 from Opus
// 5.5: its ID matches the "claude-opus-5" marker, so it inherited Opus 5's
// explicit {type:"disabled"} — which Opus 5.5 rejects ("thinking.type.disabled
// is not supported for this model"). The nearest accepted equivalent of
// "reasoning off" is adaptive thinking at low effort.
func TestOpus5_5_ReasoningOffSendsAdaptiveLow(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
for _, model := range []string{"claude-opus-5-5", "claude-opus-5-5-global"} {
t.Run(model, func(t *testing.T) {
got := wireJSON(t, p, llm.ChatRequest{
Model: model,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.NotContains(t, got, `"disabled"`,
"Opus 5.5 rejects thinking.type.disabled")
assert.Contains(t, got, `"thinking":{"type":"adaptive"}`)
assert.Contains(t, got, `"effort":"low"`)
})
}
}
// TestSonnet5_5_ReasoningOffSendsBetweenTools guards against a 400 from
// Sonnet 5.5, which rejects {type:"disabled"} ("To turn thinking off on this
// model, send thinking: {type: between_tools}"). Gateway aliases match too.
func TestSonnet5_5_ReasoningOffSendsBetweenTools(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
for _, model := range []string{"claude-sonnet-5-5", "claude-sonnet-5-5-global"} {
t.Run(model, func(t *testing.T) {
got := wireJSON(t, p, llm.ChatRequest{
Model: model,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.NotContains(t, got, `"disabled"`)
assert.Contains(t, got, `"thinking":{"type":"between_tools"}`)
})
}
// Sonnet 5 keeps its explicit disabled config.
got := wireJSON(t, p, llm.ChatRequest{Model: "claude-sonnet-5", Messages: []llm.Message{{Role: "user", Content: "hi"}}})
assert.Contains(t, got, `"thinking":{"type":"disabled"}`)
}
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())
}
+10 -54
View File
@@ -2,15 +2,10 @@ 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"
@@ -187,8 +182,6 @@ 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}
@@ -196,9 +189,13 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
if resp.UsageMetadata != nil {
lastUsage = updateUsage(lastUsage,
int(resp.UsageMetadata.PromptTokenCount),
int(resp.UsageMetadata.CandidatesTokenCount))
events <- llm.ChatEvent{
Type: llm.EventDone,
Usage: &llm.Usage{
InputTokens: int(resp.UsageMetadata.PromptTokenCount),
OutputTokens: int(resp.UsageMetadata.CandidatesTokenCount),
},
}
}
for _, cand := range resp.Candidates {
@@ -218,25 +215,9 @@ 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 = syntheticToolCallID()
id = fc.Name
}
events <- llm.ChatEvent{
Type: llm.EventToolCallStart,
@@ -259,37 +240,12 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
// Ensure a Done event is always sent
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
events <- llm.ChatEvent{Type: llm.EventDone}
}()
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.
@@ -339,7 +295,7 @@ func geminiSupportsThinking(model string) bool {
}
// geminiResolveSystemPrompt returns the effective system prompt string,
// preferring SystemPromptParts when present. Mirrors the OpenAI
// preferring SystemPromptParts when present. Mirrors the OpenAI/Qwen
// 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,7 +1,6 @@
package gemini
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
@@ -25,31 +24,3 @@ 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
@@ -1,19 +0,0 @@
// 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
@@ -1,33 +0,0 @@
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")
}
-28
View File
@@ -1,28 +0,0 @@
// Package local provides an llm.LLMProvider for a locally-served model —
// Ollama, LM Studio, llama.cpp's server, vLLM, or anything else exposing
// an OpenAI-compatible endpoint on the caller's own machine or network.
// Like providers/litellm and providers/openrouter, this adds no new
// request/stream-translation code of its own — it's a thin constructor
// around harness's existing OpenAI-compatible support.
package local
import "github.com/sausheong/harness/providers/openai"
// DefaultBaseURL is used when NewLocalProvider is called with an empty
// baseURL. It's Ollama's endpoint specifically — the most common local
// server — but any other one works the same way via an explicit baseURL.
const DefaultBaseURL = "http://localhost:11434/v1"
// NewLocalProvider returns an OpenAI-compatible provider pointed at
// baseURL, or DefaultBaseURL when baseURL is empty. No API key is
// needed — local servers generally don't authenticate requests.
// kind="local" suppresses reasoning_effort, since locally-served models
// don't uniformly support it, and keeps retryable-error classification
// from treating a down local server the way it would a hosted API
// outage (see llm/retry.go).
func NewLocalProvider(baseURL string) *openai.OpenAIProvider {
if baseURL == "" {
baseURL = DefaultBaseURL
}
return openai.NewOpenAIProviderWithKind("", baseURL, "local")
}
-46
View File
@@ -1,46 +0,0 @@
package local
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, "http://localhost:11434/v1", DefaultBaseURL)
}
// TestNewLocalProvider_HitsGivenBaseURL confirms a custom baseURL
// overrides the default and is actually what the provider talks to.
func TestNewLocalProvider_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 := NewLocalProvider(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")
}
// TestNewLocalProvider_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 TestNewLocalProvider_EmptyBaseURLDoesNotPanic(t *testing.T) {
p := NewLocalProvider("")
require.NotNil(t, p)
}
-42
View File
@@ -1,42 +0,0 @@
package openai
import (
"context"
"fmt"
"github.com/sausheong/harness/llm"
"net/http"
"net/http/httptest"
"testing"
)
func TestPreservesOutputLimitAndTrailingUsage(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, `data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"partial","type":"function","function":{"name":"bash","arguments":"{\"command\":"}}]},"finish_reason":"length"}]}`+"\n\n")
fmt.Fprint(w, `data: {"choices":[],"usage":{"prompt_tokens":50,"completion_tokens":2048,"total_tokens":2098}}`+"\n\ndata: [DONE]\n\n")
}))
defer srv.Close()
p := NewOpenAIProviderWithKind("fixture", srv.URL, "openai-compatible")
events, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "fixture"})
if err != nil {
t.Fatal(err)
}
found := false
for e := range events {
if e.Type == llm.EventToolCallDone {
t.Fatal("truncated tool accepted")
}
if e.Type == llm.EventError {
t.Fatal(e.Error)
}
if e.Type == llm.EventDone {
found = true
if e.StopReason != "length" || e.Usage == nil || e.Usage.OutputTokens != 2048 {
t.Fatalf("%+v", e)
}
}
}
if !found {
t.Fatal("missing terminal event")
}
}
+20 -72
View File
@@ -14,13 +14,6 @@ import (
"github.com/sausheong/harness/llm"
)
// pdfAttachmentPlaceholder replaces a PDF attachment (llm.ImageContent with
// MimeType "application/pdf") in outgoing messages: OpenAI's image_url part
// only accepts image MIME types, so sending a PDF that way would either be
// silently ignored or rejected by the API. Gemini accepts application/pdf
// inline natively and is not routed through this builder.
const pdfAttachmentPlaceholder = "[PDF attachment omitted: this provider can't read PDFs]"
// logOpenAIError unwraps the go-openai SDK error into a structured slog.WARN
// record so we can see exactly why LiteLLM/OpenAI rejected the request — the
// SDK's flat error string drops Param, Type, Code, and the raw response body
@@ -136,13 +129,6 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
if len(m.Images) > 0 {
var parts []openai.ChatMessagePart
for _, img := range m.Images {
if img.MimeType == "application/pdf" {
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeText,
Text: pdfAttachmentPlaceholder,
})
continue
}
encoded := base64.StdEncoding.EncodeToString(img.Data)
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
parts = append(parts, openai.ChatMessagePart{
@@ -165,13 +151,6 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
} else if len(m.Images) > 0 {
var parts []openai.ChatMessagePart
for _, img := range m.Images {
if img.MimeType == "application/pdf" {
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeText,
Text: pdfAttachmentPlaceholder,
})
continue
}
encoded := base64.StdEncoding.EncodeToString(img.Data)
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
parts = append(parts, openai.ChatMessagePart{
@@ -292,10 +271,14 @@ 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
var finishReason string
for {
resp, err := stream.Recv()
@@ -315,13 +298,6 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
InputTokens: resp.Usage.PromptTokens,
OutputTokens: resp.Usage.CompletionTokens,
}
// OpenAI-compatible servers (vLLM, llama.cpp, ...) report
// server-side prefix-cache hits via
// prompt_tokens_details.cached_tokens. Surface them as cache
// reads so downstream pricing/analytics see them.
if resp.Usage.PromptTokensDetails != nil && resp.Usage.PromptTokensDetails.CachedTokens > 0 {
lastUsage.CacheReadInputTokens = resp.Usage.PromptTokensDetails.CachedTokens
}
}
for _, choice := range resp.Choices {
@@ -361,63 +337,35 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
}
if tc.Function.Arguments != "" {
pending.args.WriteString(tc.Function.Arguments)
pending.argsJSON += tc.Function.Arguments
}
}
// Finish reason
if choice.FinishReason != "" {
finishReason = string(choice.FinishReason)
}
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
emitToolCalls(events, toolCalls)
clear(toolCalls)
// 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, Usage: lastUsage, StopReason: finishReason}
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
}()
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"}
-89
View File
@@ -6,7 +6,6 @@ import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
openai "github.com/sashabaranov/go-openai"
@@ -74,91 +73,3 @@ func TestOpenAIChatStreamPartsBeatString(t *testing.T) {
require.GreaterOrEqual(t, len(captured.Messages), 1)
require.Equal(t, "new", captured.Messages[0].Content)
}
// TestOpenAIChatStream_PDFToolResultOmittedWithPlaceholder verifies that a
// PDF attachment on a tool result is never emitted as an image_url data
// URI (which would be invalid — image_url expects an image MIME type) and
// that the placeholder text takes its place; a real image attachment in
// the same result is still emitted.
func TestOpenAIChatStream_PDFToolResultOmittedWithPlaceholder(t *testing.T) {
pngBytes := []byte{0x89, 0x50, 0x4E, 0x47}
pdfBytes := []byte("%PDF-1.4 fake")
captured := captureOpenAIRequest(t, llm.ChatRequest{
Messages: []llm.Message{
{
Role: "user",
ToolCallID: "T1",
Content: "see attached",
Images: []llm.ImageContent{
{MimeType: "image/png", Data: pngBytes},
{MimeType: "application/pdf", Data: pdfBytes},
},
},
},
})
require.NotNil(t, captured)
var sawImage, sawPlaceholder bool
for _, m := range captured.Messages {
for _, part := range m.MultiContent {
if part.Type == openai.ChatMessagePartTypeImageURL && part.ImageURL != nil {
require.NotContains(t, part.ImageURL.URL, "application/pdf", "a PDF must never be sent as image_url")
sawImage = true
}
if part.Type == openai.ChatMessagePartTypeText && strings.Contains(part.Text, pdfAttachmentPlaceholder) {
sawPlaceholder = true
}
}
}
require.True(t, sawImage, "the PNG attachment must still be emitted as image_url")
require.True(t, sawPlaceholder, "the PDF attachment must be replaced with the placeholder text")
}
// TestOpenAIChatStream_PDFUserMessageOmittedWithPlaceholder covers the
// plain user-message image branch (not a tool result).
func TestOpenAIChatStream_PDFUserMessageOmittedWithPlaceholder(t *testing.T) {
pdfBytes := []byte("%PDF-1.4 fake")
captured := captureOpenAIRequest(t, llm.ChatRequest{
Messages: []llm.Message{
{
Role: "user",
Content: "read this",
Images: []llm.ImageContent{{MimeType: "application/pdf", Data: pdfBytes}},
},
},
})
require.NotNil(t, captured)
var sawImageURL, sawPlaceholder bool
for _, m := range captured.Messages {
for _, part := range m.MultiContent {
if part.Type == openai.ChatMessagePartTypeImageURL {
sawImageURL = true
}
if part.Type == openai.ChatMessagePartTypeText && strings.Contains(part.Text, pdfAttachmentPlaceholder) {
sawPlaceholder = true
}
}
}
require.False(t, sawImageURL, "a PDF must never be sent as image_url")
require.True(t, sawPlaceholder, "the PDF attachment must be replaced with the placeholder text")
}
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")
}
-42
View File
@@ -1,42 +0,0 @@
package openai
import (
"context"
"fmt"
"github.com/sausheong/harness/llm"
"net/http"
"net/http/httptest"
"testing"
)
func TestRepeatedFinishEmitsToolOnlyOnce(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_one\",\"type\":\"function\",\"function\":{\"name\":\"bash\",\"arguments\":\"{}\"}}]}}]}\n\n")
for i := 0; i < 2; i++ {
fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n")
}
fmt.Fprint(w, "data: [DONE]\n\n")
}))
defer srv.Close()
p := NewOpenAIProviderWithKind("fixture", srv.URL, "openai-compatible")
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "fixture"})
if err != nil {
t.Fatal(err)
}
calls, done := 0, 0
for e := range stream {
if e.Type == llm.EventToolCallDone {
calls++
}
if e.Type == llm.EventDone {
done++
}
if e.Type == llm.EventError {
t.Fatal(e.Error)
}
}
if calls != 1 || done != 1 {
t.Fatalf("calls=%d done=%d", calls, done)
}
}
-23
View File
@@ -1,23 +0,0 @@
// 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
@@ -1,45 +0,0 @@
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
@@ -0,0 +1,350 @@
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
@@ -0,0 +1,26 @@
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)
}
-34
View File
@@ -1,34 +0,0 @@
# Steering boundary contract
`WithSteering` installs a prompt source for `Runtime.Run`/`RunSync`. It is polled
after a model response and between joined tools. Without a source, existing tool
concurrency and streaming kickoff behaviour is unchanged. With a source, tools
run serially and streaming kickoff is disabled, providing a boundary before
each remaining proposed call.
A source returns nil when no correction is pending. Otherwise it returns a
stable ID, nonempty UTF-8 text bounded to 8 MiB after JSON encoding, up to 16 images
with at most 32 MiB of image bytes in total, and an optional acknowledgement
callback. The source must retain that correction until acknowledgement, honour
cancellation, and return promptly. IDs are at most 128 bytes. A delivered ID
must never be reused with different text.
On delivery, remaining calls receive explicit skipped results, then the user
correction is appended under its stable ID and flushed. Only then does Harness
acknowledge the source. The next model turn sees that history. Source or
persistence errors stop execution. An acknowledgement failure also stops the
run; redelivery of the same ID/text acknowledges without appending a duplicate.
This API does not cancel an already executing tool or take over its approval.
The host must manage queue ownership, freeze text while delivery is claimed,
reconcile acknowledgement failures, and render pending/delivered state. A
correction arriving during a pending approval waits for that tool's execution
boundary; separate cancellation remains available. `RunTurn` does not currently
use this API. Native platform and integrated Hand qualification remain pending.
Steering images use the session attachment store and are verified/hydrated for
identity comparison on redelivery. `MatchesSteering` exposes that semantic
comparison to hosts reconciling interrupted acknowledgements. Text and image
bytes must remain immutable while a delivery is unresolved. These limits bound
the data; hosts must still enforce their model image capabilities and file
attachment policies before supplying a correction.
+7 -63
View File
@@ -246,7 +246,7 @@ func TestPruneToolResults(t *testing.T) {
}
// Empty spillConfig → legacy in-place truncation path.
pruneToolResults(msgs, 10000, spillConfig{}, nil)
pruneToolResults(msgs, 10000, spillConfig{})
// 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{}, nil)
pruneToolResults(msgs, 10000, spillConfig{})
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{}, nil)
pruneToolResults(msgs, 10000, spillConfig{})
// 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"}, nil)
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_abc"})
// 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, nil)
pruneToolResults(msgs, 10000, cfg)
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, nil)
pruneToolResults(msgs, 10000, cfg)
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"}, nil)
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_fail"})
got := msgs[0].Content
assert.Less(t, len(got), 20000, "fallback must still bound the message")
@@ -357,31 +357,6 @@ 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) {
@@ -896,37 +871,6 @@ 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.
-23
View File
@@ -1,23 +0,0 @@
package runtime
import (
"github.com/sausheong/harness/process"
"github.com/sausheong/harness/tool"
)
// Only typed, completed built-in capture metadata becomes an artifact reference.
// MCP JSON maps or paths mentioned in tool output are never interpreted as files.
func resultArtifacts(result tool.ToolResult) map[string]process.ArtifactInfo {
var artifacts map[string]process.ArtifactInfo
for _, stream := range []string{"stdout", "stderr"} {
info, ok := result.Metadata[stream+"_artifact"].(process.ArtifactInfo)
if !ok || info.Path == "" || len(info.Path) > 4096 || len(info.SHA256) != 64 || info.Bytes < 0 || info.Bytes > process.ArtifactFileLimit || info.Error != "" {
continue
}
if artifacts == nil {
artifacts = make(map[string]process.ArtifactInfo)
}
artifacts[stream] = info
}
return artifacts
}
-77
View File
@@ -1,77 +0,0 @@
package runtime
import (
"context"
"encoding/json"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/process"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/sausheong/harness/tools/bash"
"path/filepath"
"testing"
)
func TestDispatchedArtifactReferenceSurvivesReopen(t *testing.T) {
outputStore, err := process.NewArtifactStore(filepath.Join(t.TempDir(), "output"))
if err != nil {
t.Fatal(err)
}
store := session.NewStore(t.TempDir())
if err := store.Create("agent", "key"); err != nil {
t.Fatal(err)
}
sess, err := store.LoadExclusive("agent", "key")
if err != nil {
t.Fatal(err)
}
registry := tool.NewRegistry()
registry.Register(&bash.BashTool{WorkDir: t.TempDir(), OutputStore: outputStore})
rt := &Runtime{Session: sess, Tools: registry, AgentID: "agent"}
result, aborted := rt.dispatchTool(context.Background(), llm.ToolCall{ID: "capture", Name: "bash", Input: json.RawMessage(`{"command":"head -c 70000 /dev/zero"}`)}, nil)
if aborted || result.Error != "" {
t.Fatal(aborted, result.Error)
}
if err := sess.Close(); err != nil {
t.Fatal(err)
}
sess, err = store.LoadExclusive("agent", "key")
if err != nil {
t.Fatal(err)
}
defer sess.Close()
found := false
for _, entry := range sess.View() {
if entry.Type != session.EntryTypeToolResult {
continue
}
var data session.ToolResultData
if err := json.Unmarshal(entry.Data, &data); err != nil {
t.Fatal(err)
}
ref, ok := data.Artifacts["stdout"]
if !ok {
t.Fatal("artifact reference missing after reopen")
}
captured, err := outputStore.Read(context.Background(), ref)
if err != nil || len(captured) != 70000 || ref.Truncated {
t.Fatal("persisted artifact cannot be verified", len(captured), err)
}
for _, b := range captured {
if b != 0 {
t.Fatal("artifact bytes changed")
}
}
found = true
}
if !found {
t.Fatal("no persisted tool result")
}
}
func TestArtifactMetadataDoesNotPromoteUntrustedJSON(t *testing.T) {
result := tool.ToolResult{Output: "[stdout artifact: /outside/private]", Metadata: map[string]any{"stdout_artifact": map[string]any{"path": "/outside/private", "sha256": "claimed"}}}
if resultArtifacts(result) != nil {
t.Fatal("untrusted JSON became artifact capability")
}
}
-81
View File
@@ -1,81 +0,0 @@
package runtime
import (
"context"
"encoding/base64"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
)
type attachmentReplayProvider struct {
llmtest.Base
calls int
images []llm.ImageContent
}
func (p *attachmentReplayProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.calls++
for _, msg := range req.Messages {
p.images = append(p.images, msg.Images...)
}
events := make(chan llm.ChatEvent, 2)
events <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
events <- llm.ChatEvent{Type: llm.EventDone}
close(events)
return events, nil
}
func TestRuntimeReplaysAttachmentsAndRejectsMissingBlobs(t *testing.T) {
for _, missing := range []bool{false, true} {
name := "replay"
if missing {
name = "missing"
}
t.Run(name, func(t *testing.T) {
dir := t.TempDir()
store := session.NewStore(dir)
if err := store.Create("agent", "key"); err != nil {
t.Fatal(err)
}
sess, err := store.LoadExclusive("agent", "key")
if err != nil {
t.Fatal(err)
}
sess.Append(session.UserMessageWithImagesEntry("original", []session.ImageData{{MimeType: "image/png", Data: base64.StdEncoding.EncodeToString([]byte("original image"))}}))
if err := sess.Flush(); err != nil {
t.Fatal(err)
}
sess.Close()
sess, err = store.LoadExclusive("agent", "key")
if err != nil {
t.Fatal(err)
}
defer sess.Close()
if missing {
var data session.MessageData
json.Unmarshal(sess.History()[0].Data, &data)
if err := os.Remove(filepath.Join(dir, "agent", ".attachments", data.Images[0].Reference.SHA256)); err != nil {
t.Fatal(err)
}
}
provider := &attachmentReplayProvider{}
rt := &Runtime{Session: sess, LLM: provider, Tools: usageNoopExecutor{}, Model: "model", MaxTurns: 1}
_, err = rt.RunSync(context.Background(), "continue", nil)
if missing {
if err == nil || provider.calls != 0 {
t.Fatal("missing image silently omitted", err, provider.calls)
}
return
}
if err != nil || provider.calls != 1 || len(provider.images) != 1 || string(provider.images[0].Data) != "original image" {
t.Fatal(provider, err)
}
})
}
}
+30 -121
View File
@@ -70,23 +70,9 @@ type RuntimeInputs struct {
// 2. Parsing the reasoning mode (default-to-off + warn on invalid)
// 3. Resolving the per-agent KnowledgeGraph via deps.KGFn (nil-safe)
//
// Use BuildRuntimeContext when construction must be cancellable.
// Returns the constructed Runtime and a nil error today, but callers MUST
// check the error: the return is reserved for future validation.
func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runtime, error) {
return BuildRuntimeContext(context.Background(), deps, inputs, spec)
}
// BuildRuntimeContext propagates cancellation through MCP initialization and
// discovery. On failure, all established sessions are closed before returning;
// the caller's registry receives no partially discovered tools. The context
// bounds construction, not the lifetime of successfully connected sessions.
func BuildRuntimeContext(ctx context.Context, deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (_ *Runtime, buildErr error) {
if spec.MaxOutputTokens < 0 {
return nil, fmt.Errorf("max output tokens cannot be negative")
}
if err := ctx.Err(); err != nil {
return nil, err
}
provider, modelName := llm.ParseProviderModel(spec.Model)
reasoning, err := llm.ParseReasoningMode(spec.Reasoning)
if err != nil {
@@ -105,73 +91,51 @@ func BuildRuntimeContext(ctx context.Context, deps RuntimeDeps, inputs RuntimeIn
// callers always pass *tool.Registry; test paths that don't won't
// get load tools registered (which is fine for them).
var mcpClients []*mcp.Client
var mcpStatus []MCPServerStatus
names := make(map[string]bool)
for _, srv := range spec.MCPServers {
if srv.Name == "" || names[srv.Name] {
return nil, fmt.Errorf("mcp server names must be nonempty and unique")
}
if srv.ConnectTimeout < 0 {
return nil, fmt.Errorf("MCP connect timeout must not be negative")
}
names[srv.Name] = true
}
defer func() {
if buildErr != nil {
for _, c := range mcpClients {
_ = c.Close()
}
}
}()
var rt *Runtime
var stagedTools []tool.Tool
if _, ok := inputs.Tools.(*tool.Registry); ok {
if reg, ok := inputs.Tools.(*tool.Registry); ok {
if deps.Skills != nil {
stagedTools = append(stagedTools, &tool.LoadSkillTool{
skills := deps.Skills
reg.Register(&tool.LoadSkillTool{
Lookup: func(name string) (string, bool) {
if rt.Skills == nil {
return "", false
}
return rt.Skills.Get(name)
return skills.Get(name)
},
})
}
if deps.Memory != nil {
mem := deps.Memory
stagedTools = append(stagedTools, &tool.LoadMemoryTool{
reg.Register(&tool.LoadMemoryTool{
Lookup: func(id string) (string, bool) {
return mem.Get(id)
},
})
}
var err error
mcpClients, mcpStatus, err = connectMCPServers(ctx, spec.MCPServers)
if err != nil {
return nil, err
// Connect declared MCP servers and register their adapter tools.
// On any failure, close everything connected so far before
// returning — a partially-built Runtime would leak processes.
for _, srv := range spec.MCPServers {
cli, err := mcp.Connect(context.Background(), srv)
if err != nil {
for _, c := range mcpClients {
_ = c.Close()
}
return nil, fmt.Errorf("mcp server %q: %w", srv.Name, err)
}
for _, t := range cli.Tools() {
reg.Register(t)
}
mcpClients = append(mcpClients, cli)
}
for _, cli := range mcpClients {
stagedTools = append(stagedTools, cli.Tools()...)
}
} else if len(spec.MCPServers) > 0 {
return nil, fmt.Errorf("AgentSpec.MCPServers requires inputs.Tools to be *tool.Registry")
}
if err := ctx.Err(); err != nil {
return nil, err
}
if reg, ok := inputs.Tools.(*tool.Registry); ok {
for _, t := range stagedTools {
reg.Register(t)
}
}
// Pre-compute the static portion of the system prompt so the per-turn
// hot loop never reads config or rebuilds the indices. The load tools
// are registered above so toolNames includes them in the default
// identity tool hints.
skillsIndex, skillSources := skillIndexSnapshot(deps.Skills)
promptSources := append([]ContextSource(nil), spec.SystemPromptSources...)
skillsIndex := ""
if deps.Skills != nil {
skillsIndex = deps.Skills.FormatIndex()
}
memoryIndex := ""
if deps.Memory != nil {
memoryIndex = deps.Memory.FormatIndex()
@@ -202,9 +166,7 @@ func BuildRuntimeContext(ctx context.Context, deps RuntimeDeps, inputs RuntimeIn
}
}
loop := mergeLoopConfig(deps.AgentLoop, spec.Loop)
rt = &Runtime{
rt := &Runtime{
LLM: inputs.Provider,
Tools: inputs.Tools,
Session: inputs.Session,
@@ -213,7 +175,6 @@ func BuildRuntimeContext(ctx context.Context, deps RuntimeDeps, inputs RuntimeIn
Model: modelName,
FallbackModel: fallbackModel,
ContextWindow: spec.ContextWindow,
MaxOutputTokens: spec.MaxOutputTokens,
Provider: provider,
Reasoning: reasoning,
Workspace: spec.Workspace,
@@ -225,17 +186,10 @@ func BuildRuntimeContext(ctx context.Context, deps RuntimeDeps, inputs RuntimeIn
Permission: deps.Permission,
Compaction: inputs.Compaction,
IngestSource: inputs.IngestSource,
AgentLoop: loop,
AgentLoop: deps.AgentLoop,
StaticSystemPrompt: staticPrompt,
refreshToolPrompt: func(names []string) string {
currentSkills, sources := skillIndexSnapshot(rt.Skills)
skillSources = append([]ContextSource(nil), sources...)
return BuildStaticSystemPrompt(spec.Workspace, spec.SystemPrompt, spec.ID, spec.Name, names, deps.ConfigSummary, currentSkills, memoryIndex, deps.MemoryFiles)
},
contextSources: func() []ContextSource { return append(append([]ContextSource(nil), promptSources...), skillSources...) },
CalibratorStore: deps.CalibratorStore,
mcpClients: mcpClients,
mcpStatus: mcpStatus,
CalibratorStore: deps.CalibratorStore,
mcpClients: mcpClients,
}
// Seed the calibrator from prior (ratio, count) for this session so a
@@ -252,48 +206,3 @@ func BuildRuntimeContext(ctx context.Context, deps RuntimeDeps, inputs RuntimeIn
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.OnRunStart != nil {
out.Hooks.OnRunStart = override.Hooks.OnRunStart
}
if override.Hooks.OnRunFinish != nil {
out.Hooks.OnRunFinish = override.Hooks.OnRunFinish
}
if override.Hooks.TransformToolContext != nil {
out.Hooks.TransformToolContext = override.Hooks.TransformToolContext
}
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
}
-136
View File
@@ -1,136 +0,0 @@
package runtime
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"testing"
"time"
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/sausheong/harness/tool"
"github.com/sausheong/harness/tools/mcp"
)
func TestConstructionServerFixture(t *testing.T) {
marker := os.Getenv("HARNESS_TEST_MCP_SHUTDOWN_MARKER")
if marker == "" {
return
}
server := sdk.NewServer(&sdk.Implementation{Name: "construction-fixture", Version: "1"}, nil)
server.AddTool(&sdk.Tool{Name: "echo", InputSchema: json.RawMessage(`{"type":"object"}`)}, func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
return &sdk.CallToolResult{}, nil
})
err := server.Run(context.Background(), &sdk.StdioTransport{})
if err != nil {
os.Exit(1)
}
if err := os.WriteFile(marker, []byte("closed"), 0600); err != nil {
os.Exit(2)
}
os.Exit(0)
}
func constructionServer(t *testing.T) (mcp.ServerConfig, string) {
t.Helper()
marker := filepath.Join(t.TempDir(), "closed")
return mcp.ServerConfig{Name: "healthy", Command: os.Args[0], Args: []string{"-test.run=^TestConstructionServerFixture$"}, Env: map[string]string{"HARNESS_TEST_MCP_SHUTDOWN_MARKER": marker, "GORACE": "atexit_sleep_ms=0"}}, marker
}
func TestBuildRuntimeContextCancellationClosesPartialConnections(t *testing.T) {
healthy, marker := constructionServer(t)
reg := tool.NewRegistry()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
start := time.Now()
rt, err := BuildRuntimeContext(ctx, RuntimeDeps{}, RuntimeInputs{Tools: reg}, AgentSpec{MCPServers: []mcp.ServerConfig{healthy, {Name: "hung", Command: "sleep", Args: []string{"30"}}}})
if rt != nil || !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("build = %v, %v", rt, err)
}
if len(reg.Names()) != 0 {
t.Fatalf("partial tools leaked into registry: %v", reg.Names())
}
if _, err := os.Stat(marker); err != nil {
t.Fatalf("healthy connection not closed before return: %v", err)
}
if time.Since(start) > 3*time.Second {
t.Fatal("construction shutdown exceeded bound")
}
}
func TestBuildRuntimeContextAlreadyCancelledDoesNotMutateRegistry(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
reg := tool.NewRegistry()
rt, err := BuildRuntimeContext(ctx, RuntimeDeps{}, RuntimeInputs{Tools: reg}, AgentSpec{})
if rt != nil || !errors.Is(err, context.Canceled) || len(reg.Names()) != 0 {
t.Fatalf("build = %v, %v, tools %v", rt, err, reg.Names())
}
}
func TestBuildRuntimeContextDoesNotOwnSuccessfulSessionLifetime(t *testing.T) {
healthy, marker := constructionServer(t)
reg := tool.NewRegistry()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
rt, err := BuildRuntimeContext(ctx, RuntimeDeps{}, RuntimeInputs{Tools: reg}, AgentSpec{MCPServers: []mcp.ServerConfig{healthy}})
if err != nil {
t.Fatal(err)
}
defer rt.Close()
cancel()
pingCtx, pingCancel := context.WithTimeout(context.Background(), time.Second)
defer pingCancel()
if err := rt.mcpClients[0].Ping(pingCtx); err != nil {
t.Fatalf("construction context killed established session: %v", err)
}
if len(reg.Names()) != 1 || reg.Names()[0] != "mcp__healthy__echo" {
t.Fatalf("tools %v", reg.Names())
}
if err := rt.Close(); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(marker); err != nil {
t.Fatal("runtime close did not join child")
}
}
func TestOptionalMCPFailurePreservesHealthyCatalogue(t *testing.T) {
healthy, _ := constructionServer(t)
reg := tool.NewRegistry()
rt, err := BuildRuntimeContext(context.Background(), RuntimeDeps{}, RuntimeInputs{Tools: reg}, AgentSpec{MCPServers: []mcp.ServerConfig{
{Name: "optional", Optional: true, Command: "sleep", Args: []string{"30"}, ConnectTimeout: 50 * time.Millisecond}, healthy,
}})
if err != nil {
t.Fatal(err)
}
defer rt.Close()
if names := reg.Names(); len(names) != 1 || names[0] != "mcp__healthy__echo" {
t.Fatalf("catalogue %v", names)
}
status := rt.MCPStatus()
if len(status) != 2 || status[0].State != "unavailable" || !status[0].Optional || status[1].State != "connected" || status[1].Tools != 1 {
t.Fatalf("status %+v", status)
}
status[0].State = "mutated"
if rt.MCPStatus()[0].State != "unavailable" {
t.Fatal("mutable status escaped")
}
}
func TestOptionalMCPDoesNotSwallowOwnerCancellation(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
rt, err := BuildRuntimeContext(ctx, RuntimeDeps{}, RuntimeInputs{Tools: tool.NewRegistry()}, AgentSpec{MCPServers: []mcp.ServerConfig{{Name: "optional", Optional: true, Command: "sleep", Args: []string{"30"}}}})
if rt != nil || !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("owner cancellation: %v %v", rt, err)
}
}
func TestMCPDuplicateNamesRejectedBeforeConstruction(t *testing.T) {
reg := tool.NewRegistry()
rt, err := BuildRuntimeContext(context.Background(), RuntimeDeps{}, RuntimeInputs{Tools: reg}, AgentSpec{MCPServers: []mcp.ServerConfig{{Name: "same"}, {Name: "same"}}})
if rt != nil || err == nil || len(reg.Names()) != 0 {
t.Fatalf("duplicate names: %v %v", rt, err)
}
}
-34
View File
@@ -1,7 +1,6 @@
package runtime
import (
"context"
"testing"
"github.com/sausheong/harness/tool"
@@ -39,39 +38,6 @@ 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
@@ -1,58 +0,0 @@
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)
}
-57
View File
@@ -1,57 +0,0 @@
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())
}
-60
View File
@@ -1,60 +0,0 @@
package runtime
import (
"context"
"github.com/sausheong/harness/compaction"
"github.com/sausheong/harness/session"
"strings"
"testing"
"time"
)
func TestPinnedGuidanceReachesManualAndAsyncSummariser(t *testing.T) {
sess := session.NewSession("hand", "focus")
provider := &recordingProvider{reply: "<summary>usable summary</summary>"}
r := &Runtime{Session: sess}
pin := ContextPin{ID: "constraint", Kind: "constraint", Text: "PRESERVE EXACT CONSTRAINT"}
if err := r.SetContextPins(context.Background(), []ContextPin{pin}); err != nil {
t.Fatal(err)
}
if err := r.SetContextState(context.Background(), 0, []ContextStateItem{{ID: "decision", Kind: "decision", Text: "PRESERVE EXACT DECISION"}}); err != nil {
t.Fatal(err)
}
ctx, err := r.CompactionContext(context.Background())
if err != nil {
t.Fatal(err)
}
manager := &compaction.Manager{Summarizer: &compaction.Summarizer{Provider: provider, Model: "fixture"}, PreserveTurns: 2}
add := func() {
for i := 0; i < 10; i++ {
sess.Append(session.UserMessageEntry("task detail"))
sess.Append(session.AssistantMessageEntry("decision and evidence"))
}
}
add()
result, err := manager.MaybeCompact(ctx, sess, compaction.ReasonManual, "FOCUS ON UNRESOLVED WORK")
if err != nil || !result.Compacted {
t.Fatalf("manual: %+v %v", result, err)
}
add()
done := manager.MaybeCompactAsyncContext(ctx, sess, compaction.ReasonPreventive)
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("async compaction did not join")
}
if len(provider.requests) != 2 {
t.Fatalf("requests %d", len(provider.requests))
}
for _, request := range provider.requests {
if !strings.Contains(request.Messages[0].Content, pin.Text) || !strings.Contains(request.Messages[0].Content, "PRESERVE EXACT DECISION") {
t.Fatal("pin omitted from summariser request")
}
}
if !strings.Contains(provider.requests[0].Messages[0].Content, "FOCUS ON UNRESOLVED WORK") {
t.Fatal("manual focus omitted")
}
if strings.Contains(provider.requests[1].Messages[0].Content, "FOCUS ON UNRESOLVED WORK") {
t.Fatal("one-off focus leaked into automatic compaction")
}
}
Loaded 100 of 245 files, more files were not shown because too many files have changed in this diff. Show more