Harden Harness runtime, persistence and execution for Hand

This commit is contained in:
sausheong committed 2026-09-09 22:55:55 +08:00
1 parent 09c30fe2d5
commit 0972eed3ea
164 files changed
+15912 -506

No files matched your search

+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")
}
}
+80
View File
@@ -0,0 +1,80 @@
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, 1)
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)
}
}
+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)
}
}
+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")
}
}
+172
View File
@@ -0,0 +1,172 @@
package runtime
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"github.com/sausheong/harness/budget"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tokens"
)
const costPricesKind = "harness.budget.prices.v1"
type costPricesRecord struct {
Version int `json:"version"`
Prices []budget.PriceSnapshot `json:"prices"`
}
type costBudgetContextKey struct{ session *session.Session }
func validateCostPrices(prices []budget.PriceSnapshot) error {
if len(prices) > 16 {
return errors.New("at most 16 route prices are allowed")
}
type key struct{ provider, model, destination string }
seen := map[key]bool{}
for _, p := range prices {
if err := p.Validate(); err != nil {
return err
}
k := key{p.Provider, p.Model, p.Destination}
if seen[k] {
return errors.New("duplicate route price")
}
seen[k] = true
}
return nil
}
// SetCostPrices durably replaces explicitly reviewed session route tariffs.
// It does not change the budget ceiling or erase historical request snapshots.
func (r *Runtime) SetCostPrices(ctx context.Context, prices []budget.PriceSnapshot) 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 r.Compaction != nil && r.Compaction.HasInFlight(r.Session) {
return errors.New("compaction is running")
}
if err := validateCostPrices(prices); err != nil {
return err
}
raw, err := json.Marshal(costPricesRecord{Version: 1, Prices: prices})
if err != nil {
return err
}
return r.Session.Annotate(costPricesKind, raw)
}
func (r *Runtime) costPrices() ([]budget.PriceSnapshot, error) {
if r.Session == nil {
return nil, errors.New("session unavailable")
}
records := r.Session.Annotations(costPricesKind)
if len(records) == 0 {
return nil, nil
}
var record costPricesRecord
d := json.NewDecoder(bytes.NewReader(records[len(records)-1].Payload))
d.DisallowUnknownFields()
if err := d.Decode(&record); err != nil {
return nil, err
}
if d.Decode(new(any)) != io.EOF || record.Version != 1 {
return nil, errors.New("invalid session price record")
}
return record.Prices, validateCostPrices(record.Prices)
}
func (r *Runtime) CostPrices(ctx context.Context) ([]budget.PriceSnapshot, 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.costPrices()
}
func (r *Runtime) DecideCostBudget(ctx context.Context, currency string, limitNano int64, strict bool) error {
if !r.runMu.TryLock() {
return errors.New("runtime is already running")
}
defer r.runMu.Unlock()
if r.Compaction != nil && r.Compaction.HasInFlight(r.Session) {
return errors.New("compaction is running")
}
l, err := budget.OpenCostLedger(r.Session)
if err != nil {
return err
}
return l.Decide(ctx, currency, limitNano, strict)
}
func (r *Runtime) CostBudget(ctx context.Context) (budget.CostState, error) {
if !r.runMu.TryLock() {
return budget.CostState{}, errors.New("runtime is already running")
}
defer r.runMu.Unlock()
if err := ctx.Err(); err != nil {
return budget.CostState{}, err
}
l, err := budget.OpenCostLedger(r.Session)
if err != nil {
return budget.CostState{}, err
}
return l.State()
}
func (r *Runtime) costBudgetContext(ctx context.Context) (context.Context, error) {
if r.Session == nil {
return ctx, nil
}
key := costBudgetContextKey{r.Session}
if ctx.Value(key) != nil {
return ctx, nil
}
l, err := budget.OpenCostLedger(r.Session)
if err != nil {
return ctx, err
}
state, err := l.State()
if err != nil {
return ctx, err
}
if state.LimitNano == 0 {
return ctx, nil
}
prices, err := r.costPrices()
if err != nil {
return ctx, err
}
guard := l.Admission(func(req llm.ChatRequest, _ llm.CallCategory) (*budget.PriceSnapshot, int64, error) {
prompt := req.SystemPrompt
if len(req.SystemPromptParts) > 0 {
prompt = llm.JoinSystemPromptParts(req.SystemPromptParts)
}
input := int64(tokens.Estimate(req.Messages, prompt, req.Tools))
for _, p := range prices {
if p.Provider == req.Route.Provider && p.Destination == req.Route.Destination && p.Model == req.Model {
return &p, input, nil
}
}
return nil, input, nil
})
return context.WithValue(llm.WithCallAdmission(ctx, guard), key, true), nil
}
func (r *Runtime) budgetContext(ctx context.Context) (context.Context, error) {
if err := r.validateRunBinding(ctx); err != nil {
return ctx, err
}
ctx, err := r.tokenBudgetContext(ctx)
if err != nil {
return ctx, err
}
return r.costBudgetContext(ctx)
}
+139
View File
@@ -0,0 +1,139 @@
package runtime
import (
"context"
"errors"
"testing"
"time"
"github.com/sausheong/harness/budget"
"github.com/sausheong/harness/compaction"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
)
func runtimeFixturePrice(route llm.CallRoute, model string) budget.PriceSnapshot {
return budget.PriceSnapshot{Provider: route.Provider, Destination: route.Destination, Model: model, Currency: "USD", Source: "local test tariff", Version: "1", EffectiveAt: time.Now().Add(-time.Hour), ExpiresAt: time.Now().Add(time.Hour), InputNanoPerMillion: 1000000, OutputNanoPerMillion: 1000000, AllChargesBounded: true}
}
func TestCostBudgetRuntimeAndIndependentSummary(t *testing.T) {
ctx := context.Background()
provider := &recordingProvider{reply: "<summary>done</summary>"}
s := session.NewSession("a", "cost")
main := llm.CallRoute{Provider: "local", Destination: "http://main.example/v1"}
summary := llm.CallRoute{Provider: "local", Destination: "http://summary.example/v1"}
r := &Runtime{Session: s, Route: main, Provider: "local", Model: "fixture", LLM: provider, Tools: tool.NewRegistry(), MaxTurns: 1}
if err := r.DecideCostBudget(ctx, "USD", 1000000, true); err != nil {
t.Fatal(err)
}
events, err := r.Run(ctx, "unpriced", nil)
if err != nil {
t.Fatal(err)
}
unknown := false
for event := range events {
if errors.Is(event.Error, budget.ErrUnknownPrice) {
unknown = true
}
}
if !unknown || len(provider.requests) != 0 {
t.Fatal("unpriced runtime reached provider")
}
prices := []budget.PriceSnapshot{runtimeFixturePrice(main, "fixture"), runtimeFixturePrice(summary, "fixture")}
if err = r.SetCostPrices(ctx, prices); err != nil {
t.Fatal(err)
}
prices[0].Source = "caller mutation"
events, err = r.Run(ctx, "priced", nil)
if err != nil {
t.Fatal(err)
}
for range events {
}
state, err := r.CostBudget(ctx)
if err != nil || len(state.Attempts) != 1 || state.Attempts[0].Quote.Snapshot.Destination != main.Destination {
t.Fatalf("state %+v err %v", state, err)
}
for i := 0; i < 10; i++ {
s.Append(session.UserMessageEntry("task"))
s.Append(session.AssistantMessageEntry("evidence"))
}
manager := &compaction.Manager{Summarizer: &compaction.Summarizer{Route: summary, Provider: provider, Model: "fixture", MaxOutputTokens: 100}, PreserveTurns: 2}
manual, err := r.CompactionContext(ctx)
if err != nil {
t.Fatal(err)
}
result, err := manager.MaybeCompact(manual, s, compaction.ReasonManual, "")
if err != nil || !result.Compacted {
t.Fatalf("compaction %+v %v", result, err)
}
state, err = r.CostBudget(ctx)
if err != nil || len(state.Attempts) != 2 || state.Attempts[1].Category != llm.CallCompaction || state.Attempts[1].Quote.Snapshot.Destination != summary.Destination {
t.Fatalf("state %+v err %v", state, err)
}
installed, err := r.CostPrices(ctx)
if err != nil || installed[0].Source == "caller mutation" {
t.Fatal("caller mutation changed durable prices")
}
}
func TestRunTurnCannotBypassSessionBudgets(t *testing.T) {
ctx := context.Background()
provider := &recordingProvider{reply: "done"}
r := &Runtime{Session: session.NewSession("a", "turn"), LLM: provider, Tools: tool.NewRegistry(), Model: "fixture"}
if err := r.DecideTokenBudget(ctx, 1); err != nil {
t.Fatal(err)
}
result, err := r.RunTurn(ctx, "blocked", nil, nil)
if !errors.Is(err, budget.ErrExhausted) && !errors.Is(result.Err, budget.ErrExhausted) {
t.Fatalf("result %+v err %v", result, err)
}
if len(provider.requests) != 0 {
t.Fatal("RunTurn bypassed token budget")
}
}
func TestCostPricesRestartAndInvalidReplacement(t *testing.T) {
ctx := context.Background()
store := session.NewStore(t.TempDir())
if err := store.Create("a", "prices"); err != nil {
t.Fatal(err)
}
s, err := store.LoadExclusive("a", "prices")
if err != nil {
t.Fatal(err)
}
r := &Runtime{Session: s}
price := runtimeFixturePrice(llm.CallRoute{Provider: "local", Destination: "http://fixture.example/v1"}, "fixture")
if err = r.SetCostPrices(ctx, []budget.PriceSnapshot{price}); err != nil {
t.Fatal(err)
}
if err = r.SetCostPrices(ctx, []budget.PriceSnapshot{price, price}); err == nil {
t.Fatal("duplicate route accepted")
}
if err = r.DecideCostBudget(ctx, "USD", 1000000, true); err != nil {
t.Fatal(err)
}
if err = s.Close(); err != nil {
t.Fatal(err)
}
s, err = store.LoadExclusive("a", "prices")
if err != nil {
t.Fatal(err)
}
defer s.Close()
r.Session = s
prices, err := r.CostPrices(ctx)
if err != nil || len(prices) != 1 || prices[0].Source != price.Source || prices[0].Destination != price.Destination {
t.Fatalf("prices %+v err %v", prices, err)
}
state, err := r.CostBudget(ctx)
if err != nil || state.LimitNano != 1000000 || !state.Strict {
t.Fatalf("state %+v err %v", state, err)
}
r.runMu.Lock()
err = r.SetCostPrices(ctx, nil)
r.runMu.Unlock()
if err == nil {
t.Fatal("busy price replacement accepted")
}
}
+53
View File
@@ -0,0 +1,53 @@
package runtime
import (
"errors"
"fmt"
"github.com/sausheong/harness/tool"
"github.com/sausheong/harness/tools/mcp"
)
var ErrMCPAttachBusy = errors.New("runtime is active; defer MCP attachment until idle")
// AttachMCP transfers ownership only on success. The caller retains ownership
// on all errors, including busy, and may retry or close the client. Connection
// happens outside the runtime, so local runs can continue during discovery.
func (r *Runtime) AttachMCP(client *mcp.Client, optional bool) error {
if client == nil {
return errors.New("nil MCP client")
}
if !r.runMu.TryLock() {
return ErrMCPAttachBusy
}
defer r.runMu.Unlock()
r.mcpMu.Lock()
defer r.mcpMu.Unlock()
if r.mcpClosed {
return errors.New("runtime is closed")
}
reg, ok := r.Tools.(*tool.Registry)
if !ok || r.refreshToolPrompt == nil {
return errors.New("runtime does not support dynamic MCP attachment")
}
name := client.Name()
for _, s := range r.mcpStatus {
if s.Name == name && s.State == "connected" {
return fmt.Errorf("MCP server %q already connected", name)
}
}
if err := reg.RegisterUnique(client.Tools()); err != nil {
return err
}
r.StaticSystemPrompt = r.refreshToolPrompt(reg.Names())
r.mcpClients = append(r.mcpClients, client)
status := MCPServerStatus{Name: name, Optional: optional, State: "connected", Tools: len(client.Tools())}
for i, s := range r.mcpStatus {
if s.Name == name {
r.mcpStatus[i] = status
return nil
}
}
r.mcpStatus = append(r.mcpStatus, status)
return nil
}
+59
View File
@@ -0,0 +1,59 @@
package runtime
import (
"context"
"errors"
"os"
"testing"
"time"
"github.com/sausheong/harness/tool"
"github.com/sausheong/harness/tools/mcp"
)
func TestMCPAttachAtIdleUpdatesCatalogueAndOwnsShutdown(t *testing.T) {
config, marker := constructionServer(t)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
client, err := mcp.Connect(ctx, config)
if err != nil {
t.Fatal(err)
}
defer client.Close()
reg := tool.NewRegistry()
rt, err := BuildRuntime(RuntimeDeps{}, RuntimeInputs{Tools: reg}, AgentSpec{ID: "test"})
if err != nil {
t.Fatal(err)
}
defer rt.Close()
rt.runMu.Lock()
err = rt.AttachMCP(client, true)
rt.runMu.Unlock()
if !errors.Is(err, ErrMCPAttachBusy) || len(reg.Names()) != 0 {
t.Fatalf("active attachment: %v", err)
}
if _, err = os.Stat(marker); !os.IsNotExist(err) {
t.Fatal("rejected attachment closed caller's client")
}
if err = rt.AttachMCP(client, true); err != nil {
t.Fatal(err)
}
if len(reg.Names()) != 1 || rt.Tools.ToolDefs()[0].Name != "mcp__healthy__echo" || rt.StaticSystemPrompt != BuildStaticSystemPrompt("", "", "test", "", reg.Names(), "", "", "", "") {
t.Fatal("tool catalogue and model context diverged")
}
if status := rt.MCPStatus(); len(status) != 1 || status[0].State != "connected" {
t.Fatalf("status %+v", status)
}
if err = rt.AttachMCP(client, true); err == nil {
t.Fatal("duplicate attachment accepted")
}
if err = rt.Close(); err != nil {
t.Fatal(err)
}
if _, err = os.Stat(marker); err != nil {
t.Fatal("attached client not joined on close")
}
if err = rt.AttachMCP(client, true); err == nil {
t.Fatal("attachment after close")
}
}
+82
View File
@@ -0,0 +1,82 @@
package runtime
import (
"context"
"fmt"
"sync"
"time"
"github.com/sausheong/harness/tools/mcp"
)
const MCPConnectConcurrency = 4
// connectMCPServers joins every worker before returning. Results retain config
// order, independent of completion order; publication remains transactional in
// BuildRuntimeContext. The caller owns and must close returned clients on error.
func connectMCPServers(parent context.Context, servers []mcp.ServerConfig) ([]*mcp.Client, []MCPServerStatus, error) {
ctx, cancel := context.WithCancel(parent)
defer cancel()
clients := make([]*mcp.Client, len(servers))
status := make([]MCPServerStatus, len(servers))
var firstErr error
var fail sync.Once
jobs := make(chan int)
var workers sync.WaitGroup
for w := 0; w < min(MCPConnectConcurrency, len(servers)); w++ {
workers.Add(1)
go func() {
defer workers.Done()
for i := range jobs {
if ctx.Err() != nil {
continue
}
srv := servers[i]
serverCtx := ctx
stop := func() {}
timeout := srv.ConnectTimeout
if timeout == 0 && srv.Optional {
timeout = 5 * time.Second
}
if timeout > 0 {
serverCtx, stop = context.WithTimeout(ctx, timeout)
}
cli, err := mcp.Connect(serverCtx, srv)
stop()
status[i] = MCPServerStatus{Name: srv.Name, Optional: srv.Optional, State: "unavailable"}
if err != nil {
if !srv.Optional {
fail.Do(func() { firstErr = fmt.Errorf("mcp server %q: %w", srv.Name, err); cancel() })
}
continue
}
clients[i] = cli
status[i].State = "connected"
status[i].Tools = len(cli.Tools())
}
}()
}
dispatch:
for i := range servers {
select {
case jobs <- i:
case <-ctx.Done():
break dispatch
}
}
close(jobs)
workers.Wait()
connected := make([]*mcp.Client, 0, len(clients))
for _, cli := range clients {
if cli != nil {
connected = append(connected, cli)
}
}
if parent.Err() != nil {
return connected, nil, parent.Err()
}
if firstErr != nil {
return connected, nil, firstErr
}
return connected, status, nil
}
+84
View File
@@ -0,0 +1,84 @@
package runtime
import (
"context"
"errors"
"fmt"
"net/http"
"sync/atomic"
"testing"
"time"
"github.com/sausheong/harness/tool"
"github.com/sausheong/harness/tools/mcp"
)
type startupTransport func(*http.Request) (*http.Response, error)
func (f startupTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func TestMCPConnectionsIndependentAndBounded(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
release := make(chan struct{})
entered := make(chan struct{}, 32)
var active, peak atomic.Int32
client := &http.Client{Transport: startupTransport(func(r *http.Request) (*http.Response, error) {
n := active.Add(1)
defer active.Add(-1)
for old := peak.Load(); n > old; old = peak.Load() {
if peak.CompareAndSwap(old, n) {
break
}
}
select {
case entered <- struct{}{}:
default:
}
select {
case <-release:
case <-r.Context().Done():
}
return nil, errors.New("fixture unavailable")
})}
servers := make([]mcp.ServerConfig, 8)
for i := range servers {
servers[i] = mcp.ServerConfig{Name: fmt.Sprintf("server%d", i), Optional: true, URL: "http://fixture.invalid/mcp", HTTPClient: client}
}
type result struct {
rt *Runtime
err error
}
done := make(chan result, 1)
go func() {
rt, err := BuildRuntimeContext(ctx, RuntimeDeps{}, RuntimeInputs{Tools: tool.NewRegistry()}, AgentSpec{MCPServers: servers})
done <- result{rt, err}
}()
for i := 0; i < MCPConnectConcurrency; i++ {
select {
case <-entered:
case <-ctx.Done():
t.Fatal("connections did not start independently")
}
}
if n := active.Load(); n != MCPConnectConcurrency {
t.Fatalf("active connections %d", n)
}
close(release)
r := <-done
if r.err != nil {
t.Fatal(r.err)
}
defer r.rt.Close()
if n := peak.Load(); n > MCPConnectConcurrency {
t.Fatalf("concurrency exceeded: %d", n)
}
status := r.rt.MCPStatus()
if len(status) != len(servers) {
t.Fatalf("status count %d", len(status))
}
for i, s := range status {
if s.Name != servers[i].Name || s.State != "unavailable" {
t.Fatalf("status order %+v", status)
}
}
}
+8
View File
@@ -0,0 +1,8 @@
package runtime
func (r *Runtime) outputTokenLimit() int {
if r.MaxOutputTokens > 0 {
return r.MaxOutputTokens
}
return 8192
}
+74
View File
@@ -0,0 +1,74 @@
package runtime
import (
"context"
"errors"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"testing"
)
type outputLimitProvider struct {
llmtest.Base
limits []int
fallback bool
}
func (p *outputLimitProvider) ChatStream(_ context.Context, r llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.limits = append(p.limits, r.MaxTokens)
if p.fallback && len(p.limits) == 1 {
return nil, errors.New("529 overloaded")
}
ch := make(chan llm.ChatEvent, 1)
ch <- llm.ChatEvent{Type: llm.EventDone}
close(ch)
return ch, nil
}
func TestGenerationOutputLimitReachesRequestsAndFallback(t *testing.T) {
for _, single := range []bool{false, true} {
for _, limit := range []int{0, 123, 32768, -1} {
p := &outputLimitProvider{fallback: true}
r := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("a", "b"), Model: "primary", FallbackModel: "fallback", MaxTurns: 1, MaxOutputTokens: limit}
var err error
if single {
var result TurnResult
result, err = r.RunTurn(context.Background(), "hello", nil, nil)
if err == nil {
err = result.Err
}
} else {
var events <-chan AgentEvent
events, err = r.Run(context.Background(), "hello", nil)
if err == nil {
for e := range events {
if e.Error != nil {
err = e.Error
}
}
}
}
if limit < 0 {
if err == nil || len(p.limits) != 0 {
t.Fatal("negative limit dispatched", err, p.limits)
}
continue
}
if err != nil {
t.Fatal(err)
}
want := limit
if want == 0 {
want = 8192
}
if len(p.limits) != 2 {
t.Fatal("missing fallback", p.limits)
}
for _, got := range p.limits {
if got != want {
t.Fatalf("single=%v limit=%d got=%d", single, limit, got)
}
}
}
}
}
+92
View File
@@ -0,0 +1,92 @@
package runtime
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
)
type persistenceProvider struct {
usageDoneProvider
before func()
calls int
}
func (p *persistenceProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.calls++
if p.before != nil {
p.before()
}
return p.usageDoneProvider.ChatStream(ctx, req)
}
func TestPersistenceFailurePreventsSuccessfulRuntimeCompletion(t *testing.T) {
for _, stage := range []string{"prompt", "answer"} {
t.Run(stage, func(t *testing.T) {
root := filepath.Join(t.TempDir(), "store")
sess := session.NewSession("agent", "key")
sess.SetStore(session.NewStore(root))
provider := &persistenceProvider{}
if stage == "prompt" {
if err := os.WriteFile(root, []byte("obstruction"), 0600); err != nil {
t.Fatal(err)
}
} else {
provider.before = func() {
path := filepath.Join(root, "agent", "key.jsonl")
if err := os.Remove(path); err != nil {
t.Error(err)
}
if err := os.Mkdir(path, 0700); err != nil {
t.Error(err)
}
}
}
rt := &Runtime{AgentID: "agent", Provider: "local", Model: "fixture", Session: sess, Tools: tool.NewRegistry(), LLM: provider, MaxTurns: 1}
events, err := rt.Run(context.Background(), "work", nil)
if err != nil {
t.Fatal(err)
}
failed, done := false, false
for event := range events {
if event.Type == EventError && event.Error != nil {
failed = true
}
if event.Type == EventDone {
done = true
}
}
if !failed || done || sess.PersistenceError() == nil {
t.Fatal("persistence failure became success", failed, done)
}
if stage == "prompt" && provider.calls != 0 {
t.Fatal("unsaved prompt sent to provider")
}
})
}
}
func TestRunSyncJoinsAfterError(t *testing.T) {
entered, release := make(chan struct{}), make(chan struct{})
rt := &Runtime{AgentID: "agent", Provider: "local", Model: "fixture", Session: session.NewSession("agent", "key"), Tools: tool.NewRegistry(), LLM: &mockLLMProvider{events: []llm.ChatEvent{{Type: llm.EventError, Error: errors.New("provider failed")}}}, MaxTurns: 1}
rt.AgentLoop.Hooks.OnStop = func(context.Context, string) { close(entered); <-release }
result := make(chan error, 1)
go func() { _, err := rt.RunSync(context.Background(), "work", nil); result <- err }()
<-entered
select {
case err := <-result:
t.Fatal("RunSync returned before cleanup", err)
case <-time.After(20 * time.Millisecond):
}
close(release)
if err := <-result; err == nil {
t.Fatal("failure lost while joining")
}
}
+114
View File
@@ -0,0 +1,114 @@
package runtime
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"github.com/stretchr/testify/require"
)
type requestUsageProvider struct {
llmtest.Base
calls int
total int
failFirst bool
missingLast bool
}
func (p *requestUsageProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.calls++
if p.failFirst && p.calls == 1 {
return nil, errors.New("529 overloaded")
}
ch := make(chan llm.ChatEvent, 2)
if p.calls < p.total {
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: req.Model, Name: "noop", Input: json.RawMessage(`{}`)}}
}
usage := &llm.Usage{InputTokens: 20000, OutputTokens: 100, CacheReadInputTokens: 15000}
if p.missingLast && p.calls == p.total {
usage = nil
}
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: usage}
close(ch)
return ch, nil
}
func TestRequestUsageSeparatesLatestFromCumulative(t *testing.T) {
p := &requestUsageProvider{total: 10}
r := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("a", "k"), Model: "primary", MaxTurns: 10}
events, err := r.Run(context.Background(), "go", nil)
require.NoError(t, err)
var records []llm.RequestUsage
var total *llm.Usage
for e := range events {
if e.Type == EventRequestUsage {
records = append(records, *e.RequestUsage)
}
if e.Type == EventDone {
total = e.Usage
}
}
require.Len(t, records, 10)
require.Equal(t, 20000, records[9].Usage.InputTokens)
require.Equal(t, 200000, total.InputTokens)
for _, r := range records {
require.Equal(t, llm.CallGeneration, r.Category)
require.Equal(t, "reported", r.Source)
}
}
func TestRequestUsageRetainsUnknownFailedAttemptAndModelChange(t *testing.T) {
p := &requestUsageProvider{total: 2, failFirst: true, missingLast: true}
r := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("a", "k"), Model: "primary", FallbackModel: "fallback", MaxTurns: 2}
events, err := r.Run(context.Background(), "go", nil)
require.NoError(t, err)
var records []llm.RequestUsage
for e := range events {
if e.Type == EventRequestUsage {
records = append(records, *e.RequestUsage)
}
}
require.Len(t, records, 2)
require.Equal(t, "failed", records[0].Status)
require.Nil(t, records[0].Usage)
require.Equal(t, "primary", records[0].Model)
require.Equal(t, "fallback", records[1].Model)
require.Equal(t, llm.CallRetry, records[1].Category)
require.Equal(t, "unavailable", records[1].Source)
}
type refusalUsageProvider struct {
llmtest.Base
calls int
}
func (p *refusalUsageProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.calls++
ch := make(chan llm.ChatEvent, 1)
e := llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 10000}}
if p.calls == 1 {
e.StopReason = llm.StopReasonRefusal
e.Usage.InputTokens = 20000
}
ch <- e
close(ch)
return ch, nil
}
func TestRunTurnUsageIncludesRefusedAttempt(t *testing.T) {
p := &refusalUsageProvider{}
r := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("a", "k"), Model: "primary", FallbackModel: "fallback"}
var records []llm.RequestUsage
result, err := r.RunTurn(context.Background(), "go", nil, func(e AgentEvent) {
if e.RequestUsage != nil {
records = append(records, *e.RequestUsage)
}
})
require.NoError(t, err)
require.NoError(t, result.Err)
require.Equal(t, 30000, result.Usage.InputTokens)
require.Len(t, records, 2)
require.Equal(t, llm.CallRetry, records[1].Category)
}
+209
View File
@@ -0,0 +1,209 @@
package runtime
import (
"context"
"errors"
"fmt"
"time"
"github.com/sausheong/harness/budget"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tokens"
)
var ErrRunTokenExhausted = fmt.Errorf("run token budget: %w", budget.ErrExhausted)
var ErrRunCostExhausted = fmt.Errorf("run cost budget: %w", budget.ErrExhausted)
type RunBudgetState struct {
ID string `json:"id"`
Tokens budget.TokenState `json:"tokens"`
Cost budget.CostState `json:"cost"`
Deadline budget.DeadlineState `json:"deadline"`
}
type runBudgetKey struct{ session *session.Session }
type runBudgetBinding struct {
id string
tokens, cost bool
deadline time.Time
}
func (r *Runtime) withIdleRunBudget(ctx context.Context, fn func() error) 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 r.Compaction != nil && r.Compaction.HasInFlight(r.Session) {
return errors.New("compaction is running")
}
return fn()
}
func (r *Runtime) DecideRunTokenBudget(ctx context.Context, id string, limit int64) error {
return r.withIdleRunBudget(ctx, func() error {
l, err := budget.OpenRunTokenLedger(r.Session, id)
if err != nil {
return err
}
return l.Decide(ctx, limit)
})
}
func (r *Runtime) DecideRunCostBudget(ctx context.Context, id, currency string, limitNano int64, strict bool) error {
return r.withIdleRunBudget(ctx, func() error {
l, err := budget.OpenRunCostLedger(r.Session, id)
if err != nil {
return err
}
return l.Decide(ctx, currency, limitNano, strict)
})
}
func (r *Runtime) DecideRunTimeBudget(ctx context.Context, id string, allowance time.Duration) error {
return r.withIdleRunBudget(ctx, func() error { return budget.DecideRunDeadline(ctx, r.Session, id, allowance) })
}
func (r *Runtime) RunBudget(ctx context.Context, id string) (state RunBudgetState, err error) {
err = r.withIdleRunBudget(ctx, func() error { var e error; state, e = r.runBudgetState(id); return e })
return
}
func (r *Runtime) runBudgetState(id string) (RunBudgetState, error) {
state := RunBudgetState{ID: id}
token, err := budget.OpenRunTokenLedger(r.Session, id)
if err != nil {
return state, err
}
cost, err := budget.OpenRunCostLedger(r.Session, id)
if err != nil {
return state, err
}
state.Tokens, err = token.State()
if err != nil {
return state, err
}
state.Cost, err = cost.State()
if err != nil {
return state, err
}
state.Deadline, err = budget.ReadRunDeadline(r.Session, id)
return state, err
}
// PrepareRunBudget binds an explicitly configured logical run to all provider
// attempts, including retries and compaction, while retaining inherited guards.
// Use the returned context for the whole logical run (including continuations).
// Cancel only after every owned operation joins. Preparing/repreparing never
// changes limits or renews the deadline; unconfigured IDs fail closed.
func (r *Runtime) PrepareRunBudget(ctx context.Context, id string) (context.Context, context.CancelFunc, error) {
bound := ctx
cancel := func() {}
err := r.withIdleRunBudget(ctx, func() error {
key := runBudgetKey{r.Session}
if prior, ok := ctx.Value(key).(runBudgetBinding); ok {
if prior.id != id {
return errors.New("cannot replace an inherited run budget")
}
return r.validateRunBinding(ctx)
}
state, err := r.runBudgetState(id)
if err != nil {
return err
}
if state.Tokens.Limit == 0 && state.Cost.LimitNano == 0 && state.Deadline.Version == 0 {
return errors.New("run budget has no explicit decision")
}
bound, err = r.budgetContext(ctx)
if err != nil {
return err
}
if state.Tokens.Limit > 0 {
l, e := budget.OpenRunTokenLedger(r.Session, id)
if e != nil {
return e
}
bound = llm.WithCallAdmission(bound, runAdmission(l.Admission(runInputEstimate), ErrRunTokenExhausted))
}
if state.Cost.LimitNano > 0 {
l, e := budget.OpenRunCostLedger(r.Session, id)
if e != nil {
return e
}
prices, e := r.costPrices()
if e != nil {
return e
}
resolver := func(req llm.ChatRequest, _ llm.CallCategory) (*budget.PriceSnapshot, int64, error) {
input, e := runInputEstimate(req)
if e != nil {
return nil, 0, e
}
for _, p := range prices {
if p.Provider == req.Route.Provider && p.Destination == req.Route.Destination && p.Model == req.Model {
return &p, input, nil
}
}
return nil, input, nil
}
bound = llm.WithCallAdmission(bound, runAdmission(l.Admission(resolver), ErrRunCostExhausted))
}
withSession, sessionCancel, e := budget.WithDeadline(bound, r.Session)
if e != nil {
return e
}
withRun, runCancel, e := budget.WithRunDeadline(withSession, r.Session, id)
if e != nil {
sessionCancel()
return e
}
cancel = func() { runCancel(); sessionCancel() }
bound = context.WithValue(withRun, key, runBudgetBinding{id: id, tokens: state.Tokens.Limit > 0, cost: state.Cost.LimitNano > 0, deadline: state.Deadline.Deadline})
return nil
})
if err != nil {
cancel()
return ctx, func() {}, err
}
return bound, cancel, nil
}
func runInputEstimate(req llm.ChatRequest) (int64, error) {
prompt := req.SystemPrompt
if len(req.SystemPromptParts) > 0 {
prompt = llm.JoinSystemPromptParts(req.SystemPromptParts)
}
return int64(tokens.Estimate(req.Messages, prompt, req.Tools)), nil
}
func runAdmission(guard llm.CallAdmission, cause error) llm.CallAdmission {
classify := func(err error) error {
if errors.Is(err, budget.ErrExhausted) {
return errors.Join(cause, err)
}
return err
}
return func(ctx context.Context, req llm.ChatRequest, category llm.CallCategory, id string) (func(llm.RequestUsage) error, error) {
settle, err := guard(ctx, req, category, id)
if err != nil {
return nil, classify(err)
}
return func(usage llm.RequestUsage) error { return classify(settle(usage)) }, nil
}
}
// A newly enabled dimension or changed deadline needs a fresh binding from
// the owner context. Existing ledger guards already reload changed ceilings.
func (r *Runtime) validateRunBinding(ctx context.Context) error {
binding, ok := ctx.Value(runBudgetKey{r.Session}).(runBudgetBinding)
if !ok {
return nil
}
state, err := r.runBudgetState(binding.id)
if err != nil {
return err
}
if binding.tokens != (state.Tokens.Limit > 0) || binding.cost != (state.Cost.LimitNano > 0) || !binding.deadline.Equal(state.Deadline.Deadline) {
return errors.New("run budget decision changed; prepare a fresh context from its owner")
}
return nil
}
+246
View File
@@ -0,0 +1,246 @@
package runtime
import (
"context"
"errors"
"testing"
"time"
"github.com/sausheong/harness/budget"
"github.com/sausheong/harness/compaction"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
)
func TestRunBudgetBindingChargesRunTurnAndCompactionOnce(t *testing.T) {
ctx := context.Background()
p := &recordingProvider{reply: "<summary>done</summary>"}
r := &Runtime{Session: session.NewSession("a", "run"), LLM: p, Tools: tool.NewRegistry(), Model: "fixture", MaxTurns: 1}
if err := r.DecideTokenBudget(ctx, 1000000); err != nil {
t.Fatal(err)
}
if err := r.DecideRunTokenBudget(ctx, "logical-run", 1000000); err != nil {
t.Fatal(err)
}
bound, cancel, err := r.PrepareRunBudget(ctx, "logical-run")
if err != nil {
t.Fatal(err)
}
defer cancel()
// Repreparing must not attach another reservation for the same scope.
same, stop, err := r.PrepareRunBudget(bound, "logical-run")
if err != nil {
t.Fatal(err)
}
defer stop()
if _, stop, e := r.PrepareRunBudget(bound, "replacement"); e == nil {
stop()
t.Fatal("inherited scope replaced")
}
events, err := r.Run(same, "first", nil)
if err != nil {
t.Fatal(err)
}
for ev := range events {
if ev.Error != nil {
t.Fatal(ev.Error)
}
}
result, err := r.RunTurn(same, "second", nil, nil)
if err != nil || result.Err != nil {
t.Fatalf("turn %+v %v", result, err)
}
for i := 0; i < 10; i++ {
r.Session.Append(session.UserMessageEntry("task"))
r.Session.Append(session.AssistantMessageEntry("evidence"))
}
manager := &compaction.Manager{Summarizer: &compaction.Summarizer{Provider: p, Model: "fixture", MaxOutputTokens: 100}, PreserveTurns: 2}
manual, err := r.CompactionContext(same)
if err != nil {
t.Fatal(err)
}
compacted, err := manager.MaybeCompact(manual, r.Session, compaction.ReasonManual, "")
if err != nil || !compacted.Compacted {
t.Fatalf("summary %+v %v", compacted, err)
}
run, err := r.RunBudget(ctx, "logical-run")
if err != nil {
t.Fatal(err)
}
total, err := r.TokenBudget(ctx)
if err != nil {
t.Fatal(err)
}
if len(run.Tokens.Attempts) != 3 || len(total.Attempts) != 3 || run.Tokens.Committed != total.Committed || run.Tokens.Attempts[2].Category != llm.CallCompaction {
t.Fatalf("run=%+v total=%+v", run, total)
}
}
func TestRunBudgetBindingCannotBypassEitherScope(t *testing.T) {
for _, small := range []string{"run", "session"} {
t.Run(small, func(t *testing.T) {
ctx := context.Background()
p := &recordingProvider{reply: "done"}
r := &Runtime{Session: session.NewSession("a", "blocked"), LLM: p, Tools: tool.NewRegistry(), Model: "fixture"}
runLimit, sessionLimit := int64(100000), int64(100000)
if small == "run" {
runLimit = 1
} else {
sessionLimit = 1
}
if err := r.DecideTokenBudget(ctx, sessionLimit); err != nil {
t.Fatal(err)
}
if err := r.DecideRunTokenBudget(ctx, "job", runLimit); err != nil {
t.Fatal(err)
}
bound, cancel, err := r.PrepareRunBudget(ctx, "job")
if err != nil {
t.Fatal(err)
}
defer cancel()
events, err := r.Run(bound, "blocked", nil)
if err != nil {
t.Fatal(err)
}
var terminal error
for ev := range events {
if ev.Error != nil {
terminal = ev.Error
}
}
if !errors.Is(terminal, budget.ErrExhausted) || len(p.requests) != 0 {
t.Fatalf("admission failed: %v requests=%d", terminal, len(p.requests))
}
if small == "run" && !errors.Is(terminal, ErrRunTokenExhausted) {
t.Fatal("run reason lost", terminal)
}
run, _ := r.RunBudget(ctx, "job")
total, _ := r.TokenBudget(ctx)
if run.Tokens.Committed != 0 || total.Committed != 0 {
t.Fatal("undispatched work charged")
}
})
}
}
func TestRunBudgetDeadlineCancelsOwnedProvider(t *testing.T) {
ctx := context.Background()
p := &deadlineProvider{started: make(chan struct{}), stopped: make(chan struct{})}
r := &Runtime{Session: session.NewSession("a", "time"), LLM: p, Tools: tool.NewRegistry(), Model: "fixture"}
if _, stop, err := r.PrepareRunBudget(ctx, "missing"); err == nil {
stop()
t.Fatal("unconfigured run allowed")
}
if err := r.DecideRunTimeBudget(ctx, "timed", time.Second); err != nil {
t.Fatal(err)
}
bound, cancel, err := r.PrepareRunBudget(ctx, "timed")
if err != nil {
t.Fatal(err)
}
defer cancel()
events, err := r.Run(bound, "wait", nil)
if err != nil {
t.Fatal(err)
}
found := false
for ev := range events {
if errors.Is(ev.Error, budget.ErrRunTimeExhausted) {
found = true
}
}
if !found {
t.Fatal("run deadline cause lost")
}
select {
case <-p.stopped:
case <-time.After(time.Second):
t.Fatal("provider not stopped")
}
if _, stop, e := r.PrepareRunBudget(ctx, "timed"); !errors.Is(e, budget.ErrRunTimeExhausted) {
stop()
t.Fatal("expired deadline renewed", e)
}
}
func TestRunBudgetStaleBindingCannotOmitNewDimension(t *testing.T) {
ctx := context.Background()
p := &recordingProvider{reply: "done"}
r := &Runtime{Session: session.NewSession("a", "stale"), LLM: p, Tools: tool.NewRegistry(), Model: "fixture"}
if err := r.DecideRunTimeBudget(ctx, "job", time.Hour); err != nil {
t.Fatal(err)
}
bound, cancel, err := r.PrepareRunBudget(ctx, "job")
if err != nil {
t.Fatal(err)
}
defer cancel()
if err = r.DecideRunTokenBudget(ctx, "job", 1); err != nil {
t.Fatal(err)
}
if _, err = r.Run(bound, "must not bypass", nil); err == nil {
t.Fatal("stale binding bypassed new token limit")
}
if len(p.requests) != 0 {
t.Fatal("stale binding dispatched")
}
}
func TestRunCostBindingStrictAdmissionAndSharedCharges(t *testing.T) {
ctx := context.Background()
p := &recordingProvider{reply: "done"}
r := &Runtime{Session: session.NewSession("a", "money"), LLM: p, Tools: tool.NewRegistry(), Model: "fixture", MaxTurns: 1, Route: llm.CallRoute{Provider: "local", Destination: "fixture"}}
if err := r.DecideCostBudget(ctx, "USD", 1000000, true); err != nil {
t.Fatal(err)
}
if err := r.SetCostPrices(ctx, []budget.PriceSnapshot{runtimeFixturePrice(r.Route, r.Model)}); err != nil {
t.Fatal(err)
}
if err := r.DecideRunCostBudget(ctx, "job", "USD", 1, true); err != nil {
t.Fatal(err)
}
bound, cancel, err := r.PrepareRunBudget(ctx, "job")
if err != nil {
t.Fatal(err)
}
defer cancel()
events, err := r.Run(bound, "blocked", nil)
if err != nil {
t.Fatal(err)
}
var terminal error
for ev := range events {
if ev.Error != nil {
terminal = ev.Error
}
}
if !errors.Is(terminal, ErrRunCostExhausted) || len(p.requests) != 0 {
t.Fatalf("run cost bypass: %v", terminal)
}
total, err := r.CostBudget(ctx)
if err != nil || total.CommittedNano != 0 {
t.Fatalf("denied attempt charged session: %+v %v", total, err)
}
if err = r.DecideRunCostBudget(ctx, "job", "USD", 1000000, true); err != nil {
t.Fatal(err)
}
events, err = r.Run(bound, "resumed", nil)
if err != nil {
t.Fatal(err)
}
for ev := range events {
if ev.Error != nil {
t.Fatal(ev.Error)
}
}
state, err := r.RunBudget(ctx, "job")
if err != nil {
t.Fatal(err)
}
total, err = r.CostBudget(ctx)
if err != nil {
t.Fatal(err)
}
if state.Cost.CommittedNano <= 0 || state.Cost.CommittedNano != total.CommittedNano || len(p.requests) != 1 {
t.Fatalf("charges run=%+v total=%+v", state.Cost, total)
}
}
+30
View File
@@ -0,0 +1,30 @@
package runtime
import (
"context"
"time"
)
func (r *Runtime) startRunLifecycle(ctx context.Context) (err error) {
if hook := r.AgentLoop.Hooks.OnRunStart; hook != nil {
defer func() {
if recovered := recover(); recovered != nil {
err = recoveredPanicError("OnRunStart hook", recovered)
}
}()
return hook(ctx)
}
return nil
}
func (r *Runtime) finishRunLifecycle(parent context.Context, reason string) {
if hook := r.AgentLoop.Hooks.OnRunFinish; hook != nil {
ctx, cancel := context.WithTimeout(context.WithoutCancel(parent), 2*time.Second)
defer cancel()
defer func() {
if recovered := recover(); recovered != nil {
_ = recoveredPanicError("OnRunFinish hook", recovered)
}
}()
hook(ctx, reason)
}
}
+64
View File
@@ -0,0 +1,64 @@
package runtime
import (
"context"
"errors"
"github.com/sausheong/harness/llm"
"testing"
)
func TestRunLifecycleStartFailureAndFinishCannotChangeOutcome(t *testing.T) {
for _, mode := range []string{"run", "runturn"} {
for _, deny := range []bool{false, true} {
t.Run(mode+map[bool]string{true: "-deny", false: "-allow"}[deny], func(t *testing.T) {
starts, finishes := 0, 0
reason := ""
blocked := errors.New("start denied")
rt := hookFixture(t, LifecycleHooks{OnRunStart: func(context.Context) error {
starts++
if deny {
return blocked
}
return nil
}, OnRunFinish: func(ctx context.Context, outcome string) {
finishes++
reason = outcome
if ctx.Err() != nil {
t.Error("finish context already cancelled")
}
if _, ok := ctx.Deadline(); !ok {
t.Error("finish unbounded")
}
panic("observer cannot rewrite outcome")
}}, []llm.ChatEvent{{Type: llm.EventDone}}, nil)
defer rt.Close()
defer rt.Session.Close()
failed := false
if mode == "run" {
events, err := rt.Run(context.Background(), "hello", nil)
if err != nil {
t.Fatal(err)
}
for event := range events {
if event.Error != nil {
failed = true
}
}
} else {
result, err := rt.RunTurn(context.Background(), "hello", nil, nil)
failed = err != nil || result.Err != nil
}
if starts != 1 || finishes != 1 || failed != deny {
t.Fatal(starts, finishes, failed, deny)
}
if deny {
if reason != "error" || len(rt.Session.View()) != 0 {
t.Fatal("denied start mutated history", reason, rt.Session.View())
}
} else if reason != "completed" {
t.Fatal(reason)
}
})
}
}
}
+252 -92
View File
@@ -3,6 +3,7 @@ package runtime
import (
"context"
"encoding/base64"
"errors"
"fmt"
"log/slog"
"sort"
@@ -10,6 +11,7 @@ import (
"sync"
"time"
"github.com/sausheong/harness/budget"
"github.com/sausheong/harness/compaction"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
@@ -31,10 +33,13 @@ const (
EventCompactionStart
EventCompactionDone
EventCompactionSkipped
EventRequestUsage
)
// AgentEvent is a single streaming event from the agent.
type AgentEvent struct {
RequestUsage *llm.RequestUsage // one provider attempt, independent of cumulative Usage
Type EventType
// AgentID is the emitter's agent identifier. Empty for top-level
// (Parent==nil) runtimes; populated by Runtime.emit when forwarding a
@@ -45,11 +50,14 @@ type AgentEvent struct {
Result *tool.ToolResult
Error error
Compaction *compaction.Result // populated for EventCompaction* events
Usage *llm.Usage // on the terminal EventDone, the token total accumulated across all turns of the run (nil if the provider never reported usage); per-turn figures are available via RunTurn's TurnResult.Usage
Usage *llm.Usage // reported-only cumulative consumption on EventRequestUsage/EventDone; see USAGE.md for unknown attempts and compaction
}
// Runtime is the agent think-act loop.
type Runtime struct {
// Route identifies the client in LLM for admission; update atomically with it.
Route llm.CallRoute
LLM llm.LLMProvider
Tools tool.Executor
Session *session.Session
@@ -79,6 +87,8 @@ type Runtime struct {
// ContextWindow overrides the auto-detected window. 0 = auto-detect.
ContextWindow int
// MaxOutputTokens bounds each generation request. Zero retains the 8192 default.
MaxOutputTokens int
// StaticSystemPrompt is the cacheable portion of the system prompt.
// Built once at BuildRuntime time; reused verbatim every turn so the
@@ -144,7 +154,12 @@ type Runtime struct {
// mcpClients holds the MCP client sessions resolved from
// AgentSpec.MCPServers. Released by Close. Untouched when MCP is
// not used.
mcpClients []*mcp.Client
mcpClients []*mcp.Client
mcpMu sync.Mutex
mcpClosed bool
refreshToolPrompt func([]string) string
contextSources func() []ContextSource
mcpStatus []MCPServerStatus
// runMu enforces the Runtime contract that one session exchange runs at a
// time. TryLock lets a second caller receive a normal error instead of
@@ -159,6 +174,9 @@ type Runtime struct {
// Returns the first Close error encountered, if any; remaining
// clients are still closed.
func (r *Runtime) Close() error {
r.mcpMu.Lock()
defer r.mcpMu.Unlock()
r.mcpClosed = true
var firstErr error
for _, c := range r.mcpClients {
if err := c.Close(); err != nil && firstErr == nil {
@@ -187,7 +205,7 @@ func (r *Runtime) emit(ev AgentEvent) {
// maybeKickoffAsyncCompaction conditionally fires Compaction.MaybeCompactAsync
// when the just-finished turn left the session close enough to the trigger
// threshold that the NEXT turn would compact synchronously.
func (r *Runtime) maybeKickoffAsyncCompaction(msgs []llm.Message, parts []llm.SystemPromptPart, toolDefs []llm.ToolDef) {
func (r *Runtime) maybeKickoffAsyncCompaction(ctx context.Context, msgs []llm.Message, parts []llm.SystemPromptPart, toolDefs []llm.ToolDef) {
if r.Compaction == nil || r.Model == "" {
return
}
@@ -209,7 +227,7 @@ func (r *Runtime) maybeKickoffAsyncCompaction(msgs []llm.Message, parts []llm.Sy
if !preemptThresholdHit && !preemptCountHit {
return
}
r.Compaction.MaybeCompactAsync(r.Session, compaction.ReasonPreventive)
r.Compaction.MaybeCompactAsyncContext(ctx, r.Session, compaction.ReasonPreventive)
}
// providerSupportsCaching returns true when the runtime's provider implements
@@ -290,18 +308,75 @@ func isFileTool(name string) bool {
// Run executes the agent loop for a user message, returning a channel of events.
func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageContent) (<-chan AgentEvent, error) {
if r.MaxOutputTokens < 0 {
return nil, fmt.Errorf("max output tokens cannot be negative")
}
if !r.runMu.TryLock() {
return nil, fmt.Errorf("runtime is already running")
}
guidance, guidanceErr := r.preservedContextPrompt()
if guidanceErr != nil {
r.runMu.Unlock()
return nil, guidanceErr
}
ctx, guidanceErr = compaction.WithGuidance(ctx, guidance)
if guidanceErr != nil {
r.runMu.Unlock()
return nil, guidanceErr
}
ctx, guidanceErr = r.budgetContext(ctx)
if guidanceErr != nil {
r.runMu.Unlock()
return nil, guidanceErr
}
ctx, deadlineCancel, deadlineErr := budget.WithDeadline(ctx, r.Session)
if deadlineErr != nil {
r.runMu.Unlock()
return nil, deadlineErr
}
ctx, cancelRun := context.WithCancelCause(ctx)
events := make(chan AgentEvent, 100)
r.events = events
ledger := &llm.UsageLedger{}
ctx = llm.WithUsageObserver(ctx, func(record llm.RequestUsage) {
ledger.Record(record)
r.emit(AgentEvent{Type: EventRequestUsage, RequestUsage: &record, Usage: ledger.Total()})
})
tr := TraceFrom(ctx)
tr.Mark("agent.run.start", "user_msg_len", len(userMsg), "images", len(images))
go func() {
completed := false
defer close(events)
defer deadlineCancel()
defer cancelRun(nil)
defer r.runMu.Unlock()
defer tr.Summary()
// Registered before stop hooks so their deferred work runs before the
// final producer join and persistence fence. Events stays open throughout.
defer func() {
result, joined, err := r.Compaction.JoinInFlight(ctx, r.Session)
if joined {
kind := EventCompactionSkipped
if result.Compacted {
kind = EventCompactionDone
}
r.emit(AgentEvent{Type: kind, Compaction: &result})
}
if r.Session != nil {
err = errors.Join(err, r.Session.Flush())
}
if err != nil {
r.emit(AgentEvent{Type: EventError, Error: err})
}
if completed {
if ctx.Err() != nil {
r.emit(abortedEvent(ctx))
} else if err == nil {
r.emit(AgentEvent{Type: EventDone, Usage: ledger.Total()})
}
}
}()
// Flush the per-session calibrator once at Run end (all exit paths:
// normal, error, abort) instead of writing to disk on every LLM
@@ -320,6 +395,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
// so the natural fall-through (loop exhausted MaxTurns) records the
// right reason without an explicit assignment at that exit.
stopReason := "max_turns"
defer func() { r.finishRunLifecycle(ctx, stopReason) }()
if hook := r.AgentLoop.Hooks.OnStop; hook != nil {
defer func() { callOnStopHook(ctx, hook, stopReason) }()
}
@@ -331,6 +407,12 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
}()
if err := r.startRunLifecycle(ctx); err != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: err})
return
}
// OnUserPromptSubmit may rewrite prompt and/or images BEFORE the
// session sees them. Returning err aborts Run with EventError.
if hook := r.AgentLoop.Hooks.OnUserPromptSubmit; hook != nil {
@@ -352,11 +434,17 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
Data: base64.StdEncoding.EncodeToString(img.Data),
})
}
r.Session.Append(session.UserMessageWithImagesEntry(userMsg, imgData))
r.Session.AppendContext(ctx, session.UserMessageWithImagesEntry(userMsg, imgData))
} else {
r.Session.Append(session.UserMessageEntry(userMsg))
}
if err := r.Session.PersistenceError(); err != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: err})
return
}
if hook := r.AgentLoop.Hooks.OnSessionStart; hook != nil {
hook(ctx, r.Session)
}
@@ -424,12 +512,16 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
"reason", d.Reason)
}
var runUsage *llm.Usage // accumulated across all turns; nil until first reported
for turn := 0; turn < maxTurns; turn++ {
if err := r.Session.PersistenceError(); err != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: err})
return
}
if ctx.Err() != nil {
stopReason = "aborted"
r.emit(AgentEvent{Type: EventAborted})
r.emit(abortedEvent(ctx))
return
}
@@ -451,7 +543,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
dynamicSuffix := buildDynamicSystemPromptSuffix(r.DynamicIdentityHint, dateLine, kgContext)
pinned, pinErr := r.preservedContextPrompt()
if pinErr != nil {
r.emit(AgentEvent{Type: EventError, Error: fmt.Errorf("load context pins: %w", pinErr)})
return
}
dynamicSuffix += pinned
// Tool execution from the previous round has joined here. Refresh
// self-authored skills before assembling the next model request.
if r.Skills != nil {
r.refreshSkills()
}
staticText := r.StaticSystemPrompt
parts := []llm.SystemPromptPart{
{Text: staticText, Cache: true},
@@ -460,7 +563,12 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
parts = append(parts, llm.SystemPromptPart{Text: dynamicSuffix, Cache: false})
}
history := r.Session.View()
history, imageErr := r.Session.ResolveImages(ctx, r.Session.View())
if imageErr != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: imageErr})
return
}
msgs := assembleMessages(history)
spillCfg := spillConfig{Workspace: r.Workspace, SessionKey: r.Session.Key}
@@ -510,10 +618,11 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
req := llm.ChatRequest{
Route: r.Route,
Model: r.Model,
Messages: msgs,
Tools: toolDefs,
MaxTokens: 8192,
MaxTokens: r.outputTokenLimit(),
SystemPromptParts: parts,
CacheLastMessage: r.providerSupportsCaching(),
Reasoning: r.Reasoning,
@@ -525,7 +634,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
prefillChars += len(m.Content)
}
tr.Mark("llm.request_sent", "turn", turn, "model", r.Model, "prefill_chars", prefillChars)
stream, err := r.LLM.ChatStream(ctx, req)
stream, err := r.observeChat(ctx, req, llm.CallGeneration, r.LLM.ChatStream)
if err != nil {
if compaction.IsContextOverflow(err) && r.Compaction != nil {
r.emit(AgentEvent{Type: EventCompactionStart})
@@ -537,7 +646,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
r.prune(msgs, spillCfg)
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
req.Messages = msgs
stream, err = r.LLM.ChatStream(ctx, req)
stream, err = r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
} else {
r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res})
}
@@ -550,7 +659,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
"err", err.Error())
tr.Mark("llm.fallback", "turn", turn, "primary", req.Model, "fallback", r.FallbackModel)
req.Model = r.FallbackModel
stream, err = r.LLM.ChatStream(ctx, req)
stream, err = r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
}
if err != nil {
stopReason = "error"
@@ -564,7 +673,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
var thinkingBlocks []session.ThinkingBlockData
gotFirstToken := false
streamingOn := r.streamingToolsEnabled()
streamingOn := r.streamingToolsEnabled() && steeringSource(ctx) == nil
kickoffs := map[string]chan kickoffResult{}
kickoffStopped := false
@@ -576,6 +685,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
var refusalCategory string
streamLoop:
for {
toolIDs := make(map[string]bool)
for event := range streamSource {
switch event.Type {
case llm.EventTextDelta:
@@ -606,6 +716,13 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
continue
}
tc := *event.ToolCall
if err := acceptToolCallID(toolIDs, tc.ID); err != nil {
cancelRun(err)
// Join usage settlement before the runtime event channel closes.
for range streamSource {
}
break streamLoop
}
toolCalls = append(toolCalls, tc)
if !streamingOn || kickoffStopped {
continue
@@ -626,9 +743,6 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
case llm.EventDone:
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
if event.Usage != nil {
runUsage = addUsage(runUsage, event.Usage)
}
if event.Usage != nil && r.calibrator != nil {
// Recompute the estimate on the CURRENT msgs (which may
// have been reassembled by mid-turn compaction) so the
@@ -641,6 +755,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
case llm.EventError:
// Once tools have started, replaying the provider call can
// repeat external effects. Stop owned work and reconcile
// its results below before returning the original cause.
if len(kickoffs) > 0 || ctx.Err() != nil || errors.Is(event.Error, budget.ErrExhausted) {
cancelRun(event.Error)
if len(toolCalls) > 0 {
break streamLoop
}
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: event.Error})
return
}
if !gotFirstToken && !preTokenRetried {
if newStream, ok := r.recoverFromPreTokenError(ctx, event.Error, &req, &msgs, spillCfg); ok {
preTokenRetried = true
@@ -664,7 +790,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
kickoffs = map[string]chan kickoffResult{}
gotFirstToken = false
kickoffStopped = false
nsStream, retryErr := ns.ChatNonStreaming(ctx, req)
nsStream, retryErr := r.observeChat(ctx, req, llm.CallRetry, ns.ChatNonStreaming)
if retryErr != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: retryErr})
@@ -682,6 +808,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
}
if ctx.Err() != nil {
if len(toolCalls) > 0 {
// Reconcile started tools below before closing events;
// cancellation must not discard their session pairs.
break streamLoop
}
drainKickoffs(kickoffs)
stopReason = "aborted"
r.emit(abortedEvent(ctx))
return
}
// Classifier/model refusal (Claude Fable 5+): HTTP 200,
// stop_reason=refusal, usually no content. Without handling,
// the turn ends as a silent empty success. Retry once on the
@@ -708,7 +846,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
refused = false
retriedRefusal = true
req.Model = r.FallbackModel
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
retryStream, retryErr := r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
if retryErr != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: retryErr})
@@ -752,83 +890,83 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
}
if steered, err := r.applySteering(ctx, toolCalls); err != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: err})
return
} else if steered {
continue
}
if ctx.Err() != nil && len(toolCalls) == 0 {
stopReason = "aborted"
r.emit(abortedEvent(ctx))
return
}
if len(toolCalls) == 0 {
if len(kickoffs) > 0 {
drainKickoffs(kickoffs)
}
tr.Mark("agent.done", "turn", turn, "reason", "no_tool_calls")
if err := r.Session.Flush(); err != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: err})
return
}
stopReason = "completed"
r.emit(AgentEvent{Type: EventDone, Usage: runUsage})
r.maybeKickoffAsyncCompaction(msgs, parts, toolDefs)
completed = true
r.maybeKickoffAsyncCompaction(ctx, msgs, parts, toolDefs)
return
}
var pending []llm.ToolCall
var reconcileErr error
for _, tc := range toolCalls {
if ch, ok := kickoffs[tc.ID]; ok {
kp := <-ch
r.Session.Append(session.ToolCallEntry(kp.tc.ID, kp.tc.Name, kp.tc.Input))
if r.KG != nil {
r.kgMu.Lock()
thread = append(thread, Message{
Role: "assistant",
Content: fmt.Sprintf("[tool: %s]\n%s", kp.tc.Name, string(kp.tc.Input)),
})
r.kgMu.Unlock()
}
if kp.aborted {
r.Session.Append(session.AbortedToolResultEntry(kp.tc.ID))
if r.KG != nil {
r.kgMu.Lock()
thread = append(thread, Message{Role: "user", Content: "[error] aborted by user"})
r.kgMu.Unlock()
}
for _, tc2 := range toolCalls {
if tc2.ID == kp.tc.ID {
continue
}
ch2, ok := kickoffs[tc2.ID]
if !ok {
continue
}
kp2 := <-ch2
r.Session.Append(session.ToolCallEntry(kp2.tc.ID, kp2.tc.Name, kp2.tc.Input))
r.Session.Append(session.AbortedToolResultEntry(kp2.tc.ID))
if r.KG != nil {
r.kgMu.Lock()
thread = append(thread, Message{
Role: "assistant",
Content: fmt.Sprintf("[tool: %s]\n%s", kp2.tc.Name, string(kp2.tc.Input)),
})
thread = append(thread, Message{Role: "user", Content: "[error] aborted by user"})
r.kgMu.Unlock()
}
}
stopReason = "aborted"
r.emit(AgentEvent{Type: EventAborted})
return
}
imgData := convertToolResultImages(kp.result.Images)
r.Session.Append(session.ToolResultEntry(kp.tc.ID, kp.result.Output, kp.result.Error, imgData))
if r.KG != nil {
content := kp.result.Output
if kp.result.Error != "" {
content = "[error] " + kp.result.Error
}
r.kgMu.Lock()
thread = append(thread, Message{Role: "user", Content: content})
r.kgMu.Unlock()
}
continue
delete(kickoffs, tc.ID)
reconcileErr = errors.Join(reconcileErr, r.persistKickoff(ctx, kp, kgThreadOrNil(r.KG, &thread)))
} else {
pending = append(pending, tc)
}
pending = append(pending, tc)
}
if ctx.Err() != nil || reconcileErr != nil {
// Calls emitted by the provider but not started must remain
// paired too. Never invoke their permission hooks or tools.
for _, tc := range pending {
kp := kickoffResult{tc: tc, aborted: true}
reconcileErr = errors.Join(reconcileErr, r.persistKickoff(ctx, kp, kgThreadOrNil(r.KG, &thread)))
}
stopReason = "aborted"
if reconcileErr != nil {
r.emit(AgentEvent{Type: EventError, Error: errors.Join(context.Cause(ctx), reconcileErr)})
} else {
r.emit(abortedEvent(ctx))
}
return
}
batches := partitionToolCalls(pending, r.Tools)
for _, b := range batches {
if steeringSource(ctx) != nil {
batches = nil
for _, tc := range pending {
batches = append(batches, batch{calls: []llm.ToolCall{tc}})
}
}
for i, b := range batches {
// The first boundary was checked immediately after model output.
if i > 0 {
if steered, err := r.applySteering(ctx, pending[i:]); err != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: err})
return
} else if steered {
break
}
}
if r.runBatch(ctx, b, kgThreadOrNil(r.KG, &thread), turn, tr) {
stopReason = "aborted"
r.emit(AgentEvent{Type: EventAborted})
r.emit(abortedEvent(ctx))
return
}
}
@@ -863,7 +1001,7 @@ func (r *Runtime) recoverFromPreTokenError(ctx context.Context, err error, req *
newMsgs = prependPostCompactRestore(newMsgs, r.snapshotTouchedFiles())
*msgs = newMsgs
req.Messages = newMsgs
if s, e := r.LLM.ChatStream(ctx, *req); e == nil {
if s, e := r.observeChat(ctx, *req, llm.CallRetry, r.LLM.ChatStream); e == nil {
return s, true
}
} else {
@@ -874,7 +1012,7 @@ func (r *Runtime) recoverFromPreTokenError(ctx context.Context, err error, req *
slog.Info("llm fallback model engaged (stream error)",
"agent", r.AgentID, "primary", req.Model, "fallback", r.FallbackModel, "err", err.Error())
req.Model = r.FallbackModel
if s, e := r.LLM.ChatStream(ctx, *req); e == nil {
if s, e := r.observeChat(ctx, *req, llm.CallRetry, r.LLM.ChatStream); e == nil {
return s, true
}
}
@@ -890,18 +1028,25 @@ func (r *Runtime) RunSync(ctx context.Context, userMsg string, images []llm.Imag
}
var response strings.Builder
var runErr error
for event := range events {
switch event.Type {
case EventTextDelta:
response.WriteString(event.Text)
case EventAborted:
return response.String(), context.Canceled
if runErr == nil {
runErr = context.Canceled
}
case EventError:
return response.String(), event.Error
if runErr == nil {
runErr = event.Error
if runErr == nil {
runErr = fmt.Errorf("runtime emitted an error without details")
}
}
}
}
return response.String(), nil
return response.String(), runErr
}
// dispatchTool executes one tool call with strict tool_use ↔ tool_result
@@ -953,7 +1098,7 @@ func (r *Runtime) dispatchTool(
}
if ctx.Err() != nil {
return r.appendAbortedResult(tc.ID, kgThread), true
return r.appendAbortedResult(ctx, tc.ID, kgThread), true
}
result, err := callToolExecute(ctx, r.Tools, tc.Name, tc.Input)
@@ -962,11 +1107,11 @@ func (r *Runtime) dispatchTool(
}
if ctx.Err() != nil {
return r.appendAbortedResult(tc.ID, kgThread), true
return r.appendAbortedResult(ctx, tc.ID, kgThread), true
}
imgData := convertToolResultImages(result.Images)
r.Session.Append(session.ToolResultEntry(tc.ID, result.Output, result.Error, imgData))
r.Session.AppendContext(ctx, session.ToolResultWithArtifactsEntry(tc.ID, result.Output, result.Error, imgData, resultArtifacts(result)))
if kgThread != nil {
content := result.Output
if result.Error != "" {
@@ -1019,14 +1164,14 @@ func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (resu
}
}
if ctx.Err() != nil {
return tool.ToolResult{Error: "aborted by user"}, true
return tool.ToolResult{Error: toolAbortReason(ctx)}, true
}
result, err := callToolExecute(ctx, r.Tools, tc.Name, tc.Input)
if err != nil {
result = tool.ToolResult{Error: err.Error()}
}
if ctx.Err() != nil {
return tool.ToolResult{Error: "aborted by user"}, true
return tool.ToolResult{Error: toolAbortReason(ctx)}, true
}
if result.Error == "" && isFileTool(tc.Name) {
r.recordFileTouch(extractPathFromInput(tc.Input))
@@ -1051,16 +1196,16 @@ func (r *Runtime) appendDenialResult(toolCallID, reason string, kgThread *[]Mess
}
// appendAbortedResult writes the synthetic abort entry.
func (r *Runtime) appendAbortedResult(toolCallID string, kgThread *[]Message) tool.ToolResult {
r.Session.Append(session.AbortedToolResultEntry(toolCallID))
func (r *Runtime) appendAbortedResult(ctx context.Context, toolCallID string, kgThread *[]Message) tool.ToolResult {
r.Session.Append(session.AbortedToolResultWithReasonEntry(toolCallID, toolAbortReason(ctx)))
if kgThread != nil {
r.kgMu.Lock()
*kgThread = append(*kgThread, Message{
Role: "user", Content: "[error] aborted by user",
Role: "user", Content: "[error] " + toolAbortReason(ctx),
})
r.kgMu.Unlock()
}
return tool.ToolResult{Error: "aborted by user"}
return tool.ToolResult{Error: toolAbortReason(ctx)}
}
// convertToolResultImages adapts tool image attachments to session ImageData.
@@ -1085,3 +1230,18 @@ func kgThreadOrNil(kg KnowledgeGraph, thread *[]Message) *[]Message {
}
return thread
}
// MCPServerStatus is immutable construction evidence without credentials or raw
// transport errors. Connected servers alone contribute tools to the catalogue.
type MCPServerStatus struct {
Name string
Optional bool
State string
Tools int
}
func (r *Runtime) MCPStatus() []MCPServerStatus {
r.mcpMu.Lock()
defer r.mcpMu.Unlock()
return append([]MCPServerStatus(nil), r.mcpStatus...)
}
+88 -19
View File
@@ -9,6 +9,7 @@ import (
"strings"
"time"
"github.com/sausheong/harness/budget"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
@@ -19,7 +20,7 @@ type TurnResult struct {
StopReason string // "continue" | "completed" | "error" | "aborted"
Entries []session.SessionEntry // entries appended during THIS turn, in order
Err error
Usage *llm.Usage
Usage *llm.Usage // reported aggregate for this call, including retries
}
// TurnEmit is an optional live-streaming callback. Pass nil for headless
@@ -40,10 +41,55 @@ type TurnEmit func(AgentEvent)
// responsibility). It DOES perform bounded-synchronous knowledge-graph recall on
// the first round of an exchange (folding the hint into the system prompt) and
// async knowledge-graph ingest on the completing round.
func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.ImageContent, emit TurnEmit) (TurnResult, error) {
func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.ImageContent, emit TurnEmit) (turnOutcome TurnResult, turnError error) {
if r.MaxOutputTokens < 0 {
return TurnResult{}, fmt.Errorf("max output tokens cannot be negative")
}
if !r.runMu.TryLock() {
return TurnResult{}, fmt.Errorf("runtime is already running")
}
defer r.runMu.Unlock()
var budgetErr error
ctx, budgetErr = r.budgetContext(ctx)
if budgetErr != nil {
return TurnResult{}, budgetErr
}
ctx, deadlineCancel, deadlineErr := budget.WithDeadline(ctx, r.Session)
if deadlineErr != nil {
return TurnResult{}, deadlineErr
}
defer deadlineCancel()
ctx, cancelTurn := context.WithCancel(ctx)
defer cancelTurn()
if emit == nil {
emit = func(AgentEvent) {}
}
ledger := &llm.UsageLedger{}
ctx = llm.WithUsageObserver(ctx, ledger.Record)
emittedUsage := 0
flushUsage := func() {
records := ledger.Records()
for ; emittedUsage < len(records); emittedUsage++ {
record := records[emittedUsage]
emit(AgentEvent{Type: EventRequestUsage, RequestUsage: &record, Usage: ledger.Total()})
}
}
defer flushUsage()
defer func() {
reason := turnOutcome.StopReason
if reason == "" {
if ctx.Err() != nil {
reason = "aborted"
} else {
reason = "error"
}
}
r.finishRunLifecycle(ctx, reason)
}()
if err := r.startRunLifecycle(ctx); err != nil {
return TurnResult{StopReason: "error", Err: err}, err
}
startLen := len(r.Session.Entries())
if userMsg != "" || len(images) > 0 {
@@ -55,17 +101,23 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
Data: base64.StdEncoding.EncodeToString(img.Data),
})
}
r.Session.Append(session.UserMessageWithImagesEntry(userMsg, imgData))
r.Session.AppendContext(ctx, session.UserMessageWithImagesEntry(userMsg, imgData))
} else {
r.Session.Append(session.UserMessageEntry(userMsg))
}
}
if ctx.Err() != nil {
return r.turnSlice(startLen, true, "aborted", nil, ctx.Err()), nil
return r.turnSlice(startLen, true, "aborted", nil, context.Cause(ctx)), nil
}
history := r.Session.View()
if err := r.Session.PersistenceError(); err != nil {
return r.turnSlice(startLen, true, "error", nil, err), nil
}
history, imageErr := r.Session.ResolveImages(ctx, r.Session.View())
if imageErr != nil {
return r.turnSlice(startLen, true, "error", nil, imageErr), nil
}
msgs := assembleMessages(history)
toolDefs := r.Tools.ToolDefs()
if r.Permission != nil {
@@ -85,25 +137,31 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
}
dynamicSuffix := buildDynamicSystemPromptSuffix(r.DynamicIdentityHint, "", kgHint)
pinned, pinErr := r.preservedContextPrompt()
if pinErr != nil {
return r.turnSlice(startLen, true, "error", nil, fmt.Errorf("load context pins: %w", pinErr)), nil
}
dynamicSuffix += pinned
parts := []llm.SystemPromptPart{{Text: r.StaticSystemPrompt, Cache: true}}
if dynamicSuffix != "" {
parts = append(parts, llm.SystemPromptPart{Text: dynamicSuffix, Cache: false})
}
req := llm.ChatRequest{
Route: r.Route,
Model: r.Model,
Messages: msgs,
Tools: toolDefs,
MaxTokens: 8192,
MaxTokens: r.outputTokenLimit(),
SystemPromptParts: parts,
CacheLastMessage: r.providerSupportsCaching(),
Reasoning: r.Reasoning,
}
stream, err := r.LLM.ChatStream(ctx, req)
stream, err := r.observeChat(ctx, req, llm.CallGeneration, r.LLM.ChatStream)
if err != nil {
if r.FallbackModel != "" && r.FallbackModel != req.Model && llm.IsRetryableModelError(err) {
req.Model = r.FallbackModel
stream, err = r.LLM.ChatStream(ctx, req)
stream, err = r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
}
if err != nil {
emit(AgentEvent{Type: EventError, Error: fmt.Errorf("llm error: %w", err)})
@@ -114,13 +172,16 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
var textContent strings.Builder
var toolCalls []llm.ToolCall
var thinkingBlocks []session.ThinkingBlockData
var lastUsage *llm.Usage
retriedRefusal := false
streamLoop:
for {
toolIDs := make(map[string]bool)
var refused bool
var refusalCategory string
for event := range stream {
if event.Type == llm.EventDone || event.Type == llm.EventError {
flushUsage()
}
switch event.Type {
case llm.EventTextDelta:
textContent.WriteString(event.Text)
@@ -136,20 +197,28 @@ streamLoop:
}
case llm.EventToolCallDone:
if event.ToolCall != nil {
if err := acceptToolCallID(toolIDs, event.ToolCall.ID); err != nil {
cancelTurn()
for range stream {
}
flushUsage()
emit(AgentEvent{Type: EventError, Error: err})
return r.turnSlice(startLen, true, "error", ledger.Total(), err), nil
}
toolCalls = append(toolCalls, *event.ToolCall)
}
case llm.EventDone:
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
if event.Usage != nil {
lastUsage = event.Usage
}
case llm.EventError:
emit(AgentEvent{Type: EventError, Error: event.Error})
return r.turnSlice(startLen, true, "error", lastUsage, event.Error), nil
return r.turnSlice(startLen, true, "error", ledger.Total(), event.Error), nil
}
}
if ctx.Err() != nil {
return r.turnSlice(startLen, true, "aborted", ledger.Total(), context.Cause(ctx)), nil
}
// Same refusal contract as Run: retry once on the fallback model,
// else surface a visible explanation instead of empty silence.
if refused {
@@ -158,10 +227,10 @@ streamLoop:
textContent.Reset()
toolCalls = nil
req.Model = r.FallbackModel
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
retryStream, retryErr := r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
if retryErr != nil {
emit(AgentEvent{Type: EventError, Error: retryErr})
return r.turnSlice(startLen, true, "error", lastUsage, retryErr), nil
return r.turnSlice(startLen, true, "error", ledger.Total(), retryErr), nil
}
stream = retryStream
continue streamLoop
@@ -200,8 +269,8 @@ streamLoop:
if r.KG != nil {
r.KG.Ingest(context.Background(), sessionThread(r.Session.View()))
}
emit(AgentEvent{Type: EventDone, Usage: lastUsage})
return r.turnSlice(startLen, true, "completed", lastUsage, nil), nil
emit(AgentEvent{Type: EventDone, Usage: ledger.Total()})
return r.turnSlice(startLen, true, "completed", ledger.Total(), nil), nil
}
// RunTurn dispatches tool calls serially by design: deterministic
@@ -212,11 +281,11 @@ streamLoop:
result, aborted := r.dispatchTool(ctx, tc, nil)
emit(AgentEvent{Type: EventToolResult, ToolCall: &tc, Result: &result})
if aborted {
return r.turnSlice(startLen, true, "aborted", lastUsage, ctx.Err()), nil
return r.turnSlice(startLen, true, "aborted", ledger.Total(), context.Cause(ctx)), nil
}
}
return r.turnSlice(startLen, false, "continue", lastUsage, nil), nil
return r.turnSlice(startLen, false, "continue", ledger.Total(), nil), nil
}
// turnSlice builds a TurnResult from the entries appended since startLen.
+66
View File
@@ -0,0 +1,66 @@
package runtime
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
)
func TestRunTurnPinsAfterCompactionRestartAndCorruption(t *testing.T) {
ctx := context.Background()
store := session.NewStore(t.TempDir())
if err := store.Create("agent", "turn-pins"); err != nil {
t.Fatal(err)
}
sess, err := store.LoadExclusive("agent", "turn-pins")
if err != nil {
t.Fatal(err)
}
defer func() { sess.Close() }()
provider := &recordingProvider{reply: "done"}
r := &Runtime{Session: sess, LLM: provider, Tools: tool.NewRegistry(), StaticSystemPrompt: "identity"}
if err = r.SetContextPins(ctx, []ContextPin{{ID: "objective", Kind: "objective", Text: "EXACT OBJECTIVE"}, {ID: "constraint", Kind: "constraint", Text: "EXACT CONSTRAINT"}}); err != nil {
t.Fatal(err)
}
for i := 0; i < 3; i++ {
sess.Compact("summary omits all pins", 0)
if err = sess.Flush(); err != nil {
t.Fatal(err)
}
if err = sess.Close(); err != nil {
t.Fatal(err)
}
sess, err = store.LoadExclusive("agent", "turn-pins")
if err != nil {
t.Fatal(err)
}
r.Session = sess
result, err := r.RunTurn(ctx, "continue", nil, nil)
if err != nil || result.Err != nil || result.StopReason != "completed" {
t.Fatalf("%+v %v", result, err)
}
req := provider.requests[len(provider.requests)-1]
prompt := llm.JoinSystemPromptParts(req.SystemPromptParts)
for _, text := range []string{"EXACT OBJECTIVE", "EXACT CONSTRAINT"} {
if strings.Count(prompt, text) != 1 {
t.Fatalf("missing or duplicated pin: %s", prompt)
}
}
}
if err = sess.Annotate(contextPinsKind, json.RawMessage(`{"version":99,"pins":[]}`)); err != nil {
t.Fatal(err)
}
before := len(provider.requests)
result, err := r.RunTurn(ctx, "must not dispatch", nil, nil)
if err == nil && result.Err == nil {
t.Fatal("corrupt pins accepted")
}
if len(provider.requests) != before {
t.Fatal("provider dispatched with corrupt pins")
}
}
+21
View File
@@ -163,3 +163,24 @@ func TestRunTurn_PreCancelledContext(t *testing.T) {
require.Error(t, res.Err)
require.EqualValues(t, 0, llmProvider.calls.Load(), "LLM must not be called when context is pre-cancelled")
}
func TestRunTurnExcludesConcurrentRuntimeOperations(t *testing.T) {
rt := &Runtime{LLM: &scriptedStreamLLM{events: []scriptedStreamEvent{{typ: llm.EventTextDelta, text: "hello"}, {typ: llm.EventDone}}}, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), AgentID: "a", Model: "test"}
rt.runMu.Lock()
_, err := rt.RunTurn(context.Background(), "rejected", nil, nil)
rt.runMu.Unlock()
require.Error(t, err)
require.Empty(t, rt.Session.Entries())
observed := false
_, err = rt.RunTurn(context.Background(), "accepted", nil, func(AgentEvent) {
observed = true
if rt.runMu.TryLock() {
rt.runMu.Unlock()
t.Error("runtime lock released during RunTurn")
}
})
require.NoError(t, err)
require.True(t, observed)
require.True(t, rt.runMu.TryLock(), "runtime lock not released after RunTurn")
rt.runMu.Unlock()
}
+81
View File
@@ -0,0 +1,81 @@
package runtime
import (
"context"
"encoding/json"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/sausheong/harness/tool/skills"
"github.com/sausheong/harness/tool/skills/disk"
"strings"
"testing"
"time"
)
type authoringProvider struct {
llmtest.Base
prompts []string
}
func (p *authoringProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.prompts = append(p.prompts, llm.JoinSystemPromptParts(req.SystemPromptParts))
ch := make(chan llm.ChatEvent, 2)
switch len(p.prompts) {
case 1:
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "author", Name: "skill_manage", Input: json.RawMessage(`{"action":"create","name":"authored-skill","body":"---\ndescription: newly authored workflow\n---\nunique procedure body"}`)}}
case 2:
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "load", Name: "load_skill", Input: json.RawMessage(`{"name":"authored-skill"}`)}}
}
ch <- llm.ChatEvent{Type: llm.EventDone}
close(ch)
return ch, nil
}
func TestSkillAuthoringRefreshesNextModelRequest(t *testing.T) {
store := disk.NewStore(t.TempDir())
reg := tool.NewRegistry()
reg.Register(&skills.SkillTool{Store: store})
provider := &authoringProvider{}
rt, err := BuildRuntime(RuntimeDeps{Skills: store.AsSkillProvider()}, RuntimeInputs{Tools: reg, Session: session.NewSession("test", "skills")}, AgentSpec{ID: "test", SystemPrompt: "fixed identity", MaxTurns: 4})
if err != nil {
t.Fatal(err)
}
defer rt.Close()
rt.LLM = provider
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
events, err := rt.Run(ctx, "create then load the workflow", nil)
if err != nil {
t.Fatal(err)
}
done := false
loaded := false
for event := range events {
if event.Type == EventError {
t.Errorf("runtime error: %v", event.Error)
}
if event.Type == EventDone {
done = true
}
if event.Type == EventToolResult && event.ToolCall != nil && event.ToolCall.Name == "load_skill" {
encoded, _ := json.Marshal(event)
loaded = strings.Contains(string(encoded), "unique procedure body")
}
}
if !done || !loaded || len(provider.prompts) != 3 {
t.Fatalf("done=%v loaded=%v requests=%d", done, loaded, len(provider.prompts))
}
if strings.Contains(provider.prompts[0], "newly authored workflow") {
t.Fatal("skill existed before authoring")
}
for _, prompt := range provider.prompts[1:] {
if !strings.Contains(prompt, "newly authored workflow") || !strings.Contains(prompt, "fixed identity") {
t.Fatalf("next request omitted refreshed skill: %s", prompt)
}
}
if _, ok, err := store.Get(ctx, "authored-skill"); err != nil || !ok {
t.Fatalf("skill not persisted: %v", err)
}
}
+26
View File
@@ -0,0 +1,26 @@
package runtime
import "fmt"
// RefreshSkills refreshes discovery while idle. Run also refreshes between
// model requests, after preceding tool calls have joined. Providers must bound
// filesystem work; callers cannot refresh concurrently with an active run.
func (r *Runtime) RefreshSkills() error {
if !r.runMu.TryLock() {
return fmt.Errorf("runtime is already running")
}
defer r.runMu.Unlock()
r.refreshSkills()
return nil
}
func (r *Runtime) refreshSkills() {
if r.refreshToolPrompt == nil {
return
}
var names []string
if r.Tools != nil {
names = r.Tools.Names()
}
r.StaticSystemPrompt = r.refreshToolPrompt(names)
}
+81
View File
@@ -0,0 +1,81 @@
package runtime
import (
"context"
"github.com/sausheong/harness/tool"
"github.com/sausheong/harness/tool/skills"
"github.com/sausheong/harness/tool/skills/disk"
"strings"
"testing"
)
func TestRefreshSkillsDiscoversAuthoredAndRemovedSkills(t *testing.T) {
store := disk.NewStore(t.TempDir())
rt, err := BuildRuntime(RuntimeDeps{Skills: store.AsSkillProvider(), ConfigSummary: "configuration retained", MemoryFiles: "memory retained"}, RuntimeInputs{Tools: tool.NewRegistry()}, AgentSpec{ID: "test", SystemPrompt: "identity retained"})
if err != nil {
t.Fatal(err)
}
defer rt.Close()
initial := rt.StaticSystemPrompt
if _, err = store.Create(context.Background(), skills.Skill{Name: "new-skill", Description: "new description", Body: "procedure"}); err != nil {
t.Fatal(err)
}
rt.runMu.Lock()
err = rt.RefreshSkills()
rt.runMu.Unlock()
if err == nil || rt.StaticSystemPrompt != initial {
t.Fatal("busy refresh mutated prompt")
}
if err = rt.RefreshSkills(); err != nil {
t.Fatal(err)
}
for _, want := range []string{"new-skill", "new description", "identity retained", "configuration retained", "memory retained"} {
if !strings.Contains(rt.StaticSystemPrompt, want) {
t.Fatalf("missing %s", want)
}
}
if err = store.Remove(context.Background(), "new-skill"); err != nil {
t.Fatal(err)
}
if err = rt.RefreshSkills(); err != nil {
t.Fatal(err)
}
if rt.StaticSystemPrompt != initial {
t.Fatal("removed skill remains or unrelated context changed")
}
}
func TestRefreshSkillsUsesCurrentProviderForToolAndIndex(t *testing.T) {
ctx := context.Background()
first := disk.NewStore(t.TempDir())
second := disk.NewStore(t.TempDir())
for _, entry := range []struct {
store *disk.Store
body string
}{{first, "original"}, {second, "replacement"}} {
if _, err := entry.store.Create(ctx, skills.Skill{Name: "selected", Description: entry.body, Body: entry.body}); err != nil {
t.Fatal(err)
}
}
rt, err := BuildRuntime(RuntimeDeps{Skills: first.AsSkillProvider()}, RuntimeInputs{Tools: tool.NewRegistry()}, AgentSpec{ID: "test"})
if err != nil {
t.Fatal(err)
}
defer rt.Close()
rt.Skills = second.AsSkillProvider()
if err = rt.RefreshSkills(); err != nil {
t.Fatal(err)
}
result, err := rt.Tools.Execute(ctx, "load_skill", []byte(`{"name":"selected"}`))
if err != nil || result.Error != "" || !strings.Contains(result.Output, "replacement") || strings.Contains(result.Output, "original") || !strings.Contains(rt.StaticSystemPrompt, "replacement") {
t.Fatal(result, err, rt.StaticSystemPrompt)
}
rt.Skills = nil
if err = rt.RefreshSkills(); err != nil {
t.Fatal(err)
}
result, err = rt.Tools.Execute(ctx, "load_skill", []byte(`{"name":"selected"}`))
if err != nil || result.Error == "" || strings.Contains(rt.StaticSystemPrompt, "replacement") {
t.Fatal("removed provider still used", result, err)
}
}
+171
View File
@@ -0,0 +1,171 @@
package runtime
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"reflect"
"strings"
"unicode/utf8"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
type steeringContextKey struct{}
// SteeringMessage identifies one correction. Source retains it until Acknowledge
// succeeds. ID must be stable across retry; Text must not change after delivery.
type SteeringMessage struct {
ID string
Text string
Images []llm.ImageContent
Acknowledge func() error
}
type SteeringSource func(context.Context) (*SteeringMessage, error)
// WithSteering enables safe-boundary delivery for Run. Tool execution becomes
// serial and streaming kickoff is disabled so no eligible later tool can race a
// correction. Source is called after model output and between joined tools.
// A nil message means no correction. Source must return promptly and honour ctx.
func WithSteering(ctx context.Context, source SteeringSource) context.Context {
return context.WithValue(ctx, steeringContextKey{}, source)
}
func steeringSource(ctx context.Context) SteeringSource {
source, _ := ctx.Value(steeringContextKey{}).(SteeringSource)
return source
}
func (r *Runtime) applySteering(ctx context.Context, pending []llm.ToolCall) (bool, error) {
source := steeringSource(ctx)
if source == nil {
return false, nil
}
if err := ctx.Err(); err != nil {
return false, err
}
message, err := source(ctx)
if err != nil || message == nil {
return false, err
}
if message.ID == "" || len(message.ID) > 128 || strings.ContainsAny(message.ID, "\r\n\x00") || !utf8.ValidString(message.ID) || !utf8.ValidString(message.Text) || strings.TrimSpace(message.Text) == "" || len(message.Text) > 8<<20 {
return false, errors.New("invalid steering identity or text")
}
if len(message.Images) > 16 {
return false, errors.New("too many steering images")
}
totalImageBytes := 0
for _, img := range message.Images {
if len(img.Data) > (32<<20)-totalImageBytes {
return false, errors.New("steering images exceed 32 MiB")
}
totalImageBytes += len(img.Data)
if img.MimeType == "" {
return false, errors.New("steering image MIME type missing")
}
}
entry := session.UserMessageEntry(message.Text)
if len(entry.Data) > 8<<20 {
return false, errors.New("encoded steering text exceeds 8 MiB")
}
if len(message.Images) > 0 {
entry = session.UserMessageWithImagesEntry(message.Text, convertToolResultImages(message.Images))
}
entry.ID = "steering_" + message.ID
for _, prior := range r.Session.Entries() {
if prior.ID != entry.ID {
continue
}
matches, err := MatchesSteering(ctx, r.Session, *message, prior)
if err != nil {
return false, err
}
if !matches {
return false, errors.New("conflicting delivered steering identity")
}
if err := r.Session.Flush(); err != nil {
return false, err
}
if message.Acknowledge != nil {
return false, message.Acknowledge()
}
return false, nil
}
// Reconcile every proposed call before injecting user input. Unexecuted tools
// get explicit error results so provider histories never contain orphan calls.
for _, tc := range pending {
r.Session.AppendContext(ctx, session.ToolCallEntry(tc.ID, tc.Name, tc.Input))
r.Session.AppendContext(ctx, session.ToolResultEntry(tc.ID, "", "skipped because user steering superseded this tool call", nil))
}
r.Session.AppendContext(ctx, entry)
if err := r.Session.Flush(); err != nil {
return false, err
}
if message.Acknowledge != nil {
if err := message.Acknowledge(); err != nil {
return true, err
}
}
return true, nil
}
// MatchesSteering compares a delivered correction with its immutable source,
// hydrating and verifying referenced image bytes before comparing semantics.
// It is also used by hosts reconciling an interrupted acknowledgement.
func MatchesSteering(ctx context.Context, sess *session.Session, message SteeringMessage, prior session.SessionEntry) (bool, error) {
if prior.ID != "steering_"+message.ID || prior.Type != session.EntryTypeMessage || prior.Role != "user" {
return false, nil
}
// Reject count/size/digest mismatches before hydration. A small forged JSONL
// record can otherwise reference many large blobs and expand without bound.
if len(message.Images) > 16 {
return false, errors.New("too many steering images")
}
total := 0
for _, img := range message.Images {
if len(img.Data) > (32<<20)-total {
return false, errors.New("steering images exceed 32 MiB")
}
total += len(img.Data)
}
var stored session.MessageData
if err := json.Unmarshal(prior.Data, &stored); err != nil {
return false, err
}
if stored.Text != message.Text || len(stored.Images) != len(message.Images) {
return false, nil
}
for i, img := range stored.Images {
want := message.Images[i]
if img.MimeType != want.MimeType {
return false, nil
}
if img.Reference != nil {
if img.Data != "" {
return false, errors.New("ambiguous steering image representation")
}
if err := img.Reference.Validate(); err != nil {
return false, err
}
digest := sha256.Sum256(want.Data)
if img.Reference.Size != int64(len(want.Data)) || img.Reference.SHA256 != hex.EncodeToString(digest[:]) {
return false, nil
}
} else if img.Data != base64.StdEncoding.EncodeToString(want.Data) {
return false, nil
}
}
entries, err := sess.ResolveImages(ctx, []session.SessionEntry{prior})
if err != nil {
return false, err
}
var actual session.MessageData
if err := json.Unmarshal(entries[0].Data, &actual); err != nil {
return false, err
}
expected := session.MessageData{Text: message.Text, Images: convertToolResultImages(message.Images)}
return reflect.DeepEqual(actual, expected), nil
}
+54
View File
@@ -0,0 +1,54 @@
package runtime
import (
"context"
"crypto/sha256"
"encoding/hex"
"testing"
"github.com/sausheong/harness/attachment"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
func TestSteeringMismatchRejectedBeforeBlobAccess(t *testing.T) {
// An in-memory session cannot resolve references. A mismatch must nevertheless
// return false without attempting hydration or opening any attachment store.
sess := session.NewSession("a", "key")
data := []byte("expected")
digest := sha256.Sum256(data)
good := session.ImageData{MimeType: "image/png", Reference: &attachment.Ref{SHA256: hex.EncodeToString(digest[:]), Size: int64(len(data))}}
message := SteeringMessage{ID: "x", Text: "inspect", Images: []llm.ImageContent{{MimeType: "image/png", Data: data}}}
for _, mode := range []string{"count", "size", "digest", "mime", "text"} {
t.Run(mode, func(t *testing.T) {
image := good
ref := *good.Reference
image.Reference = &ref
text := message.Text
images := []session.ImageData{image}
switch mode {
case "count":
images = append(images, image)
case "size":
ref.Size = 32 << 20
case "digest":
ref.SHA256 = hex.EncodeToString(make([]byte, 32))
case "mime":
images[0].MimeType = "image/jpeg"
case "text":
text = "different"
}
entry := session.UserMessageWithImagesEntry(text, images)
entry.ID = "steering_x"
matched, err := MatchesSteering(context.Background(), sess, message, entry)
if err != nil || matched {
t.Fatal("mismatch attempted blob access", matched, err)
}
})
}
entry := session.UserMessageWithImagesEntry(message.Text, []session.ImageData{good})
entry.ID = "steering_x"
if _, err := MatchesSteering(context.Background(), sess, message, entry); err == nil {
t.Fatal("matching reference skipped integrity read")
}
}
+60
View File
@@ -0,0 +1,60 @@
package runtime
import (
"context"
"errors"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
func TestSteeringImagesPersistAndRetryWithoutDuplicate(t *testing.T) {
store := session.NewStore(t.TempDir())
if err := store.Create("a", "key"); err != nil {
t.Fatal(err)
}
sess, err := store.LoadExclusive("a", "key")
if err != nil {
t.Fatal(err)
}
message := SteeringMessage{ID: "with-image", Text: "inspect this", Images: []llm.ImageContent{{MimeType: "image/png", Data: []byte("pixels")}}}
ackErr := errors.New("acknowledgement unavailable")
message.Acknowledge = func() error { return ackErr }
ctx := WithSteering(context.Background(), func(context.Context) (*SteeringMessage, error) { return &message, nil })
rt := &Runtime{Session: sess}
if applied, err := rt.applySteering(ctx, nil); !applied || !errors.Is(err, ackErr) {
t.Fatal(applied, err)
}
if err := sess.Close(); err != nil {
t.Fatal(err)
}
sess, err = store.LoadExclusive("a", "key")
if err != nil {
t.Fatal(err)
}
defer sess.Close()
rt.Session = sess
before := len(sess.Entries())
ack := false
message.Acknowledge = func() error { ack = true; return nil }
if applied, err := rt.applySteering(ctx, nil); err != nil || applied || !ack || len(sess.Entries()) != before {
t.Fatal("image retry duplicated or conflicted", applied, err, ack)
}
message.Images[0].Data = []byte("different")
if _, err := rt.applySteering(ctx, nil); err == nil {
t.Fatal("conflicting image identity accepted")
}
}
func TestSteeringImagesValidateBeforeSkippingTools(t *testing.T) {
rt := &Runtime{Session: session.NewSession("a", "key")}
message := SteeringMessage{ID: "bad-image", Text: "inspect", Images: []llm.ImageContent{{Data: []byte("pixels")}}}
ctx := WithSteering(context.Background(), func(context.Context) (*SteeringMessage, error) { return &message, nil })
if _, err := rt.applySteering(ctx, []llm.ToolCall{{ID: "pending", Name: "read"}}); err == nil {
t.Fatal("invalid image accepted")
}
if len(rt.Session.Entries()) != 0 {
t.Fatal("invalid steering changed proposed tool history")
}
}
+111
View File
@@ -0,0 +1,111 @@
package runtime
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
func TestSteeringStopsRemainingToolsAndAcknowledgesDurably(t *testing.T) {
exec := newTimedExecutor()
exec.addTool("read")
exec.markSafe("read")
first := &llm.ToolCall{ID: "one", Name: "read", Input: json.RawMessage(`{}`)}
second := &llm.ToolCall{ID: "two", Name: "read", Input: json.RawMessage(`{}`)}
provider := &scriptedStreamLLM{events: []scriptedStreamEvent{{typ: llm.EventToolCallDone, toolCall: first}, {typ: llm.EventToolCallDone, toolCall: second}, {typ: llm.EventDone}}}
store := session.NewStore(t.TempDir())
if err := store.Create("a", "k"); err != nil {
t.Fatal(err)
}
sess, err := store.LoadExclusive("a", "k")
if err != nil {
t.Fatal(err)
}
rt := &Runtime{LLM: provider, Tools: exec, Session: sess, AgentID: "a", Model: "test", MaxTurns: 3, AgentLoop: LoopConfig{StreamingTools: true}}
ack := false
ctx := WithSteering(context.Background(), func(context.Context) (*SteeringMessage, error) {
if exec.callCount() == 0 || ack {
return nil, nil
}
return &SteeringMessage{ID: "correction", Text: "Stop reading and answer", Acknowledge: func() error { ack = true; return nil }}, nil
})
if _, err := rt.RunSync(ctx, "go", nil); err != nil {
t.Fatal(err)
}
if exec.callCount() != 1 || !ack {
t.Fatal("remaining tool ran or correction lost", exec.callCount(), ack)
}
if err := sess.Close(); err != nil {
t.Fatal(err)
}
sess, err = store.LoadExclusive("a", "k")
if err != nil {
t.Fatal(err)
}
defer sess.Close()
calls, results, corrections := 0, 0, 0
for _, entry := range sess.Entries() {
switch entry.Type {
case session.EntryTypeToolCall:
calls++
case session.EntryTypeToolResult:
results++
}
if entry.ID == "steering_correction" {
corrections++
}
}
if calls != 2 || results != 2 || corrections != 1 {
t.Fatal(calls, results, corrections)
}
rt.Session = sess
before := len(sess.Entries())
ctx = WithSteering(context.Background(), func(context.Context) (*SteeringMessage, error) {
return &SteeringMessage{ID: "correction", Text: "Stop reading and answer"}, nil
})
if applied, err := rt.applySteering(ctx, nil); err != nil || applied || len(sess.Entries()) != before {
t.Fatal("redelivery duplicated input", applied, err)
}
}
func TestSteeringDoesNotAcknowledgePersistenceFailure(t *testing.T) {
store := session.NewStore(t.TempDir())
if err := store.Create("a", "k"); err != nil {
t.Fatal(err)
}
sess, err := store.LoadExclusive("a", "k")
if err != nil {
t.Fatal(err)
}
if err := sess.Close(); err != nil {
t.Fatal(err)
}
ack := false
rt := &Runtime{Session: sess}
ctx := WithSteering(context.Background(), func(context.Context) (*SteeringMessage, error) {
return &SteeringMessage{ID: "x", Text: "correction", Acknowledge: func() error { ack = true; return nil }}, nil
})
if _, err := rt.applySteering(ctx, nil); err == nil || ack {
t.Fatal("failed write acknowledged", err, ack)
}
}
func TestSteeringSourceErrorAndInvalidInputDoNotWrite(t *testing.T) {
rt := &Runtime{Session: session.NewSession("a", "k")}
sentinel := errors.New("queue unavailable")
ctx := WithSteering(context.Background(), func(context.Context) (*SteeringMessage, error) { return nil, sentinel })
if _, err := rt.applySteering(ctx, nil); !errors.Is(err, sentinel) {
t.Fatal(err)
}
ctx = WithSteering(context.Background(), func(context.Context) (*SteeringMessage, error) { return &SteeringMessage{ID: "x", Text: " "}, nil })
if _, err := rt.applySteering(ctx, nil); err == nil {
t.Fatal("invalid correction accepted")
}
if len(rt.Session.Entries()) != 0 {
t.Fatal("failed steering changed history")
}
}
+28
View File
@@ -1,6 +1,10 @@
package runtime
import (
"context"
"errors"
"fmt"
"github.com/sausheong/harness/session"
"os"
"github.com/sausheong/harness/llm"
@@ -51,3 +55,27 @@ func drainKickoffs(kickoffs map[string]chan kickoffResult) {
<-ch
}
}
// persistKickoff reconciles one joined tool without rewriting a completed
// result as cancelled. Persistence must outlive run cancellation so completed
// output and image references are not lost when the provider fails.
func (r *Runtime) persistKickoff(ctx context.Context, kp kickoffResult, thread *[]Message) error {
persistCtx := context.WithoutCancel(ctx)
callErr := r.Session.AppendContext(persistCtx, session.ToolCallEntry(kp.tc.ID, kp.tc.Name, kp.tc.Input))
entry := session.ToolResultWithArtifactsEntry(kp.tc.ID, kp.result.Output, kp.result.Error, convertToolResultImages(kp.result.Images), resultArtifacts(kp.result))
content := kp.result.Output
if kp.result.Error != "" {
content = "[error] " + kp.result.Error
}
if kp.aborted {
entry = session.AbortedToolResultWithReasonEntry(kp.tc.ID, toolAbortReason(ctx))
content = "[error] " + toolAbortReason(ctx)
}
resultErr := r.Session.AppendContext(persistCtx, entry)
if thread != nil {
r.kgMu.Lock()
*thread = append(*thread, Message{Role: "assistant", Content: fmt.Sprintf("[tool: %s]\n%s", kp.tc.Name, string(kp.tc.Input))}, Message{Role: "user", Content: content})
r.kgMu.Unlock()
}
return errors.Join(callErr, resultErr)
}
+188
View File
@@ -0,0 +1,188 @@
package runtime
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/sausheong/harness/budget"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
type interruptedToolProvider struct {
recordingProvider
started <-chan struct{}
cause error
usage *llm.Usage
waitDeadline bool
}
func (p *interruptedToolProvider) ChatStream(ctx context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
out := make(chan llm.ChatEvent)
go func() {
defer close(out)
tc := llm.ToolCall{ID: "running-read", Name: "read", Input: json.RawMessage(`{}`)}
for _, typ := range []llm.EventType{llm.EventToolCallStart, llm.EventToolCallDone} {
select {
case out <- llm.ChatEvent{Type: typ, ToolCall: &tc}:
case <-ctx.Done():
return
}
}
select {
case <-p.started:
case <-ctx.Done():
return
}
// The terminal error is deliberately emitted only AFTER the concurrent
// tool has started, so a sequential implementation cannot pass this test.
if p.waitDeadline {
<-ctx.Done()
return
}
terminal := llm.ChatEvent{Type: llm.EventError, Error: p.cause}
if p.usage != nil {
terminal = llm.ChatEvent{Type: llm.EventDone, Usage: p.usage}
}
select {
case out <- terminal:
case <-ctx.Done():
}
}()
return out, nil
}
func TestStreamingBudgetExhaustionJoinsAndPersistsStartedTool(t *testing.T) {
for _, kind := range []string{"deadline", "token_settlement", "cost_settlement", "provider_error"} {
cause := budget.ErrTimeExhausted
switch kind {
case "token_settlement":
cause = budget.ErrExhausted
case "cost_settlement":
cause = budget.ErrCostExhausted
case "provider_error":
cause = errors.New("provider failed after tool start")
}
t.Run(kind, func(t *testing.T) {
t.Setenv("HARNESS_STREAMING_TOOLS", "1")
store := session.NewStore(t.TempDir())
if err := store.Create("a", "stream-budget"); err != nil {
t.Fatal(err)
}
sess, err := store.LoadExclusive("a", "stream-budget")
if err != nil {
t.Fatal(err)
}
defer func() {
if sess != nil {
sess.Close()
}
}()
started := make(chan struct{})
exec := newTimedExecutor()
exec.addTool("read")
exec.markSafe("read")
exec.blockUntil = make(chan struct{})
exec.onExecuteStart = func() { close(started) }
p := &interruptedToolProvider{started: started, cause: cause}
rt := &Runtime{Session: sess, LLM: p, Tools: exec, Model: "fixture", MaxTurns: 1}
switch kind {
case "deadline":
p.waitDeadline = true
if err = rt.DecideTimeBudget(context.Background(), time.Second); err != nil {
t.Fatal(err)
}
case "token_settlement":
p.usage = &llm.Usage{InputTokens: 2000000, OutputTokens: 1}
if err = rt.DecideTokenBudget(context.Background(), 100000); err != nil {
t.Fatal(err)
}
case "cost_settlement":
p.usage = &llm.Usage{InputTokens: 2000000, OutputTokens: 1}
rt.Route = llm.CallRoute{Provider: "local", Destination: "fixture"}
if err = rt.SetCostPrices(context.Background(), []budget.PriceSnapshot{runtimeFixturePrice(rt.Route, rt.Model)}); err != nil {
t.Fatal(err)
}
if err = rt.DecideCostBudget(context.Background(), "USD", 100000, true); err != nil {
t.Fatal(err)
}
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
events, err := rt.Run(ctx, "read", nil)
if err != nil {
t.Fatal(err)
}
done := make(chan bool, 1)
go func() {
found := false
for ev := range events {
if errors.Is(ev.Error, cause) {
found = true
}
}
done <- found
}()
select {
case found := <-done:
if !found {
t.Fatal("budget cause lost")
}
case <-time.After(2 * time.Second):
cancel()
<-done
t.Fatal("stream failure did not stop and join running tool")
}
if err = sess.Close(); err != nil {
t.Fatal(err)
}
sess = nil
sess, err = store.LoadExclusive("a", "stream-budget")
if err != nil {
t.Fatal(err)
}
if kind == "token_settlement" {
ledger, e := budget.OpenTokenLedger(sess)
if e != nil {
t.Fatal(e)
}
state, e := ledger.State()
if e != nil || !state.Exhausted || state.Committed != 2000001 {
t.Fatalf("token ledger %+v %v", state, e)
}
}
if kind == "cost_settlement" {
ledger, e := budget.OpenCostLedger(sess)
if e != nil {
t.Fatal(e)
}
state, e := ledger.State()
if e != nil || !state.Exhausted || state.CommittedNano != 2000001 {
t.Fatalf("cost ledger %+v %v", state, e)
}
}
calls, results := 0, 0
for _, e := range sess.View() {
if e.Type == session.EntryTypeToolCall {
calls++
}
if e.Type == session.EntryTypeToolResult {
results++
var d session.ToolResultData
if err = json.Unmarshal(e.Data, &d); err != nil {
t.Fatal(err)
}
if d.ToolCallID != "running-read" || !d.Aborted || !d.IsError || !strings.Contains(d.Error, cause.Error()) {
t.Fatalf("bad result: %+v", d)
}
}
}
if calls != 1 || results != 1 {
t.Fatalf("lost pair: calls=%d results=%d", calls, results)
}
})
}
}
+176
View File
@@ -0,0 +1,176 @@
package runtime
import (
"context"
"encoding/json"
"errors"
"sync/atomic"
"testing"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
)
type mixedToolExecutor struct {
*timedExecutor
running chan struct{}
pendingInvoked atomic.Bool
}
func (e *mixedToolExecutor) Execute(ctx context.Context, name string, in json.RawMessage) (tool.ToolResult, error) {
if name == "pending" {
e.pendingInvoked.Store(true)
}
if name == "running" {
close(e.running)
<-ctx.Done()
return tool.ToolResult{}, ctx.Err()
}
return tool.ToolResult{Output: "completed evidence"}, nil
}
type mixedToolProvider struct {
recordingProvider
order []string
running, completed <-chan struct{}
cause error
}
func (p *mixedToolProvider) ChatStream(ctx context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
out := make(chan llm.ChatEvent)
go func() {
defer close(out)
for _, name := range p.order {
tc := llm.ToolCall{ID: name, Name: name, Input: json.RawMessage(`{}`)}
for _, typ := range []llm.EventType{llm.EventToolCallStart, llm.EventToolCallDone} {
select {
case out <- llm.ChatEvent{Type: typ, ToolCall: &tc}:
case <-ctx.Done():
return
}
}
}
select {
case <-p.running:
case <-ctx.Done():
return
}
select {
case <-p.completed:
case <-ctx.Done():
return
}
select {
case out <- llm.ChatEvent{Type: llm.EventError, Error: p.cause}:
case <-ctx.Done():
}
}()
return out, nil
}
func TestStreamingReconcileMixedResults(t *testing.T) {
for _, order := range [][]string{{"running", "completed", "pending"}, {"completed", "running", "pending"}, {"completed"}} {
t.Run(order[0], func(t *testing.T) {
t.Setenv("HARNESS_STREAMING_TOOLS", "1")
store := session.NewStore(t.TempDir())
if err := store.Create("a", "mixed"); err != nil {
t.Fatal(err)
}
sess, err := store.LoadExclusive("a", "mixed")
if err != nil {
t.Fatal(err)
}
defer func() {
if sess != nil {
sess.Close()
}
}()
base := newTimedExecutor()
for _, name := range order {
base.addTool(name)
if name != "pending" {
base.markSafe(name)
}
}
exec := &mixedToolExecutor{timedExecutor: base, running: make(chan struct{})}
if len(order) == 1 {
close(exec.running)
}
completed := make(chan struct{})
cause := errors.New("interrupted mixed stream")
p := &mixedToolProvider{order: order, running: exec.running, completed: completed, cause: cause}
rt := &Runtime{Session: sess, LLM: p, Tools: exec, Model: "fixture", MaxTurns: 1}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
events, err := rt.Run(ctx, "mixed", nil)
if err != nil {
t.Fatal(err)
}
done := make(chan bool, 1)
go func() {
found := false
for ev := range events {
if ev.Type == EventToolResult && ev.ToolCall.ID == "completed" {
close(completed)
}
if errors.Is(ev.Error, cause) {
found = true
}
}
done <- found
}()
select {
case found := <-done:
if !found {
t.Error("original error lost")
}
case <-time.After(3 * time.Second):
t.Fatal("result reconciliation failed to join")
}
if exec.pendingInvoked.Load() {
t.Error("pending tool was executed after cancellation")
}
if err = sess.Close(); err != nil {
t.Fatal(err)
}
sess = nil
sess, err = store.LoadExclusive("a", "mixed")
if err != nil {
t.Fatal(err)
}
calls := map[string]int{}
results := map[string][]session.ToolResultData{}
for _, entry := range sess.View() {
if entry.Type == session.EntryTypeToolCall {
var d session.ToolCallData
if err = json.Unmarshal(entry.Data, &d); err != nil {
t.Fatal(err)
}
calls[d.ID]++
}
if entry.Type == session.EntryTypeToolResult {
var d session.ToolResultData
if err = json.Unmarshal(entry.Data, &d); err != nil {
t.Fatal(err)
}
results[d.ToolCallID] = append(results[d.ToolCallID], d)
}
}
for _, name := range order {
if calls[name] != 1 || len(results[name]) != 1 {
t.Errorf("%s pairs: %d/%d", name, calls[name], len(results[name]))
continue
}
d := results[name][0]
if name == "completed" {
if d.Aborted || d.IsError || d.Output != "completed evidence" {
t.Errorf("completed result changed: %+v", d)
}
} else if !d.Aborted || !d.IsError || d.Error != cause.Error() {
t.Errorf("bad aborted result: %+v", d)
}
}
})
}
}
+54
View File
@@ -0,0 +1,54 @@
package runtime
import (
"context"
"errors"
"time"
"github.com/sausheong/harness/budget"
)
func (r *Runtime) DecideTimeBudget(ctx context.Context, allowance time.Duration) error {
if !r.runMu.TryLock() {
return errors.New("runtime is already running")
}
defer r.runMu.Unlock()
if r.Compaction != nil && r.Compaction.HasInFlight(r.Session) {
return errors.New("compaction is running")
}
return budget.DecideDeadline(ctx, r.Session, allowance)
}
func (r *Runtime) TimeBudget(ctx context.Context) (budget.DeadlineState, error) {
if !r.runMu.TryLock() {
return budget.DeadlineState{}, errors.New("runtime is already running")
}
defer r.runMu.Unlock()
if err := ctx.Err(); err != nil {
return budget.DeadlineState{}, err
}
return budget.ReadDeadline(r.Session)
}
// SessionDeadlineContext is for owned operations such as manual compaction.
// The caller must join child work before invoking the returned cancel function.
func (r *Runtime) SessionDeadlineContext(ctx context.Context) (context.Context, context.CancelFunc, error) {
if !r.runMu.TryLock() {
return ctx, func() {}, errors.New("runtime is already running")
}
defer r.runMu.Unlock()
return budget.WithDeadline(ctx, r.Session)
}
func abortedEvent(ctx context.Context) AgentEvent {
if cause := context.Cause(ctx); cause != nil && cause != context.Canceled {
return AgentEvent{Type: EventError, Error: cause}
}
return AgentEvent{Type: EventAborted}
}
// Preserve explicit cancellation causes without attributing deadlines to users.
func toolAbortReason(ctx context.Context) string {
if cause := context.Cause(ctx); cause != nil && cause != context.Canceled {
return cause.Error()
}
return "aborted by user"
}
+123
View File
@@ -0,0 +1,123 @@
//go:build darwin || linux
package runtime
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"testing"
"time"
"github.com/sausheong/harness/budget"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/sausheong/harness/tools/bash"
)
func TestTimeBudgetStopsShellDescendantAndPersistsPair(t *testing.T) {
for _, mode := range []string{"0", "1"} {
t.Run("streaming_"+mode, func(t *testing.T) {
t.Setenv("HARNESS_STREAMING_TOOLS", mode)
checkTimeBudgetShell(t)
})
}
}
func checkTimeBudgetShell(t *testing.T) {
work := t.TempDir()
store := session.NewStore(t.TempDir())
if err := store.Create("a", "shell-deadline"); err != nil {
t.Fatal(err)
}
sess, err := store.LoadExclusive("a", "shell-deadline")
if err != nil {
t.Fatal(err)
}
defer func() {
if sess != nil {
sess.Close()
}
}()
tc := llm.ToolCall{ID: "deadline-shell", Name: "bash", Input: json.RawMessage(`{"command":"printf started > started; (sleep 3; printf survived > survived) & wait"}`)}
provider := &mockLLMProvider{events: []llm.ChatEvent{{Type: llm.EventToolCallStart, ToolCall: &tc}, {Type: llm.EventToolCallDone, ToolCall: &tc}, {Type: llm.EventDone}}}
registry := tool.NewRegistry()
registry.Register(&bash.BashTool{WorkDir: work})
rt := &Runtime{Session: sess, LLM: provider, Tools: registry, Model: "fixture", AgentID: "a", MaxTurns: 2}
if err = rt.DecideTimeBudget(context.Background(), time.Second); err != nil {
t.Fatal(err)
}
begin := time.Now()
events, err := rt.Run(context.Background(), "exercise deadline", nil)
if err != nil {
t.Fatal(err)
}
ended := make(chan bool, 1)
go func() {
exhausted := false
for event := range events {
if errors.Is(event.Error, budget.ErrTimeExhausted) {
exhausted = true
}
}
ended <- exhausted
}()
select {
case exhausted := <-ended:
if !exhausted {
t.Fatal("time exhaustion cause lost")
}
case <-time.After(6 * time.Second):
t.Fatal("shell operation failed to join")
}
if _, err = os.Stat(filepath.Join(work, "started")); err != nil {
t.Fatal("shell never started", err)
}
// Wait beyond the descendant's scheduled write: returning alone does not
// establish that the owned process group stopped.
if remaining := 3500*time.Millisecond - time.Since(begin); remaining > 0 {
time.Sleep(remaining)
}
if _, err = os.Stat(filepath.Join(work, "survived")); !os.IsNotExist(err) {
t.Fatalf("descendant survived expiry: %v", err)
}
if err = sess.Close(); err != nil {
t.Fatal(err)
}
sess = nil
sess, err = store.LoadExclusive("a", "shell-deadline")
if err != nil {
t.Fatal(err)
}
calls, results := 0, 0
for _, entry := range sess.View() {
if entry.Type == session.EntryTypeToolCall {
var data session.ToolCallData
if err = json.Unmarshal(entry.Data, &data); err != nil {
t.Fatal(err)
}
if data.ID == tc.ID {
calls++
}
}
if entry.Type == session.EntryTypeToolResult {
var data session.ToolResultData
if err = json.Unmarshal(entry.Data, &data); err != nil {
t.Fatal(err)
}
if data.ToolCallID == tc.ID {
results++
if !data.Aborted || !data.IsError || data.Error != budget.ErrTimeExhausted.Error() {
t.Fatalf("cancelled tool recorded success: %+v", data)
}
}
}
}
if calls != 1 || results != 1 {
t.Fatalf("persisted calls=%d results=%d", calls, results)
}
t.Logf("deadline process/descendant check and reopen completed in %s", time.Since(begin))
}
+81
View File
@@ -0,0 +1,81 @@
package runtime
import (
"context"
"errors"
"testing"
"time"
"github.com/sausheong/harness/budget"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
)
type deadlineProvider struct {
recordingProvider
started, stopped chan struct{}
}
func (p *deadlineProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
close(p.started)
out := make(chan llm.ChatEvent)
go func() { defer close(out); <-ctx.Done(); close(p.stopped) }()
return out, nil
}
func TestTimeBudgetCancelsRunningProviderAndBlocksNextRun(t *testing.T) {
ctx := context.Background()
p := &deadlineProvider{started: make(chan struct{}), stopped: make(chan struct{})}
r := &Runtime{Session: session.NewSession("a", "deadline"), LLM: p, Tools: tool.NewRegistry(), Model: "fixture", MaxTurns: 1}
if err := r.DecideTimeBudget(ctx, time.Second); err != nil {
t.Fatal(err)
}
events, err := r.Run(ctx, "wait", nil)
if err != nil {
t.Fatal(err)
}
select {
case <-p.started:
case <-time.After(3 * time.Second):
t.Fatal("provider not started")
}
finished := make(chan bool, 1)
go func() {
exhausted := false
for event := range events {
if errors.Is(event.Error, budget.ErrTimeExhausted) {
exhausted = true
}
}
finished <- exhausted
}()
select {
case exhausted := <-finished:
if !exhausted {
t.Fatal("deadline lost budget outcome")
}
case <-time.After(3 * time.Second):
t.Fatal("runtime failed to join after deadline")
}
select {
case <-p.stopped:
case <-time.After(time.Second):
t.Fatal("provider did not observe cancellation")
}
if _, err = r.Run(ctx, "cannot renew", nil); !errors.Is(err, budget.ErrTimeExhausted) {
t.Fatalf("expired new run: %v", err)
}
}
func TestToolAbortReason(t *testing.T) {
user, cancel := context.WithCancel(context.Background())
cancel()
if got := toolAbortReason(user); got != "aborted by user" {
t.Fatal(got)
}
deadline, stop := context.WithCancelCause(context.Background())
stop(budget.ErrTimeExhausted)
if got := toolAbortReason(deadline); got != budget.ErrTimeExhausted.Error() {
t.Fatal(got)
}
}
+76
View File
@@ -0,0 +1,76 @@
package runtime
import (
"context"
"errors"
"github.com/sausheong/harness/budget"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tokens"
)
type tokenBudgetContextKey struct{ session *session.Session }
// DecideTokenBudget records an explicit absolute session token ceiling. It may
// resume exhaustion, but never erases prior charges or uncertain reservations.
func (r *Runtime) DecideTokenBudget(ctx context.Context, limit int64) error {
if !r.runMu.TryLock() {
return errors.New("runtime is already running")
}
defer r.runMu.Unlock()
if r.Compaction != nil && r.Compaction.HasInFlight(r.Session) {
return errors.New("compaction is running")
}
ledger, err := budget.OpenTokenLedger(r.Session)
if err != nil {
return err
}
return ledger.Decide(ctx, limit)
}
func (r *Runtime) TokenBudget(ctx context.Context) (budget.TokenState, error) {
if !r.runMu.TryLock() {
return budget.TokenState{}, errors.New("runtime is already running")
}
defer r.runMu.Unlock()
if err := ctx.Err(); err != nil {
return budget.TokenState{}, err
}
ledger, err := budget.OpenTokenLedger(r.Session)
if err != nil {
return budget.TokenState{}, err
}
return ledger.State()
}
// tokenBudgetContext is called under runMu. A session without a configured
// ceiling retains existing behaviour. A configured ceiling is reloaded on every
// admission, including after restart. Inherited parent guards remain attached.
func (r *Runtime) tokenBudgetContext(ctx context.Context) (context.Context, error) {
if r.Session == nil {
return ctx, nil
}
key := tokenBudgetContextKey{r.Session}
if ctx.Value(key) != nil {
return ctx, nil
}
ledger, err := budget.OpenTokenLedger(r.Session)
if err != nil {
return ctx, err
}
state, err := ledger.State()
if err != nil {
return ctx, err
}
if state.Limit == 0 {
return ctx, nil
}
guard := ledger.Admission(func(req llm.ChatRequest) (int64, error) {
prompt := req.SystemPrompt
if len(req.SystemPromptParts) > 0 {
prompt = llm.JoinSystemPromptParts(req.SystemPromptParts)
}
return int64(tokens.Estimate(req.Messages, prompt, req.Tools)), nil
})
return context.WithValue(llm.WithCallAdmission(ctx, guard), key, true), nil
}
+75
View File
@@ -0,0 +1,75 @@
package runtime
import (
"context"
"errors"
"testing"
"github.com/sausheong/harness/budget"
"github.com/sausheong/harness/compaction"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
)
func TestTokenBudgetGovernsRuntimeAndManualCompaction(t *testing.T) {
ctx := context.Background()
provider := &recordingProvider{reply: "<summary>done</summary>"}
s := session.NewSession("a", "budget")
r := &Runtime{Session: s, LLM: provider, Model: "fixture", Tools: tool.NewRegistry(), MaxTurns: 1}
if err := r.DecideTokenBudget(ctx, 1); err != nil {
t.Fatal(err)
}
events, err := r.Run(ctx, "hello", nil)
if err != nil {
t.Fatal(err)
}
exhausted := false
for event := range events {
if errors.Is(event.Error, budget.ErrExhausted) {
exhausted = true
}
}
if !exhausted || len(provider.requests) != 0 {
t.Fatal("exhausted runtime dispatched provider or lost cause")
}
state, err := r.TokenBudget(ctx)
if err != nil || !state.Exhausted {
t.Fatalf("state %+v %v", state, err)
}
if err = r.DecideTokenBudget(ctx, 100000); err != nil {
t.Fatal(err)
}
events, err = r.Run(ctx, "continue", nil)
if err != nil {
t.Fatal(err)
}
for range events {
}
state, err = r.TokenBudget(ctx)
if err != nil || len(state.Attempts) != 1 || state.Attempts[0].Category != llm.CallGeneration {
t.Fatalf("state %+v %v", state, err)
}
for i := 0; i < 10; i++ {
s.Append(session.UserMessageEntry("task"))
s.Append(session.AssistantMessageEntry("evidence"))
}
manager := &compaction.Manager{Summarizer: &compaction.Summarizer{Provider: provider, Model: "fixture", MaxOutputTokens: 100}, PreserveTurns: 2}
manual, err := r.CompactionContext(ctx)
if err != nil {
t.Fatal(err)
}
// Reusing a prepared context must not reserve twice against this session.
manual, err = r.CompactionContext(manual)
if err != nil {
t.Fatal(err)
}
result, err := manager.MaybeCompact(manual, s, compaction.ReasonManual, "")
if err != nil || !result.Compacted {
t.Fatalf("result %+v err %v", result, err)
}
state, err = r.TokenBudget(ctx)
if err != nil || len(state.Attempts) != 2 || state.Attempts[1].Category != llm.CallCompaction || state.Committed <= 0 {
t.Fatalf("state %+v err %v", state, err)
}
}
+16
View File
@@ -0,0 +1,16 @@
package runtime
import "fmt"
// Provider IDs identify result ownership within a single response. Never
// overwrite a running result channel or dispatch an ambiguous second call.
func acceptToolCallID(seen map[string]bool, id string) error {
if id == "" {
return fmt.Errorf("provider returned an empty tool call ID")
}
if seen[id] {
return fmt.Errorf("provider returned a duplicate tool call ID")
}
seen[id] = true
return nil
}
+78
View File
@@ -0,0 +1,78 @@
package runtime
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
func TestMalformedToolCallIDsCannotExecuteTwice(t *testing.T) {
for _, mode := range []string{"streaming", "sequential", "runturn"} {
for _, kind := range []string{"duplicate", "empty"} {
t.Run(mode+"_"+kind, func(t *testing.T) {
t.Setenv("HARNESS_STREAMING_TOOLS", "0")
if mode == "streaming" {
t.Setenv("HARNESS_STREAMING_TOOLS", "1")
}
tc := llm.ToolCall{ID: "same", Name: "read", Input: json.RawMessage(`{}`)}
if kind == "empty" {
tc.ID = ""
}
scripted := []llm.ChatEvent{{Type: llm.EventToolCallStart, ToolCall: &tc}, {Type: llm.EventToolCallDone, ToolCall: &tc}}
if kind == "duplicate" {
scripted = append(scripted, llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &tc})
}
scripted = append(scripted, llm.ChatEvent{Type: llm.EventDone})
exec := newTimedExecutor()
exec.addTool("read")
exec.markSafe("read")
rt := &Runtime{Session: session.NewSession("a", "ids"), LLM: &mockLLMProvider{events: scripted}, Tools: exec, Model: "fixture", MaxTurns: 1}
var terminal error
if mode == "runturn" {
result, err := rt.RunTurn(context.Background(), "read", nil, nil)
terminal = err
if terminal == nil {
terminal = result.Err
}
} else {
events, err := rt.Run(context.Background(), "read", nil)
if err != nil {
t.Fatal(err)
}
for ev := range events {
if ev.Type == EventError {
terminal = ev.Error
}
}
}
if terminal == nil || !strings.Contains(terminal.Error(), "tool call ID") {
t.Fatalf("missing identity error: %v", terminal)
}
allowed := 0
if mode == "streaming" && kind == "duplicate" {
allowed = 1
}
if exec.callCount() > allowed {
t.Fatalf("executed %d calls, maximum %d", exec.callCount(), allowed)
}
seen := map[string]bool{}
for _, e := range rt.Session.View() {
if e.Type == session.EntryTypeToolCall {
var d session.ToolCallData
if err := json.Unmarshal(e.Data, &d); err != nil {
t.Fatal(err)
}
if d.ID == "" || seen[d.ID] {
t.Fatalf("invalid persisted identity %q", d.ID)
}
seen[d.ID] = true
}
}
})
}
}
}
+55
View File
@@ -0,0 +1,55 @@
package runtime
import (
"context"
"errors"
"unicode/utf8"
"github.com/sausheong/harness/llm"
)
// ToolContextText is an editable projection of a tool-result message. Index is
// its host-owned request position; role, identity and error metadata are absent.
type ToolContextText struct {
Index int
Text string
}
const MaxTransformedToolTextBytes = 256 << 10
func (r *Runtime) observeChat(ctx context.Context, req llm.ChatRequest, category llm.CallCategory, call func(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error)) (<-chan llm.ChatEvent, error) {
hook := r.AgentLoop.Hooks.TransformToolContext
if hook != nil {
input := []ToolContextText{}
for i, message := range req.Messages {
if (message.Role == "user" || message.Role == "tool") && message.ToolCallID != "" {
input = append(input, ToolContextText{Index: i, Text: message.Content})
}
}
if len(input) > 0 {
// Preserve an independent list of host-owned indices even if the hook edits
// its input slice in place. Strings cannot mutate recorded message bytes.
expected := append([]ToolContextText(nil), input...)
output, err := hook(ctx, input)
if err != nil {
return nil, err
}
if err = ctx.Err(); err != nil {
return nil, err
}
if len(output) != len(expected) {
return nil, errors.New("tool context transform changed message count")
}
for i, item := range output {
if item.Index != expected[i].Index || len(item.Text) > MaxTransformedToolTextBytes || !utf8.ValidString(item.Text) {
return nil, errors.New("invalid transformed tool context")
}
}
req.Messages = append([]llm.Message(nil), req.Messages...)
for _, item := range output {
req.Messages[item.Index].Content = item.Text
}
}
}
return llm.ObserveChat(ctx, req, category, call)
}
+70
View File
@@ -0,0 +1,70 @@
package runtime
import (
"context"
"errors"
"github.com/sausheong/harness/llm"
"strings"
"testing"
)
func TestToolContextProjectionPreservesProtectedRequest(t *testing.T) {
original := []llm.Message{{Role: "system", Content: "policy"}, {Role: "user", Content: "instruction"}, {Role: "user", ToolCallID: "tool-1", Content: " original ", IsError: true}}
req := llm.ChatRequest{Messages: original}
r := &Runtime{}
r.AgentLoop.Hooks.TransformToolContext = func(ctx context.Context, items []ToolContextText) ([]ToolContextText, error) {
if len(items) != 1 || items[0].Index != 2 {
t.Fatal(items)
}
items[0].Text = "transformed"
return items, nil
}
called := false
stream, err := r.observeChat(context.Background(), req, llm.CallGeneration, func(ctx context.Context, got llm.ChatRequest) (<-chan llm.ChatEvent, error) {
called = true
if got.Messages[0].Content != "policy" || got.Messages[1].Content != "instruction" || got.Messages[2].Content != "transformed" || got.Messages[2].ToolCallID != "tool-1" || !got.Messages[2].IsError {
t.Fatal(got.Messages)
}
ch := make(chan llm.ChatEvent)
close(ch)
return ch, nil
})
if stream != nil {
for range stream {
}
}
if err != nil || !called || original[2].Content != " original " {
t.Fatal("request or source mutation", err, original)
}
}
func TestToolContextRejectsInvalidBatchBeforeProvider(t *testing.T) {
for _, mode := range []string{"protected-index", "missing", "large", "error", "cancel"} {
t.Run(mode, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
r := &Runtime{}
r.AgentLoop.Hooks.TransformToolContext = func(ctx context.Context, items []ToolContextText) ([]ToolContextText, error) {
switch mode {
case "protected-index":
items[0].Index = 0
case "missing":
return nil, nil
case "large":
items[0].Text = strings.Repeat("x", MaxTransformedToolTextBytes+1)
case "error":
return nil, errors.New("mandatory transform failed")
case "cancel":
cancel()
}
return items, nil
}
_, err := r.observeChat(ctx, llm.ChatRequest{Messages: []llm.Message{{Role: "user", Content: "protected"}, {Role: "user", ToolCallID: "id", Content: "original"}}}, llm.CallGeneration, func(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
t.Fatal("provider called after invalid transform")
return nil, nil
})
if err == nil {
t.Fatal("invalid transform succeeded")
}
})
}
}
+20 -2
View File
@@ -37,12 +37,15 @@ type AgentSpec struct {
// SystemPrompt overrides the built-in default identity. Empty ⇒
// BuildStaticSystemPrompt composes a default identity string from
// the registered tool names.
SystemPrompt string
SystemPrompt string
SystemPromptSources []ContextSource
// MaxTurns caps the tool-use loop (default 25 when 0).
MaxTurns int
// ContextWindow overrides the auto-detected window from
// tokens.ContextWindow. 0 ⇒ auto-detect.
ContextWindow int
// MaxOutputTokens bounds each generation request. Zero retains the 8192 default.
MaxOutputTokens int
// Reasoning maps to each provider's native reasoning knob. Use
// llm.ReasoningOff (zero value), Low, Medium, or High.
Reasoning string
@@ -101,6 +104,21 @@ type HookDecision struct {
// that hook is skipped. Hooks run synchronously on the runtime
// goroutine; expensive work should be deferred by the implementation.
type LifecycleHooks struct {
// OnRunStart is an admission callback for each accepted Run or RunTurn call,
// after budget setup and before appending user input or contacting a provider.
// Failure aborts the call. RunTurn emits one lifecycle pair per invocation.
OnRunStart func(context.Context) error
// OnRunFinish observes the established outcome and cannot change it. The
// runtime supplies a cancellation-independent cleanup context capped at 2s.
OnRunFinish func(context.Context, string)
// TransformToolContext runs before each actual provider request, including
// retries, on tool text only. Preserve entry indices and count. Returned text
// is bounded to 256 KiB per entry and affects only the request copy, never
// persisted tool results. Errors abort before provider admission. Configure
// hooks before execution; implementations must respect context cancellation.
TransformToolContext func(context.Context, []ToolContextText) ([]ToolContextText, error)
// OnUserPromptSubmit fires once at the top of Run, BEFORE the
// user message is appended to the session. The hook may rewrite
// the prompt and/or images; the rewritten values are what the
@@ -133,7 +151,7 @@ type LifecycleHooks struct {
// static system prompt and resolve a skill body on demand via the
// load_skill tool. Optional — pass nil on Deps.Skills to disable.
//
// FormatIndex is called once at BuildRuntime time; the returned string
// FormatIndex is called at BuildRuntime time and safe request boundaries; the returned string
// is concatenated into the cacheable static system prompt. Get is wired
// through tool.LoadSkillTool's Lookup closure; load_skill.Execute
// calls it at agent-loop time.