5 Commits
Author SHA1 Message Date
sausheong 3ca0994437 Reject empty and truncated answers and expose complete tool calls 2026-09-11 23:48:25 +08:00
sausheong 019a38f111 Fix repeated stream finishes and preserve cancellation causes 2026-09-10 16:34:12 +08:00
Chang Sau Sheong 3170b28251 Merge pull request #5 from sausheong/codex/update-readme-v0.4.0
Document Harness v0.4.0 capabilities
2026-09-10 07:57:45 +08:00
sausheong 036fe1e547 Document Harness v0.4.0 capabilities 2026-09-10 07:45:54 +08:00
Chang Sau Sheong 4cec5b57f8 Merge pull request #4 from sausheong/codex/hand-release-v0.4.0
Prepare Harness v0.4.0: execution isolation and durable runtime
2026-09-10 01:15:20 +08:00
18 changed files with 409 additions and 27 deletions

No files matched your search

+63 -18
View File
@@ -5,7 +5,7 @@ streaming agent loop, tool registry, session storage, compaction, and
token budgeting needed to run a multi-provider agent in production. BYO
concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins.
> **Status: v0.3.9.** Latest tagged release. The `runtime` API
> **Status: v0.4.0.** Latest tagged release. The `runtime` API
> surface may still shift in the v0.x line — pin your version.
## Why Harness
@@ -26,6 +26,33 @@ opinions about how your agents should be deployed. There is no
`harness` binary. You import packages, compose a `Runtime`, and call
`rt.Run(ctx, msg, nil)`.
## What's in v0.4.0
v0.4.0 adds the operational controls needed by a production coding
agent while keeping Harness a composable Go library:
- **Explicit execution boundaries.** `execution.Host` labels commands
as unrestricted host execution. `execution.Container` uses an
immutable image ID, explicit mounts and environment, resource limits,
and fail-closed startup with no host fallback.
- **Request, token, cost, run, and time budgets.** Provider calls can be
admitted before dispatch and settled against reported usage. Unknown
usage remains unknown rather than being counted as zero.
- **Request-level usage accounting.** The ledger records main,
compaction, and other provider calls without double-counting cache
token subsets. See [`USAGE.md`](./USAGE.md).
- **Durable session evolution.** Versioned JSONL records, writer leases,
attachments, branches, annotations, crash recovery, and explicit,
backed-up migration from legacy sessions. See
[`SESSION_FORMAT.md`](./SESSION_FORMAT.md).
- **Steering and inspectable context.** Hosts can queue corrections at
joined tool boundaries, pin context, inspect composed state, and
retain stable tool-call identity. See
[`runtime/STEERING.md`](./runtime/STEERING.md).
- **Bounded process output and joined cleanup.** Commands and stdio MCP
servers use managed process groups on Unix, bounded inline output,
and optional private spill artifacts.
## What Harness is for
Harness is well-suited to:
@@ -107,7 +134,11 @@ in only what you need (e.g. `tools/file` without `tools/browser`).
```
github.com/sausheong/harness/
├── attachment/ # Bounded private attachment storage
├── budget/ # Token, cost, run and deadline budgets
├── execution/ # Explicit host/container execution backends
├── llm/ # LLMProvider interface, Message/ToolDef/ChatRequest types
├── process/ # Managed subprocesses and bounded output capture
├── session/ # Append-only session DAG (Session, SessionEntry, Store)
├── tokens/ # char/4 estimator + Calibrator + CalibratorStore
├── compaction/ # Three-stage summarize-and-splice manager
@@ -192,7 +223,7 @@ how to plug in hooks, MCP servers, skills, permissions, and more.
## Examples
Four end-to-end agents ship in [`examples/`](./examples). Each is a
Five end-to-end agents ship in [`examples/`](./examples). Each is a
self-contained `main.go` you can `go run`:
| Example | What it shows | API surface |
@@ -241,13 +272,14 @@ none of it.
## Components
A general agent harness has ~16 conceptual components: the loop, the
model invocation layer, the tool registry, permission gating,
A general agent harness spans the loop, the model invocation layer,
the tool registry, permission gating,
context/compaction, the system prompt, sub-agents, hooks, MCP, skills,
session persistence, writable memory, writable skills, a
self-improvement reviewer, UI, and entrypoints. harness implements the
in-process, library-shaped subset of those. The rest is left to the
caller — you own the binary, you own the UI, you own the channel.
self-improvement reviewer, budgets, execution boundaries, attachments,
UI, and entrypoints. Harness implements the in-process, library-shaped
subset of those. The rest is left to the caller — you own the binary,
you own the UI, you own the channel.
| # | Component | Where it lives in harness |
|---|---|---|
@@ -265,11 +297,14 @@ caller — you own the binary, you own the UI, you own the channel.
| 12 | **Writable memory** | `tool/memory` package: `MemoryStore` interface, `MemoryTool` (action-discriminated), JSONL on-disk default. Wraps any backend; `*jsonl.Store` doubles as a `runtime.MemoryProvider`. |
| 13 | **Writable skills** | `tool/skills` package: `SkillStore` interface, `SkillTool` (six actions: create/patch/replace/remove/list/get), directory-on-disk default. Patch supports surgical string-match with three error categories. |
| 14 | **Self-improvement reviewer** | `runtime.Review` — one-shot reviewer Runtime against a finished session. Designed to be called from `LifecycleHooks.OnStop` in a goroutine. Snapshots parent's session; shares Memory/Skills writes; recursion guard via `AgentID = "__review__"`. |
| 15 | **Budgets and usage** | `budget` + `llm.WithCallAdmission` / `WithUsageObserver` — pre-dispatch admission, request settlement, durable run/token/cost limits, deadlines, and reported-only accounting |
| 16 | **Execution boundary** | `execution.Backend` — explicitly labelled host execution or a fail-closed Docker container with an immutable image, allowlisted environment, mounts, limits, and joined cleanup |
| 17 | **Attachments and artifacts** | `attachment.Store`, session attachment records, and bounded process output artifacts with integrity checks and private storage |
Deliberately not in scope (numbers from the same conceptual list):
Deliberately not in scope:
- **15 — UI**: harness emits events; the caller renders.
- **16 — Entrypoints**: harness is a library. There is no `harness`
- **UI**: harness emits events; the caller renders.
- **Entrypoints**: harness is a library. There is no `harness`
binary. The example agents in `examples/` show how a binary is
assembled.
@@ -315,6 +350,14 @@ Deliberately not in scope (numbers from the same conceptual list):
`clientcredentials.Config.Client(ctx)`) as `HTTPClient` —
auto-refresh comes for free. Call `Runtime.Close()` to release
sessions.
- **Execution mode is an explicit trust decision.** `execution.Host`
has access to the caller's host authority and says so through
`Boundary()`. `execution.Container` requires a real Docker socket,
immutable `sha256:` image, explicit workspace and resources, and
never falls back to host execution. Network and workspace writes are
disabled unless enabled. MCP servers, hooks, and other in-process host
integrations remain outside that container boundary unless the caller
separately isolates them.
- **Six providers, one interface.** Anthropic, OpenAI, Gemini, LiteLLM,
OpenRouter, and local (Ollama, LM Studio, etc.) ship built-in — LiteLLM,
OpenRouter, and local cost none of that ~300 LOC each, since all three
@@ -351,9 +394,10 @@ these, you'll need to bring them yourself or layer them on top:
- **A skill / plugin marketplace.** Skills are `//go:embed` markdown
in your binary, or whatever your `SkillProvider` resolves at
runtime. There is no central registry.
- **Auth / billing / multi-tenant infrastructure.** Per-agent
policy lives in `PermissionChecker`; everything else is your
problem.
- **Authentication and multi-tenant infrastructure.** Per-agent policy
lives in `PermissionChecker`. Harness supplies accounting and budget
primitives, but the caller owns identity, tenancy, provider billing
reconciliation, and the durable policy service.
- **Shell-command hooks.** Hooks are typed Go callbacks on
`LifecycleHooks`, not subprocess invocations driven by a config
file.
@@ -374,18 +418,19 @@ hermetic:
LTA_DATAMALL_KEY=... go test -tags live ./examples/lta-agent/...
```
The runtime test suite includes some rare timing-sensitive cases —
if a streaming-tools test flakes once, re-run before treating it as
a real failure.
The release qualification workflow runs uncached race-enabled tests on
hosted Linux and macOS, reconciles the complete test inventory, rejects
skips and incomplete packages, and repeats critical process-lifecycle
tests. See [`scripts/QUALIFICATION.md`](./scripts/QUALIFICATION.md).
## Status
`v0.3.9` is the latest tagged release. The v0.x line follows Go
`v0.4.0` is the latest tagged release. The v0.x line follows Go
module semver: minor bumps may break API, patch bumps are bug-fix
only. Pin your dependency:
```bash
go get github.com/sausheong/harness@v0.3.9
go get github.com/sausheong/harness@v0.4.0
```
Likely sources of v0.x churn before a v1.0.0:
+6
View File
@@ -119,6 +119,7 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
}
var sb strings.Builder
var terminalReason string
for ev := range stream {
switch ev.Type {
case llm.EventTextDelta:
@@ -126,6 +127,8 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
return "", errors.New("summariser response exceeds 256 KiB")
}
sb.WriteString(ev.Text)
case llm.EventDone:
terminalReason = ev.StopReason
case llm.EventError:
return "", fmt.Errorf("compaction: stream error: %w", ev.Error)
}
@@ -133,6 +136,9 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
if err := callCtx.Err(); err != nil {
return "", err
}
if terminalReason == "length" || terminalReason == "max_tokens" {
return "", errors.New("summariser reached its output limit; original history retained")
}
out := strings.TrimSpace(sb.String())
if out == "" {
return "", ErrEmptySummary
+26
View File
@@ -0,0 +1,26 @@
package compaction
import (
"context"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"strings"
"testing"
)
type truncatedSummaryProvider struct{ llmtest.Base }
func (truncatedSummaryProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
ch := make(chan llm.ChatEvent, 2)
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Incomplete summary"}
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: "length"}
close(ch)
return ch, nil
}
func TestRejectTruncatedSummary(t *testing.T) {
s := Summarizer{Provider: truncatedSummaryProvider{}, Model: "fixture"}
out, err := s.callOnce(context.Background(), "history", "")
if err == nil || out != "" || !strings.Contains(err.Error(), "output limit") {
t.Fatalf("%q %v", out, err)
}
}
+42
View File
@@ -0,0 +1,42 @@
package openai
import (
"context"
"fmt"
"github.com/sausheong/harness/llm"
"net/http"
"net/http/httptest"
"testing"
)
func TestPreservesOutputLimitAndTrailingUsage(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, `data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"partial","type":"function","function":{"name":"bash","arguments":"{\"command\":"}}]},"finish_reason":"length"}]}`+"\n\n")
fmt.Fprint(w, `data: {"choices":[],"usage":{"prompt_tokens":50,"completion_tokens":2048,"total_tokens":2098}}`+"\n\ndata: [DONE]\n\n")
}))
defer srv.Close()
p := NewOpenAIProviderWithKind("fixture", srv.URL, "openai-compatible")
events, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "fixture"})
if err != nil {
t.Fatal(err)
}
found := false
for e := range events {
if e.Type == llm.EventToolCallDone {
t.Fatal("truncated tool accepted")
}
if e.Type == llm.EventError {
t.Fatal(e.Error)
}
if e.Type == llm.EventDone {
found = true
if e.StopReason != "length" || e.Usage == nil || e.Usage.OutputTokens != 2048 {
t.Fatalf("%+v", e)
}
}
}
if !found {
t.Fatal("missing terminal event")
}
}
+6 -1
View File
@@ -274,6 +274,7 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
toolCalls := make(map[int]*pendingTC)
var lastUsage *llm.Usage
var finishReason string
for {
resp, err := stream.Recv()
@@ -337,13 +338,17 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
// Finish reason
if choice.FinishReason != "" {
finishReason = string(choice.FinishReason)
}
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
emitToolCalls(events, toolCalls)
clear(toolCalls)
}
}
}
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage, StopReason: finishReason}
}()
return events, nil
+42
View File
@@ -0,0 +1,42 @@
package openai
import (
"context"
"fmt"
"github.com/sausheong/harness/llm"
"net/http"
"net/http/httptest"
"testing"
)
func TestRepeatedFinishEmitsToolOnlyOnce(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_one\",\"type\":\"function\",\"function\":{\"name\":\"bash\",\"arguments\":\"{}\"}}]}}]}\n\n")
for i := 0; i < 2; i++ {
fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n")
}
fmt.Fprint(w, "data: [DONE]\n\n")
}))
defer srv.Close()
p := NewOpenAIProviderWithKind("fixture", srv.URL, "openai-compatible")
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "fixture"})
if err != nil {
t.Fatal(err)
}
calls, done := 0, 0
for e := range stream {
if e.Type == llm.EventToolCallDone {
calls++
}
if e.Type == llm.EventDone {
done++
}
if e.Type == llm.EventError {
t.Fatal(e.Error)
}
}
if calls != 1 || done != 1 {
t.Fatalf("calls=%d done=%d", calls, done)
}
}
+2 -1
View File
@@ -24,7 +24,8 @@ func (p *attachmentReplayProvider) ChatStream(_ context.Context, req llm.ChatReq
for _, msg := range req.Messages {
p.images = append(p.images, msg.Images...)
}
events := make(chan llm.ChatEvent, 1)
events := make(chan llm.ChatEvent, 2)
events <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
events <- llm.ChatEvent{Type: llm.EventDone}
close(events)
return events, nil
+95
View File
@@ -0,0 +1,95 @@
package runtime
import (
"context"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"strings"
"testing"
)
type emptyResponseProvider struct {
llmtest.Base
responses [][]llm.ChatEvent
calls int
limits []int
}
func (p *emptyResponseProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.limits = append(p.limits, req.MaxTokens)
i := min(p.calls, len(p.responses)-1)
p.calls++
ch := make(chan llm.ChatEvent, len(p.responses[i]))
for _, e := range p.responses[i] {
ch <- e
}
close(ch)
return ch, nil
}
func TestEmptyAndTruncatedResponses(t *testing.T) {
done := llm.ChatEvent{Type: llm.EventDone, StopReason: "stop"}
text := llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
for _, tc := range []struct {
name string
responses [][]llm.ChatEvent
calls int
want string
}{
{"empty", [][]llm.ChatEvent{{done}}, 2, "no answer"},
{"recovery", [][]llm.ChatEvent{{done}, {text, done}}, 2, ""},
{"normal", [][]llm.ChatEvent{{text, done}}, 1, ""},
{"length", [][]llm.ChatEvent{{{Type: llm.EventDone, StopReason: "length", Usage: &llm.Usage{OutputTokens: 2048}}}}, 1, "output limit"},
{"partial", [][]llm.ChatEvent{{text, {Type: llm.EventDone, StopReason: "max_tokens"}}}, 1, "output limit"},
{"whitespace", [][]llm.ChatEvent{{{Type: llm.EventTextDelta, Text: " \n"}, done}}, 1, "no answer"},
{"thinking", [][]llm.ChatEvent{{{Type: llm.EventThinkingBlock, ThinkingBlock: &llm.ThinkingBlock{Thinking: "opaque"}}, done}}, 2, "no answer"},
} {
t.Run(tc.name, func(t *testing.T) {
p := &emptyResponseProvider{responses: tc.responses}
rt := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("test", "test"), Model: "fixture", MaxOutputTokens: 2048, MaxTurns: 2}
reason := ""
rt.AgentLoop.Hooks.OnStop = func(_ context.Context, r string) { reason = r }
events, err := rt.Run(context.Background(), "question", nil)
if err != nil {
t.Fatal(err)
}
var failure error
for e := range events {
if e.Type == EventError {
failure = e.Error
}
}
if tc.want == "" {
if failure != nil || reason != "completed" {
t.Fatalf("%v %s", failure, reason)
}
} else if failure == nil || !strings.Contains(failure.Error(), tc.want) || reason == "completed" {
t.Fatalf("%v %s", failure, reason)
}
if p.calls != tc.calls {
t.Fatalf("calls %d", p.calls)
}
for _, limit := range p.limits {
if limit != 2048 {
t.Fatalf("changed limit %d", limit)
}
}
})
}
}
func TestSingleTurnRejectsEmptyAndTruncatedResponses(t *testing.T) {
for _, reason := range []string{"stop", "length", "max_tokens"} {
t.Run(reason, func(t *testing.T) {
p := &emptyResponseProvider{responses: [][]llm.ChatEvent{{{Type: llm.EventDone, StopReason: reason}}}}
rt := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("test", "single"), Model: "fixture", MaxOutputTokens: 2048}
result, err := rt.RunTurn(context.Background(), "question", nil, nil)
if err != nil {
t.Fatal(err)
}
if result.Err == nil || result.StopReason == "completed" || p.calls != 1 {
t.Fatalf("%+v calls=%d", result, p.calls)
}
})
}
}
+2 -1
View File
@@ -20,7 +20,8 @@ func (p *outputLimitProvider) ChatStream(_ context.Context, r llm.ChatRequest) (
if p.fallback && len(p.limits) == 1 {
return nil, errors.New("529 overloaded")
}
ch := make(chan llm.ChatEvent, 1)
ch := make(chan llm.ChatEvent, 2)
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
ch <- llm.ChatEvent{Type: llm.EventDone}
close(ch)
return ch, nil
+7 -1
View File
@@ -29,6 +29,9 @@ func (p *requestUsageProvider) ChatStream(_ context.Context, req llm.ChatRequest
if p.calls < p.total {
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: req.Model, Name: "noop", Input: json.RawMessage(`{}`)}}
}
if p.calls >= p.total {
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
}
usage := &llm.Usage{InputTokens: 20000, OutputTokens: 100, CacheReadInputTokens: 15000}
if p.missingLast && p.calls == p.total {
usage = nil
@@ -87,7 +90,10 @@ type refusalUsageProvider struct {
func (p *refusalUsageProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.calls++
ch := make(chan llm.ChatEvent, 1)
ch := make(chan llm.ChatEvent, 2)
if p.calls > 1 {
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
}
e := llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 10000}}
if p.calls == 1 {
e.StopReason = llm.StopReasonRefusal
+1 -1
View File
@@ -30,7 +30,7 @@ func TestRunLifecycleStartFailureAndFinishCannotChangeOutcome(t *testing.T) {
t.Error("finish unbounded")
}
panic("observer cannot rewrite outcome")
}}, []llm.ChatEvent{{Type: llm.EventDone}}, nil)
}}, []llm.ChatEvent{{Type: llm.EventTextDelta, Text: "Answer"}, {Type: llm.EventDone}}, nil)
defer rt.Close()
defer rt.Session.Close()
failed := false
+40 -1
View File
@@ -34,6 +34,8 @@ const (
EventCompactionDone
EventCompactionSkipped
EventRequestUsage
// EventToolCallReady carries complete arguments before tool execution.
EventToolCallReady
)
// AgentEvent is a single streaming event from the agent.
@@ -602,7 +604,12 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
thresholdHit := window > 0 && estimate > int(threshold*float64(window))
msgCap := r.Compaction.MessageCap
countHit := msgCap > 0 && len(msgs) > msgCap
if thresholdHit || countHit {
keep := r.Compaction.PreserveTurns
if keep <= 0 {
keep = 4
}
_, _, eligible := compaction.Split(r.Session.View(), keep)
if (thresholdHit || countHit) && eligible {
r.emit(AgentEvent{Type: EventCompactionStart})
res, _ := r.Compaction.MaybeCompact(ctx, r.Session, compaction.ReasonPreventive, "")
if res.Compacted {
@@ -682,6 +689,8 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
preTokenRetried := false
retriedRefusal := false
var refused bool
retriedEmpty := false
var terminalReason string
var refusalCategory string
streamLoop:
for {
@@ -723,6 +732,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
break streamLoop
}
r.emit(AgentEvent{Type: EventToolCallReady, ToolCall: &tc})
toolCalls = append(toolCalls, tc)
if !streamingOn || kickoffStopped {
continue
@@ -741,6 +751,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}()
case llm.EventDone:
terminalReason = event.StopReason
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
if event.Usage != nil && r.calibrator != nil {
@@ -866,6 +877,22 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
textContent.WriteString(note)
r.emit(AgentEvent{Type: EventTextDelta, Text: note})
}
// Retry only an empty, non-truncated response with no tool activity.
// Keep the same request and output allowance; never replay tools.
limited := terminalReason == "length" || terminalReason == "max_tokens"
if !limited && !refused && strings.TrimSpace(textContent.String()) == "" && len(toolCalls) == 0 && len(kickoffs) == 0 && !gotFirstToken && !retriedEmpty {
retriedEmpty = true
terminalReason = ""
thinkingBlocks = nil
retryStream, retryErr := r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
if retryErr != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: retryErr})
return
}
streamSource = retryStream
continue streamLoop
}
break streamLoop
}
tr.Mark("llm.stream_end", "turn", turn,
@@ -904,6 +931,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
return
}
if len(toolCalls) == 0 {
var responseErr error
if terminalReason == "length" || terminalReason == "max_tokens" {
responseErr = fmt.Errorf("model reached its output limit (%d tokens) before finishing; increase max_output or use a model with a larger output allowance", req.MaxTokens)
} else if strings.TrimSpace(textContent.String()) == "" {
responseErr = errors.New("model returned no answer; try again or choose another model")
}
if responseErr != nil {
drainKickoffs(kickoffs)
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: responseErr})
return
}
if len(kickoffs) > 0 {
drainKickoffs(kickoffs)
}
+13
View File
@@ -173,6 +173,7 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
var toolCalls []llm.ToolCall
var thinkingBlocks []session.ThinkingBlockData
retriedRefusal := false
var terminalReason string
streamLoop:
for {
toolIDs := make(map[string]bool)
@@ -205,9 +206,11 @@ streamLoop:
emit(AgentEvent{Type: EventError, Error: err})
return r.turnSlice(startLen, true, "error", ledger.Total(), err), nil
}
emit(AgentEvent{Type: EventToolCallReady, ToolCall: event.ToolCall})
toolCalls = append(toolCalls, *event.ToolCall)
}
case llm.EventDone:
terminalReason = event.StopReason
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
case llm.EventError:
@@ -257,6 +260,16 @@ streamLoop:
}
if len(toolCalls) == 0 {
var responseErr error
if terminalReason == "length" || terminalReason == "max_tokens" {
responseErr = fmt.Errorf("model reached its output limit (%d tokens) before finishing; increase max_output or use a model with a larger output allowance", req.MaxTokens)
} else if strings.TrimSpace(textContent.String()) == "" {
responseErr = fmt.Errorf("model returned no answer; try again or choose another model")
}
if responseErr != nil {
emit(AgentEvent{Type: EventError, Error: responseErr})
return r.turnSlice(startLen, true, "error", ledger.Total(), responseErr), nil
}
// Exchange complete: ingest the full thread once. Background + best-effort
// (the KG spawns its own bounded goroutine), so it never delays the turn.
// context.Background() because the request ctx may be cancelling and the
+2
View File
@@ -27,6 +27,8 @@ func (p *authoringProvider) ChatStream(_ context.Context, req llm.ChatRequest) (
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"}`)}}
default:
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Skill created and loaded."}
}
ch <- llm.ChatEvent{Type: llm.EventDone}
close(ch)
+1 -1
View File
@@ -45,7 +45,7 @@ func (r *Runtime) applySteering(ctx context.Context, pending []llm.ToolCall) (bo
return false, nil
}
if err := ctx.Err(); err != nil {
return false, err
return false, context.Cause(ctx)
}
message, err := source(ctx)
if err != nil || message == nil {
+18
View File
@@ -0,0 +1,18 @@
package runtime
import (
"context"
"errors"
"testing"
)
func TestSteeringPreservesProtocolCancellationCause(t *testing.T) {
cause := errors.New("duplicate tool call ID")
ctx, cancel := context.WithCancelCause(context.Background())
cancel(cause)
ctx = WithSteering(ctx, func(context.Context) (*SteeringMessage, error) { t.Fatal("called after cancellation"); return nil, nil })
_, err := (&Runtime{}).applySteering(ctx, nil)
if !errors.Is(err, cause) {
t.Fatalf("lost cause: %v", err)
}
}
+3 -2
View File
@@ -102,7 +102,8 @@ func (s *scriptedStreamLLM) ChatStream(ctx context.Context, _ llm.ChatRequest) (
go func() {
defer close(out)
if n != 1 {
// Subsequent turns: terminate quickly with no tool calls.
// Subsequent turns: answer without further tool calls.
out <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
out <- llm.ChatEvent{Type: llm.EventDone}
return
}
@@ -791,7 +792,7 @@ func TestRun_StreamingCortexAppendIsRaceClean(t *testing.T) {
Model: "test",
MaxTurns: 2,
KG: neverRecallKG{}, // non-nil sentinel; never invoked
IngestSource: "cron", // disables deferred IngestThreadAsync
IngestSource: "cron", // disables deferred IngestThreadAsync
}
// Trivial userMsg "ok" → ShouldRecall returns false → no Recall call on
+40
View File
@@ -0,0 +1,40 @@
package runtime
import (
"context"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"testing"
)
func TestToolReadyCarriesArgumentsBeforeResult(t *testing.T) {
provider := &emptyResponseProvider{responses: [][]llm.ChatEvent{
{{Type: llm.EventToolCallStart, ToolCall: &llm.ToolCall{ID: "one", Name: "noop"}}, {Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "one", Name: "noop", Input: []byte(`{"command":"echo hi"}`)}}, {Type: llm.EventDone}},
{{Type: llm.EventTextDelta, Text: "Done"}, {Type: llm.EventDone}},
}}
rt := &Runtime{LLM: provider, Tools: usageNoopExecutor{}, Session: session.NewSession("test", "ready"), Model: "fixture", MaxTurns: 2}
stream, err := rt.Run(context.Background(), "go", nil)
if err != nil {
t.Fatal(err)
}
ready, results := 0, 0
for e := range stream {
switch e.Type {
case EventToolCallReady:
ready++
if e.ToolCall == nil || string(e.ToolCall.Input) != `{"command":"echo hi"}` {
t.Fatalf("%+v", e)
}
case EventToolResult:
results++
if ready != 1 {
t.Fatal("result before arguments")
}
case EventError:
t.Fatal(e.Error)
}
}
if ready != 1 || results != 1 {
t.Fatalf("ready=%d results=%d", ready, results)
}
}