29 Commits
Author SHA1 Message Date
sausheong 1098ee0362 Document Harness v0.6.2 in README 2026-10-03 19:35:10 +08:00
sausheong d199a33b1a Upgrade modelcontextprotocol/go-sdk to v1.8.0 2026-10-03 19:30:43 +08:00
sausheong 5a1983af2f Upgrade google.golang.org/genai to v1.72.0 2026-10-03 19:29:45 +08:00
sausheong e7f2641af5 Upgrade anthropic-sdk-go to v1.78.0 2026-10-03 19:28:49 +08:00
sausheong e10c8d2119 Add a commit-msg hook that rejects AI attribution trailers
Enable per clone with: git config core.hooksPath scripts/hooks
2026-10-03 19:28:07 +08:00
sausheong 40fb986b3f feat: MCP adapter falls back to structured content when a tool returns no text
Servers that return their result only as structuredContent (no TextContent
block) reached the agent as an empty result. Serialize StructuredContent to
JSON in that case; when text is present it still wins, since the MCP spec
has tools send the same data as text.
2026-09-30 21:04:09 +08:00
sausheong 611198dc64 Document Harness v0.6.0 in README 2026-09-28 22:15:58 +08:00
sausheong 26f81ac21f feat: exa_search tool backed by the Exa Search API
ExaSearchTool (tools/web) calls POST https://api.exa.ai/search with
query-relevant highlights, optional category, domain and published-date
filters, and the shared SSRF-safe search client.
2026-09-28 15:13:10 +08:00
sausheong d47a71f779 feat: Stagehand natural-language browser tool
Add tools/stagehand, a browser tool built on the Stagehand Go SDK
(act/observe/extract/navigate/get_text/screenshot) with persistent named
sessions. Runs on local Chrome by default or Browserbase when an API key
is configured. Stagehand's internal inference is routed through the
harness LLMProvider via NewGenerateFunc, so it shares the agent's
provider, usage observers and admission guards.

The Stagehand SDK requires Go 1.26, so the module now declares go 1.26.0.
2026-09-28 01:25:08 +08:00
sausheong 62f3424f30 feat: PDF attachments as Anthropic document blocks
Reuses llm.ImageContent/session.ImageData with MimeType
"application/pdf" rather than adding a new field: images already flow
tool result -> session entry -> reload -> provider end to end, so a
MIME check at the provider edge is the smallest change.

- Anthropic provider emits a document block (source.type=base64,
  media_type=application/pdf) for a PDF attachment in a tool result or
  a user message; images are unaffected. Cache control now also
  applies to document blocks.
- OpenAI provider replaces a PDF attachment with a text placeholder
  instead of an invalid image_url data URI; images still emitted.
  Gemini already accepts application/pdf inline and needs no change.
2026-09-26 00:41:54 +08:00
sausheong a1f34cce4c Send adaptive low-effort thinking for Opus 5.5 when reasoning is off
Opus 5.5 returns 400 on thinking {type:"disabled"}, and its ID matched the
"claude-opus-5" marker, so it inherited Opus 5's explicit disabled config.
2026-09-23 19:18:37 +08:00
sausheong 9a013f6f4b Raise WebFetchTool's output cap to ~1M tokens
MaxOutputLength was 50,000 chars, truncating fetched pages to a few
paragraphs well before hitting any model's context window. Match Sonnet
5's 1M-token context using this codebase's 4-chars/token estimate
(session.Session.EstimateTokens), and raise the raw HTTP read cap
(maxFetchSize) to 8MB so plain-text/JSON responses that don't shrink
during HTML->markdown conversion aren't cut short before the output cap
even applies.
2026-09-22 17:45:40 +08:00
sausheong 1e5b6599bb Document Harness v0.4.2 response handling and tool events 2026-09-13 21:19:39 +08:00
sausheong 3ca0994437 Reject empty and truncated answers and expose complete tool calls 2026-09-11 23:48:25 +08:00
sausheong 019a38f111 Fix repeated stream finishes and preserve cancellation causes 2026-09-10 16:34:12 +08:00
Chang Sau Sheong 3170b28251 Merge pull request #5 from sausheong/codex/update-readme-v0.4.0
Document Harness v0.4.0 capabilities
2026-09-10 07:57:45 +08:00
sausheong 036fe1e547 Document Harness v0.4.0 capabilities 2026-09-10 07:45:54 +08:00
Chang Sau Sheong 4cec5b57f8 Merge pull request #4 from sausheong/codex/hand-release-v0.4.0
Prepare Harness v0.4.0: execution isolation and durable runtime
2026-09-10 01:15:20 +08:00
sausheong 5d4632ffe3 Place macOS qualification workspaces in Colima shared home 2026-09-10 00:52:13 +08:00
sausheong a1c4d5d78c Provision hosted macOS Docker and avoid fixture build engine dependency 2026-09-10 00:37:33 +08:00
sausheong cc756425e8 Prepare and record Docker qualification fixtures 2026-09-10 00:23:04 +08:00
sausheong 0972eed3ea Harden Harness runtime, persistence and execution for Hand 2026-09-09 22:55:55 +08:00
sausheong 09c30fe2d5 Update README: bump stale version references to v0.3.9
Both "Status" mentions were still pinned at v0.3.6 (three releases
behind). Also documents Runtime.DynamicIdentityHint in the components
table — added this session, previously undocumented outside code
comments.
2026-09-07 21:06:05 +08:00
sausheong 50b791d3b6 Rename providers/ollama to providers/local
Ollama is one local-model server among several (LM Studio, llama.cpp's
server, vLLM, ...) that all speak the same OpenAI-compatible shape —
naming the package (and provider name downstream) after one of them
was misleading. Same constructor, same default endpoint (Ollama's,
being the most common), just generically named: NewLocalProvider.

This renames a package published minutes ago in v0.3.8 with no other
known consumers yet, so no compatibility shim is kept.
2026-09-07 13:27:58 +08:00
sausheong 3b5aadb31f Add an ollama provider for local models
Thin constructor over the existing OpenAI-compatible path, same shape
as litellm/openrouter: NewOllamaProvider(baseURL) defaults to Ollama's
local endpoint (http://localhost:11434/v1) and needs no API key, since
Ollama doesn't authenticate requests. Also covers other local servers
that share Ollama's OpenAI-compatible endpoint shape (LM Studio,
llama.cpp's server, vLLM).
2026-09-07 11:57:56 +08:00
sausheong 897643db18 Add a regression test proving a mid-session model switch is real
Verifies, at the Runtime.Run level, that mutating Model and
DynamicIdentityHint between two Run calls in the same session (exactly
what hand's tui.Controller.SwitchModel does) actually changes the
ChatRequest.Model sent on the next call, not just the system prompt
text. If this ever regressed, a caller-side "/model" fix would look
correct in its own unit tests while the model actually being queried
silently stayed the old one.
2026-09-07 00:22:07 +08:00
sausheong 0ccfdb2a24 Add Runtime.DynamicIdentityHint, a live, per-turn identity fact
Runtime.StaticSystemPrompt is cached and reused verbatim every turn —
right for anything that doesn't change mid-conversation, wrong for a
fact a caller needs to update live (e.g. after a runtime model switch)
and have the model actually notice. A model tends to just repeat what
it already told the user earlier in the same conversation over a
background instruction it read once near the top of a large cached
block, so updating only the static prompt after a switch left the
model insisting it was still whatever it started as.

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

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

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

Match on tier (Pro vs. everything else) instead of enumerating every
version: every Pro-tier Gemini release so far ships 2M, everything
else at least 1M, and both hold for a model this table has never seen
the exact version string of.
2026-09-05 22:06:59 +08:00
207 changed files with 19079 additions and 1006 deletions

No files matched your search

+76
View File
@@ -0,0 +1,76 @@
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/
+3
View File
@@ -43,3 +43,6 @@ support-agent-audit.jsonl
# Env
.env
.env.local
# Keep native qualification setup with its runner.
!scripts/QUALIFICATION.md
+178 -32
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.3.6.** Latest tagged release. The `runtime` API
> **Status: v0.6.2.** Latest tagged release. The `runtime` API
> surface may still shift in the v0.x line — pin your version.
## Why Harness
@@ -26,6 +26,90 @@ 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.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:
@@ -82,13 +166,13 @@ a lot. The package is optimized for the use cases above, not these.
## Requirements
- **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`.
- **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.
- **An LLM API key**, depending on which provider(s) you wire in:
`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, Google ADC for Gemini, or a
Qwen DashScope key. For local models, point `openai.NewOpenAIProviderWithKind`
at an Ollama endpoint — no key required.
LiteLLM/OpenRouter key for those aggregators. For local models
(Ollama, LM Studio, etc.), `local.NewLocalProvider` needs no key at all.
- **Optional: an MCP server** for `tools/mcp` integrations (any
binary that speaks the Model Context Protocol — `npx
@modelcontextprotocol/server-filesystem`, etc.).
@@ -107,7 +191,11 @@ 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
@@ -119,14 +207,18 @@ github.com/sausheong/harness/
│ # MemoryProvider/SkillProvider/KnowledgeGraph interfaces
├── providers/
│ ├── anthropic/ # Anthropic LLMProvider (with prompt caching)
│ ├── openai/ # OpenAI / OpenAI-compatible / local Ollama
│ ├── openai/ # OpenAI / OpenAI-compatible
│ ├── gemini/ # Google Gemini via google.golang.org/genai
│ └── qwen/ # Alibaba Qwen (OpenAI-compatible endpoint)
│ ├── litellm/ # Self-hosted LiteLLM proxy (OpenAI-compatible)
│ ├── openrouter/ # OpenRouter aggregator (OpenAI-compatible)
│ └── local/ # Local model server — Ollama, LM Studio, etc. (OpenAI-compatible, no API key)
└── 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, ssrf guard
├── web/ # web_fetch, web_search, exa_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
```
@@ -190,7 +282,7 @@ how to plug in hooks, MCP servers, skills, permissions, and more.
## Examples
Four end-to-end agents ship in [`examples/`](./examples). Each is a
Five 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 |
@@ -239,13 +331,14 @@ none of it.
## Components
A general agent harness has ~16 conceptual components: the loop, the
model invocation layer, the tool registry, permission gating,
A general agent harness spans 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, 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, 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.
| # | Component | Where it lives in harness |
|---|---|---|
@@ -254,7 +347,7 @@ caller — you own the binary, 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 from the per-turn dynamic suffix; provider-side `cache_control` placement is automatic |
| 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 |
| 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 |
@@ -263,19 +356,24 @@ caller — you own the binary, 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 (numbers from the same conceptual list):
Deliberately not in scope:
- **15 — UI**: harness emits events; the caller renders.
- **16 — Entrypoints**: harness is a library. There is no `harness`
- **UI**: harness emits events; the caller renders.
- **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`, `EventToolResult`, `EventDone`, and friends
through a `<-chan ChatEvent`. There is no buffered "give me the
`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
whole response" path — even the non-streaming fallback re-emits
through the same channel.
- **Prompt-cache discipline.** Tool definitions are sorted, system
@@ -313,9 +411,19 @@ Deliberately not in scope (numbers from the same conceptual list):
`clientcredentials.Config.Client(ctx)`) as `HTTPClient` —
auto-refresh comes for free. Call `Runtime.Close()` to release
sessions.
- **Four providers, one interface.** Anthropic, OpenAI (and
OpenAI-compatible / local Ollama), Gemini, and Qwen ship built-in.
Adding a fifth is implementing `llm.Provider` (~300 LOC).
- **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).
See [`developer.md`](./developer.md) for a step-by-step guide to
building agents on top of Harness, including diagrams of the
@@ -347,9 +455,10 @@ 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.
- **Auth / billing / multi-tenant infrastructure.** Per-agent
policy lives in `PermissionChecker`; everything else is your
problem.
- **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.
- **Shell-command hooks.** Hooks are typed Go callbacks on
`LifecycleHooks`, not subprocess invocations driven by a config
file.
@@ -370,18 +479,19 @@ hermetic:
LTA_DATAMALL_KEY=... go test -tags live ./examples/lta-agent/...
```
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.
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).
## Status
`v0.3.6` is the latest tagged release. The v0.x line follows Go
`v0.6.2` is the latest tagged release. The v0.x line follows Go
module semver: minor bumps may break API, patch bumps are bug-fix
only. Pin your dependency:
```bash
go get github.com/sausheong/harness@v0.3.6
go get github.com/sausheong/harness@v0.6.2
```
Likely sources of v0.x churn before a v1.0.0:
@@ -400,3 +510,39 @@ 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
@@ -0,0 +1,120 @@
# 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
@@ -0,0 +1,63 @@
# 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
@@ -0,0 +1,26 @@
# 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
@@ -0,0 +1,14 @@
//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
@@ -0,0 +1,34 @@
//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
@@ -0,0 +1,267 @@
// 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
@@ -0,0 +1,185 @@
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
@@ -0,0 +1,349 @@
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
@@ -0,0 +1,232 @@
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
@@ -0,0 +1,87 @@
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
@@ -0,0 +1,89 @@
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
@@ -0,0 +1,135 @@
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
@@ -0,0 +1,46 @@
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
@@ -0,0 +1,247 @@
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
@@ -0,0 +1,159 @@
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
@@ -0,0 +1,94 @@
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
@@ -0,0 +1,64 @@
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
@@ -0,0 +1,206 @@
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
@@ -0,0 +1,302 @@
// 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
@@ -0,0 +1,177 @@
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
@@ -0,0 +1,46 @@
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")
}
}
+122 -48
View File
@@ -4,16 +4,15 @@ 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 autocompact attempts that drop to the
// placeholder stage (stage 3), MaybeCompact stops attempting compaction
// After this many consecutive failed autocompact attempts, MaybeCompact stops attempting compaction
// for the session and returns Skipped="circuit_breaker".
//
// The breaker resets on any genuine summarizer success (stage 1 or 2
@@ -34,6 +33,8 @@ 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
@@ -46,7 +47,23 @@ 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
@@ -65,13 +82,14 @@ 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 // session.ID → in-flight handle
inFlight map[string]*inFlightCompaction // stable session key → active or unconsumed 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
@@ -90,11 +108,32 @@ 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, error) {
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() }()
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",
@@ -124,27 +163,20 @@ func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reaso
slog.Info("compaction triggered", "session_id", sess.ID, "reason", string(reason))
summary, err := m.Summarizer.Summarize(ctx, toCompact, instructions)
combined, err := guidanceFor(ctx, instructions)
if err != nil {
return Result{Reason: reason, Skipped: "invalid_guidance"}, err
}
summary, err := m.Summarizer.Summarize(ctx, toCompact, combined)
if err != nil {
skipReason := classifySummarizerError(err)
slog.Warn("compaction skipped", "session_id", sess.ID, "reason", string(reason), "skipped", skipReason, "detail", err.Error())
// A hard error from Summarize means even stage 3 didn't run.
// Count it as a failure for breaker accounting.
// Leave both raw and effective history unchanged on summarizer failure.
m.incrementFailure(key)
return Result{Reason: reason, Skipped: skipReason}, nil
}
// 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)
}
m.resetFailures(key)
first := toCompact[0]
last := toCompact[len(toCompact)-1]
@@ -156,14 +188,8 @@ 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
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)
if err := sess.CommitCompaction(view[len(view)-1].ID, entry, toPreserve); err != nil {
return Result{}, err
}
dur := time.Since(start).Milliseconds()
@@ -197,6 +223,18 @@ 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)
@@ -211,27 +249,26 @@ func (m *Manager) MaybeCompactAsync(sess *session.Session, reason Reason) <-chan
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 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()
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, "")
}()
return fl.done
}
@@ -281,8 +318,16 @@ func (m *Manager) HasInFlight(sess *session.Session) bool {
key := stableKey(sess)
m.inFlightMu.Lock()
defer m.inFlightMu.Unlock()
_, ok := m.inFlight[key]
return ok
fl, ok := m.inFlight[key]
if !ok {
return false
}
select {
case <-fl.done:
return false
default:
return true
}
}
// ForgetSession removes the per-session lock, failure counter, and
@@ -300,6 +345,9 @@ 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)
@@ -307,9 +355,7 @@ func (m *Manager) ForgetSession(sess *session.Session) {
m.failMu.Lock()
delete(m.failures, key)
m.failMu.Unlock()
// 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.
// Clear tracking after joining; the owner must prevent concurrent launches.
m.inFlightMu.Lock()
delete(m.inFlight, key)
m.inFlightMu.Unlock()
@@ -389,3 +435,31 @@ 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
}
+84 -24
View File
@@ -93,12 +93,7 @@ func TestManagerRefusesShortSession(t *testing.T) {
assert.Equal(t, "too_short", res.Skipped)
}
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.
func TestManagerSummarizerErrorSkipsWithoutSummary(t *testing.T) {
mgr := &Manager{
Summarizer: &Summarizer{
Provider: &fakeProvider{text: ""},
@@ -110,9 +105,9 @@ func TestManagerSummarizerErrorFallsBackToPlaceholder(t *testing.T) {
sess := longSession()
res, err := mgr.MaybeCompact(context.Background(), sess, ReasonManual, "")
require.NoError(t, err)
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")
assert.False(t, res.Compacted)
assert.Empty(t, res.Summary)
assert.NotEmpty(t, res.Skipped)
}
func TestManagerSerializesPerSession(t *testing.T) {
@@ -342,24 +337,11 @@ func TestCircuitBreakerTripsAfterMaxFailures(t *testing.T) {
}
sess := longSession()
// 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.
// Failed attempts leave history available and increment the breaker.
for i := range MaxConsecutiveFailures {
res, err := mgr.MaybeCompact(context.Background(), sess, ReasonPreventive, "")
require.NoError(t, err, "iteration %d", i)
assert.True(t, res.Compacted, "iteration %d should still attempt", i)
assert.False(t, res.Compacted, "iteration %d must preserve history", i)
// Add new turns so the next iteration has something to compact.
sess.Append(session.UserMessageEntry("follow-up"))
sess.Append(session.AssistantMessageEntry("more reply"))
@@ -429,3 +411,81 @@ 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
@@ -0,0 +1,29 @@
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
@@ -0,0 +1,36 @@
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
@@ -0,0 +1,22 @@
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())
}
+41 -43
View File
@@ -18,25 +18,21 @@ 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 {
Provider llm.LLMProvider
Model string // bare model id, e.g. "qwen2.5:3b-instruct"
Timeout time.Duration // per-call deadline; 0 → 60s
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
}
// 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...>).
//
// 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.
// 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.
func (s *Summarizer) Summarize(ctx context.Context, entries []session.SessionEntry, additionalInstructions string) (string, error) {
return s.summarizeWithFallback(ctx, entries, additionalInstructions)
}
@@ -49,16 +45,8 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
}
stage1Err := err
// 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".
// Cancellation and per-call deadlines stop retries and retain their
// classification for the manager.
if ctxErr := ctx.Err(); ctxErr != nil || errors.Is(stage1Err, context.DeadlineExceeded) {
return "", stage1Err
}
@@ -67,7 +55,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
// stage 3 in that case.
// the final error in that case.
if isOverflowError(stage1Err) || isStreamError(stage1Err) {
small, droppedCount := buildSmallOnlyTranscript(entries)
if droppedCount > 0 {
@@ -79,9 +67,10 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
}
}
// 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
if failure := errors.Join(stage1Err, err); failure != nil {
return "", failure
}
return "", ErrEmptySummary
}
// callOnce performs a single summarizer invocation against a pre-built
@@ -94,6 +83,16 @@ 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 {
@@ -103,6 +102,7 @@ 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,22 +111,34 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
SystemPromptParts: []llm.SystemPromptPart{
{Text: systemPrompt, Cache: true},
},
MaxTokens: 4096,
MaxTokens: maxTokens,
}
stream, err := s.Provider.ChatStream(callCtx, req)
stream, err := llm.ObserveChat(callCtx, req, llm.CallCompaction, s.Provider.ChatStream)
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
@@ -161,20 +173,6 @@ 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.
+9 -24
View File
@@ -58,37 +58,26 @@ func TestSummarizerTrimsWhitespace(t *testing.T) {
assert.Equal(t, "summary text", got)
}
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".
func TestSummarizerEmptyResponseReturnsError(t *testing.T) {
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.NoError(t, err)
assert.Contains(t, got, "compaction failed")
require.Error(t, err)
assert.Empty(t, got)
}
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.
func TestSummarizerProviderErrorReturnsError(t *testing.T) {
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.NoError(t, err)
assert.Contains(t, got, "compaction failed")
require.Error(t, err)
assert.Empty(t, got)
}
// flakyProvider returns ChatStream errors a configured number of times,
@@ -153,7 +142,7 @@ func TestSummarizeFallbackToSmallOnlyOnOverflow(t *testing.T) {
"second-stage success must produce the summary")
}
func TestSummarizeFallbackToPlaceholderWhenAllStagesFail(t *testing.T) {
func TestSummarizeReturnsErrorWhenAllStagesFail(t *testing.T) {
entries := []session.SessionEntry{session.UserMessageEntry("hi")}
s := &Summarizer{
Provider: &flakyProvider{failsRemaining: 99, successText: ""},
@@ -161,12 +150,8 @@ func TestSummarizeFallbackToPlaceholderWhenAllStagesFail(t *testing.T) {
Timeout: time.Second,
}
got, err := s.Summarize(context.Background(), entries, "")
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")
require.Error(t, err)
assert.Empty(t, got)
}
func TestSummarizePerCallTimeoutPropagates(t *testing.T) {
+26
View File
@@ -0,0 +1,26 @@
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
@@ -0,0 +1,33 @@
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)
}
+7 -4
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.25+ project that depends
you've read [`README.md`](./README.md) and have a Go 1.26+ project that depends
on `github.com/sausheong/harness`.
> Two complete examples ship in [`examples/`](./examples) — `minimal/` (file +
@@ -59,7 +59,8 @@ required pieces are inside `inputs`; everything in `deps` is optional;
The four mandatory pieces:
* **`llm.LLMProvider`** (in `RuntimeInputs.Provider`) — a streaming
chat client (Anthropic / OpenAI / Gemini / Qwen, or your own).
chat client (Anthropic / OpenAI / Gemini / LiteLLM / OpenRouter /
local (Ollama, LM Studio, etc.), or your own).
* **`tool.Registry`** (in `RuntimeInputs.Tools`) — the tools the LLM
may invoke. Each tool implements `tool.Tool`.
* **`session.Session`** (in `RuntimeInputs.Session`) — append-only
@@ -387,9 +388,11 @@ Each provider has its own constructor. All return an `llm.LLMProvider`.
|--------------|--------------------------------------------------------|-------------------------------------|
| Anthropic | `anthropic.NewAnthropicProvider(apiKey, baseURL)` | `baseURL == ""` → official endpoint |
| OpenAI | `openai.NewOpenAIProvider(apiKey, baseURL)` | `baseURL == ""` → official endpoint |
| OpenAI-compat| `openai.NewOpenAIProviderWithKind(apiKey, baseURL, "ollama"\|"compat")` | for local Ollama, etc. |
| OpenAI-compat| `openai.NewOpenAIProviderWithKind(apiKey, baseURL, "local"\|"openai-compatible")` | for local Ollama, etc. |
| Gemini | `gemini.NewGeminiProvider(ctx, apiKey)` | takes `context.Context` |
| Qwen | `qwen.NewQwenProvider(apiKey, baseURL)` | OpenAI-compatible endpoint |
| LiteLLM | `litellm.NewLiteLLMProvider(apiKey, baseURL)` | `baseURL` required (self-hosted) |
| OpenRouter | `openrouter.NewOpenRouterProvider(apiKey, baseURL)` | `baseURL == ""` → OpenRouter's public endpoint |
| Local | `local.NewLocalProvider(baseURL)` | `baseURL == ""` → `http://localhost:11434/v1` (Ollama's default; override for LM Studio, llama.cpp, vLLM, etc.); no API key |
The provider you pass on `RuntimeInputs.Provider` only needs to match the
provider prefix in `AgentSpec.Model` — `runtime.BuildRuntime` parses
+293
View File
@@ -0,0 +1,293 @@
// 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
@@ -0,0 +1,164 @@
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
@@ -0,0 +1,90 @@
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
@@ -0,0 +1,33 @@
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
@@ -0,0 +1,145 @@
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
@@ -0,0 +1,58 @@
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
@@ -0,0 +1,129 @@
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
@@ -0,0 +1,138 @@
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
@@ -0,0 +1,90 @@
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
@@ -0,0 +1,54 @@
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
@@ -0,0 +1,12 @@
//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
@@ -0,0 +1,16 @@
//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
}
+15 -5
View File
@@ -1,19 +1,20 @@
module github.com/sausheong/harness
go 1.25.1
go 1.26.0
require (
github.com/JohannesKaufmann/html-to-markdown/v2 v2.5.0
github.com/anthropics/anthropic-sdk-go v1.35.0
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-20250724212937-08a3db8b4327
github.com/chromedp/chromedp v0.14.2
github.com/modelcontextprotocol/go-sdk v1.5.0
github.com/modelcontextprotocol/go-sdk v1.8.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
google.golang.org/genai v1.72.0
)
require (
@@ -21,8 +22,11 @@ require (
cloud.google.com/go/auth v0.9.3 // indirect
cloud.google.com/go/compute/metadata v0.9.0 // indirect
github.com/JohannesKaufmann/dom v0.2.0 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/buger/jsonparser v1.1.2 // 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/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
@@ -30,13 +34,16 @@ require (
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.2 // indirect
github.com/google/jsonschema-go v0.4.3 // 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
@@ -44,11 +51,14 @@ 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/v4 v4.0.0-rc.2 // indirect
golang.org/x/crypto v0.49.0 // indirect
golang.org/x/mod v0.38.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.35.0 // indirect
golang.org/x/time v0.15.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
+30 -10
View File
@@ -10,8 +10,14 @@ github.com/JohannesKaufmann/dom v0.2.0 h1:1bragmEb19K8lHAqgFgqCpiPCFEZMTXzOIEjux
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/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/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=
@@ -23,6 +29,8 @@ github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipw
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=
@@ -70,8 +78,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.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
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/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=
@@ -81,12 +89,16 @@ 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.5.0 h1:CHU0FIX9kpueNkxuYtfYQn1Z0slhFzBZuq+x6IiblIU=
github.com/modelcontextprotocol/go-sdk v1.5.0/go.mod h1:gggDIhoemhWs3BGkGwd1umzEXCEMMvAnhTrnbXJKKKA=
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/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=
@@ -100,6 +112,8 @@ 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=
@@ -136,6 +150,8 @@ go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfC
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
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=
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=
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.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
@@ -144,6 +160,8 @@ golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL
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=
@@ -171,20 +189,22 @@ 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.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
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.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
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/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.49.0 h1:Se+QJaH2GYK1aaR1o5S38mlU2GD5FnVvP76nfkV7LH0=
google.golang.org/genai v1.49.0/go.mod h1:A3kkl0nyBjyFlNjgxIwKq70julKbIxpSxqKO5gw/gmk=
google.golang.org/genai v1.72.0 h1:sn3V1cHkHQhMcjtUrO2y1r54jprbFjmeokBU1IKfpZk=
google.golang.org/genai v1.72.0/go.mod h1:2j40fGpqPPIZNjaDKmjGGjYwCJi6Nm2ofmyP65GnqtY=
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=
+57
View File
@@ -0,0 +1,57 @@
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
@@ -0,0 +1,138 @@
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 -2
View File
@@ -34,8 +34,8 @@ const stripCacheMax = 256
// ApplyStripList runs StripFields over each tool's Parameters with the
// given field-strip list, preserving input order and accumulating
// diagnostics across all tools. The per-provider NormalizeToolSchema
// methods (OpenAI, Qwen, Gemini) are thin wrappers over this helper —
// only the strip list differs. Anthropic doesn't use this (identity).
// methods (OpenAI, Gemini) are thin wrappers over this helper — only the
// strip list differs. Anthropic doesn't use this (identity).
//
// Memoized: identical inputs return cached output without re-walking
// the JSON Schema. Cache key is a SHA-256 over (sorted fields, tool
+23 -7
View File
@@ -22,10 +22,14 @@ const (
EventThinkingBlock
)
// ImageContent holds image data for multimodal messages.
// 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.
type ImageContent struct {
MimeType string // "image/jpeg", "image/png", etc.
Data []byte // raw image bytes
MimeType string // "image/jpeg", "image/png", "application/pdf", etc.
Data []byte // raw bytes
}
// Message represents a conversation message.
@@ -98,7 +102,7 @@ type SystemPromptPart struct {
// Zero value (ReasoningOff) means no extended reasoning — safe default
// for existing call sites that don't set the field. Each provider maps
// this to its native config (Anthropic thinking budget, OpenAI
// reasoning_effort, Gemini ThinkingConfig, Qwen enable_thinking).
// reasoning_effort, Gemini ThinkingConfig).
type ReasoningMode string
const (
@@ -152,7 +156,17 @@ 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
@@ -181,6 +195,8 @@ type ChatRequest struct {
}
// 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"`
@@ -295,10 +311,10 @@ func JoinSystemPromptParts(parts []SystemPromptPart) string {
// ProviderOptions holds connection details for creating an LLM provider.
// Kept here so consumers can pass a single struct around even though the
// concrete provider constructors live in subpackages
// (harness/providers/{anthropic,openai,gemini,qwen}). Each subpackage's
// New() takes the relevant fields directly.
// (harness/providers/{anthropic,openai,gemini,litellm,openrouter}). Each
// subpackage's New() takes the relevant fields directly.
type ProviderOptions struct {
APIKey string
BaseURL string
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini" | "qwen"
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini"
}
+186
View File
@@ -0,0 +1,186 @@
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
@@ -0,0 +1,50 @@
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
@@ -0,0 +1,84 @@
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
@@ -0,0 +1,84 @@
//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
@@ -0,0 +1,216 @@
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
@@ -0,0 +1,15 @@
//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
@@ -0,0 +1,182 @@
//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
@@ -0,0 +1,20 @@
//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
@@ -0,0 +1,44 @@
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
@@ -0,0 +1,41 @@
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
@@ -0,0 +1,40 @@
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
@@ -0,0 +1,28 @@
// 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
@@ -0,0 +1,24 @@
//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
@@ -0,0 +1,28 @@
//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
@@ -0,0 +1,161 @@
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
@@ -0,0 +1,104 @@
//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")
}
}
+35 -2
View File
@@ -160,6 +160,16 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
slog.Info("anthropic adaptive thinking",
"model", model,
"effort", string(anthropicEffort(req.Reasoning)))
} 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,
@@ -354,7 +364,7 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
events <- llm.ChatEvent{
Type: llm.EventDone,
Usage: &llm.Usage{
InputTokens: int(inputTokens),
InputTokens: int(inputTokens + cacheCreationTokens + cacheReadTokens),
OutputTokens: int(event.Usage.OutputTokens),
CacheCreationInputTokens: int(cacheCreationTokens),
CacheReadInputTokens: int(cacheReadTokens),
@@ -457,7 +467,7 @@ func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRe
events <- llm.ChatEvent{
Type: llm.EventDone,
Usage: &llm.Usage{
InputTokens: int(msg.Usage.InputTokens),
InputTokens: int(msg.Usage.InputTokens + msg.Usage.CacheCreationInputTokens + msg.Usage.CacheReadInputTokens),
OutputTokens: int(msg.Usage.OutputTokens),
CacheCreationInputTokens: int(msg.Usage.CacheCreationInputTokens),
CacheReadInputTokens: int(msg.Usage.CacheReadInputTokens),
@@ -557,6 +567,13 @@ func anthropicThinksByDefault(model string) bool {
return false
}
// 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 {
@@ -621,6 +638,10 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
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 != "" {
@@ -694,6 +715,8 @@ 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
}
@@ -709,6 +732,16 @@ 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{
+117 -1
View File
@@ -221,6 +221,101 @@ 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{
@@ -424,7 +519,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, 10, done.Usage.InputTokens)
require.Equal(t, 69, done.Usage.InputTokens) // 10 uncached + 42 cache creation + 17 cache read
}
// TestBuildMessageParamsIsPure protects the cache-prefix invariant
@@ -759,6 +854,27 @@ func TestOpus5AndSonnet5_ThinkByDefault_ReasoningOffSendsDisabled(t *testing.T)
}
}
// 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"`)
})
}
}
func TestLegacyThinkingModels_KeepBudgetTokens(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
got := wireJSON(t, p, llm.ChatRequest{
+1 -1
View File
@@ -339,7 +339,7 @@ func geminiSupportsThinking(model string) bool {
}
// geminiResolveSystemPrompt returns the effective system prompt string,
// preferring SystemPromptParts when present. Mirrors the OpenAI/Qwen
// preferring SystemPromptParts when present. Mirrors the OpenAI
// resolution path but the per-provider helper avoids importing the
// genai SDK in test code.
func geminiResolveSystemPrompt(req llm.ChatRequest) string {
+19
View File
@@ -0,0 +1,19 @@
// Package litellm provides an llm.LLMProvider for a self-hosted LiteLLM
// proxy. LiteLLM speaks the OpenAI chat-completions wire format and
// itself routes to dozens of underlying vendors, so this package adds no
// new request/stream-translation code of its own — it's a thin
// constructor around harness's existing OpenAI-compatible support.
package litellm
import "github.com/sausheong/harness/providers/openai"
// NewLiteLLMProvider returns an OpenAI-compatible provider pointed at
// baseURL, a self-hosted LiteLLM proxy endpoint. Unlike OpenRouter,
// LiteLLM has no public default endpoint — callers must supply a
// non-empty baseURL (cmd/hand's buildProvider, for example, rejects an
// empty one with a clear error before ever reaching here).
// kind="openai-compatible" suppresses reasoning_effort, since not every
// model LiteLLM routes a request to is guaranteed to support it.
func NewLiteLLMProvider(apiKey, baseURL string) *openai.OpenAIProvider {
return openai.NewOpenAIProviderWithKind(apiKey, baseURL, "openai-compatible")
}
+33
View File
@@ -0,0 +1,33 @@
package litellm
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
// TestNewLiteLLMProvider_HitsGivenBaseURL confirms the provider actually
// targets the baseURL it was constructed with, and that a streamed
// response comes back through it — not re-testing OpenAI wire-format
// translation itself (already covered by providers/openai's own tests),
// just that this thin constructor wires the base URL through correctly.
func TestNewLiteLLMProvider_HitsGivenBaseURL(t *testing.T) {
var hit bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hit = true
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: [DONE]\n\n"))
}))
t.Cleanup(srv.Close)
p := NewLiteLLMProvider("test-key", srv.URL+"/v1")
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{SystemPrompt: "hi"})
require.NoError(t, err)
for range stream {
}
require.True(t, hit, "provider did not hit the configured baseURL")
}
+28
View File
@@ -0,0 +1,28 @@
// 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
@@ -0,0 +1,46 @@
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
@@ -0,0 +1,42 @@
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")
}
}
+27 -1
View File
@@ -14,6 +14,13 @@ 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
@@ -129,6 +136,13 @@ 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{
@@ -151,6 +165,13 @@ 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{
@@ -274,6 +295,7 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
toolCalls := make(map[int]*pendingTC)
var lastUsage *llm.Usage
var finishReason string
for {
resp, err := stream.Recv()
@@ -337,13 +359,17 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
// Finish reason
if choice.FinishReason != "" {
finishReason = string(choice.FinishReason)
}
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
emitToolCalls(events, toolCalls)
clear(toolCalls)
}
}
}
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage, StopReason: finishReason}
}()
return events, nil
+70
View File
@@ -6,6 +6,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
openai "github.com/sashabaranov/go-openai"
@@ -74,6 +75,75 @@ func TestOpenAIChatStreamPartsBeatString(t *testing.T) {
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}
+42
View File
@@ -0,0 +1,42 @@
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
@@ -0,0 +1,23 @@
// Package openrouter provides an llm.LLMProvider for OpenRouter, an
// aggregator that fronts hundreds of underlying models behind one
// OpenAI-compatible endpoint. Like providers/litellm, this adds no new
// request/stream-translation code of its own — it's a thin constructor
// around harness's existing OpenAI-compatible support.
package openrouter
import "github.com/sausheong/harness/providers/openai"
// DefaultBaseURL is OpenRouter's public API endpoint, used when
// NewOpenRouterProvider is called with an empty baseURL.
const DefaultBaseURL = "https://openrouter.ai/api/v1"
// NewOpenRouterProvider returns an OpenAI-compatible provider pointed at
// baseURL, or DefaultBaseURL when baseURL is empty. kind="openai-compatible"
// suppresses reasoning_effort, since OpenRouter's underlying models don't
// uniformly support it.
func NewOpenRouterProvider(apiKey, baseURL string) *openai.OpenAIProvider {
if baseURL == "" {
baseURL = DefaultBaseURL
}
return openai.NewOpenAIProviderWithKind(apiKey, baseURL, "openai-compatible")
}
+45
View File
@@ -0,0 +1,45 @@
package openrouter
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
func TestDefaultBaseURL(t *testing.T) {
require.Equal(t, "https://openrouter.ai/api/v1", DefaultBaseURL)
}
// TestNewOpenRouterProvider_HitsGivenBaseURL confirms a custom baseURL
// overrides the default and is actually what the provider talks to.
func TestNewOpenRouterProvider_HitsGivenBaseURL(t *testing.T) {
var hit bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hit = true
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: [DONE]\n\n"))
}))
t.Cleanup(srv.Close)
p := NewOpenRouterProvider("test-key", srv.URL+"/v1")
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{SystemPrompt: "hi"})
require.NoError(t, err)
for range stream {
}
require.True(t, hit, "provider did not hit the configured baseURL")
}
// TestNewOpenRouterProvider_EmptyBaseURLDoesNotPanic confirms the empty
// -> DefaultBaseURL fallback path constructs a usable provider (the
// actual outbound host isn't inspectable from outside the openai
// package — OpenAIProvider's client config is unexported — so this
// checks the fallback doesn't panic or return nil, and DefaultBaseURL's
// own value is asserted separately above).
func TestNewOpenRouterProvider_EmptyBaseURLDoesNotPanic(t *testing.T) {
p := NewOpenRouterProvider("test-key", "")
require.NotNil(t, p)
}
-370
View File
@@ -1,370 +0,0 @@
package qwen
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"strings"
openai "github.com/sashabaranov/go-openai"
"github.com/sausheong/harness/llm"
)
// pendingTC accumulates a streamed tool call across deltas. args uses
// strings.Builder so repeated argument fragments append in O(n) total
// (not O(n²) from string concatenation).
type pendingTC struct {
id string
name string
args strings.Builder
}
// emitToolCalls sends EventToolCallDone for each completed tool call in
// ascending index order so tool_use block order is deterministic across
// turns (prompt-cache stability).
func emitToolCalls(events chan<- llm.ChatEvent, toolCalls map[int]*pendingTC) {
maxIdx := -1
for idx := range toolCalls {
if idx > maxIdx {
maxIdx = idx
}
}
for idx := 0; idx <= maxIdx; idx++ {
tc, ok := toolCalls[idx]
if !ok || tc.name == "" {
continue
}
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: tc.id,
Name: tc.name,
Input: json.RawMessage(tc.args.String()),
},
}
}
}
// QwenProvider implements llm.LLMProvider using the Qwen Chat Completions API.
// Qwen uses an OpenAI-compatible API, so we reuse the go-openai client.
type QwenProvider struct {
client *openai.Client
}
// NewQwenProvider creates a new Qwen LLM provider.
// The Qwen API is OpenAI-compatible, so we use the go-openai client
// with Qwen's base URL.
func NewQwenProvider(apiKey, baseURL string) *QwenProvider {
cfg := openai.DefaultConfig(apiKey)
if baseURL != "" {
cfg.BaseURL = baseURL
} else {
// Default to Qwen's official API endpoint
cfg.BaseURL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
client := openai.NewClientWithConfig(cfg)
return &QwenProvider{client: client}
}
func (p *QwenProvider) Models() []llm.ModelInfo {
return []llm.ModelInfo{
{ID: "qwen-plus", Name: "Qwen Plus", Provider: "qwen"},
{ID: "qwen-turbo", Name: "Qwen Turbo", Provider: "qwen"},
{ID: "qwen-max", Name: "Qwen Max", Provider: "qwen"},
{ID: "qwen-coder-plus", Name: "Qwen Coder Plus", Provider: "qwen"},
{ID: "qwen-vl-plus", Name: "Qwen VL Plus", Provider: "qwen"},
}
}
func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
// Build messages
msgs := make([]openai.ChatCompletionMessage, 0, len(req.Messages)+1)
if sysPrompt := qwenResolveSystemPrompt(req); sysPrompt != "" {
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleSystem,
Content: sysPrompt,
})
}
for _, m := range req.Messages {
switch m.Role {
case "user":
if m.ToolCallID != "" {
if len(m.Images) > 0 {
// Tool result with images: use multi-content parts
var parts []openai.ChatMessagePart
for _, img := range m.Images {
encoded := base64.StdEncoding.EncodeToString(img.Data)
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: dataURI,
Detail: openai.ImageURLDetailAuto,
},
})
}
if m.Content != "" {
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeText,
Text: m.Content,
})
}
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
MultiContent: parts,
ToolCallID: m.ToolCallID,
})
} else {
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: m.Content,
ToolCallID: m.ToolCallID,
})
}
} else if len(m.Images) > 0 {
var parts []openai.ChatMessagePart
for _, img := range m.Images {
encoded := base64.StdEncoding.EncodeToString(img.Data)
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: dataURI,
Detail: openai.ImageURLDetailAuto,
},
})
}
if m.Content != "" {
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeText,
Text: m.Content,
})
}
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
MultiContent: parts,
})
} else {
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: m.Content,
})
}
case "assistant":
msg := openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleAssistant,
Content: m.Content,
}
for _, tc := range m.ToolCalls {
msg.ToolCalls = append(msg.ToolCalls, openai.ToolCall{
ID: tc.ID,
Type: openai.ToolTypeFunction,
Function: openai.FunctionCall{
Name: tc.Name,
Arguments: string(tc.Input),
},
})
}
msgs = append(msgs, msg)
}
}
// Build tools
var tools []openai.Tool
for _, t := range req.Tools {
var params any
if err := json.Unmarshal(t.Parameters, &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,
MaxCompletionTokens: maxTokens,
Stream: true,
StreamOptions: &openai.StreamOptions{IncludeUsage: true},
}
if len(tools) > 0 {
openaiReq.Tools = tools
}
if req.Temperature > 0 {
openaiReq.Temperature = float32(req.Temperature)
}
if enabled, diag, ok := p.BuildEnableThinking(model, req.Reasoning); ok {
// TODO: Qwen DashScope expects a custom top-level "enable_thinking"
// JSON field that go-openai v1.41 does not expose via any
// ExtraBody/RawJSON mechanism. Wiring it requires either upgrading
// to a go-openai version with custom-field support or adding a
// custom HTTP roundtripper. Tracked as a Phase 2 follow-up.
_ = enabled
_ = diag
slog.Info("qwen thinking requested",
"model", model,
"requested", string(req.Reasoning),
"clamped_to_bool", true,
"reason", diag.Reason,
"sdk_limitation", "enable_thinking not yet wired to wire format")
} else if req.Reasoning != llm.ReasoningOff {
slog.Info("reasoning ignored",
"provider", "qwen",
"model", model,
"requested", string(req.Reasoning),
"reason", "model does not support thinking")
}
stream, err := p.client.CreateChatCompletionStream(ctx, openaiReq)
if err != nil {
return nil, err
}
events := make(chan llm.ChatEvent, 100)
go func() {
defer close(events)
defer stream.Close()
// Track tool calls being built up across deltas
toolCalls := make(map[int]*pendingTC)
for {
resp, err := stream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
return
}
for _, choice := range resp.Choices {
delta := choice.Delta
// Text content
if delta.Content != "" {
events <- llm.ChatEvent{
Type: llm.EventTextDelta,
Text: delta.Content,
}
}
// Tool calls
for _, tc := range delta.ToolCalls {
idx := 0
if tc.Index != nil {
idx = *tc.Index
}
pending, exists := toolCalls[idx]
if !exists {
pending = &pendingTC{}
toolCalls[idx] = pending
}
if tc.ID != "" {
pending.id = tc.ID
}
if tc.Function.Name != "" {
pending.name = tc.Function.Name
events <- llm.ChatEvent{
Type: llm.EventToolCallStart,
ToolCall: &llm.ToolCall{
ID: pending.id,
Name: pending.name,
},
}
}
if tc.Function.Arguments != "" {
pending.args.WriteString(tc.Function.Arguments)
}
}
// Finish reason
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
// Emit completed tool calls in index order.
emitToolCalls(events, toolCalls)
}
}
}
events <- llm.ChatEvent{Type: llm.EventDone}
}()
return events, nil
}
// NormalizeToolSchema strips $ref and definitions from each tool's
// JSON Schema. Qwen DashScope tracks the OpenAI function-calling
// shape, so the same restricted JSON Schema subset applies (and the
// same openaiUnsupportedFields list is reused).
func (p *QwenProvider) NormalizeToolSchema(tools []llm.ToolDef) ([]llm.ToolDef, []llm.Diagnostic) {
return llm.ApplyStripList(tools, []string{"$ref", "definitions"})
}
// BuildEnableThinking maps a llm.ReasoningMode to Qwen's enable_thinking
// boolean. Returns (false, empty diag, false) when off or the model
// doesn't support thinking. For any non-off mode on a supported model,
// returns (true, clamped diag, true) — the boolean toggle loses the
// requested low/medium/high granularity, so the diag always fires.
func (p *QwenProvider) BuildEnableThinking(model string, mode llm.ReasoningMode) (bool, llm.Diagnostic, bool) {
if mode == llm.ReasoningOff {
return false, llm.Diagnostic{}, false
}
if !qwenSupportsThinking(model) {
return false, llm.Diagnostic{}, false
}
return true, llm.Diagnostic{
Action: "clamped",
Reason: "qwen reasoning is boolean; granularity ignored",
}, true
}
// qwenSupportsThinking returns true for Qwen models that support the
// enable_thinking parameter. Conservative — unknown IDs default to
// false (only QwQ and Qwen3 family models accept this field).
func qwenSupportsThinking(model string) bool {
prefixes := []string{"qwen-qwq", "qwen3"}
for _, prefix := range prefixes {
if strings.HasPrefix(model, prefix) {
return true
}
}
return false
}
// qwenResolveSystemPrompt returns the effective system prompt string,
// preferring SystemPromptParts when present. Mirrors the OpenAI/Gemini
// resolution helpers.
func qwenResolveSystemPrompt(req llm.ChatRequest) string {
if len(req.SystemPromptParts) > 0 {
return llm.JoinSystemPromptParts(req.SystemPromptParts)
}
return req.SystemPrompt
}
-45
View File
@@ -1,45 +0,0 @@
package qwen
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
func TestQwenResolveSystemPromptPrefersParts(t *testing.T) {
got := qwenResolveSystemPrompt(llm.ChatRequest{
SystemPrompt: "legacy",
SystemPromptParts: []llm.SystemPromptPart{{Text: "new-a"}, {Text: "new-b"}},
})
require.Equal(t, "new-a\nnew-b", got)
}
func TestQwenResolveSystemPromptFallback(t *testing.T) {
got := qwenResolveSystemPrompt(llm.ChatRequest{SystemPrompt: "legacy"})
require.Equal(t, "legacy", got)
}
func TestQwenResolveSystemPromptEmpty(t *testing.T) {
got := qwenResolveSystemPrompt(llm.ChatRequest{})
require.Equal(t, "", got)
}
func TestEmitToolCalls_OrderedByIndex(t *testing.T) {
mk := func(id, name string) *pendingTC {
p := &pendingTC{id: id, name: name}
p.args.WriteString("{}")
return p
}
toolCalls := map[int]*pendingTC{1: mk("b", "second"), 0: mk("a", "first")}
ch := make(chan llm.ChatEvent, 10)
emitToolCalls(ch, toolCalls)
close(ch)
var ids []string
for ev := range ch {
if ev.Type == llm.EventToolCallDone {
ids = append(ids, ev.ToolCall.ID)
}
}
require.Equal(t, []string{"a", "b"}, ids)
}
+34
View File
@@ -0,0 +1,34 @@
# 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.
+23
View File
@@ -0,0 +1,23 @@
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
@@ -0,0 +1,77 @@
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
@@ -0,0 +1,81 @@
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)
}
})
}
}
+82 -29
View File
@@ -70,9 +70,23 @@ 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)
//
// Returns the constructed Runtime and a nil error today, but callers MUST
// check the error: the return is reserved for future validation.
// Use BuildRuntimeContext when construction must be cancellable.
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 {
@@ -91,51 +105,73 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
// 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
if reg, ok := inputs.Tools.(*tool.Registry); ok {
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 deps.Skills != nil {
skills := deps.Skills
reg.Register(&tool.LoadSkillTool{
stagedTools = append(stagedTools, &tool.LoadSkillTool{
Lookup: func(name string) (string, bool) {
return skills.Get(name)
if rt.Skills == nil {
return "", false
}
return rt.Skills.Get(name)
},
})
}
if deps.Memory != nil {
mem := deps.Memory
reg.Register(&tool.LoadMemoryTool{
stagedTools = append(stagedTools, &tool.LoadMemoryTool{
Lookup: func(id string) (string, bool) {
return mem.Get(id)
},
})
}
// 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)
var err error
mcpClients, mcpStatus, err = connectMCPServers(ctx, spec.MCPServers)
if err != nil {
return nil, err
}
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 := ""
if deps.Skills != nil {
skillsIndex = deps.Skills.FormatIndex()
}
skillsIndex, skillSources := skillIndexSnapshot(deps.Skills)
promptSources := append([]ContextSource(nil), spec.SystemPromptSources...)
memoryIndex := ""
if deps.Memory != nil {
memoryIndex = deps.Memory.FormatIndex()
@@ -168,7 +204,7 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
loop := mergeLoopConfig(deps.AgentLoop, spec.Loop)
rt := &Runtime{
rt = &Runtime{
LLM: inputs.Provider,
Tools: inputs.Tools,
Session: inputs.Session,
@@ -177,6 +213,7 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
Model: modelName,
FallbackModel: fallbackModel,
ContextWindow: spec.ContextWindow,
MaxOutputTokens: spec.MaxOutputTokens,
Provider: provider,
Reasoning: reasoning,
Workspace: spec.Workspace,
@@ -190,8 +227,15 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
IngestSource: inputs.IngestSource,
AgentLoop: loop,
StaticSystemPrompt: staticPrompt,
CalibratorStore: deps.CalibratorStore,
mcpClients: mcpClients,
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,
}
// Seed the calibrator from prior (ratio, count) for this session so a
@@ -227,6 +271,15 @@ func mergeLoopConfig(base, override LoopConfig) LoopConfig {
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
}
+136
View File
@@ -0,0 +1,136 @@
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)
}
}
+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)
}
+60
View File
@@ -0,0 +1,60 @@
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")
}
}
+178
View File
@@ -0,0 +1,178 @@
package runtime
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/sausheong/harness/compaction"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
)
type joinedSummaryProvider struct {
llmtest.Base
entered, cancelled, release chan struct{}
beforeReturn func()
}
func (p *joinedSummaryProvider) ChatStream(ctx context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
close(p.entered)
select {
case <-p.release:
case <-ctx.Done():
close(p.cancelled)
<-p.release
return nil, ctx.Err()
}
if p.beforeReturn != nil {
p.beforeReturn()
}
ch := make(chan llm.ChatEvent, 2)
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Summary of original work and constraints."}
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 70, OutputTokens: 7}}
close(ch)
return ch, nil
}
func TestRuntimeJoinsDeferredBackgroundCompactionAndUsage(t *testing.T) {
for _, cancelRun := range []bool{false, true} {
name := "complete"
if cancelRun {
name = "cancel"
}
t.Run(name, func(t *testing.T) {
sess := session.NewSession("agent", "key")
for i := 0; i < 8; i++ {
sess.Append(session.UserMessageEntry("question"))
sess.Append(session.AssistantMessageEntry("answer"))
}
summary := &joinedSummaryProvider{entered: make(chan struct{}), cancelled: make(chan struct{}), release: make(chan struct{})}
var releaseOnce sync.Once
release := func() { releaseOnce.Do(func() { close(summary.release) }) }
defer release()
manager := &compaction.Manager{PreserveTurns: 1, Summarizer: &compaction.Summarizer{Provider: summary, Model: "summary", Timeout: time.Second}}
rt := &Runtime{Tools: usageNoopExecutor{}, LLM: &requestUsageProvider{total: 1}, Session: sess, Model: "generation", ContextWindow: 1000000, MaxTurns: 1, Compaction: manager}
rt.AgentLoop.Hooks.OnStop = func(ctx context.Context, _ string) {
manager.MaybeCompactAsyncContext(ctx, sess, compaction.ReasonManual)
}
ledger := &llm.UsageLedger{}
ctx, cancel := context.WithCancel(llm.WithUsageObserver(context.Background(), ledger.Record))
defer cancel()
events, err := rt.Run(ctx, "go", nil)
if err != nil {
t.Fatal(err)
}
joined := make(chan struct{})
var observed []AgentEvent
go func() {
for event := range events {
observed = append(observed, event)
}
close(joined)
}()
select {
case <-summary.entered:
case <-time.After(3 * time.Second):
t.Fatal("background summary not started")
}
if cancelRun {
cancel()
select {
case <-summary.cancelled:
case <-time.After(time.Second):
t.Fatal("parent cancellation lost")
}
}
select {
case <-joined:
t.Fatal("runtime stream closed before background joined")
case <-time.After(20 * time.Millisecond):
}
release()
select {
case <-joined:
case <-time.After(3 * time.Second):
t.Fatal("runtime did not join background")
}
if manager.HasInFlight(sess) {
t.Fatal("producer remains after runtime close")
}
var doneCount, abortedCount int
for i, event := range observed {
if event.Type == EventDone {
doneCount++
if i != len(observed)-1 || event.Usage == nil || event.Usage.InputTokens != 20070 {
t.Fatalf("done must be last with final accounting: %+v", event)
}
}
if event.Type == EventAborted {
abortedCount++
}
if event.Type == EventError && !cancelRun {
t.Fatalf("unexpected error: %v", event.Error)
}
}
if cancelRun && (doneCount != 0 || abortedCount != 1) {
t.Fatalf("cancel: done=%d aborted=%d", doneCount, abortedCount)
}
if !cancelRun && (doneCount != 1 || abortedCount != 0) {
t.Fatalf("success: done=%d aborted=%d", doneCount, abortedCount)
}
records := ledger.Records()
if len(records) != 2 || records[1].Category != llm.CallCompaction {
t.Fatal("background observer context lost", records)
}
if cancelRun {
if records[1].Status != "cancelled" {
t.Fatal(records[1])
}
} else if records[1].Usage == nil || records[1].Usage.InputTokens != 70 {
t.Fatal(records[1])
}
})
}
}
func TestRuntimeReportsAlreadyFinishedCompactionError(t *testing.T) {
sess := session.NewSession("agent", "key")
for i := 0; i < 8; i++ {
sess.Append(session.UserMessageEntry("question"))
sess.Append(session.AssistantMessageEntry("answer"))
}
summary := &joinedSummaryProvider{entered: make(chan struct{}), cancelled: make(chan struct{}), release: make(chan struct{})}
// A concurrent branch change makes the summary's source view stale. This is
// a real CommitCompaction error, without making the session writer fail.
summary.beforeReturn = func() { sess.Append(session.UserMessageEntry("new branch work")) }
close(summary.release)
manager := &compaction.Manager{PreserveTurns: 1, Summarizer: &compaction.Summarizer{Provider: summary, Model: "summary", Timeout: time.Second}}
rt := &Runtime{Tools: usageNoopExecutor{}, LLM: &requestUsageProvider{total: 1}, Session: sess, Model: "generation", ContextWindow: 1000000, MaxTurns: 1, Compaction: manager}
rt.AgentLoop.Hooks.OnStop = func(ctx context.Context, _ string) {
<-manager.MaybeCompactAsyncContext(ctx, sess, compaction.ReasonManual)
}
events, err := rt.Run(context.Background(), "go", nil)
if err != nil {
t.Fatal(err)
}
var errorsSeen, doneSeen int
for event := range events {
if event.Type == EventError {
if !errors.Is(event.Error, session.ErrSessionChanged) {
t.Fatalf("expected stale-session error, got %v", event.Error)
}
errorsSeen++
}
if event.Type == EventDone {
doneSeen++
}
}
if errorsSeen != 1 || doneSeen != 0 {
t.Fatalf("completed failed producer: errors=%d done=%d", errorsSeen, doneSeen)
}
if err := sess.Flush(); err != nil {
t.Fatalf("error must originate in compaction, not persistence: %v", err)
}
}
+10 -5
View File
@@ -142,18 +142,23 @@ func BuildStaticSystemPrompt(
}
// buildDynamicSystemPromptSuffix concatenates the per-turn dynamic context
// — the date line and the cortex hint — into a single string the runtime
// sends as the second (un-cached) SystemPromptPart. The date line, when
// non-empty, appears at the top so the model anchors on "today" before
// the per-turn content. Returns "" when all inputs are empty/nil.
// — the identity hint, date line, and cortex hint — into a single string
// the runtime sends as the second (un-cached) SystemPromptPart. identityHint
// leads (see Runtime.DynamicIdentityHint: it needs to outweigh the model's
// own prior in-conversation statements, so it gets the most prominent
// position), then the date line so the model anchors on "today" before the
// per-turn content. Returns "" when all inputs are empty/nil.
//
// As of sub-project 5, skill bodies and memory entries are no longer
// auto-injected here. Their indices live in the cached static prompt
// and the agent loads bodies on demand via the load_skill / load_memory
// tools. This trims 5–15 KB of speculative skill bodies and 5–10 KB of
// speculative memory bodies from every prefill.
func buildDynamicSystemPromptSuffix(dateLine, cortexContext string) string {
func buildDynamicSystemPromptSuffix(identityHint, dateLine, cortexContext string) string {
var sb strings.Builder
if identityHint != "" {
sb.WriteString(identityHint)
}
if dateLine != "" {
sb.WriteString(dateLine)
}
+114
View File
@@ -0,0 +1,114 @@
package runtime
import (
"context"
"fmt"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/tokens"
)
// ContextContribution describes size, never the potentially sensitive body.
type ContextContribution struct {
Kind string `json:"kind"`
Name string `json:"name"`
Count int `json:"count"`
EstimatedTokens int `json:"estimated_tokens"`
}
// ContextSource describes a component already included in the installed prompt.
// These estimates are subsets of the static category, not additional tokens.
type ContextSource struct {
Kind string `json:"kind"`
Path string `json:"path"`
EstimatedTokens int `json:"estimated_tokens"`
}
type SkillIndexSnapshotter interface {
IndexSnapshot() (string, []ContextSource)
}
func skillIndexSnapshot(provider SkillProvider) (string, []ContextSource) {
if provider == nil {
return "", nil
}
if snapshotter, ok := provider.(SkillIndexSnapshotter); ok {
return snapshotter.IndexSnapshot()
}
return provider.FormatIndex(), nil
}
type ContextInspection struct {
Sources []ContextSource `json:"sources,omitempty"`
OmittedSources int `json:"omitted_sources,omitempty"`
EstimateMethod string `json:"estimate_method"`
EstimatedTokens int `json:"estimated_tokens"`
Contributions []ContextContribution `json:"contributions"`
Limitations []string `json:"limitations"`
}
// InspectContext measures the installed static prompt, current effective history
// and registered schemas while idle. It does not make provider calls or refresh
// discovery. Dynamic retrieval and a future user message are not included.
func (r *Runtime) InspectContext(ctx context.Context) (ContextInspection, error) {
var out ContextInspection
if !r.runMu.TryLock() {
return out, fmt.Errorf("runtime is already running")
}
defer r.runMu.Unlock()
if err := ctx.Err(); err != nil {
return out, err
}
var messages []llm.Message
if r.Session != nil {
history, err := r.Session.ResolveImages(ctx, r.Session.View())
if err != nil {
return out, err
}
messages = assembleMessages(history)
}
var defs []llm.ToolDef
if r.Tools != nil {
defs = r.Tools.ToolDefs()
}
if r.contextSources != nil {
sources := r.contextSources()
if len(sources) > 128 {
out.OmittedSources = len(sources) - 128
sources = sources[:128]
}
out.Sources = append([]ContextSource(nil), sources...)
}
out.EstimateMethod = "UTF-8 bytes / 4 with message framing and fixed image allowance; not provider-reported usage"
pinned, err := r.contextPinsPrompt()
if err != nil {
return out, err
}
statePrompt, err := r.contextStatePrompt()
if err != nil {
return out, err
}
out.EstimatedTokens = tokens.Estimate(messages, r.StaticSystemPrompt+pinned+statePrompt, defs)
out.Contributions = append(out.Contributions, ContextContribution{Kind: "static_prompt", Name: "Installed identity, guidance, skills and memory", Count: 1, EstimatedTokens: tokens.Estimate(nil, r.StaticSystemPrompt, nil)})
var ordinary, results []llm.Message
for _, m := range messages {
if m.Role == "tool" {
results = append(results, m)
} else {
ordinary = append(ordinary, m)
}
}
out.Contributions = append(out.Contributions,
ContextContribution{Kind: "messages", Name: "Effective conversation", Count: len(ordinary), EstimatedTokens: tokens.Estimate(ordinary, "", nil)},
ContextContribution{Kind: "tool_results", Name: "Effective tool results", Count: len(results), EstimatedTokens: tokens.Estimate(results, "", nil)},
ContextContribution{Kind: "tool_schemas", Name: "Registered tool schemas", Count: len(defs), EstimatedTokens: tokens.Estimate(nil, "", defs)})
if pinned != "" {
pins, _ := r.contextPins()
out.Contributions = append(out.Contributions, ContextContribution{Kind: "pins", Name: "Pinned objectives and constraints", Count: len(pins), EstimatedTokens: tokens.Estimate(nil, pinned, nil)})
}
if statePrompt != "" {
state, _ := r.contextState()
out.Contributions = append(out.Contributions, ContextContribution{Kind: "task_state", Name: "Structured objectives, decisions, unresolved work and evidence references", Count: len(state.Items), EstimatedTokens: tokens.Estimate(nil, statePrompt, nil)})
}
out.Limitations = []string{"Source estimates are subsets of the static prompt category, not additional tokens.", "Excludes the next user message, per-request date/identity suffix and dynamic retrieval.", "Estimates include only effective history after compaction; raw archived history is not counted.", "Image estimates use a fixed allowance, not provider-specific tiles or resolution.", "Components round down individually; their sum can differ slightly from the total."}
return out, nil
}
+44
View File
@@ -0,0 +1,44 @@
package runtime
import (
"context"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tokens"
"github.com/sausheong/harness/tool"
"strings"
"testing"
)
func TestInspectContextEstimatesWithoutChangingHistory(t *testing.T) {
s := session.NewSession("test", "inspect")
s.Append(session.UserMessageEntry("private content must not be returned"))
reg := tool.NewRegistry()
reg.Register(echoTool{})
r := &Runtime{Session: s, Tools: reg, StaticSystemPrompt: strings.Repeat("a", 100)}
got, err := r.InspectContext(context.Background())
if err != nil {
t.Fatal(err)
}
want := tokens.Estimate([]llm.Message{{Role: "user", Content: "private content must not be returned"}}, r.StaticSystemPrompt, reg.ToolDefs())
if got.EstimatedTokens != want || len(got.Contributions) != 4 {
t.Fatalf("inspection: %+v want %d", got, want)
}
if got.Contributions[1].Count != 1 || got.Contributions[3].Count != 1 || !strings.Contains(got.EstimateMethod, "not provider-reported") {
t.Fatalf("metadata: %+v", got)
}
if len(s.View()) != 1 {
t.Fatal("inspection changed history")
}
r.runMu.Lock()
_, err = r.InspectContext(context.Background())
r.runMu.Unlock()
if err == nil {
t.Fatal("busy inspection accepted")
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err = r.InspectContext(ctx); err == nil {
t.Fatal("cancelled inspection accepted")
}
}
+137
View File
@@ -0,0 +1,137 @@
package runtime
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/sausheong/harness/compaction"
"io"
"strings"
"unicode/utf8"
)
const contextPinsKind = "harness.context_pins"
type ContextPin struct {
ID string `json:"id"`
Kind string `json:"kind"`
Text string `json:"text"`
}
type contextPinsRecord struct {
Version int `json:"version"`
Pins []ContextPin `json:"pins"`
}
func validatePins(pins []ContextPin) error {
if len(pins) > 16 {
return errors.New("at most 16 context pins are allowed")
}
seen := map[string]bool{}
for _, pin := range pins {
if pin.ID == "" || len(pin.ID) > 64 || strings.IndexFunc(pin.ID, func(r rune) bool { return !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-' || r == '_') }) >= 0 || seen[pin.ID] {
return errors.New("pin IDs must be unique lowercase identifiers of 1-64 characters")
}
seen[pin.ID] = true
if pin.Kind != "objective" && pin.Kind != "constraint" {
return errors.New("pin kind must be objective or constraint")
}
if strings.TrimSpace(pin.Text) == "" || len(pin.Text) > 2048 || !utf8.ValidString(pin.Text) || strings.ContainsRune(pin.Text, 0) {
return errors.New("pin text must contain 1-2048 UTF-8 bytes without NUL")
}
}
return nil
}
// SetContextPins replaces the session-wide pin set durably while idle. An empty
// set clears pins. Pins do not grant capabilities and are independent of branch
// selection; changing sessions changes the pin set.
func (r *Runtime) SetContextPins(ctx context.Context, pins []ContextPin) error {
if !r.runMu.TryLock() {
return errors.New("runtime is already running")
}
defer r.runMu.Unlock()
if err := ctx.Err(); err != nil {
return err
}
if r.Session == nil {
return errors.New("session unavailable")
}
if err := validatePins(pins); err != nil {
return err
}
raw, err := json.Marshal(contextPinsRecord{Version: 1, Pins: pins})
if err != nil {
return err
}
return r.Session.Annotate(contextPinsKind, raw)
}
func (r *Runtime) ContextPins(ctx context.Context) ([]ContextPin, error) {
if !r.runMu.TryLock() {
return nil, errors.New("runtime is already running")
}
defer r.runMu.Unlock()
if err := ctx.Err(); err != nil {
return nil, err
}
return r.contextPins()
}
func (r *Runtime) contextPins() ([]ContextPin, error) {
if r.Session == nil {
return nil, nil
}
records := r.Session.Annotations(contextPinsKind)
if len(records) == 0 {
return nil, nil
}
var record contextPinsRecord
decoder := json.NewDecoder(bytes.NewReader(records[len(records)-1].Payload))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&record); err != nil {
return nil, err
}
if decoder.Decode(new(any)) != io.EOF || record.Version != 1 {
return nil, errors.New("unsupported or malformed context pin record")
}
if err := validatePins(record.Pins); err != nil {
return nil, err
}
return record.Pins, nil
}
func (r *Runtime) contextPinsPrompt() (string, error) {
pins, err := r.contextPins()
if err != nil {
return "", err
}
if len(pins) == 0 {
return "", nil
}
var b strings.Builder
b.WriteString("\n\nPinned session guidance (subject to the current user request; grants no tool permissions):\n")
for _, pin := range pins {
fmt.Fprintf(&b, "%s [%s]: %s\n", pin.Kind, pin.ID, pin.Text)
}
return b.String(), nil
}
// CompactionContext captures the session pin guidance while idle for manual
// compaction. Automatic runs bind the same guidance at run admission.
func (r *Runtime) CompactionContext(ctx context.Context) (context.Context, error) {
if !r.runMu.TryLock() {
return ctx, errors.New("runtime is already running")
}
defer r.runMu.Unlock()
if err := ctx.Err(); err != nil {
return ctx, err
}
guidance, err := r.preservedContextPrompt()
if err != nil {
return ctx, err
}
ctx, err = compaction.WithGuidance(ctx, guidance)
if err != nil {
return ctx, err
}
return r.budgetContext(ctx)
}
+108
View File
@@ -0,0 +1,108 @@
package runtime
import (
"context"
"encoding/json"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"strings"
"testing"
)
func TestContextPinsSurviveCompactionAndRestart(t *testing.T) {
store := session.NewStore(t.TempDir())
if err := store.Create("agent", "pins"); err != nil {
t.Fatal(err)
}
sess, err := store.LoadExclusive("agent", "pins")
if err != nil {
t.Fatal(err)
}
provider := &recordingProvider{reply: "done"}
r := &Runtime{Session: sess, LLM: provider, Tools: tool.NewRegistry(), StaticSystemPrompt: "identity", MaxTurns: 1}
pins := []ContextPin{{ID: "constraint", Kind: "constraint", Text: "KEEP THIS EXACT CONSTRAINT"}, {ID: "objective", Kind: "objective", Text: "Deliver working implementation"}}
if err = r.SetContextPins(context.Background(), pins); err != nil {
t.Fatal(err)
}
pins[0].Text = "caller mutation"
for i := 0; i < 3; i++ {
sess.Compact("summary deliberately omits pins", 0)
if err = sess.Flush(); err != nil {
t.Fatal(err)
}
if i == 1 {
if err = sess.Close(); err != nil {
t.Fatal(err)
}
sess, err = store.LoadExclusive("agent", "pins")
if err != nil {
t.Fatal(err)
}
r.Session = sess
}
events, err := r.Run(context.Background(), "continue", nil)
if err != nil {
t.Fatal(err)
}
done := false
for event := range events {
if event.Type == EventError {
t.Fatal(event.Error)
}
if event.Type == EventDone {
done = true
}
}
if !done {
t.Fatal("run did not complete")
}
}
defer sess.Close()
if len(provider.requests) != 3 {
t.Fatal("missing requests")
}
for _, request := range provider.requests {
prompt := llm.JoinSystemPromptParts(request.SystemPromptParts)
if !strings.Contains(prompt, "KEEP THIS EXACT CONSTRAINT") || !strings.Contains(prompt, "Deliver working implementation") {
t.Fatal("pins omitted after compaction")
}
}
inspected, err := r.InspectContext(context.Background())
if err != nil {
t.Fatal(err)
}
if inspected.Contributions[len(inspected.Contributions)-1].Kind != "pins" {
t.Fatal("pins not counted")
}
if err = r.SetContextPins(context.Background(), nil); err != nil {
t.Fatal(err)
}
got, err := r.ContextPins(context.Background())
if err != nil || len(got) != 0 {
t.Fatal("clear failed", err)
}
}
func TestContextPinsValidationAndCorruptRecord(t *testing.T) {
r := &Runtime{Session: session.NewSession("agent", "pins")}
for _, pins := range [][]ContextPin{{{ID: "bad id", Kind: "constraint", Text: "x"}}, {{ID: "ok", Kind: "other", Text: "x"}}, {{ID: "ok", Kind: "objective", Text: strings.Repeat("x", 2049)}}} {
if err := r.SetContextPins(context.Background(), pins); err == nil {
t.Fatal("invalid pins accepted")
}
}
if len(r.Session.Annotations(contextPinsKind)) != 0 {
t.Fatal("invalid write persisted")
}
r.runMu.Lock()
err := r.SetContextPins(context.Background(), nil)
r.runMu.Unlock()
if err == nil {
t.Fatal("busy update accepted")
}
if err = r.Session.Annotate(contextPinsKind, json.RawMessage(`{"version":99,"pins":[]}`)); err != nil {
t.Fatal(err)
}
if _, err = r.ContextPins(context.Background()); err == nil {
t.Fatal("unsupported record ignored")
}
}
+161
View File
@@ -0,0 +1,161 @@
package runtime
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"strings"
"unicode/utf8"
"github.com/sausheong/harness/session"
)
const contextStateKind = "harness.context_state"
// ContextStateItem records task facts independently of generated summaries.
// Reference is an opaque evidence locator, never opened or treated as proof.
type ContextStateItem struct {
ID string `json:"id"`
Kind string `json:"kind"`
Text string `json:"text"`
Reference string `json:"reference,omitempty"`
}
// ContextState is session-wide, including across branch selection. Revision is
// required on replacement so a stale client cannot silently discard newer work.
type ContextState struct {
Revision int `json:"revision"`
Items []ContextStateItem `json:"items"`
}
type contextStateRecord struct {
Version int `json:"version"`
Items []ContextStateItem `json:"items"`
}
func encodeContextState(items []ContextStateItem) ([]byte, error) {
if len(items) > 32 {
return nil, errors.New("at most 32 structured context items are allowed")
}
seen := map[string]bool{}
for _, item := range items {
if item.ID == "" || len(item.ID) > 64 || strings.IndexFunc(item.ID, func(r rune) bool { return !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-' || r == '_') }) >= 0 || seen[item.ID] {
return nil, errors.New("context item IDs must be unique lowercase identifiers of 1-64 characters")
}
seen[item.ID] = true
switch item.Kind {
case "objective", "decision", "unresolved_work", "verification_reference":
default:
return nil, errors.New("unsupported structured context kind")
}
if strings.TrimSpace(item.Text) == "" || len(item.Text) > 2048 || !utf8.ValidString(item.Text) || strings.ContainsRune(item.Text, 0) {
return nil, errors.New("context text must contain 1-2048 UTF-8 bytes without NUL")
}
if len(item.Reference) > 1024 || !utf8.ValidString(item.Reference) || strings.ContainsRune(item.Reference, 0) {
return nil, errors.New("context reference must be at most 1024 UTF-8 bytes without NUL")
}
if item.Kind == "verification_reference" && strings.TrimSpace(item.Reference) == "" {
return nil, errors.New("verification context requires an evidence reference")
}
}
raw, err := json.Marshal(contextStateRecord{Version: 1, Items: items})
if len(raw) > 8192 {
return nil, errors.New("structured context exceeds 8 KiB encoded limit")
}
return raw, err
}
func (r *Runtime) contextState() (ContextState, error) {
var state ContextState
if r.Session == nil {
return state, errors.New("session unavailable")
}
records := r.Session.Annotations(contextStateKind)
state.Revision = len(records)
if len(records) == 0 {
return state, nil
}
payload := records[len(records)-1].Payload
if len(payload) > 8192 {
return state, errors.New("structured context exceeds 8 KiB")
}
var rec contextStateRecord
dec := json.NewDecoder(bytes.NewReader(payload))
dec.DisallowUnknownFields()
if err := dec.Decode(&rec); err != nil {
return state, err
}
if rec.Version != 1 || dec.Decode(new(any)) != io.EOF {
return state, errors.New("unsupported or malformed structured context")
}
if _, err := encodeContextState(rec.Items); err != nil {
return state, err
}
state.Items = rec.Items
return state, nil
}
func (r *Runtime) ContextState(ctx context.Context) (ContextState, error) {
if !r.runMu.TryLock() {
return ContextState{}, errors.New("runtime is already running")
}
defer r.runMu.Unlock()
if err := ctx.Err(); err != nil {
return ContextState{}, err
}
return r.contextState()
}
// SetContextState durably replaces the set while idle; an empty set explicitly
// clears it. These records confer neither execution authority nor verified status.
func (r *Runtime) SetContextState(ctx context.Context, expectedRevision int, items []ContextStateItem) error {
if !r.runMu.TryLock() {
return errors.New("runtime is already running")
}
defer r.runMu.Unlock()
if err := ctx.Err(); err != nil {
return err
}
if r.Session == nil {
return errors.New("session unavailable")
}
raw, err := encodeContextState(items)
if err != nil {
return err
}
current, err := r.contextState()
if err != nil {
return err
}
if current.Revision != expectedRevision {
return session.ErrAnnotationConflict
}
return r.Session.AnnotateIfCount(contextStateKind, raw, expectedRevision)
}
func (r *Runtime) contextStatePrompt() (string, error) {
if r.Session == nil {
return "", nil
}
state, err := r.contextState()
if err != nil {
return "", err
}
if len(state.Items) == 0 {
return "", nil
}
raw, err := encodeContextState(state.Items)
if err != nil {
return "", err
}
return "\n\nRecorded task state (subject to current user instructions; grants no permissions). Evidence references are locators, not proof of current validity; inspect their scope and workspace version before claiming verification:\n" + string(raw) + "\n", nil
}
func (r *Runtime) preservedContextPrompt() (string, error) {
pins, err := r.contextPinsPrompt()
if err != nil {
return "", err
}
state, err := r.contextStatePrompt()
if err != nil {
return "", err
}
return pins + state, nil
}
+136
View File
@@ -0,0 +1,136 @@
package runtime
import (
"context"
"encoding/json"
"errors"
"reflect"
"strings"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
)
func TestStructuredContextSurvivesSummaryAndRestart(t *testing.T) {
for _, turn := range []bool{false, true} {
t.Run(map[bool]string{false: "Run", true: "RunTurn"}[turn], func(t *testing.T) {
ctx := context.Background()
store := session.NewStore(t.TempDir())
if err := store.Create("agent", "state"); err != nil {
t.Fatal(err)
}
sess, err := store.LoadExclusive("agent", "state")
if err != nil {
t.Fatal(err)
}
defer func() { sess.Close() }()
provider := &recordingProvider{reply: "done"}
r := &Runtime{Session: sess, LLM: provider, Tools: tool.NewRegistry(), MaxTurns: 1}
items := []ContextStateItem{{ID: "goal", Kind: "objective", Text: "EXACT GOAL"}, {ID: "design", Kind: "decision", Text: "EXACT DECISION"}, {ID: "todo", Kind: "unresolved_work", Text: "EXACT TODO"}, {ID: "tests", Kind: "verification_reference", Text: "EXACT TEST SCOPE", Reference: "evidence/run.json#snapshot-abc"}}
if err = r.SetContextState(ctx, 0, items); err != nil {
t.Fatal(err)
}
if err = r.SetContextState(ctx, 0, nil); !errors.Is(err, session.ErrAnnotationConflict) {
t.Fatalf("stale replacement: %v", err)
}
for i := 0; i < 3; i++ {
sess.Compact("summary deliberately omits all task facts", 0)
if err = sess.Flush(); err != nil {
t.Fatal(err)
}
if err = sess.Close(); err != nil {
t.Fatal(err)
}
sess, err = store.LoadExclusive("agent", "state")
if err != nil {
t.Fatal(err)
}
r.Session = sess
if turn {
result, err := r.RunTurn(ctx, "continue", nil, nil)
if err != nil || result.Err != nil {
t.Fatalf("%+v %v", result, err)
}
} else {
events, err := r.Run(ctx, "continue", nil)
if err != nil {
t.Fatal(err)
}
for e := range events {
if e.Type == EventError {
t.Fatal(e.Error)
}
}
}
prompt := llm.JoinSystemPromptParts(provider.requests[len(provider.requests)-1].SystemPromptParts)
for _, item := range items {
if !strings.Contains(prompt, item.Text) || !strings.Contains(prompt, item.Reference) {
t.Fatal("structured state lost", prompt)
}
}
state, err := r.ContextState(ctx)
if err != nil || state.Revision != 1 || !reflect.DeepEqual(state.Items, items) {
t.Fatalf("%+v %v", state, err)
}
}
view, err := r.InspectContext(ctx)
if err != nil {
t.Fatal(err)
}
if view.Contributions[len(view.Contributions)-1].Kind != "task_state" {
t.Fatal("context estimate omits task state")
}
if err = r.SetContextState(ctx, 1, nil); err != nil {
t.Fatal(err)
}
state, err := r.ContextState(ctx)
if err != nil || state.Revision != 2 || len(state.Items) != 0 {
t.Fatal(state, err)
}
})
}
}
func TestStructuredContextRejectsInvalidAndCorruptState(t *testing.T) {
ctx := context.Background()
p := &recordingProvider{reply: "done"}
r := &Runtime{Session: session.NewSession("a", "s"), LLM: p, Tools: tool.NewRegistry()}
invalid := [][]ContextStateItem{
{{ID: "a", Kind: "verification_reference", Text: "test"}},
{{ID: "a", Kind: "unknown", Text: "test"}},
{{ID: "a", Kind: "objective", Text: "x"}, {ID: "a", Kind: "decision", Text: "y"}},
{{ID: "a", Kind: "objective", Text: strings.Repeat("x", 2049)}},
}
large := []ContextStateItem{}
for _, id := range []string{"a", "b", "c", "d"} {
large = append(large, ContextStateItem{ID: id, Kind: "objective", Text: strings.Repeat("x", 2048)})
}
invalid = append(invalid, large)
for _, items := range invalid {
if err := r.SetContextState(ctx, 0, items); err == nil {
t.Fatal("invalid state accepted")
}
}
if len(r.Session.Annotations(contextStateKind)) != 0 {
t.Fatal("invalid records persisted")
}
cancelled, cancel := context.WithCancel(ctx)
cancel()
if err := r.SetContextState(cancelled, 0, nil); !errors.Is(err, context.Canceled) {
t.Fatal(err)
}
if err := r.Session.Annotate(contextStateKind, json.RawMessage(`{"version":2,"items":[]}`)); err != nil {
t.Fatal(err)
}
result, err := r.RunTurn(ctx, "do not dispatch", nil, nil)
if err == nil && result.Err == nil {
t.Fatal("corrupt state accepted")
}
if len(p.requests) != 0 {
t.Fatal("corrupt state dispatched provider")
}
if _, err = r.CompactionContext(ctx); err == nil {
t.Fatal("corrupt state compacted")
}
}
+12 -4
View File
@@ -85,17 +85,17 @@ func TestBuildStaticSystemPromptIncludesMemoryFiles(t *testing.T) {
}
func TestBuildDynamicSystemPromptSuffixEmpty(t *testing.T) {
got := buildDynamicSystemPromptSuffix("", "")
got := buildDynamicSystemPromptSuffix("", "", "")
require.Equal(t, "", got)
}
func TestBuildDynamicSystemPromptSuffixHintOnly(t *testing.T) {
got := buildDynamicSystemPromptSuffix("", "\n\nHINT")
got := buildDynamicSystemPromptSuffix("", "", "\n\nHINT")
require.Equal(t, "\n\nHINT", got)
}
func TestBuildDynamicSystemPromptSuffixDateAndHint(t *testing.T) {
got := buildDynamicSystemPromptSuffix("Today's date is 2026-05-01.", "\n\nKG_HINT")
got := buildDynamicSystemPromptSuffix("", "Today's date is 2026-05-01.", "\n\nKG_HINT")
dateIdx := strings.Index(got, "Today's date is")
hintIdx := strings.Index(got, "KG_HINT")
require.True(t, dateIdx >= 0 && hintIdx > dateIdx,
@@ -103,11 +103,19 @@ func TestBuildDynamicSystemPromptSuffixDateAndHint(t *testing.T) {
}
func TestBuildDynamicSystemPromptSuffixIncludesDate(t *testing.T) {
got := buildDynamicSystemPromptSuffix("Today's date is 2026-05-01.", "")
got := buildDynamicSystemPromptSuffix("", "Today's date is 2026-05-01.", "")
require.True(t, strings.HasPrefix(got, "Today's date is 2026-05-01."),
"date line must appear at the top of the dynamic suffix")
}
func TestBuildDynamicSystemPromptSuffixIdentityHintLeadsDate(t *testing.T) {
got := buildDynamicSystemPromptSuffix("IDENTITY_HINT", "Today's date is 2026-05-01.", "\n\nKG_HINT")
identityIdx := strings.Index(got, "IDENTITY_HINT")
dateIdx := strings.Index(got, "Today's date is")
require.True(t, identityIdx == 0 && dateIdx > identityIdx,
"order must be identity hint < date; got %d %d", identityIdx, dateIdx)
}
func TestFormatDateLine(t *testing.T) {
cases := []struct {
name string
Loaded 100 of 207 files, more files were not shown because too many files have changed in this diff. Show more