Initial commit: Go agentic harness extracted from Felix
This commit is contained in:
commit
1f2c471ff9
89 files changed
+19388
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,183 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
|
||||
"github.com/sausheong/harness/compaction"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tokens"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// RuntimeDeps holds the long-lived dependencies that every Runtime in this
|
||||
// process shares. Built once at startup and reused for every Runtime
|
||||
// construction (including subagent runtimes built by the task tool factory).
|
||||
type RuntimeDeps struct {
|
||||
// Skills, when non-nil, contributes a Skills Index to the static
|
||||
// system prompt and backs the load_skill tool. Optional.
|
||||
Skills SkillProvider
|
||||
// Memory, when non-nil, contributes a Memory Index to the static
|
||||
// system prompt and backs the load_memory tool. Optional.
|
||||
Memory MemoryProvider
|
||||
// Permission gates tool execution. nil → allow-all.
|
||||
Permission tool.PermissionChecker
|
||||
// KGFn returns the per-agent KnowledgeGraph for the given model
|
||||
// string. Nil at the call site means KG is disabled for this Runtime.
|
||||
// The function shape (rather than a single KG) lets consumers route
|
||||
// the chatting agent's own model to the KG's underlying LLM (Felix
|
||||
// uses this to mirror the chat model into Cortex's extractor).
|
||||
KGFn func(model string) KnowledgeGraph
|
||||
// AgentLoop carries the loop tunables (concurrency cap, depth cap,
|
||||
// streaming-tools toggle). Copied verbatim into every Runtime built
|
||||
// here. Zero value → readers fall back to env vars then defaults.
|
||||
AgentLoop LoopConfig
|
||||
// CalibratorStore is the per-(agentID, sessionKey) persistence layer
|
||||
// for the token Calibrator. nil disables persistence; in-memory
|
||||
// learning still happens.
|
||||
CalibratorStore *tokens.CalibratorStore
|
||||
// ConfigSummary, when non-empty, is prepended to the static system
|
||||
// prompt's context block. Consumers can use this to advertise the
|
||||
// list of configured agents, channel bindings, etc. — anything that
|
||||
// changes only on hot-reload.
|
||||
ConfigSummary string
|
||||
// MemoryFiles, when non-empty, is appended to the static system
|
||||
// prompt. Consumers compose this themselves (Felix walks
|
||||
// FELIX.md / AGENTS.md from workspace + $HOME).
|
||||
MemoryFiles string
|
||||
}
|
||||
|
||||
// RuntimeInputs holds the per-Runtime-instance inputs that genuinely vary
|
||||
// per call site: the resolved LLM provider for this agent's model, the tool
|
||||
// executor (different per cron/chat/subagent path), the session, the
|
||||
// per-agent compaction manager, and the IngestSource flag.
|
||||
type RuntimeInputs struct {
|
||||
Provider llm.LLMProvider
|
||||
Tools tool.Executor
|
||||
Session *session.Session
|
||||
Compaction *compaction.Manager
|
||||
IngestSource string // "" | "chat" | "cron"
|
||||
}
|
||||
|
||||
// BuildRuntime constructs a Runtime for the given AgentSpec using the
|
||||
// supplied deps + inputs. Centralises three patterns:
|
||||
// 1. Parsing the model identifier (provider/model)
|
||||
// 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.
|
||||
func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runtime, error) {
|
||||
provider, modelName := llm.ParseProviderModel(spec.Model)
|
||||
reasoning, err := llm.ParseReasoningMode(spec.Reasoning)
|
||||
if err != nil {
|
||||
slog.Error("invalid reasoning mode in agent spec; defaulting to off",
|
||||
"agent", spec.ID, "value", spec.Reasoning, "err", err)
|
||||
reasoning = llm.ReasoningOff
|
||||
}
|
||||
var kg KnowledgeGraph
|
||||
if deps.KGFn != nil {
|
||||
kg = deps.KGFn(spec.Model)
|
||||
}
|
||||
|
||||
// Register the on-demand load tools onto the agent's tool registry
|
||||
// when the corresponding manager is non-nil. Type-assert to
|
||||
// *tool.Registry rather than widening tool.Executor — production
|
||||
// callers always pass *tool.Registry; test paths that don't won't
|
||||
// get load tools registered (which is fine for them).
|
||||
if reg, ok := inputs.Tools.(*tool.Registry); ok {
|
||||
if deps.Skills != nil {
|
||||
skills := deps.Skills
|
||||
reg.Register(&tool.LoadSkillTool{
|
||||
Lookup: func(name string) (string, bool) {
|
||||
return skills.Get(name)
|
||||
},
|
||||
})
|
||||
}
|
||||
if deps.Memory != nil {
|
||||
mem := deps.Memory
|
||||
reg.Register(&tool.LoadMemoryTool{
|
||||
Lookup: func(id string) (string, bool) {
|
||||
return mem.Get(id)
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 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()
|
||||
}
|
||||
memoryIndex := ""
|
||||
if deps.Memory != nil {
|
||||
memoryIndex = deps.Memory.FormatIndex()
|
||||
}
|
||||
var toolNames []string
|
||||
if inputs.Tools != nil {
|
||||
toolNames = inputs.Tools.Names()
|
||||
}
|
||||
staticPrompt := BuildStaticSystemPrompt(
|
||||
spec.Workspace, spec.SystemPrompt, spec.ID, spec.Name,
|
||||
toolNames, deps.ConfigSummary, skillsIndex,
|
||||
memoryIndex, deps.MemoryFiles,
|
||||
)
|
||||
|
||||
// Strip the provider prefix off FallbackModel so the runtime hands
|
||||
// the same provider client a bare model id on retry. Cross-provider
|
||||
// fallback isn't supported here.
|
||||
fallbackModel := ""
|
||||
if spec.FallbackModel != "" {
|
||||
fbProvider, fbModel := llm.ParseProviderModel(spec.FallbackModel)
|
||||
if fbProvider != "" && fbProvider != provider {
|
||||
slog.Warn("fallbackModel ignored: cross-provider fallback not supported",
|
||||
"agent", spec.ID,
|
||||
"primary_provider", provider,
|
||||
"fallback", spec.FallbackModel)
|
||||
} else {
|
||||
fallbackModel = fbModel
|
||||
}
|
||||
}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: inputs.Provider,
|
||||
Tools: inputs.Tools,
|
||||
Session: inputs.Session,
|
||||
AgentID: spec.ID,
|
||||
AgentName: spec.Name,
|
||||
Model: modelName,
|
||||
FallbackModel: fallbackModel,
|
||||
ContextWindow: spec.ContextWindow,
|
||||
Provider: provider,
|
||||
Reasoning: reasoning,
|
||||
Workspace: spec.Workspace,
|
||||
MaxTurns: spec.MaxTurns,
|
||||
SystemPrompt: spec.SystemPrompt,
|
||||
Skills: deps.Skills,
|
||||
Memory: deps.Memory,
|
||||
KG: kg,
|
||||
Permission: deps.Permission,
|
||||
Compaction: inputs.Compaction,
|
||||
IngestSource: inputs.IngestSource,
|
||||
AgentLoop: deps.AgentLoop,
|
||||
StaticSystemPrompt: staticPrompt,
|
||||
CalibratorStore: deps.CalibratorStore,
|
||||
}
|
||||
|
||||
// Seed the calibrator from prior (ratio, count) for this session so a
|
||||
// long session that's been split across many rebuilds retains its
|
||||
// learned chars→tokens ratio. Skipped for subagent sessions and when
|
||||
// no store is configured.
|
||||
if deps.CalibratorStore != nil && inputs.Session != nil && inputs.Session.Key != "" && inputs.Session.Key != "subagent" {
|
||||
ratio, count := deps.CalibratorStore.Load(spec.ID, inputs.Session.Key)
|
||||
if count > 0 {
|
||||
rt.calibrator = tokens.NewCalibrator()
|
||||
rt.calibrator.Restore(ratio, count)
|
||||
}
|
||||
}
|
||||
|
||||
return rt, nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBuildRuntimeSetsProviderAndStaticPrompt(t *testing.T) {
|
||||
spec := AgentSpec{ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5"}
|
||||
deps := RuntimeDeps{ConfigSummary: "Configured channels: cli"}
|
||||
inputs := RuntimeInputs{}
|
||||
|
||||
rt, err := BuildRuntime(deps, inputs, spec)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "anthropic", rt.Provider)
|
||||
require.Equal(t, "claude-sonnet-4-5", rt.Model)
|
||||
require.NotEmpty(t, rt.StaticSystemPrompt)
|
||||
require.Contains(t, rt.StaticSystemPrompt, `"A" agent (id: a)`)
|
||||
require.Contains(t, rt.StaticSystemPrompt, "Configured channels: cli")
|
||||
}
|
||||
|
||||
func TestBuildRuntimeLocalProvider(t *testing.T) {
|
||||
spec := AgentSpec{ID: "x", Name: "X", Model: "local/qwen2.5:3b"}
|
||||
rt, err := BuildRuntime(RuntimeDeps{}, RuntimeInputs{}, spec)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "local", rt.Provider)
|
||||
}
|
||||
|
||||
func TestBuildRuntimeMinimalSpecSafe(t *testing.T) {
|
||||
spec := AgentSpec{ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5"}
|
||||
rt, err := BuildRuntime(RuntimeDeps{}, RuntimeInputs{}, spec)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "anthropic", rt.Provider)
|
||||
require.NotEmpty(t, rt.StaticSystemPrompt)
|
||||
}
|
||||
|
||||
func TestBuildRuntimeUsesCallerProvidedMemoryFiles(t *testing.T) {
|
||||
// Caller composes memoryFiles however they want (Felix walks
|
||||
// FELIX.md/AGENTS.md from workspace + $HOME; other consumers may
|
||||
// build it from a wiki dump, a doc index, etc.). Harness only
|
||||
// concatenates it into the static prompt.
|
||||
const sentinel = "MEMFILE_END_TO_END_SENTINEL"
|
||||
deps := RuntimeDeps{
|
||||
MemoryFiles: "\n\n## Project memory: AGENTS.md\n\n" + sentinel,
|
||||
}
|
||||
rt, err := BuildRuntime(deps, RuntimeInputs{}, AgentSpec{
|
||||
ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, rt.StaticSystemPrompt, sentinel)
|
||||
require.Contains(t, rt.StaticSystemPrompt, "## Project memory:")
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// recordingProvider captures every ChatRequest it receives and emits a
|
||||
// canned text response. Used to inspect what the runtime sends to the
|
||||
// LLM across turns.
|
||||
type recordingProvider struct {
|
||||
llmtest.Base
|
||||
mu sync.Mutex
|
||||
requests []llm.ChatRequest
|
||||
reply string
|
||||
}
|
||||
|
||||
func (r *recordingProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
r.mu.Lock()
|
||||
r.requests = append(r.requests, req)
|
||||
r.mu.Unlock()
|
||||
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
go func() {
|
||||
defer close(ch)
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: r.reply}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
}()
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// requestPrefixSignature renders the cache-relevant portion of a request:
|
||||
// system prompt, tool definitions in their request-given order, and the
|
||||
// message list excluding the final user turn. Two calls in the same
|
||||
// session that differ only in the freshly-arrived user message must
|
||||
// produce identical signatures.
|
||||
//
|
||||
// This intentionally does NOT sort tools — it renders them in the exact
|
||||
// order the runtime hands them to the LLM, matching the byte sequence
|
||||
// Anthropic/OpenAI prompt caches actually see. A separate test asserts
|
||||
// that the tool registry returns tools in sorted order; this signature
|
||||
// reflects what the runtime actually sends.
|
||||
func requestPrefixSignature(t *testing.T, req llm.ChatRequest) string {
|
||||
t.Helper()
|
||||
var sb strings.Builder
|
||||
sb.WriteString("SYS:")
|
||||
sb.WriteString(req.SystemPrompt)
|
||||
sb.WriteString("\nTOOLS:")
|
||||
for _, td := range req.Tools {
|
||||
sb.WriteString("\n ")
|
||||
sb.WriteString(td.Name)
|
||||
sb.WriteString("|")
|
||||
sb.WriteString(td.Description)
|
||||
sb.WriteString("|")
|
||||
sb.WriteString(string(td.Parameters))
|
||||
}
|
||||
sb.WriteString("\nMSGS_EXCL_LAST:")
|
||||
for i := 0; i < len(req.Messages)-1; i++ {
|
||||
sb.WriteString("\n ")
|
||||
sb.WriteString(req.Messages[i].Role)
|
||||
sb.WriteString(":")
|
||||
sb.WriteString(req.Messages[i].Content)
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// TestRequestPrefixIsByteStableAcrossTurns runs two consecutive turns of the
|
||||
// agent loop with identical inputs. The second request's prefix (system
|
||||
// prompt + tool defs + all-but-last message) must be byte-identical to the
|
||||
// first request's full content (system prompt + tool defs + all messages).
|
||||
//
|
||||
// This is the cache-stability invariant: turn N+1's prefix is turn N's full
|
||||
// prompt. Anthropic and OpenAI prompt caches both depend on this. The
|
||||
// compaction-View bug we shipped a fix for would have been caught by an
|
||||
// earlier version of this test (it changed the prefix dramatically when
|
||||
// compaction fired).
|
||||
func TestRequestPrefixIsByteStableAcrossTurns(t *testing.T) {
|
||||
rec := &recordingProvider{reply: "ok"}
|
||||
|
||||
sess := session.NewSession("test-agent", "test-key")
|
||||
reg := tool.NewRegistry()
|
||||
reg.Register(&mockTool{name: "zebra", output: "z"})
|
||||
reg.Register(&mockTool{name: "alpha", output: "a"})
|
||||
reg.Register(&mockTool{name: "mango", output: "m"})
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: rec,
|
||||
Tools: reg,
|
||||
Session: sess,
|
||||
Model: "rec-model",
|
||||
Workspace: t.TempDir(),
|
||||
MaxTurns: 5,
|
||||
}
|
||||
|
||||
// Turn 1
|
||||
events, err := rt.Run(context.Background(), "hello", nil)
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
|
||||
// Turn 2 — same session, same agent, same tools.
|
||||
events, err = rt.Run(context.Background(), "world", nil)
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
require.GreaterOrEqual(t, len(rec.requests), 2,
|
||||
"expected at least 2 ChatStream calls, got %d", len(rec.requests))
|
||||
|
||||
req1 := rec.requests[0]
|
||||
req2 := rec.requests[1]
|
||||
|
||||
// turn 2's request layout: [...turn1.Messages, assistantN, userN+1]
|
||||
// turn 2's prefix = everything except the freshly-arrived user msg
|
||||
// = turn 1's full request + the assistant reply we
|
||||
// captured between turns.
|
||||
//
|
||||
// Build the expected prefix by appending the assistant reply onto turn 1's
|
||||
// message list, then render the resulting request the same way we render
|
||||
// turn 2 with its trailing user msg stripped. The two must be byte-equal.
|
||||
expected := req1
|
||||
expected.Messages = append(append([]llm.Message{}, req1.Messages...),
|
||||
llm.Message{Role: "assistant", Content: rec.reply})
|
||||
turn1FullPlusAssistant := fullSignature(t, expected)
|
||||
turn2Prefix := prefixWithoutLastMessage(t, req2)
|
||||
assert.Equal(t, turn1FullPlusAssistant, turn2Prefix,
|
||||
"turn 2 prefix must byte-match turn 1's full request plus the assistant reply")
|
||||
}
|
||||
|
||||
// fullSignature renders the entire request the same way requestPrefixSignature
|
||||
// does, but includes the final message too.
|
||||
func fullSignature(t *testing.T, req llm.ChatRequest) string {
|
||||
t.Helper()
|
||||
sig := requestPrefixSignature(t, req)
|
||||
if len(req.Messages) > 0 {
|
||||
last := req.Messages[len(req.Messages)-1]
|
||||
sig += "\n " + last.Role + ":" + last.Content
|
||||
}
|
||||
return sig
|
||||
}
|
||||
|
||||
// prefixWithoutLastMessage is requestPrefixSignature but with the last
|
||||
// message of the previous turn (the assistant reply that turn N's run
|
||||
// appended) re-included, since that's part of turn N+1's prefix.
|
||||
//
|
||||
// turn N's request: [sys, tools, ...msgs, userN]
|
||||
// after turn N: session also contains [...msgs, userN, assistantN]
|
||||
// turn N+1's request: [sys, tools, ...msgs, userN, assistantN, userN+1]
|
||||
// ^^^^^^^^^^^^^^^^^^^^^^
|
||||
// the prefix at turn N+1
|
||||
// excluding the new user msg
|
||||
//
|
||||
// So turn N+1's prefix = turn N's full request + assistantN.
|
||||
// We test that subset by stripping the last message of turn N+1.
|
||||
func prefixWithoutLastMessage(t *testing.T, req llm.ChatRequest) string {
|
||||
t.Helper()
|
||||
if len(req.Messages) == 0 {
|
||||
return requestPrefixSignature(t, req)
|
||||
}
|
||||
clone := req
|
||||
clone.Messages = req.Messages[:len(req.Messages)-1]
|
||||
return fullSignature(t, clone)
|
||||
}
|
||||
|
||||
// strippingRecordingProvider is like recordingProvider but also strips
|
||||
// the "format" field from tool schemas. Used to prove the runtime
|
||||
// actually calls NormalizeToolSchema (rather than passing tools
|
||||
// through unchanged).
|
||||
type strippingRecordingProvider struct {
|
||||
llmtest.Base
|
||||
mu sync.Mutex
|
||||
requests []llm.ChatRequest
|
||||
reply string
|
||||
}
|
||||
|
||||
func (p *strippingRecordingProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.mu.Lock()
|
||||
p.requests = append(p.requests, req)
|
||||
p.mu.Unlock()
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
go func() {
|
||||
defer close(ch)
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: p.reply}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
}()
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (p *strippingRecordingProvider) NormalizeToolSchema(tools []llm.ToolDef) ([]llm.ToolDef, []llm.Diagnostic) {
|
||||
out := make([]llm.ToolDef, len(tools))
|
||||
var diags []llm.Diagnostic
|
||||
for i, t := range tools {
|
||||
newParams, d := llm.StripFields(t.Name, t.Parameters, []string{"format"})
|
||||
td := t
|
||||
td.Parameters = newParams
|
||||
out[i] = td
|
||||
diags = append(diags, d...)
|
||||
}
|
||||
return out, diags
|
||||
}
|
||||
|
||||
// customMockTool is a local mock tool whose JSON Schema parameters can
|
||||
// be supplied per-instance. We use it here (instead of the package-wide
|
||||
// mockTool) so this test can register a tool whose schema contains the
|
||||
// "format" field that strippingRecordingProvider strips, without
|
||||
// touching agent_test.go's shared fixture.
|
||||
type customMockTool struct {
|
||||
name string
|
||||
schema []byte
|
||||
output string
|
||||
}
|
||||
|
||||
func (t *customMockTool) Name() string { return t.name }
|
||||
func (t *customMockTool) Description() string { return "custom mock tool" }
|
||||
func (t *customMockTool) Parameters() json.RawMessage { return json.RawMessage(t.schema) }
|
||||
func (t *customMockTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
|
||||
func (t *customMockTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
|
||||
return tool.ToolResult{Output: t.output}, nil
|
||||
}
|
||||
|
||||
// TestRuntimeCallsNormalizeToolSchema asserts that the agent runtime
|
||||
// invokes NormalizeToolSchema before constructing the ChatRequest
|
||||
// (so the model sees the provider's normalized tool list, not the raw
|
||||
// tool definitions). Also asserts byte-determinism across turns —
|
||||
// required for prompt cache stability.
|
||||
func TestRuntimeCallsNormalizeToolSchema(t *testing.T) {
|
||||
rec := &strippingRecordingProvider{reply: "ok"}
|
||||
|
||||
sess := session.NewSession("test-agent", "test-key")
|
||||
reg := tool.NewRegistry()
|
||||
// Register a tool whose schema has "format" — the stripper above
|
||||
// will remove it. If the runtime doesn't call NormalizeToolSchema,
|
||||
// "format" survives and the assertion below fails.
|
||||
reg.Register(&customMockTool{
|
||||
name: "fetch",
|
||||
schema: []byte(`{"type":"object","properties":{"url":{"type":"string","format":"uri"}}}`),
|
||||
output: "ok",
|
||||
})
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: rec,
|
||||
Tools: reg,
|
||||
Session: sess,
|
||||
Model: "rec-model",
|
||||
Workspace: t.TempDir(),
|
||||
MaxTurns: 3,
|
||||
}
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
events, err := rt.Run(context.Background(), "ping", nil)
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
}
|
||||
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
require.GreaterOrEqual(t, len(rec.requests), 3, "expected at least 3 ChatStream calls")
|
||||
|
||||
// Determinism: all turns must have byte-identical Tools.
|
||||
for i := 1; i < len(rec.requests); i++ {
|
||||
require.Equal(t, len(rec.requests[0].Tools), len(rec.requests[i].Tools))
|
||||
for j := range rec.requests[0].Tools {
|
||||
assert.Equal(t,
|
||||
string(rec.requests[0].Tools[j].Parameters),
|
||||
string(rec.requests[i].Tools[j].Parameters),
|
||||
"turn %d tool %d parameters must byte-match turn 0", i, j)
|
||||
}
|
||||
}
|
||||
|
||||
// Normalization actually happened: the "format" field is gone.
|
||||
require.Greater(t, len(rec.requests[0].Tools), 0)
|
||||
var schema map[string]any
|
||||
require.NoError(t, json.Unmarshal(rec.requests[0].Tools[0].Parameters, &schema))
|
||||
props := schema["properties"].(map[string]any)
|
||||
url := props["url"].(map[string]any)
|
||||
_, hasFormat := url["format"]
|
||||
assert.False(t, hasFormat,
|
||||
"runtime must call NormalizeToolSchema; format should be stripped")
|
||||
}
|
||||
|
||||
// TestReasoningIsInRequestPrefix asserts that the agent's Reasoning
|
||||
// setting flows into ChatRequest and remains stable across turns.
|
||||
// Required for prompt cache hits with reasoning enabled.
|
||||
func TestReasoningIsInRequestPrefix(t *testing.T) {
|
||||
rec := &recordingProvider{reply: "ok"}
|
||||
sess := session.NewSession("test-agent", "test-key")
|
||||
reg := tool.NewRegistry()
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: rec,
|
||||
Tools: reg,
|
||||
Session: sess,
|
||||
Model: "rec-model",
|
||||
Reasoning: llm.ReasoningHigh,
|
||||
Workspace: t.TempDir(),
|
||||
MaxTurns: 3,
|
||||
}
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
events, err := rt.Run(context.Background(), "ping", nil)
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
}
|
||||
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
require.GreaterOrEqual(t, len(rec.requests), 2)
|
||||
assert.Equal(t, llm.ReasoningHigh, rec.requests[0].Reasoning)
|
||||
assert.Equal(t, llm.ReasoningHigh, rec.requests[1].Reasoning,
|
||||
"reasoning level must be stable across turns")
|
||||
}
|
||||
|
||||
func TestToolDefsSortedByNameInRequest(t *testing.T) {
|
||||
rec := &recordingProvider{reply: "ok"}
|
||||
sess := session.NewSession("test-agent", "test-key")
|
||||
reg := tool.NewRegistry()
|
||||
reg.Register(&mockTool{name: "zebra", output: "z"})
|
||||
reg.Register(&mockTool{name: "alpha", output: "a"})
|
||||
reg.Register(&mockTool{name: "mango", output: "m"})
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: rec, Tools: reg, Session: sess,
|
||||
Model: "rec-model", Workspace: t.TempDir(), MaxTurns: 5,
|
||||
}
|
||||
|
||||
events, err := rt.Run(context.Background(), "hello", nil)
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
require.GreaterOrEqual(t, len(rec.requests), 1)
|
||||
names := make([]string, 0, len(rec.requests[0].Tools))
|
||||
for _, td := range rec.requests[0].Tools {
|
||||
names = append(names, td.Name)
|
||||
}
|
||||
require.Equal(t, []string{"alpha", "mango", "zebra"}, names)
|
||||
}
|
||||
|
||||
func TestRuntimeSendsStructuredSystemPromptParts(t *testing.T) {
|
||||
rec := &recordingProvider{reply: "ok"}
|
||||
sess := session.NewSession("test-agent", "test-key")
|
||||
|
||||
spec := AgentSpec{ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5"}
|
||||
rt, err := BuildRuntime(
|
||||
RuntimeDeps{},
|
||||
RuntimeInputs{Provider: rec, Tools: tool.NewRegistry(), Session: sess},
|
||||
spec,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
rt.MaxTurns = 5
|
||||
|
||||
events, err := rt.Run(context.Background(), "hi", nil)
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
require.GreaterOrEqual(t, len(rec.requests), 1)
|
||||
req0 := rec.requests[0]
|
||||
require.NotEmpty(t, req0.SystemPromptParts, "expected SystemPromptParts to be populated")
|
||||
require.True(t, req0.SystemPromptParts[0].Cache, "first part must be cache-marked")
|
||||
require.Contains(t, req0.SystemPromptParts[0].Text, `"A" agent (id: a)`)
|
||||
require.True(t, req0.CacheLastMessage, "Anthropic provider must request CacheLastMessage")
|
||||
}
|
||||
|
||||
func TestRuntimeStaticPromptByteStableAcrossTurns(t *testing.T) {
|
||||
rec := &recordingProvider{reply: "ok"}
|
||||
sess := session.NewSession("test-agent", "test-key")
|
||||
spec := AgentSpec{ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5"}
|
||||
rt, err := BuildRuntime(
|
||||
RuntimeDeps{},
|
||||
RuntimeInputs{Provider: rec, Tools: tool.NewRegistry(), Session: sess},
|
||||
spec,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
rt.MaxTurns = 5
|
||||
|
||||
for _, msg := range []string{"hello", "world"} {
|
||||
ev, err := rt.Run(context.Background(), msg, nil)
|
||||
require.NoError(t, err)
|
||||
for range ev {
|
||||
}
|
||||
}
|
||||
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
require.GreaterOrEqual(t, len(rec.requests), 2)
|
||||
require.Equal(t,
|
||||
rec.requests[0].SystemPromptParts[0].Text,
|
||||
rec.requests[1].SystemPromptParts[0].Text,
|
||||
"static system prompt must be byte-identical across turns",
|
||||
)
|
||||
}
|
||||
|
||||
func TestRuntimeDynamicSuffixIncludesDate(t *testing.T) {
|
||||
rec := &recordingProvider{reply: "ok"}
|
||||
sess := session.NewSession("test-agent", "test-key")
|
||||
spec := AgentSpec{ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5"}
|
||||
rt, err := BuildRuntime(
|
||||
RuntimeDeps{},
|
||||
RuntimeInputs{Provider: rec, Tools: tool.NewRegistry(), Session: sess},
|
||||
spec,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
rt.MaxTurns = 5
|
||||
|
||||
ev, err := rt.Run(context.Background(), "hi", nil)
|
||||
require.NoError(t, err)
|
||||
for range ev {
|
||||
}
|
||||
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
require.GreaterOrEqual(t, len(rec.requests), 1)
|
||||
require.GreaterOrEqual(t, len(rec.requests[0].SystemPromptParts), 2,
|
||||
"expected static + dynamic parts")
|
||||
require.Contains(t, rec.requests[0].SystemPromptParts[1].Text, "Today's date is ",
|
||||
"dynamic suffix must contain the date line")
|
||||
}
|
||||
|
||||
// TestRuntimeDateLineComputedOncePerRun is a pure-function check: calling
|
||||
// buildDynamicSystemPromptSuffix twice with the same dateLine produces
|
||||
// identical output for that portion. Combined with the runtime call site
|
||||
// in runtime.go (which computes dateLine once before the for-turn loop),
|
||||
// this proves the date is stable across turns of a single Run.
|
||||
func TestRuntimeDateLineComputedOncePerRun(t *testing.T) {
|
||||
dl := "Today's date is 2026-05-01."
|
||||
a := buildDynamicSystemPromptSuffix(dl, "")
|
||||
b := buildDynamicSystemPromptSuffix(dl, "")
|
||||
require.Equal(t, a, b)
|
||||
}
|
||||
|
||||
func TestRuntimeNonAnthropicHasCacheLastMessageFalse(t *testing.T) {
|
||||
rec := &recordingProvider{reply: "ok"}
|
||||
sess := session.NewSession("test-agent", "test-key")
|
||||
spec := AgentSpec{ID: "a", Name: "A", Model: "openai/gpt-4o"}
|
||||
rt, err := BuildRuntime(
|
||||
RuntimeDeps{},
|
||||
RuntimeInputs{Provider: rec, Tools: tool.NewRegistry(), Session: sess},
|
||||
spec,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
rt.MaxTurns = 5
|
||||
|
||||
ev, err := rt.Run(context.Background(), "hi", nil)
|
||||
require.NoError(t, err)
|
||||
for range ev {
|
||||
}
|
||||
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
require.False(t, rec.requests[0].CacheLastMessage)
|
||||
}
|
||||
|
||||
func TestRuntimeStaticPromptIncludesMemoryFilesContent(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
|
||||
// Consumers compose MemoryFiles themselves and pass via RuntimeDeps —
|
||||
// the harness concatenates it verbatim into the static prompt.
|
||||
memBlock := "\n\n## Project memory: /tmp/x\n\nRUNTIME_MEMFILE_INTEGRATION_SENTINEL"
|
||||
|
||||
rec := &recordingProvider{reply: "ok"}
|
||||
sess := session.NewSession("test-agent", "test-key")
|
||||
spec := AgentSpec{
|
||||
ID: "a",
|
||||
Name: "A",
|
||||
Workspace: workspace,
|
||||
Model: "anthropic/claude-sonnet-4-5",
|
||||
}
|
||||
rt, err := BuildRuntime(
|
||||
RuntimeDeps{MemoryFiles: memBlock},
|
||||
RuntimeInputs{Provider: rec, Tools: tool.NewRegistry(), Session: sess},
|
||||
spec,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
rt.MaxTurns = 5
|
||||
|
||||
ev, err := rt.Run(context.Background(), "hi", nil)
|
||||
require.NoError(t, err)
|
||||
for range ev {
|
||||
}
|
||||
|
||||
rec.mu.Lock()
|
||||
defer rec.mu.Unlock()
|
||||
require.GreaterOrEqual(t, len(rec.requests), 1)
|
||||
staticPart := rec.requests[0].SystemPromptParts[0].Text
|
||||
require.Contains(t, staticPart, "RUNTIME_MEMFILE_INTEGRATION_SENTINEL")
|
||||
require.Contains(t, staticPart, "## Project memory:")
|
||||
require.True(t, rec.requests[0].SystemPromptParts[0].Cache,
|
||||
"static part with memory files must still be cache-marked")
|
||||
}
|
||||
@@ -0,0 +1,602 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
const maxToolResultLen = 4000 // truncate tool results longer than this
|
||||
|
||||
// detectImageMIME returns the actual MIME type based on magic bytes.
|
||||
// Falls back to the provided hint if the format is unrecognized.
|
||||
func detectImageMIME(data []byte, hint string) string {
|
||||
if len(data) >= 3 && data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF {
|
||||
return "image/jpeg"
|
||||
}
|
||||
if len(data) >= 4 && data[0] == 0x89 && data[1] == 'P' && data[2] == 'N' && data[3] == 'G' {
|
||||
return "image/png"
|
||||
}
|
||||
if len(data) >= 4 && data[0] == 'G' && data[1] == 'I' && data[2] == 'F' && data[3] == '8' {
|
||||
return "image/gif"
|
||||
}
|
||||
if len(data) >= 4 && data[0] == 'R' && data[1] == 'I' && data[2] == 'F' && data[3] == 'F' {
|
||||
return "image/webp"
|
||||
}
|
||||
return hint
|
||||
}
|
||||
|
||||
const defaultIdentityBase = `You are an AI agent. Conduct yourself professionally and politely. Be concise and direct. When executing tasks, think step by step and use your tools to accomplish the user's goals. When you need to call multiple independent tools to gather information, emit them in a single response (parallel tool calls) rather than waiting for each one — this cuts response latency on local models.`
|
||||
|
||||
// toolHints maps tool names to usage guidance injected into the default identity.
|
||||
var toolHints = map[string]string{
|
||||
"read_file": "You can read files. You have vision capabilities — you can see and analyze images by using read_file on image files. Do not say you cannot see or analyze images.",
|
||||
"write_file": "You can create or overwrite files.",
|
||||
"edit_file": "You can make targeted edits to existing files.",
|
||||
"bash": "You can execute bash commands on the user's machine. ALWAYS wrap file paths in double quotes when invoking bash (e.g. ls \"/path/with spaces/file.txt\") so paths with spaces or special characters survive shell tokenization.",
|
||||
"web_fetch": "You can fetch web pages using the web_fetch tool.",
|
||||
"web_search": "You can search the web using the web_search tool.",
|
||||
"browser": "You can automate a headless browser for interactive pages using the browser tool.",
|
||||
"send_message": "You can send messages to other users or channels using the send_message tool.",
|
||||
"cron": "You can schedule recurring tasks using the cron tool.",
|
||||
"todo_write": "You have a todo_write tool, but use it sparingly. Start working on the user's request directly — do NOT pre-plan with a sequence of todo_write calls. Reserve todo_write for genuinely long, multi-stage work (roughly 5+ independent subtasks that will span many turns). When you do initialize a list, emit every `add` as a parallel tool call in a single assistant response — never one item per turn.",
|
||||
"load_skill": "You can load a skill body on demand by name via load_skill. Consult the Skills Index in your system prompt to pick the right skill name; the body is returned as the tool output.",
|
||||
"load_memory": "You can load a memory entry body on demand by id via load_memory. Consult the Memory Index in your system prompt to pick the right entry id.",
|
||||
}
|
||||
|
||||
// buildDefaultIdentity constructs the default identity prompt tailored to
|
||||
// the tools actually available to this agent.
|
||||
func buildDefaultIdentity(toolNames []string) string {
|
||||
if len(toolNames) == 0 {
|
||||
return defaultIdentityBase
|
||||
}
|
||||
available := make(map[string]bool, len(toolNames))
|
||||
for _, name := range toolNames {
|
||||
available[name] = true
|
||||
}
|
||||
var hints []string
|
||||
for _, name := range toolNames {
|
||||
if h, ok := toolHints[name]; ok {
|
||||
hints = append(hints, h)
|
||||
}
|
||||
}
|
||||
if len(hints) == 0 {
|
||||
return defaultIdentityBase
|
||||
}
|
||||
return defaultIdentityBase + " " + strings.Join(hints, " ")
|
||||
}
|
||||
|
||||
// BuildStaticSystemPrompt assembles the portion of the system prompt that
|
||||
// does not change across turns within a Run: identity (from systemPrompt
|
||||
// arg, IDENTITY.md in workspace, or the built-in default tailored to
|
||||
// toolNames), agent self-identity, then the four caller-provided context
|
||||
// blocks in order — configSummary, skillsIndex, memoryIndex, memoryFiles.
|
||||
//
|
||||
// Pure with one allowed exception: it reads IDENTITY.md from workspace
|
||||
// when systemPrompt is empty. Caller pre-resolves configSummary,
|
||||
// skillsIndex, memoryIndex, and memoryFiles so neither config loading
|
||||
// nor skill/memory index assembly nor memory-file disk reads happen
|
||||
// per-turn. Suitable to call once at Runtime construction.
|
||||
//
|
||||
// configSummary is the consumer's place to advertise things like the
|
||||
// configured agents, channel bindings, configuration paths, or any other
|
||||
// hot-reload-bound context. Felix uses it to inject a list of configured
|
||||
// agents and the path to felix.json5; other consumers can leave it empty.
|
||||
//
|
||||
// memoryFiles is the consumer's place to inject project / user memory
|
||||
// files (e.g., Felix walks FELIX.md and AGENTS.md from workspace + $HOME).
|
||||
func BuildStaticSystemPrompt(
|
||||
workspace, systemPrompt, agentID, agentName string,
|
||||
toolNames []string,
|
||||
configSummary string,
|
||||
skillsIndex string,
|
||||
memoryIndex string,
|
||||
memoryFiles string,
|
||||
) string {
|
||||
var base string
|
||||
if systemPrompt != "" {
|
||||
base = systemPrompt
|
||||
} else {
|
||||
identityPath := filepath.Join(workspace, "IDENTITY.md")
|
||||
data, err := os.ReadFile(identityPath)
|
||||
if err != nil {
|
||||
base = buildDefaultIdentity(toolNames)
|
||||
} else {
|
||||
base = string(data)
|
||||
}
|
||||
}
|
||||
|
||||
if agentID != "" {
|
||||
base += fmt.Sprintf("\n\nYou are the %q agent (id: %s).", agentName, agentID)
|
||||
}
|
||||
|
||||
if configSummary != "" {
|
||||
base += "\n\n" + configSummary
|
||||
}
|
||||
if skillsIndex != "" {
|
||||
base += skillsIndex
|
||||
}
|
||||
if memoryIndex != "" {
|
||||
base += memoryIndex
|
||||
}
|
||||
if memoryFiles != "" {
|
||||
base += memoryFiles
|
||||
}
|
||||
|
||||
return base
|
||||
}
|
||||
|
||||
// buildDynamicSystemPromptSuffix concatenates the per-turn dynamic context
|
||||
// — the date line and the cortex hint — into a single string the runtime
|
||||
// sends as the second (un-cached) SystemPromptPart. The date line, when
|
||||
// non-empty, appears at the top so the model anchors on "today" before
|
||||
// the per-turn content. Returns "" when all inputs are empty/nil.
|
||||
//
|
||||
// As of sub-project 5, skill bodies and memory entries are no longer
|
||||
// auto-injected here. Their indices live in the cached static prompt
|
||||
// and the agent loads bodies on demand via the load_skill / load_memory
|
||||
// tools. This trims 5–15 KB of speculative skill bodies and 5–10 KB of
|
||||
// speculative memory bodies from every prefill.
|
||||
func buildDynamicSystemPromptSuffix(dateLine, cortexContext string) string {
|
||||
var sb strings.Builder
|
||||
if dateLine != "" {
|
||||
sb.WriteString(dateLine)
|
||||
}
|
||||
if cortexContext != "" {
|
||||
sb.WriteString(cortexContext)
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// assembleMessages converts session history into LLM messages.
|
||||
// It ensures that every tool_use block in an assistant message has a
|
||||
// corresponding tool_result in the next user message. Orphaned tool calls
|
||||
// (e.g. from interrupted sessions) get synthetic error results injected.
|
||||
func assembleMessages(history []session.SessionEntry) []llm.Message {
|
||||
// First pass: collect tool result IDs so we can detect orphaned tool calls.
|
||||
resultIDs := make(map[string]bool)
|
||||
for _, entry := range history {
|
||||
if entry.Type == session.EntryTypeToolResult {
|
||||
var tr session.ToolResultData
|
||||
if err := json.Unmarshal(entry.Data, &tr); err == nil {
|
||||
resultIDs[tr.ToolCallID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var msgs []llm.Message
|
||||
|
||||
for _, entry := range history {
|
||||
switch entry.Type {
|
||||
case session.EntryTypeCompaction:
|
||||
var cd session.CompactionData
|
||||
if err := json.Unmarshal(entry.Data, &cd); err != nil {
|
||||
continue
|
||||
}
|
||||
// The summary is followed by an explicit continuation directive
|
||||
// so the model resumes the conversation rather than treating it
|
||||
// as a fresh start. Without this, models tend to reply with
|
||||
// openers like "I'm ready to help! Our previous conversation
|
||||
// covered X" — which loses the in-flight task context that
|
||||
// the user's next message implicitly relies on.
|
||||
content := "[Previous conversation summary]\n\n" + cd.Summary +
|
||||
"\n\nContinue the conversation from where it left off without asking the user any further questions. " +
|
||||
"Resume directly — do not acknowledge the summary, do not recap what was happening, " +
|
||||
"do not preface with \"I'll continue\" or similar. Pick up the last task as if the break never happened."
|
||||
msgs = append(msgs, llm.Message{
|
||||
Role: "user",
|
||||
Content: content,
|
||||
})
|
||||
|
||||
case session.EntryTypeMeta:
|
||||
// Meta entries (e.g. compaction summaries) are treated as system context
|
||||
var md session.MessageData
|
||||
if err := json.Unmarshal(entry.Data, &md); err != nil {
|
||||
continue
|
||||
}
|
||||
msgs = append(msgs, llm.Message{
|
||||
Role: "user",
|
||||
Content: "[Session Summary]\n" + md.Text,
|
||||
})
|
||||
|
||||
case session.EntryTypeMessage:
|
||||
var md session.MessageData
|
||||
if err := json.Unmarshal(entry.Data, &md); err != nil {
|
||||
continue
|
||||
}
|
||||
// Before appending a new message, check if the last assistant
|
||||
// message has orphaned tool calls that need synthetic results.
|
||||
msgs = injectMissingToolResults(msgs)
|
||||
msg := llm.Message{
|
||||
Role: entry.Role,
|
||||
Content: md.Text,
|
||||
}
|
||||
// Convert session images to LLM image content
|
||||
if entry.Role == "user" {
|
||||
for _, img := range md.Images {
|
||||
data, err := base64.StdEncoding.DecodeString(img.Data)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
msg.Images = append(msg.Images, llm.ImageContent{
|
||||
MimeType: detectImageMIME(data, img.MimeType),
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
}
|
||||
msgs = append(msgs, msg)
|
||||
|
||||
case session.EntryTypeToolCall:
|
||||
var td session.ToolCallData
|
||||
if err := json.Unmarshal(entry.Data, &td); err != nil {
|
||||
continue
|
||||
}
|
||||
// Skip a corrupted tool_call entry that has no ID — the
|
||||
// API requires every tool_use block to have a non-empty
|
||||
// tool_use_id that the matching tool_result references.
|
||||
// Reaches here when an old session file was written with
|
||||
// the pre-fix ToolCallEntry that swallowed marshal errors
|
||||
// on an empty json.RawMessage input and persisted
|
||||
// "data":null on disk. Skipping leaves the tool unpaired,
|
||||
// which assembleMessages's later injectMissingToolResults
|
||||
// pass would otherwise paper over with a synthetic error
|
||||
// result — but here both call AND result are absent from
|
||||
// the assistant message, which is the only safe shape
|
||||
// because the tool_result entry under it has no tool_use
|
||||
// to anchor to.
|
||||
if td.ID == "" {
|
||||
continue
|
||||
}
|
||||
// Tool calls are part of the assistant turn — merge into the last assistant message
|
||||
// or create one if needed
|
||||
if len(msgs) == 0 || msgs[len(msgs)-1].Role != "assistant" {
|
||||
msgs = append(msgs, llm.Message{Role: "assistant"})
|
||||
}
|
||||
msgs[len(msgs)-1].ToolCalls = append(msgs[len(msgs)-1].ToolCalls, llm.ToolCall{
|
||||
ID: td.ID,
|
||||
Name: td.Tool,
|
||||
Input: td.Input,
|
||||
})
|
||||
|
||||
case session.EntryTypeToolResult:
|
||||
var tr session.ToolResultData
|
||||
if err := json.Unmarshal(entry.Data, &tr); err != nil {
|
||||
continue
|
||||
}
|
||||
// Skip an orphan tool_result whose matching tool_call was
|
||||
// dropped above (e.g. corrupted "data":null tool_call from
|
||||
// the pre-fix ToolCallEntry). Sending the tool_result alone
|
||||
// would trigger Anthropic's "messages.N.content.0:
|
||||
// unexpected tool_use_id" 400 because no preceding
|
||||
// assistant message contains a tool_use with this ID.
|
||||
if !lastAssistantHasToolCall(msgs, tr.ToolCallID) {
|
||||
continue
|
||||
}
|
||||
content := tr.Output
|
||||
if tr.Error != "" {
|
||||
content = tr.Error
|
||||
}
|
||||
if content == "" {
|
||||
content = "(no output)"
|
||||
}
|
||||
msg := llm.Message{
|
||||
Role: "user",
|
||||
Content: content,
|
||||
ToolCallID: tr.ToolCallID,
|
||||
IsError: tr.IsError,
|
||||
}
|
||||
// Convert session images to LLM image content
|
||||
for _, img := range tr.Images {
|
||||
data, err := base64.StdEncoding.DecodeString(img.Data)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
msg.Images = append(msg.Images, llm.ImageContent{
|
||||
MimeType: detectImageMIME(data, img.MimeType),
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
msgs = append(msgs, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// Final check: handle orphaned tool calls at the end of history.
|
||||
msgs = injectMissingToolResults(msgs)
|
||||
|
||||
return msgs
|
||||
}
|
||||
|
||||
// injectMissingToolResults walks the message sequence and inserts synthetic
|
||||
// tool_result user messages for any assistant tool_calls that lack a matching
|
||||
// tool_result in the immediately-following user messages. Handles both
|
||||
// end-of-history orphans (the original case) and mid-history orphans (which
|
||||
// can occur when a Phase B parallel dispatch crashes mid-batch and the
|
||||
// session is later /resume'd).
|
||||
//
|
||||
// Algorithm: scan left-to-right; for each assistant message with ToolCalls,
|
||||
// collect the next k user messages' ToolCallIDs (where k = len(ToolCalls)).
|
||||
// Any tc.ID missing from that set gets a synthetic error tool_result inserted
|
||||
// immediately after the assistant message.
|
||||
func injectMissingToolResults(msgs []llm.Message) []llm.Message {
|
||||
if len(msgs) == 0 {
|
||||
return msgs
|
||||
}
|
||||
out := make([]llm.Message, 0, len(msgs))
|
||||
i := 0
|
||||
for i < len(msgs) {
|
||||
m := msgs[i]
|
||||
out = append(out, m)
|
||||
if m.Role != "assistant" || len(m.ToolCalls) == 0 {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
// Collect tool_call_ids present in the next user-role messages
|
||||
// immediately after this assistant turn. Stop when we hit a non-user
|
||||
// message or a user message lacking ToolCallID (which means it's a
|
||||
// regular user prompt, not a tool result).
|
||||
seen := map[string]bool{}
|
||||
j := i + 1
|
||||
for j < len(msgs) && msgs[j].Role == "user" && msgs[j].ToolCallID != "" {
|
||||
seen[msgs[j].ToolCallID] = true
|
||||
j++
|
||||
}
|
||||
// For each tool_call without a matching result, append a synthetic.
|
||||
for _, tc := range m.ToolCalls {
|
||||
if !seen[tc.ID] {
|
||||
out = append(out, llm.Message{
|
||||
Role: "user",
|
||||
Content: "(tool execution was interrupted)",
|
||||
ToolCallID: tc.ID,
|
||||
IsError: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
i++ // advance past this assistant; the for-loop will copy the user tool_results next iteration
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// lastAssistantHasToolCall reports whether the most recent assistant
|
||||
// message in msgs contains a tool_call with the given ID. Used by
|
||||
// assembleMessages to decide whether a tool_result entry has a
|
||||
// preceding tool_use to anchor to. Walks backward through msgs and
|
||||
// stops at the first assistant message it finds — there can only be
|
||||
// one preceding assistant block before any given tool_result run.
|
||||
func lastAssistantHasToolCall(msgs []llm.Message, id string) bool {
|
||||
if id == "" {
|
||||
return false
|
||||
}
|
||||
for i := len(msgs) - 1; i >= 0; i-- {
|
||||
if msgs[i].Role != "assistant" {
|
||||
continue
|
||||
}
|
||||
for _, tc := range msgs[i].ToolCalls {
|
||||
if tc.ID == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false // first assistant we hit didn't have it; no earlier one will count
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// truncationMarker / spillMarker uniquely identify content that
|
||||
// pruneToolResults has already shortened (truncated in-place) or spilled
|
||||
// to disk, so re-runs across turns become cheap no-ops instead of
|
||||
// re-scanning multi-hundred-KB tool outputs each time. Both markers are
|
||||
// recognised on idempotency check; only spillMarker is written when a
|
||||
// spillConfig is supplied and the disk write succeeds.
|
||||
const (
|
||||
truncationMarker = "[truncated — "
|
||||
spillMarker = "[spilled — "
|
||||
)
|
||||
|
||||
// spillConfig configures disk-spillover behaviour for pruneToolResults.
|
||||
// Zero value (Workspace == "") disables spillover and falls back to the
|
||||
// legacy in-place truncation path — keeping tests and any code path
|
||||
// without a workspace working unchanged.
|
||||
//
|
||||
// When Workspace is set, oversized tool results are written to
|
||||
// <Workspace>/.felix/spill/<SessionKey>/<ToolCallID>.txt and the message
|
||||
// is rewritten as: head preview (first maxLen chars cut at newline) +
|
||||
// spillMarker pointing the model at the absolute path so it can recover
|
||||
// the full output via read_file (which gates on Workspace).
|
||||
type spillConfig struct {
|
||||
Workspace string
|
||||
SessionKey string
|
||||
}
|
||||
|
||||
// spillToolResult writes content to the workspace-local spill directory
|
||||
// and returns the absolute path. Caller is responsible for handing that
|
||||
// path to the model. Returns an error on any I/O failure so callers can
|
||||
// fall back to truncation.
|
||||
func spillToolResult(cfg spillConfig, toolCallID, content string) (string, error) {
|
||||
if cfg.Workspace == "" || cfg.SessionKey == "" || toolCallID == "" {
|
||||
return "", fmt.Errorf("spillToolResult: workspace, session key, and tool call id are required")
|
||||
}
|
||||
dir := filepath.Join(cfg.Workspace, ".felix", "spill", cfg.SessionKey)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return "", fmt.Errorf("spill mkdir: %w", err)
|
||||
}
|
||||
path := filepath.Join(dir, toolCallID+".txt")
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
return "", fmt.Errorf("spill write: %w", err)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// pruneToolResults bounds oversized tool results in the message history
|
||||
// to prevent context window overflow and bound prefill growth. Only
|
||||
// affects tool result messages (identified by having a ToolCallID).
|
||||
// Idempotent: messages already shortened in a prior turn are skipped via
|
||||
// marker detection (truncationMarker or spillMarker).
|
||||
//
|
||||
// Two modes:
|
||||
// - With cfg.Workspace + cfg.SessionKey set: the FULL original content
|
||||
// is written to <Workspace>/.felix/spill/<SessionKey>/<ToolCallID>.txt
|
||||
// and the message becomes "<head>\n\n[spilled — N of M chars saved
|
||||
// to <abs path>; use read_file to access the full output]". The
|
||||
// model can recover the entire output via read_file, eliminating the
|
||||
// "re-run the tool" round-trip.
|
||||
// - Without spill config (or on spill write failure): falls back to
|
||||
// the legacy in-place truncation with truncationMarker. This keeps
|
||||
// callers without a workspace (tests, edge paths) working.
|
||||
//
|
||||
// Either way the retained head is the FIRST maxLen chars cut at the
|
||||
// nearest newline boundary — most tool outputs (file reads, command
|
||||
// output) are front-loaded with the most relevant info, so the head
|
||||
// preview is usually enough on its own.
|
||||
func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig) {
|
||||
for i := range msgs {
|
||||
if msgs[i].ToolCallID == "" || len(msgs[i].Content) <= maxLen {
|
||||
continue
|
||||
}
|
||||
// Already-shortened content carries one of the markers near the
|
||||
// end; skip the expensive LastIndex scan over hundreds of KB.
|
||||
if strings.Contains(msgs[i].Content, truncationMarker) ||
|
||||
strings.Contains(msgs[i].Content, spillMarker) {
|
||||
continue
|
||||
}
|
||||
originalLen := len(msgs[i].Content)
|
||||
head := msgs[i].Content[:maxLen]
|
||||
if idx := strings.LastIndex(head, "\n"); idx > maxLen/2 {
|
||||
head = head[:idx]
|
||||
}
|
||||
|
||||
// Try spill first if configured. On any failure, fall through to
|
||||
// legacy truncation so the prefill stays bounded either way.
|
||||
if cfg.Workspace != "" && cfg.SessionKey != "" {
|
||||
if path, err := spillToolResult(cfg, msgs[i].ToolCallID, msgs[i].Content); err == nil {
|
||||
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars saved to %s; use read_file to access the full output]",
|
||||
head, spillMarker, len(head), originalLen, path)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars; re-run the tool with offset/limit to see more]",
|
||||
head, truncationMarker, len(head), originalLen)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// FormatDateLine returns the canonical date line injected into the
|
||||
// dynamic system suffix every Run. Single-line, deterministic format.
|
||||
//
|
||||
// "Today's date is YYYY-MM-DD."
|
||||
//
|
||||
// Uses the caller's process timezone (no UTC normalization) so "today"
|
||||
// matches the user's local sense of the day.
|
||||
func FormatDateLine(now time.Time) string {
|
||||
return fmt.Sprintf("Today's date is %s.", now.Format("2006-01-02"))
|
||||
}
|
||||
|
||||
// PostCompactRestoreFiles caps how many recently-touched files
|
||||
// buildPostCompactRestore re-injects after a successful compaction.
|
||||
// 5 mirrors Claude Code's harness behaviour (harness.md §3) and keeps
|
||||
// the restore message bounded.
|
||||
const PostCompactRestoreFiles = 5
|
||||
|
||||
// PostCompactRestoreBytesPerFile bounds the per-file byte budget for
|
||||
// the restore message. ~5 KB per file × 5 files ≈ 25 KB total — modest
|
||||
// next to a 200K-token context window, large enough to carry a typical
|
||||
// source file's relevant region.
|
||||
const PostCompactRestoreBytesPerFile = 5 * 1024
|
||||
|
||||
// extractPathFromInput returns the "path" field from a tool call's
|
||||
// JSON input, or "" if absent / unparseable. Used by Runtime to record
|
||||
// which files the agent has touched (read_file/write_file/edit_file
|
||||
// all share the same {"path": "..."} schema).
|
||||
func extractPathFromInput(raw []byte) string {
|
||||
if len(raw) == 0 {
|
||||
return ""
|
||||
}
|
||||
var probe struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &probe); err != nil {
|
||||
return ""
|
||||
}
|
||||
return probe.Path
|
||||
}
|
||||
|
||||
// buildPostCompactRestore produces a single user-role llm.Message
|
||||
// containing the latest contents of the most-recent K touched files,
|
||||
// or returns an empty message (Content == "") when there's nothing
|
||||
// useful to inject.
|
||||
//
|
||||
// Selection: walks files newest-to-oldest (caller passes them in
|
||||
// touch order, so we range from the back), takes up to maxFiles paths
|
||||
// that exist and read successfully. Files larger than maxBytesPerFile
|
||||
// are read up to the cap and a short "[truncated]" marker appended —
|
||||
// truncating from the head matches our tool-result spillover convention
|
||||
// and keeps imports/declarations visible.
|
||||
//
|
||||
// Format is wrapped in <system-reminder>...<file path="...">...</file>
|
||||
// tags so the model recognises it as out-of-band context, not a fresh
|
||||
// user request. Mirrors how Claude Code re-injects POST_COMPACT files.
|
||||
func buildPostCompactRestore(files []string, maxFiles, maxBytesPerFile int) llm.Message {
|
||||
if len(files) == 0 || maxFiles <= 0 || maxBytesPerFile <= 0 {
|
||||
return llm.Message{}
|
||||
}
|
||||
var sb strings.Builder
|
||||
sb.WriteString("<system-reminder>\nFiles you were recently working with — full contents below for context restoration after history compaction. The file system is the source of truth; re-read with the read_file tool if you need updated content.\n\n")
|
||||
picked := 0
|
||||
for i := len(files) - 1; i >= 0 && picked < maxFiles; i-- {
|
||||
path := files[i]
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || info.IsDir() {
|
||||
continue
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
truncated := false
|
||||
if len(data) > maxBytesPerFile {
|
||||
data = data[:maxBytesPerFile]
|
||||
if idx := strings.LastIndex(string(data), "\n"); idx > maxBytesPerFile/2 {
|
||||
data = data[:idx]
|
||||
}
|
||||
truncated = true
|
||||
}
|
||||
fmt.Fprintf(&sb, "<file path=%q>\n", path)
|
||||
sb.Write(data)
|
||||
if !strings.HasSuffix(string(data), "\n") {
|
||||
sb.WriteString("\n")
|
||||
}
|
||||
if truncated {
|
||||
fmt.Fprintf(&sb, "[truncated — over %d bytes]\n", maxBytesPerFile)
|
||||
}
|
||||
sb.WriteString("</file>\n\n")
|
||||
picked++
|
||||
}
|
||||
if picked == 0 {
|
||||
return llm.Message{}
|
||||
}
|
||||
sb.WriteString("</system-reminder>")
|
||||
return llm.Message{Role: "user", Content: sb.String()}
|
||||
}
|
||||
|
||||
// prependPostCompactRestore is the runtime-facing helper: builds the
|
||||
// restore message with the standard caps and prepends it to msgs when
|
||||
// non-empty. Returns msgs unchanged when there are no touched files,
|
||||
// when every file fails to read, or when buildPostCompactRestore
|
||||
// otherwise produces an empty message — keeps the call sites in
|
||||
// runtime.go to a single line and centralises the cap policy.
|
||||
func prependPostCompactRestore(msgs []llm.Message, touched []string) []llm.Message {
|
||||
restore := buildPostCompactRestore(touched, PostCompactRestoreFiles, PostCompactRestoreBytesPerFile)
|
||||
if restore.Content == "" {
|
||||
return msgs
|
||||
}
|
||||
out := make([]llm.Message, 0, len(msgs)+1)
|
||||
out = append(out, restore)
|
||||
out = append(out, msgs...)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestBuildStaticSystemPromptWithIdentityFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.WriteFile(
|
||||
filepath.Join(dir, "IDENTITY.md"),
|
||||
[]byte("CUSTOM IDENTITY"),
|
||||
0o644,
|
||||
))
|
||||
|
||||
got := BuildStaticSystemPrompt(
|
||||
dir, "", "alpha", "Alpha",
|
||||
[]string{"read_file"},
|
||||
"Configured channels: cli",
|
||||
"\n\n## Skills Index\n\n- foo",
|
||||
"",
|
||||
"",
|
||||
)
|
||||
require.Contains(t, got, "CUSTOM IDENTITY")
|
||||
require.Contains(t, got, `"Alpha" agent (id: alpha)`)
|
||||
require.Contains(t, got, "Configured channels: cli")
|
||||
require.Contains(t, got, "## Skills Index")
|
||||
}
|
||||
|
||||
func TestBuildStaticSystemPromptConfigOverride(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "IDENTITY.md"), []byte("FROM_IDENTITY_FILE"), 0o644))
|
||||
|
||||
got := BuildStaticSystemPrompt(dir, "FROM CONFIG", "id", "Name", nil, "", "", "", "")
|
||||
require.Contains(t, got, "FROM CONFIG")
|
||||
require.NotContains(t, got, "FROM_IDENTITY_FILE")
|
||||
}
|
||||
|
||||
func TestBuildStaticSystemPromptDefaultIdentity(t *testing.T) {
|
||||
dir := t.TempDir() // no IDENTITY.md
|
||||
got := BuildStaticSystemPrompt(dir, "", "id", "Name", []string{"read_file", "bash"}, "", "", "", "")
|
||||
require.Contains(t, got, defaultIdentityBase)
|
||||
require.Contains(t, got, "read files")
|
||||
require.Contains(t, got, "bash commands")
|
||||
}
|
||||
|
||||
func TestBuildStaticSystemPromptByteStableAcrossCalls(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a := BuildStaticSystemPrompt(dir, "", "id", "Name", []string{"read_file"}, "summary", "index", "memidx", "")
|
||||
b := BuildStaticSystemPrompt(dir, "", "id", "Name", []string{"read_file"}, "summary", "index", "memidx", "")
|
||||
require.Equal(t, a, b, "BuildStaticSystemPrompt must be deterministic")
|
||||
}
|
||||
|
||||
func TestBuildStaticSystemPromptIncludesMemoryIndex(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
got := BuildStaticSystemPrompt(
|
||||
dir, "", "id", "Name",
|
||||
[]string{"read_file"},
|
||||
"", "",
|
||||
"\n\n## Memory Index\n\n- **note1** — A note: one-line desc",
|
||||
"",
|
||||
)
|
||||
require.Contains(t, got, "## Memory Index")
|
||||
require.Contains(t, got, "**note1**")
|
||||
require.Contains(t, got, "one-line desc")
|
||||
}
|
||||
|
||||
func TestBuildStaticSystemPromptIncludesMemoryFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
got := BuildStaticSystemPrompt(
|
||||
dir, "", "id", "Name",
|
||||
[]string{"read_file"},
|
||||
"", "", "",
|
||||
"\n\n## Project memory: /tmp/x\n\nUNIQUE_MEM_FILES_SENTINEL",
|
||||
)
|
||||
require.Contains(t, got, "UNIQUE_MEM_FILES_SENTINEL")
|
||||
require.Contains(t, got, "## Project memory:")
|
||||
}
|
||||
|
||||
func TestBuildDynamicSystemPromptSuffixEmpty(t *testing.T) {
|
||||
got := buildDynamicSystemPromptSuffix("", "")
|
||||
require.Equal(t, "", got)
|
||||
}
|
||||
|
||||
func TestBuildDynamicSystemPromptSuffixHintOnly(t *testing.T) {
|
||||
got := buildDynamicSystemPromptSuffix("", "\n\nHINT")
|
||||
require.Equal(t, "\n\nHINT", got)
|
||||
}
|
||||
|
||||
func TestBuildDynamicSystemPromptSuffixDateAndHint(t *testing.T) {
|
||||
got := buildDynamicSystemPromptSuffix("Today's date is 2026-05-01.", "\n\nKG_HINT")
|
||||
dateIdx := strings.Index(got, "Today's date is")
|
||||
hintIdx := strings.Index(got, "KG_HINT")
|
||||
require.True(t, dateIdx >= 0 && hintIdx > dateIdx,
|
||||
"order must be date < hint; got %d %d", dateIdx, hintIdx)
|
||||
}
|
||||
|
||||
func TestBuildDynamicSystemPromptSuffixIncludesDate(t *testing.T) {
|
||||
got := buildDynamicSystemPromptSuffix("Today's date is 2026-05-01.", "")
|
||||
require.True(t, strings.HasPrefix(got, "Today's date is 2026-05-01."),
|
||||
"date line must appear at the top of the dynamic suffix")
|
||||
}
|
||||
|
||||
func TestFormatDateLine(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
in time.Time
|
||||
want string
|
||||
}{
|
||||
{"may day", time.Date(2026, 5, 1, 12, 0, 0, 0, time.UTC), "Today's date is 2026-05-01."},
|
||||
{"new year", time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC), "Today's date is 2027-01-01."},
|
||||
{"single digit month", time.Date(2026, 3, 9, 23, 59, 59, 0, time.UTC), "Today's date is 2026-03-09."},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := FormatDateLine(tc.in)
|
||||
require.Equal(t, tc.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// maxAgentDepth returns the maximum subagent recursion depth permitted for
|
||||
// this Runtime. Precedence:
|
||||
// 1. Runtime.AgentLoop.MaxAgentDepth (>0) — config wins.
|
||||
// 2. HARNESS_MAX_AGENT_DEPTH env var (>0) — env fallback.
|
||||
// 3. Default 3.
|
||||
//
|
||||
// The cap exists to prevent runaway delegation chains (a parent invokes a
|
||||
// subagent that invokes another subagent ad infinitum). 3 was chosen as a
|
||||
// safe default that allows two-hop delegation patterns (default -> researcher
|
||||
// -> web_fetcher) while still terminating quickly.
|
||||
func (r *Runtime) maxAgentDepth() int {
|
||||
if r.AgentLoop.MaxAgentDepth > 0 {
|
||||
return r.AgentLoop.MaxAgentDepth
|
||||
}
|
||||
if v := os.Getenv("HARNESS_MAX_AGENT_DEPTH"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return 3
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
)
|
||||
|
||||
func TestMaxAgentDepth_Default(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_AGENT_DEPTH", "")
|
||||
if got := (&Runtime{}).maxAgentDepth(); got != 3 {
|
||||
t.Fatalf("got %d, want 3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaxAgentDepth_EnvOverride(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_AGENT_DEPTH", "5")
|
||||
if got := (&Runtime{}).maxAgentDepth(); got != 5 {
|
||||
t.Fatalf("got %d, want 5", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaxAgentDepth_InvalidFallsBack(t *testing.T) {
|
||||
cases := []string{"garbage", "0", "-1", "1.5", " 3 "}
|
||||
for _, v := range cases {
|
||||
t.Run(v, func(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_AGENT_DEPTH", v)
|
||||
if got := (&Runtime{}).maxAgentDepth(); got != 3 {
|
||||
t.Fatalf("env=%q: got %d, want 3", v, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntime_MaxAgentDepth_ConfigWinsOverEnv(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_AGENT_DEPTH", "7")
|
||||
r := &Runtime{AgentLoop: LoopConfig{MaxAgentDepth: 5}}
|
||||
if got := r.maxAgentDepth(); got != 5 {
|
||||
t.Errorf("got %d, want 5 (config wins)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntime_MaxAgentDepth_EnvWhenConfigZero(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_AGENT_DEPTH", "7")
|
||||
r := &Runtime{AgentLoop: LoopConfig{}}
|
||||
if got := r.maxAgentDepth(); got != 7 {
|
||||
t.Errorf("got %d, want 7 (env when config 0)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntime_MaxAgentDepth_DefaultWhenBothUnset(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_AGENT_DEPTH", "")
|
||||
r := &Runtime{AgentLoop: LoopConfig{}}
|
||||
if got := r.maxAgentDepth(); got != 3 {
|
||||
t.Errorf("got %d, want 3 (default)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntime_MaxAgentDepth_ConfigZeroOrNegativeFallsBackToEnv(t *testing.T) {
|
||||
// 0 in config means "use fallback"; negative is treated the same.
|
||||
for _, v := range []int{0, -1, -10} {
|
||||
t.Setenv("HARNESS_MAX_AGENT_DEPTH", "9")
|
||||
r := &Runtime{AgentLoop: LoopConfig{MaxAgentDepth: v}}
|
||||
if got := r.maxAgentDepth(); got != 9 {
|
||||
t.Errorf("config=%d: got %d, want 9 (env fallback)", v, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// fakeExecutor implements tool.Executor for dispatchTool tests.
|
||||
type fakeExecutor struct {
|
||||
called bool
|
||||
result tool.ToolResult
|
||||
err error
|
||||
// onExecute, when non-nil, runs before returning. Useful for triggering
|
||||
// ctx cancel mid-execution.
|
||||
onExecute func(ctx context.Context)
|
||||
}
|
||||
|
||||
func (f *fakeExecutor) Execute(ctx context.Context, name string, input json.RawMessage) (tool.ToolResult, error) {
|
||||
f.called = true
|
||||
if f.onExecute != nil {
|
||||
f.onExecute(ctx)
|
||||
}
|
||||
return f.result, f.err
|
||||
}
|
||||
func (f *fakeExecutor) ToolDefs() []llm.ToolDef { return nil }
|
||||
func (f *fakeExecutor) Names() []string { return nil }
|
||||
func (f *fakeExecutor) Get(name string) (tool.Tool, bool) { return nil, false }
|
||||
|
||||
// fakeChecker implements tool.PermissionChecker.
|
||||
type fakeChecker struct {
|
||||
decision tool.Decision
|
||||
}
|
||||
|
||||
func (c *fakeChecker) Check(_ context.Context, _, _ string, _ json.RawMessage) tool.Decision {
|
||||
return c.decision
|
||||
}
|
||||
|
||||
func (c *fakeChecker) FilterToolDefs(toolDefs []llm.ToolDef, _ string) []llm.ToolDef {
|
||||
return toolDefs
|
||||
}
|
||||
|
||||
// newDispatchRuntime returns a Runtime sufficient for dispatchTool tests.
|
||||
func newDispatchRuntime(exec tool.Executor, perm tool.PermissionChecker) *Runtime {
|
||||
return &Runtime{
|
||||
AgentID: "test_agent",
|
||||
Tools: exec,
|
||||
Permission: perm,
|
||||
Session: session.NewSession("test_agent", "test_key"),
|
||||
}
|
||||
}
|
||||
|
||||
// sampleToolCall returns a representative llm.ToolCall.
|
||||
func sampleToolCall() llm.ToolCall {
|
||||
return llm.ToolCall{ID: "tc_1", Name: "read_file", Input: json.RawMessage(`{"path":"/tmp/x"}`)}
|
||||
}
|
||||
|
||||
// lastEntries returns the final n entries from the session for assertions.
|
||||
func lastEntries(s *session.Session, n int) []session.SessionEntry {
|
||||
all := s.View()
|
||||
if len(all) < n {
|
||||
return all
|
||||
}
|
||||
return all[len(all)-n:]
|
||||
}
|
||||
|
||||
// decodeToolResult unmarshals a ToolResult entry's data.
|
||||
func decodeToolResult(t *testing.T, e session.SessionEntry) session.ToolResultData {
|
||||
t.Helper()
|
||||
require.Equal(t, session.EntryTypeToolResult, e.Type)
|
||||
var d session.ToolResultData
|
||||
require.NoError(t, json.Unmarshal(e.Data, &d))
|
||||
return d
|
||||
}
|
||||
|
||||
func TestDispatchTool_CleanResult(t *testing.T) {
|
||||
exec := &fakeExecutor{
|
||||
result: tool.ToolResult{Output: "hello"},
|
||||
}
|
||||
r := newDispatchRuntime(exec, nil)
|
||||
|
||||
result, aborted := r.dispatchTool(context.Background(), sampleToolCall(), nil)
|
||||
|
||||
require.False(t, aborted)
|
||||
require.Equal(t, "hello", result.Output)
|
||||
require.Empty(t, result.Error)
|
||||
require.True(t, exec.called)
|
||||
|
||||
entries := lastEntries(r.Session, 2)
|
||||
require.Equal(t, session.EntryTypeToolCall, entries[0].Type)
|
||||
d := decodeToolResult(t, entries[1])
|
||||
require.Equal(t, "hello", d.Output)
|
||||
require.False(t, d.IsError)
|
||||
require.False(t, d.Aborted)
|
||||
}
|
||||
|
||||
func TestDispatchTool_ToolReturnsError(t *testing.T) {
|
||||
exec := &fakeExecutor{
|
||||
result: tool.ToolResult{Error: "file not found"},
|
||||
}
|
||||
r := newDispatchRuntime(exec, nil)
|
||||
|
||||
result, aborted := r.dispatchTool(context.Background(), sampleToolCall(), nil)
|
||||
|
||||
require.False(t, aborted)
|
||||
require.Equal(t, "file not found", result.Error)
|
||||
|
||||
entries := lastEntries(r.Session, 2)
|
||||
d := decodeToolResult(t, entries[1])
|
||||
require.Equal(t, "file not found", d.Error)
|
||||
require.True(t, d.IsError)
|
||||
require.False(t, d.Aborted)
|
||||
}
|
||||
|
||||
func TestDispatchTool_ExecuteReturnsGoError(t *testing.T) {
|
||||
exec := &fakeExecutor{
|
||||
err: errors.New("transport failure"),
|
||||
}
|
||||
r := newDispatchRuntime(exec, nil)
|
||||
|
||||
result, aborted := r.dispatchTool(context.Background(), sampleToolCall(), nil)
|
||||
|
||||
require.False(t, aborted)
|
||||
require.Contains(t, result.Error, "transport failure")
|
||||
|
||||
entries := lastEntries(r.Session, 2)
|
||||
d := decodeToolResult(t, entries[1])
|
||||
require.Contains(t, d.Error, "transport failure")
|
||||
require.True(t, d.IsError)
|
||||
}
|
||||
|
||||
func TestDispatchTool_PermissionDenied(t *testing.T) {
|
||||
exec := &fakeExecutor{
|
||||
result: tool.ToolResult{Output: "should not appear"},
|
||||
}
|
||||
perm := &fakeChecker{decision: tool.Decision{
|
||||
Behavior: tool.DecisionDeny,
|
||||
Reason: "policy denies bash",
|
||||
}}
|
||||
r := newDispatchRuntime(exec, perm)
|
||||
|
||||
result, aborted := r.dispatchTool(context.Background(), sampleToolCall(), nil)
|
||||
|
||||
require.False(t, aborted)
|
||||
require.False(t, exec.called, "Execute must not run when denied")
|
||||
require.Equal(t, "policy denies bash", result.Error)
|
||||
|
||||
entries := lastEntries(r.Session, 2)
|
||||
d := decodeToolResult(t, entries[1])
|
||||
require.Equal(t, "policy denies bash", d.Error)
|
||||
require.True(t, d.IsError)
|
||||
require.False(t, d.Aborted)
|
||||
}
|
||||
|
||||
func TestDispatchTool_CancelledBeforeExecute(t *testing.T) {
|
||||
exec := &fakeExecutor{
|
||||
result: tool.ToolResult{Output: "should not appear"},
|
||||
}
|
||||
r := newDispatchRuntime(exec, nil)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel() // already cancelled
|
||||
|
||||
result, aborted := r.dispatchTool(ctx, sampleToolCall(), nil)
|
||||
|
||||
require.True(t, aborted)
|
||||
require.False(t, exec.called, "Execute must not run when ctx is already cancelled")
|
||||
require.Equal(t, "aborted by user", result.Error)
|
||||
|
||||
entries := lastEntries(r.Session, 2)
|
||||
d := decodeToolResult(t, entries[1])
|
||||
require.True(t, d.Aborted)
|
||||
require.True(t, d.IsError)
|
||||
require.Equal(t, "aborted by user", d.Error)
|
||||
}
|
||||
|
||||
func TestDispatchTool_CancelledAfterExecute(t *testing.T) {
|
||||
// Executor completes successfully but ctx is cancelled before dispatchTool
|
||||
// notices. Real output must be discarded; abort marker written.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
exec := &fakeExecutor{
|
||||
result: tool.ToolResult{Output: "real output that should be dropped"},
|
||||
onExecute: func(_ context.Context) {
|
||||
cancel() // cancel during Execute
|
||||
},
|
||||
}
|
||||
r := newDispatchRuntime(exec, nil)
|
||||
|
||||
result, aborted := r.dispatchTool(ctx, sampleToolCall(), nil)
|
||||
|
||||
require.True(t, aborted)
|
||||
require.True(t, exec.called)
|
||||
require.Equal(t, "aborted by user", result.Error)
|
||||
require.Empty(t, result.Output)
|
||||
|
||||
entries := lastEntries(r.Session, 2)
|
||||
d := decodeToolResult(t, entries[1])
|
||||
require.True(t, d.Aborted)
|
||||
require.Empty(t, d.Output)
|
||||
}
|
||||
|
||||
func TestDispatchTool_ExecutorReturnsCtxErrIsRecordedAsAborted(t *testing.T) {
|
||||
// A ctx-aware tool that returns ctx.Err() when cancelled. dispatchTool
|
||||
// must record this as an abort (Aborted=true), not a normal error,
|
||||
// because the user pressed Ctrl-C — the tool didn't fail organically.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
exec := &fakeExecutor{
|
||||
onExecute: func(c context.Context) {
|
||||
cancel()
|
||||
},
|
||||
err: context.Canceled, // simulates a ctx-aware tool returning ctx.Err()
|
||||
}
|
||||
r := newDispatchRuntime(exec, nil)
|
||||
|
||||
result, aborted := r.dispatchTool(ctx, sampleToolCall(), nil)
|
||||
|
||||
require.True(t, aborted, "must report aborted when ctx is cancelled, even if executor surfaced ctx.Err()")
|
||||
require.True(t, exec.called)
|
||||
require.Equal(t, "aborted by user", result.Error, "result must carry the abort reason, not the executor's error")
|
||||
|
||||
entries := lastEntries(r.Session, 2)
|
||||
d := decodeToolResult(t, entries[1])
|
||||
require.True(t, d.Aborted, "session entry must be marked Aborted")
|
||||
require.Equal(t, "aborted by user", d.Error)
|
||||
require.Empty(t, d.Output)
|
||||
}
|
||||
|
||||
func TestDispatchTool_CortexThreadAtomicWithSession(t *testing.T) {
|
||||
// Verifies the cortex thread receives matching messages in lockstep
|
||||
// with the session writes — this is the atomicity contract dispatchTool
|
||||
// promises to Phase B/C/D parallel callers.
|
||||
exec := &fakeExecutor{
|
||||
result: tool.ToolResult{Output: "hello"},
|
||||
}
|
||||
r := newDispatchRuntime(exec, nil)
|
||||
|
||||
thread := []Message{}
|
||||
_, aborted := r.dispatchTool(context.Background(), sampleToolCall(), &thread)
|
||||
|
||||
require.False(t, aborted)
|
||||
require.Len(t, thread, 2, "cortex thread must receive one assistant message + one user message")
|
||||
|
||||
// First message: the assistant tool-call announcement.
|
||||
require.Equal(t, "assistant", thread[0].Role)
|
||||
require.Contains(t, thread[0].Content, "[tool: read_file]")
|
||||
require.Contains(t, thread[0].Content, `"path":"/tmp/x"`)
|
||||
|
||||
// Second message: the user-side result. Clean output (no error prefix).
|
||||
require.Equal(t, "user", thread[1].Role)
|
||||
require.Equal(t, "hello", thread[1].Content)
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
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/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// --- 6a: subagent context inheritance ---
|
||||
|
||||
func TestInheritParentHistoryCopiesViewIntoSubagentSession(t *testing.T) {
|
||||
parent := session.NewSession("parent", "key")
|
||||
parent.Append(session.UserMessageEntry("first user msg"))
|
||||
parent.Append(session.AssistantMessageEntry("first reply"))
|
||||
parent.Append(session.UserMessageEntry("second user msg"))
|
||||
|
||||
sub := NewSubagentSession("sub")
|
||||
inheritParentHistory(sub, parent)
|
||||
|
||||
subView := sub.View()
|
||||
require.Len(t, subView, 3, "all 3 parent entries must land in subagent")
|
||||
|
||||
// Order preserved.
|
||||
var got []string
|
||||
for _, e := range subView {
|
||||
var data session.MessageData
|
||||
require.NoError(t, decodeMessage(e, &data))
|
||||
got = append(got, data.Text)
|
||||
}
|
||||
assert.Equal(t, []string{"first user msg", "first reply", "second user msg"}, got)
|
||||
}
|
||||
|
||||
func TestInheritParentHistoryWalksFromInheritedLeaf(t *testing.T) {
|
||||
// The first inherited entry must lose its ParentID — otherwise the
|
||||
// subagent's empty leafID lets Append leave a dangling pointer to a
|
||||
// parent entry that doesn't exist in the subagent's entryMap, and
|
||||
// View() walking back from that leaf either short-circuits early
|
||||
// or includes nothing.
|
||||
parent := session.NewSession("parent", "key")
|
||||
parent.Append(session.UserMessageEntry("u1"))
|
||||
parent.Append(session.AssistantMessageEntry("a1"))
|
||||
|
||||
sub := NewSubagentSession("sub")
|
||||
inheritParentHistory(sub, parent)
|
||||
|
||||
// View walks back from leaf via ParentID; we must reach BOTH entries.
|
||||
require.Len(t, sub.View(), 2, "View must traverse all inherited entries")
|
||||
}
|
||||
|
||||
func TestInheritParentHistoryEmptyParentIsNoOp(t *testing.T) {
|
||||
parent := session.NewSession("parent", "key") // no entries
|
||||
sub := NewSubagentSession("sub")
|
||||
inheritParentHistory(sub, parent)
|
||||
assert.Empty(t, sub.View())
|
||||
}
|
||||
|
||||
func TestSubagentFactoryInheritsContextWhenFlagSet(t *testing.T) {
|
||||
cfg := newTwoAgentCfg(t)
|
||||
// Enable InheritContext on the researcher.
|
||||
cfgInheritOn := func(id string) (SubagentSpec, bool) {
|
||||
ss, ok := cfg.Resolve(id)
|
||||
if ok && ss.Spec.ID == "researcher" {
|
||||
ss.InheritContext = true
|
||||
}
|
||||
return ss, ok
|
||||
}
|
||||
parent := &Runtime{
|
||||
LLM: &scriptedTextLLM{text: "p"},
|
||||
Session: session.NewSession("default", "test"),
|
||||
AgentID: "default",
|
||||
Model: "p",
|
||||
}
|
||||
parent.Session.Append(session.UserMessageEntry("ORIGINAL_USER_MSG"))
|
||||
parent.Session.Append(session.AssistantMessageEntry("ORIGINAL_REPLY"))
|
||||
|
||||
subLLM := &scriptedTextLLM{text: "ok"}
|
||||
factory := MakeSubagentFactory(cfgInheritOn, RuntimeDeps{}, subagentBuilderForLLM(subLLM), parent)
|
||||
|
||||
runner, err := factory(context.Background(), "researcher", 0)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Pull the subagent's runtime out via the adapter to inspect its
|
||||
// pre-populated session before the run advances the chain.
|
||||
rt := runner.(*subagentRunnerAdapter).rt
|
||||
view := rt.Session.View()
|
||||
require.Len(t, view, 2, "InheritContext must copy parent's 2 entries")
|
||||
var first session.MessageData
|
||||
require.NoError(t, decodeMessage(view[0], &first))
|
||||
assert.Equal(t, "ORIGINAL_USER_MSG", first.Text)
|
||||
}
|
||||
|
||||
func TestSubagentFactoryDoesNotInheritWhenFlagUnset(t *testing.T) {
|
||||
cfg := newTwoAgentCfg(t)
|
||||
parent := &Runtime{
|
||||
LLM: &scriptedTextLLM{text: "p"},
|
||||
Session: session.NewSession("default", "test"),
|
||||
AgentID: "default",
|
||||
Model: "p",
|
||||
}
|
||||
parent.Session.Append(session.UserMessageEntry("ORIGINAL_USER_MSG"))
|
||||
|
||||
factory := MakeSubagentFactory(cfg.Resolve, RuntimeDeps{}, subagentBuilderForLLM(&scriptedTextLLM{text: "ok"}), parent)
|
||||
runner, err := factory(context.Background(), "researcher", 0)
|
||||
require.NoError(t, err)
|
||||
rt := runner.(*subagentRunnerAdapter).rt
|
||||
assert.Empty(t, rt.Session.View(), "subagent must start with empty session when InheritContext is false")
|
||||
}
|
||||
|
||||
// --- 6b: provider fallback model ---
|
||||
|
||||
// retryableThenSuccessProvider returns IsRetryableModelError on the first
|
||||
// call and a working stream on the second. Used to verify the runtime's
|
||||
// fallback retry flips req.Model and re-invokes ChatStream.
|
||||
type retryableThenSuccessProvider struct {
|
||||
llmtest.Base
|
||||
calls int
|
||||
modelsSeen []string
|
||||
finalText string
|
||||
}
|
||||
|
||||
func (p *retryableThenSuccessProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.calls++
|
||||
p.modelsSeen = append(p.modelsSeen, req.Model)
|
||||
if p.calls == 1 {
|
||||
// errors.New so the runtime can call .Error() safely. The
|
||||
// substring classifier in IsRetryableModelError catches "529"
|
||||
// and "overloaded" — exercises the same retry path as a typed
|
||||
// anthropic.Error{StatusCode:529} would, without the SDK
|
||||
// internals's panic on partially-constructed Error structs.
|
||||
return nil, errors.New("anthropic 529 overloaded — try again")
|
||||
}
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: p.finalText}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func TestRuntimeFallbackModelRetriesOnRetryableError(t *testing.T) {
|
||||
prov := &retryableThenSuccessProvider{finalText: "fallback won"}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-sonnet-4-5",
|
||||
FallbackModel: "claude-haiku-3-5",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 2,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
out, err := rt.RunSync(context.Background(), "do it", nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "fallback won", out)
|
||||
require.Equal(t, 2, prov.calls, "primary call + fallback retry = 2 calls")
|
||||
assert.Equal(t, "claude-sonnet-4-5", prov.modelsSeen[0])
|
||||
assert.Equal(t, "claude-haiku-3-5", prov.modelsSeen[1])
|
||||
}
|
||||
|
||||
// nonRetryableProvider always returns a non-retryable error. The runtime
|
||||
// must NOT engage the fallback (otherwise misconfigurations get masked).
|
||||
type nonRetryableProvider struct {
|
||||
llmtest.Base
|
||||
calls int
|
||||
}
|
||||
|
||||
func (p *nonRetryableProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.calls++
|
||||
return nil, errors.New("invalid api key")
|
||||
}
|
||||
|
||||
func TestRuntimeFallbackModelDoesNotEngageOnNonRetryableError(t *testing.T) {
|
||||
prov := &nonRetryableProvider{}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-sonnet-4-5",
|
||||
FallbackModel: "claude-haiku-3-5",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 2,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
_, err := rt.RunSync(context.Background(), "do it", nil)
|
||||
require.Error(t, err, "non-retryable error must surface to caller")
|
||||
assert.Equal(t, 1, prov.calls, "no retry on non-retryable error")
|
||||
}
|
||||
|
||||
func TestRuntimeFallbackModelNoFallbackConfigured(t *testing.T) {
|
||||
prov := &retryableThenSuccessProvider{finalText: "should not reach"}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-sonnet-4-5",
|
||||
// FallbackModel: "" — fallback disabled
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 2,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
_, err := rt.RunSync(context.Background(), "do it", nil)
|
||||
require.Error(t, err, "with no fallback configured the retryable error still fails")
|
||||
assert.Equal(t, 1, prov.calls, "no retry without configured fallback")
|
||||
}
|
||||
|
||||
func TestBuildRuntimeStripsProviderPrefixFromFallbackModel(t *testing.T) {
|
||||
spec := AgentSpec{
|
||||
ID: "a",
|
||||
Name: "A",
|
||||
Model: "anthropic/claude-sonnet-4-5",
|
||||
FallbackModel: "anthropic/claude-haiku-3-5",
|
||||
Workspace: t.TempDir(),
|
||||
MaxTurns: 5,
|
||||
}
|
||||
rt, err := BuildRuntime(
|
||||
RuntimeDeps{},
|
||||
RuntimeInputs{
|
||||
Provider: &scriptedTextLLM{text: "ok"},
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
},
|
||||
spec,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "claude-haiku-3-5", rt.FallbackModel,
|
||||
"provider prefix must be stripped — Runtime.LLM is bound to a single provider")
|
||||
}
|
||||
|
||||
func TestBuildRuntimeRejectsCrossProviderFallback(t *testing.T) {
|
||||
// Cross-provider fallback (anthropic primary, openai fallback) is
|
||||
// nonsense given Runtime.LLM holds one provider client. Discard
|
||||
// rather than silently swap to a model the wrong client can't
|
||||
// route, and log a warning so the misconfig is visible.
|
||||
spec := AgentSpec{
|
||||
ID: "a",
|
||||
Name: "A",
|
||||
Model: "anthropic/claude-sonnet-4-5",
|
||||
FallbackModel: "openai/gpt-4o-mini",
|
||||
Workspace: t.TempDir(),
|
||||
MaxTurns: 5,
|
||||
}
|
||||
rt, err := BuildRuntime(
|
||||
RuntimeDeps{},
|
||||
RuntimeInputs{
|
||||
Provider: &scriptedTextLLM{text: "ok"},
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
},
|
||||
spec,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "", rt.FallbackModel, "cross-provider fallback must be discarded")
|
||||
}
|
||||
|
||||
// decodeMessage unmarshals a session entry's MessageData payload.
|
||||
func decodeMessage(e session.SessionEntry, dst *session.MessageData) error {
|
||||
return json.Unmarshal(e.Data, dst)
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// batch is a contiguous group of tool calls that may be dispatched together.
|
||||
// concurrencySafe=true means they can run in parallel; false means single-call
|
||||
// (the partitioner emits one batch per unsafe call).
|
||||
type batch struct {
|
||||
concurrencySafe bool
|
||||
calls []llm.ToolCall
|
||||
}
|
||||
|
||||
// partitionToolCalls groups consecutive concurrency-safe calls into one batch
|
||||
// each, and emits a single-call batch for every unsafe call. Order is
|
||||
// preserved both within and across batches. Tools not found in the executor
|
||||
// are treated as unsafe (defensive). If a tool's IsConcurrencySafe panics,
|
||||
// the recover treats it as unsafe and logs at WARN.
|
||||
func partitionToolCalls(tcs []llm.ToolCall, ex tool.Executor) []batch {
|
||||
out := []batch{}
|
||||
for _, tc := range tcs {
|
||||
safe := isCallConcurrencySafe(tc, ex)
|
||||
// Append to the previous safe batch if both are safe; otherwise start
|
||||
// a new batch. Unsafe calls always start their own batch (single-call).
|
||||
if safe && len(out) > 0 && out[len(out)-1].concurrencySafe {
|
||||
out[len(out)-1].calls = append(out[len(out)-1].calls, tc)
|
||||
continue
|
||||
}
|
||||
out = append(out, batch{concurrencySafe: safe, calls: []llm.ToolCall{tc}})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// isCallConcurrencySafe looks up the tool and asks it; recovers from any
|
||||
// panic in the tool's IsConcurrencySafe and treats it as unsafe.
|
||||
func isCallConcurrencySafe(tc llm.ToolCall, ex tool.Executor) (safe bool) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
slog.Warn("tool IsConcurrencySafe panicked; treating as unsafe",
|
||||
"tool", tc.Name, "panic", r)
|
||||
safe = false
|
||||
}
|
||||
}()
|
||||
tool, ok := ex.Get(tc.Name)
|
||||
if !ok {
|
||||
return false // unknown tool → unsafe (dispatchTool will report the error)
|
||||
}
|
||||
return tool.IsConcurrencySafe(tc.Input)
|
||||
}
|
||||
|
||||
// maxToolConcurrency returns the cap on concurrent tool dispatch within a
|
||||
// safe batch. Precedence:
|
||||
// 1. Runtime.AgentLoop.MaxToolConcurrency (>0) — config wins.
|
||||
// 2. HARNESS_MAX_TOOL_CONCURRENCY env var (>0) — env fallback.
|
||||
// 3. Default 10.
|
||||
func (r *Runtime) maxToolConcurrency() int {
|
||||
if r.AgentLoop.MaxToolConcurrency > 0 {
|
||||
return r.AgentLoop.MaxToolConcurrency
|
||||
}
|
||||
if v := os.Getenv("HARNESS_MAX_TOOL_CONCURRENCY"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return 10
|
||||
}
|
||||
|
||||
// runBatch dispatches the calls in a batch. Concurrency-safe batches with len
|
||||
// > 1 fan out via sync.WaitGroup + semaphore (capped by maxToolConcurrency()).
|
||||
// Single-call batches (any safety) call dispatchTool directly. Returns true
|
||||
// if any call was aborted, in which case Run should break the outer loop.
|
||||
//
|
||||
// Sibling cancellation: parallel goroutines see the parent ctx. They are NOT
|
||||
// cancelled by sibling errors or sibling aborts — only by user abort (parent
|
||||
// ctx cancel). Reads are independent; a failed web_fetch should not invalidate
|
||||
// a parallel read_file.
|
||||
//
|
||||
// Event emission: each goroutine emits EventToolResult via r.emit as it
|
||||
// completes (completion order, not input order). When this function returns,
|
||||
// every call in the batch has had its event emitted. Subagent runtimes
|
||||
// forward each emission up to their parent's events channel.
|
||||
func (r *Runtime) runBatch(
|
||||
ctx context.Context,
|
||||
b batch,
|
||||
kgThread *[]Message,
|
||||
turn int,
|
||||
tr *Trace,
|
||||
) (aborted bool) {
|
||||
// Single-call batch (safe or unsafe): direct synchronous dispatch.
|
||||
if len(b.calls) == 1 {
|
||||
tc := b.calls[0]
|
||||
result, abortedOne := r.dispatchTool(ctx, tc, kgThread)
|
||||
r.emitToolResult(tr, turn, tc, result, abortedOne)
|
||||
return abortedOne
|
||||
}
|
||||
|
||||
// Parallel batch: WaitGroup + semaphore.
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
anyAborted atomic.Bool
|
||||
sem = make(chan struct{}, r.maxToolConcurrency())
|
||||
)
|
||||
wg.Add(len(b.calls))
|
||||
for i := range b.calls {
|
||||
tc := b.calls[i]
|
||||
sem <- struct{}{} // block when at cap
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
|
||||
result, abortedOne := r.dispatchTool(ctx, tc, kgThread)
|
||||
r.emitToolResult(tr, turn, tc, result, abortedOne)
|
||||
if abortedOne {
|
||||
anyAborted.Store(true)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return anyAborted.Load()
|
||||
}
|
||||
|
||||
// emitToolResult writes the per-call trace mark, log line, and EventToolResult.
|
||||
// Centralised so the parallel runBatch and the single-call path produce the
|
||||
// same event/log shape. Routes through r.emit so subagent runtimes forward
|
||||
// the event to their parent's channel as well.
|
||||
func (r *Runtime) emitToolResult(tr *Trace, turn int, tc llm.ToolCall, result tool.ToolResult, aborted bool) {
|
||||
tr.Mark("tool.exec",
|
||||
"turn", turn,
|
||||
"tool", tc.Name,
|
||||
"err", result.Error != "",
|
||||
"output_chars", len(result.Output),
|
||||
"aborted", aborted)
|
||||
|
||||
if result.Error != "" {
|
||||
slog.Warn("tool error", "tool", tc.Name, "id", tc.ID, "error", result.Error)
|
||||
} else {
|
||||
outPreview := result.Output
|
||||
if len(outPreview) > 500 {
|
||||
outPreview = outPreview[:500] + "...(truncated)"
|
||||
}
|
||||
slog.Debug("tool result", "tool", tc.Name, "id", tc.ID, "output_len", len(result.Output), "output", outPreview)
|
||||
}
|
||||
|
||||
r.emit(AgentEvent{
|
||||
Type: EventToolResult,
|
||||
ToolCall: &tc,
|
||||
Result: &result,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type classifyExecutor struct {
|
||||
safe map[string]bool
|
||||
panics map[string]bool
|
||||
}
|
||||
|
||||
func (e *classifyExecutor) Execute(_ context.Context, _ string, _ json.RawMessage) (tool.ToolResult, error) {
|
||||
return tool.ToolResult{}, nil
|
||||
}
|
||||
func (e *classifyExecutor) ToolDefs() []llm.ToolDef { return nil }
|
||||
func (e *classifyExecutor) Names() []string { return nil }
|
||||
func (e *classifyExecutor) Get(name string) (tool.Tool, bool) {
|
||||
if _, ok := e.safe[name]; !ok {
|
||||
return nil, false
|
||||
}
|
||||
return &classifyTool{name: name, safe: e.safe[name], doPanic: e.panics[name]}, true
|
||||
}
|
||||
|
||||
type classifyTool struct {
|
||||
name string
|
||||
safe bool
|
||||
doPanic bool
|
||||
}
|
||||
|
||||
func (t *classifyTool) Name() string { return t.name }
|
||||
func (t *classifyTool) Description() string { return "" }
|
||||
func (t *classifyTool) Parameters() json.RawMessage { return nil }
|
||||
func (t *classifyTool) Execute(_ context.Context, _ json.RawMessage) (tool.ToolResult, error) {
|
||||
return tool.ToolResult{}, nil
|
||||
}
|
||||
func (t *classifyTool) IsConcurrencySafe(_ json.RawMessage) bool {
|
||||
if t.doPanic {
|
||||
panic("test-induced panic")
|
||||
}
|
||||
return t.safe
|
||||
}
|
||||
|
||||
func tc(name string) llm.ToolCall {
|
||||
return llm.ToolCall{ID: "tc_" + name, Name: name, Input: json.RawMessage(`{}`)}
|
||||
}
|
||||
|
||||
func TestPartition_Empty(t *testing.T) {
|
||||
ex := &classifyExecutor{safe: map[string]bool{}}
|
||||
require.Empty(t, partitionToolCalls(nil, ex))
|
||||
require.Empty(t, partitionToolCalls([]llm.ToolCall{}, ex))
|
||||
}
|
||||
|
||||
func TestPartition_AllSafe(t *testing.T) {
|
||||
ex := &classifyExecutor{safe: map[string]bool{"r": true}}
|
||||
calls := []llm.ToolCall{tc("r"), tc("r"), tc("r")}
|
||||
batches := partitionToolCalls(calls, ex)
|
||||
require.Len(t, batches, 1)
|
||||
require.True(t, batches[0].concurrencySafe)
|
||||
require.Len(t, batches[0].calls, 3)
|
||||
}
|
||||
|
||||
func TestPartition_AllUnsafe(t *testing.T) {
|
||||
ex := &classifyExecutor{safe: map[string]bool{"w": false}}
|
||||
calls := []llm.ToolCall{tc("w"), tc("w"), tc("w")}
|
||||
batches := partitionToolCalls(calls, ex)
|
||||
require.Len(t, batches, 3)
|
||||
for _, b := range batches {
|
||||
require.False(t, b.concurrencySafe)
|
||||
require.Len(t, b.calls, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPartition_Mixed(t *testing.T) {
|
||||
ex := &classifyExecutor{safe: map[string]bool{"r": true, "w": false}}
|
||||
// [safe, safe, unsafe, safe] → 3 batches: [{safe,2}, {unsafe,1}, {safe,1}]
|
||||
calls := []llm.ToolCall{tc("r"), tc("r"), tc("w"), tc("r")}
|
||||
batches := partitionToolCalls(calls, ex)
|
||||
require.Len(t, batches, 3)
|
||||
|
||||
require.True(t, batches[0].concurrencySafe)
|
||||
require.Len(t, batches[0].calls, 2)
|
||||
|
||||
require.False(t, batches[1].concurrencySafe)
|
||||
require.Len(t, batches[1].calls, 1)
|
||||
|
||||
require.True(t, batches[2].concurrencySafe)
|
||||
require.Len(t, batches[2].calls, 1)
|
||||
}
|
||||
|
||||
func TestPartition_ToolNotFoundIsUnsafe(t *testing.T) {
|
||||
ex := &classifyExecutor{safe: map[string]bool{}}
|
||||
batches := partitionToolCalls([]llm.ToolCall{tc("missing")}, ex)
|
||||
require.Len(t, batches, 1)
|
||||
require.False(t, batches[0].concurrencySafe, "unknown tool must be treated as unsafe")
|
||||
}
|
||||
|
||||
func TestPartition_PanicIsRecoveredAsUnsafe(t *testing.T) {
|
||||
ex := &classifyExecutor{
|
||||
safe: map[string]bool{"p": true}, // would be safe…
|
||||
panics: map[string]bool{"p": true}, // …but IsConcurrencySafe panics
|
||||
}
|
||||
batches := partitionToolCalls([]llm.ToolCall{tc("p")}, ex)
|
||||
require.Len(t, batches, 1)
|
||||
require.False(t, batches[0].concurrencySafe, "panic must be recovered and treated as unsafe")
|
||||
}
|
||||
|
||||
func TestMaxToolConcurrency_Default(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_CONCURRENCY", "")
|
||||
require.Equal(t, 10, (&Runtime{}).maxToolConcurrency())
|
||||
}
|
||||
|
||||
func TestMaxToolConcurrency_EnvOverride(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_CONCURRENCY", "3")
|
||||
require.Equal(t, 3, (&Runtime{}).maxToolConcurrency())
|
||||
}
|
||||
|
||||
func TestMaxToolConcurrency_InvalidEnvFallsBack(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_CONCURRENCY", "garbage")
|
||||
require.Equal(t, 10, (&Runtime{}).maxToolConcurrency())
|
||||
}
|
||||
|
||||
func TestMaxToolConcurrency_ZeroFallsBack(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_CONCURRENCY", "0")
|
||||
require.Equal(t, 10, (&Runtime{}).maxToolConcurrency(), "0 is invalid; fall back to default")
|
||||
}
|
||||
|
||||
func TestRuntime_MaxToolConcurrency_ConfigWinsOverEnv(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_CONCURRENCY", "7")
|
||||
r := &Runtime{AgentLoop: LoopConfig{MaxToolConcurrency: 4}}
|
||||
require.Equal(t, 4, r.maxToolConcurrency(), "config should win over env")
|
||||
}
|
||||
|
||||
func TestRuntime_MaxToolConcurrency_EnvWhenConfigZero(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_CONCURRENCY", "7")
|
||||
r := &Runtime{AgentLoop: LoopConfig{}}
|
||||
require.Equal(t, 7, r.maxToolConcurrency(), "env should fill in when config is zero")
|
||||
}
|
||||
|
||||
func TestRuntime_MaxToolConcurrency_DefaultWhenBothUnset(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_CONCURRENCY", "")
|
||||
r := &Runtime{AgentLoop: LoopConfig{}}
|
||||
require.Equal(t, 10, r.maxToolConcurrency(), "default 10 when neither set")
|
||||
}
|
||||
|
||||
func TestRuntime_MaxToolConcurrency_ConfigZeroOrNegativeFallsBackToEnv(t *testing.T) {
|
||||
for _, v := range []int{0, -1, -10} {
|
||||
t.Setenv("HARNESS_MAX_TOOL_CONCURRENCY", "9")
|
||||
r := &Runtime{AgentLoop: LoopConfig{MaxToolConcurrency: v}}
|
||||
require.Equalf(t, 9, r.maxToolConcurrency(), "config=%d should fall back to env", v)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// --- providerSupportsMidLoopCompaction ---
|
||||
|
||||
func TestProviderSupportsMidLoopCompactionMatrix(t *testing.T) {
|
||||
cases := map[string]bool{
|
||||
"anthropic": true,
|
||||
"openai": true,
|
||||
"gemini": true,
|
||||
"local": false,
|
||||
"ollama": false,
|
||||
"": false, // empty/unknown defaults to off (safety)
|
||||
"deepseek": false, // not yet classified — opt-in via the switch
|
||||
}
|
||||
for provider, want := range cases {
|
||||
r := &Runtime{Provider: provider}
|
||||
assert.Equalf(t, want, r.providerSupportsMidLoopCompaction(),
|
||||
"provider=%q", provider)
|
||||
}
|
||||
}
|
||||
|
||||
// --- recordFileTouch ordering + dedupe ---
|
||||
|
||||
func TestRecordFileTouchAppendsAndDedupesByMoveToBack(t *testing.T) {
|
||||
r := &Runtime{}
|
||||
r.recordFileTouch("a.go")
|
||||
r.recordFileTouch("b.go")
|
||||
r.recordFileTouch("c.go")
|
||||
r.recordFileTouch("a.go") // re-touch — should move to back, not duplicate
|
||||
|
||||
got := r.snapshotTouchedFiles()
|
||||
assert.Equal(t, []string{"b.go", "c.go", "a.go"}, got)
|
||||
}
|
||||
|
||||
func TestRecordFileTouchIgnoresEmptyPath(t *testing.T) {
|
||||
r := &Runtime{}
|
||||
r.recordFileTouch("")
|
||||
r.recordFileTouch("x.go")
|
||||
r.recordFileTouch("")
|
||||
|
||||
assert.Equal(t, []string{"x.go"}, r.snapshotTouchedFiles())
|
||||
}
|
||||
|
||||
func TestSnapshotTouchedFilesReturnsCopy(t *testing.T) {
|
||||
r := &Runtime{}
|
||||
r.recordFileTouch("a.go")
|
||||
snap := r.snapshotTouchedFiles()
|
||||
snap[0] = "mutated"
|
||||
// Mutation of the snapshot must not bleed back into the live slice;
|
||||
// otherwise concurrent post-compact restore reads could observe
|
||||
// torn paths under load.
|
||||
assert.Equal(t, []string{"a.go"}, r.snapshotTouchedFiles())
|
||||
}
|
||||
|
||||
// --- extractPathFromInput ---
|
||||
|
||||
func TestExtractPathFromInputHappyPath(t *testing.T) {
|
||||
in, _ := json.Marshal(map[string]string{"path": "/tmp/foo.go"})
|
||||
assert.Equal(t, "/tmp/foo.go", extractPathFromInput(in))
|
||||
}
|
||||
|
||||
func TestExtractPathFromInputMissingFieldReturnsEmpty(t *testing.T) {
|
||||
in, _ := json.Marshal(map[string]string{"command": "ls"})
|
||||
assert.Equal(t, "", extractPathFromInput(in))
|
||||
}
|
||||
|
||||
func TestExtractPathFromInputBadJSONReturnsEmpty(t *testing.T) {
|
||||
assert.Equal(t, "", extractPathFromInput([]byte("not-json{")))
|
||||
assert.Equal(t, "", extractPathFromInput(nil))
|
||||
}
|
||||
|
||||
// --- buildPostCompactRestore ---
|
||||
|
||||
func TestBuildPostCompactRestoreFormatsLatestKFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a := filepath.Join(dir, "a.go")
|
||||
b := filepath.Join(dir, "b.go")
|
||||
c := filepath.Join(dir, "c.go")
|
||||
require.NoError(t, os.WriteFile(a, []byte("package a\n"), 0o644))
|
||||
require.NoError(t, os.WriteFile(b, []byte("package b\n"), 0o644))
|
||||
require.NoError(t, os.WriteFile(c, []byte("package c\n"), 0o644))
|
||||
|
||||
// Touch order: a, b, c — newest is c. K=2 should pick c then b
|
||||
// (newest-first walk), and skip a entirely.
|
||||
msg := buildPostCompactRestore([]string{a, b, c}, 2, 1024)
|
||||
|
||||
require.Equal(t, "user", msg.Role)
|
||||
assert.Contains(t, msg.Content, "<system-reminder>")
|
||||
assert.Contains(t, msg.Content, "</system-reminder>")
|
||||
assert.Contains(t, msg.Content, c, "newest file must be present")
|
||||
assert.Contains(t, msg.Content, b, "second-newest must be present")
|
||||
assert.NotContains(t, msg.Content, a, "K=2 cap must drop the oldest")
|
||||
}
|
||||
|
||||
func TestBuildPostCompactRestoreSkipsMissingAndDir(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
good := filepath.Join(dir, "good.go")
|
||||
require.NoError(t, os.WriteFile(good, []byte("ok\n"), 0o644))
|
||||
missing := filepath.Join(dir, "missing.go")
|
||||
subdir := filepath.Join(dir, "sub")
|
||||
require.NoError(t, os.Mkdir(subdir, 0o755))
|
||||
|
||||
msg := buildPostCompactRestore([]string{missing, subdir, good}, 5, 1024)
|
||||
assert.Contains(t, msg.Content, good)
|
||||
assert.NotContains(t, msg.Content, missing)
|
||||
assert.NotContains(t, msg.Content, "<file path=\""+subdir)
|
||||
}
|
||||
|
||||
func TestBuildPostCompactRestoreReturnsEmptyWhenNothingReadable(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
missing := filepath.Join(dir, "ghost.go")
|
||||
msg := buildPostCompactRestore([]string{missing}, 5, 1024)
|
||||
assert.Equal(t, "", msg.Content,
|
||||
"all-failed read must collapse to empty (caller skips empty)")
|
||||
}
|
||||
|
||||
func TestBuildPostCompactRestoreTruncatesOversizedFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
big := filepath.Join(dir, "big.txt")
|
||||
// 4 KB file, cap at 1 KB → should get truncation marker
|
||||
content := strings.Repeat("x", 4*1024)
|
||||
require.NoError(t, os.WriteFile(big, []byte(content), 0o644))
|
||||
|
||||
msg := buildPostCompactRestore([]string{big}, 1, 1024)
|
||||
assert.Contains(t, msg.Content, "[truncated — over 1024 bytes]")
|
||||
// Sanity: the included content must be ≤ cap + marker overhead.
|
||||
// Anything close to 4 KB means the cap silently failed.
|
||||
assert.Less(t, len(msg.Content), 2*1024)
|
||||
}
|
||||
|
||||
func TestBuildPostCompactRestoreEmptyInputs(t *testing.T) {
|
||||
assert.Equal(t, "", buildPostCompactRestore(nil, 5, 1024).Content)
|
||||
assert.Equal(t, "", buildPostCompactRestore([]string{"x"}, 0, 1024).Content)
|
||||
assert.Equal(t, "", buildPostCompactRestore([]string{"x"}, 5, 0).Content)
|
||||
}
|
||||
|
||||
// --- prependPostCompactRestore (runtime-facing wrapper) ---
|
||||
|
||||
func TestPrependPostCompactRestoreInjectsBeforeExisting(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
f := filepath.Join(dir, "f.go")
|
||||
require.NoError(t, os.WriteFile(f, []byte("hi\n"), 0o644))
|
||||
|
||||
original := []llm.Message{
|
||||
{Role: "user", Content: "what next?"},
|
||||
}
|
||||
got := prependPostCompactRestore(original, []string{f})
|
||||
|
||||
require.Len(t, got, 2)
|
||||
assert.Equal(t, "user", got[0].Role)
|
||||
assert.Contains(t, got[0].Content, "<system-reminder>")
|
||||
assert.Contains(t, got[0].Content, f)
|
||||
assert.Equal(t, original[0], got[1], "original messages must follow restore intact")
|
||||
}
|
||||
|
||||
func TestPrependPostCompactRestoreReturnsUnchangedWhenNoFiles(t *testing.T) {
|
||||
original := []llm.Message{{Role: "user", Content: "hi"}}
|
||||
got := prependPostCompactRestore(original, nil)
|
||||
assert.Equal(t, original, got)
|
||||
}
|
||||
|
||||
func TestPrependPostCompactRestoreReturnsUnchangedWhenAllUnreadable(t *testing.T) {
|
||||
original := []llm.Message{{Role: "user", Content: "hi"}}
|
||||
got := prependPostCompactRestore(original, []string{"/nonexistent/ghost.go"})
|
||||
assert.Equal(t, original, got, "unreadable touched files must not produce an empty restore wrapper")
|
||||
}
|
||||
@@ -0,0 +1,773 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/compaction"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tokens"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// EventType identifies the kind of agent event.
|
||||
type EventType int
|
||||
|
||||
const (
|
||||
EventTextDelta EventType = iota
|
||||
EventToolCallStart
|
||||
EventToolResult
|
||||
EventDone
|
||||
EventError
|
||||
EventAborted
|
||||
EventCompactionStart
|
||||
EventCompactionDone
|
||||
EventCompactionSkipped
|
||||
)
|
||||
|
||||
// AgentEvent is a single streaming event from the agent.
|
||||
type AgentEvent struct {
|
||||
Type EventType
|
||||
// AgentID is the emitter's agent identifier. Empty for top-level
|
||||
// (Parent==nil) runtimes; populated by Runtime.emit when forwarding a
|
||||
// subagent's event up to its parent.
|
||||
AgentID string
|
||||
Text string
|
||||
ToolCall *llm.ToolCall
|
||||
Result *tool.ToolResult
|
||||
Error error
|
||||
Compaction *compaction.Result // populated for EventCompaction* events
|
||||
Usage *llm.Usage // populated for EventDone when the provider reported it
|
||||
}
|
||||
|
||||
// Runtime is the agent think-act loop.
|
||||
type Runtime struct {
|
||||
LLM llm.LLMProvider
|
||||
Tools tool.Executor
|
||||
Session *session.Session
|
||||
AgentID string
|
||||
AgentName string
|
||||
Model string
|
||||
Reasoning llm.ReasoningMode // optional; zero value = ReasoningOff
|
||||
Workspace string
|
||||
MaxTurns int
|
||||
// AgentLoop carries the loop tunables (concurrency cap, depth cap,
|
||||
// streaming-tools toggle). Zero value → readers fall back to env vars
|
||||
// then compiled-in defaults.
|
||||
AgentLoop LoopConfig
|
||||
SystemPrompt string // optional: inline system prompt
|
||||
Skills SkillProvider // optional: skill index + load_skill backend
|
||||
Memory MemoryProvider // optional: memory index + load_memory backend
|
||||
KG KnowledgeGraph // optional: knowledge-graph plug point
|
||||
Compaction *compaction.Manager // optional; nil → no compaction
|
||||
|
||||
// Provider is the LLM provider name parsed from the agent's
|
||||
// "provider/model" model string (e.g., "anthropic", "openai", "local").
|
||||
Provider string
|
||||
|
||||
// FallbackModel is the bare model name to retry against on a synchronous
|
||||
// ChatStream error matching llm.IsRetryableModelError.
|
||||
FallbackModel string
|
||||
|
||||
// ContextWindow overrides the auto-detected window. 0 = auto-detect.
|
||||
ContextWindow int
|
||||
|
||||
// StaticSystemPrompt is the cacheable portion of the system prompt.
|
||||
// Built once at BuildRuntime time; reused verbatim every turn so the
|
||||
// prompt cache hits.
|
||||
StaticSystemPrompt string
|
||||
|
||||
// Permission gates tool execution at dispatch time. nil → allow-all.
|
||||
Permission tool.PermissionChecker
|
||||
|
||||
// Depth is the recursion level for subagents. 0 for top-level agents.
|
||||
Depth int
|
||||
|
||||
// Parent points to the Runtime that invoked this Runtime as a subagent.
|
||||
Parent *Runtime
|
||||
|
||||
events chan AgentEvent
|
||||
|
||||
// kgMu serializes appends to the per-Run KG thread when parallel
|
||||
// dispatchTool calls happen from multiple goroutines.
|
||||
kgMu sync.Mutex
|
||||
|
||||
// touchedFiles is the in-order list of file paths the agent has
|
||||
// successfully read/written/edited during this Runtime's lifetime.
|
||||
touchedMu sync.Mutex
|
||||
touchedFiles []string
|
||||
|
||||
// IngestSource controls whether this run's thread is ingested into the KG.
|
||||
// "chat" (or empty) ingests; any other value skips ingest.
|
||||
IngestSource string
|
||||
|
||||
// CalibratorStore persists the per-session token Calibrator. nil = off.
|
||||
CalibratorStore *tokens.CalibratorStore
|
||||
|
||||
calibrator *tokens.Calibrator
|
||||
}
|
||||
|
||||
// emit sends ev to this runtime's events channel and forwards a copy to
|
||||
// Parent.events when this is a subagent. Forward is non-blocking — drops
|
||||
// when the parent's channel is full.
|
||||
func (r *Runtime) emit(ev AgentEvent) {
|
||||
if r.Parent != nil {
|
||||
forward := ev
|
||||
forward.AgentID = r.AgentID
|
||||
select {
|
||||
case r.Parent.events <- forward:
|
||||
default:
|
||||
}
|
||||
}
|
||||
r.events <- ev
|
||||
}
|
||||
|
||||
// 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) {
|
||||
if r.Compaction == nil || r.Model == "" {
|
||||
return
|
||||
}
|
||||
if r.Compaction.HasInFlight(r.Session) {
|
||||
return
|
||||
}
|
||||
if r.calibrator == nil {
|
||||
r.calibrator = tokens.NewCalibrator()
|
||||
}
|
||||
estimate := r.calibrator.Adjust(tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs))
|
||||
window := tokens.ContextWindowFor(r.Model, r.ContextWindow)
|
||||
threshold := 0.6
|
||||
if r.Compaction.Threshold > 0 {
|
||||
threshold = r.Compaction.Threshold
|
||||
}
|
||||
preemptThresholdHit := window > 0 && float64(estimate) > 0.8*threshold*float64(window)
|
||||
msgCap := r.Compaction.MessageCap
|
||||
preemptCountHit := msgCap > 0 && len(msgs) > int(0.8*float64(msgCap))
|
||||
if !preemptThresholdHit && !preemptCountHit {
|
||||
return
|
||||
}
|
||||
r.Compaction.MaybeCompactAsync(r.Session, compaction.ReasonPreventive)
|
||||
}
|
||||
|
||||
// providerSupportsCaching returns true when the runtime's provider implements
|
||||
// Anthropic-style explicit prompt caching.
|
||||
func (r *Runtime) providerSupportsCaching() bool {
|
||||
return r.Provider == "anthropic"
|
||||
}
|
||||
|
||||
// providerSupportsMidLoopCompaction returns true for hosted frontier
|
||||
// providers that handle mid-loop summary injection cleanly.
|
||||
func (r *Runtime) providerSupportsMidLoopCompaction() bool {
|
||||
switch r.Provider {
|
||||
case "anthropic", "openai", "gemini":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// recordFileTouch appends path to the touched-files list, deduping by moving
|
||||
// an existing entry to the end.
|
||||
func (r *Runtime) recordFileTouch(path string) {
|
||||
if path == "" || r == nil {
|
||||
return
|
||||
}
|
||||
r.touchedMu.Lock()
|
||||
defer r.touchedMu.Unlock()
|
||||
for i, p := range r.touchedFiles {
|
||||
if p == path {
|
||||
r.touchedFiles = append(append(r.touchedFiles[:i:i], r.touchedFiles[i+1:]...), path)
|
||||
return
|
||||
}
|
||||
}
|
||||
r.touchedFiles = append(r.touchedFiles, path)
|
||||
}
|
||||
|
||||
// snapshotTouchedFiles returns a copy of the current touched-files list.
|
||||
func (r *Runtime) snapshotTouchedFiles() []string {
|
||||
r.touchedMu.Lock()
|
||||
defer r.touchedMu.Unlock()
|
||||
out := make([]string, len(r.touchedFiles))
|
||||
copy(out, r.touchedFiles)
|
||||
return out
|
||||
}
|
||||
|
||||
// isFileTool reports whether a tool name's input contains a "path" field.
|
||||
func isFileTool(name string) bool {
|
||||
switch name {
|
||||
case "read_file", "write_file", "edit_file":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Run executes the agent loop for a user message, returning a channel of events.
|
||||
func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageContent) (<-chan AgentEvent, error) {
|
||||
r.events = make(chan AgentEvent, 100)
|
||||
tr := TraceFrom(ctx)
|
||||
tr.Mark("agent.run.start", "user_msg_len", len(userMsg), "images", len(images))
|
||||
|
||||
go func() {
|
||||
defer close(r.events)
|
||||
defer tr.Summary()
|
||||
|
||||
if len(images) > 0 {
|
||||
var imgData []session.ImageData
|
||||
for _, img := range images {
|
||||
imgData = append(imgData, session.ImageData{
|
||||
MimeType: img.MimeType,
|
||||
Data: base64.StdEncoding.EncodeToString(img.Data),
|
||||
})
|
||||
}
|
||||
r.Session.Append(session.UserMessageWithImagesEntry(userMsg, imgData))
|
||||
} else {
|
||||
r.Session.Append(session.UserMessageEntry(userMsg))
|
||||
}
|
||||
|
||||
// Initialise KG thread and recall (once, before the loop). Recall
|
||||
// runs in a background goroutine so it overlaps with message
|
||||
// assembly. The main goroutine waits for it (with an 800ms cap)
|
||||
// before invoking the LLM. Ingest is gated by IngestSource.
|
||||
var thread []Message
|
||||
kgContext := ""
|
||||
var kgCh chan string
|
||||
var kgCancel context.CancelFunc
|
||||
shouldIngest := r.IngestSource == "" || r.IngestSource == "chat"
|
||||
if r.KG != nil {
|
||||
thread = []Message{{Role: "user", Content: userMsg}}
|
||||
if r.KG.ShouldRecall(userMsg) {
|
||||
kgCh = make(chan string, 1)
|
||||
var kgCtx context.Context
|
||||
kgCtx, kgCancel = context.WithCancel(ctx)
|
||||
kgStart := time.Now()
|
||||
kg := r.KG
|
||||
go func() {
|
||||
hint := kg.Recall(kgCtx, userMsg)
|
||||
tr.Mark("kg.recall", "len", len(hint), "dur_ms_local", time.Since(kgStart).Milliseconds())
|
||||
kgCh <- hint
|
||||
}()
|
||||
} else {
|
||||
tr.Mark("kg.recall.skipped", "reason", "trivial")
|
||||
}
|
||||
|
||||
kg := r.KG
|
||||
defer func() {
|
||||
if kgCancel != nil {
|
||||
kgCancel()
|
||||
}
|
||||
if shouldIngest && len(thread) > 1 {
|
||||
kg.Ingest(context.Background(), thread)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
maxTurns := r.MaxTurns
|
||||
if maxTurns == 0 {
|
||||
maxTurns = 25
|
||||
}
|
||||
|
||||
// Computed once per Run so the date stays stable across turns.
|
||||
dateLine := FormatDateLine(time.Now())
|
||||
|
||||
for turn := 0; turn < maxTurns; turn++ {
|
||||
if ctx.Err() != nil {
|
||||
r.emit(AgentEvent{Type: EventAborted})
|
||||
return
|
||||
}
|
||||
|
||||
phaseStart := time.Now()
|
||||
|
||||
// KG hint: on first turn wait for the background Recall (with
|
||||
// 800ms cap so a slow embedder can't stall the request).
|
||||
if kgCh != nil && kgContext == "" {
|
||||
select {
|
||||
case kgContext = <-kgCh:
|
||||
case <-time.After(800 * time.Millisecond):
|
||||
tr.Mark("kg.recall.timeout", "turn", turn, "budget_ms", 800)
|
||||
if kgCancel != nil {
|
||||
kgCancel()
|
||||
kgCancel = nil
|
||||
}
|
||||
}
|
||||
kgCh = nil
|
||||
}
|
||||
|
||||
dynamicSuffix := buildDynamicSystemPromptSuffix(dateLine, kgContext)
|
||||
|
||||
staticText := r.StaticSystemPrompt
|
||||
parts := []llm.SystemPromptPart{
|
||||
{Text: staticText, Cache: true},
|
||||
}
|
||||
if dynamicSuffix != "" {
|
||||
parts = append(parts, llm.SystemPromptPart{Text: dynamicSuffix, Cache: false})
|
||||
}
|
||||
|
||||
history := r.Session.View()
|
||||
msgs := assembleMessages(history)
|
||||
|
||||
spillCfg := spillConfig{Workspace: r.Workspace, SessionKey: r.Session.Key}
|
||||
pruneToolResults(msgs, maxToolResultLen, spillCfg)
|
||||
|
||||
toolDefs := r.Tools.ToolDefs()
|
||||
if r.Permission != nil {
|
||||
toolDefs = r.Permission.FilterToolDefs(toolDefs, r.AgentID)
|
||||
}
|
||||
sort.SliceStable(toolDefs, func(i, j int) bool {
|
||||
return toolDefs[i].Name < toolDefs[j].Name
|
||||
})
|
||||
toolDefs, diags := r.LLM.NormalizeToolSchema(toolDefs)
|
||||
for _, d := range diags {
|
||||
slog.Info("tool schema normalized",
|
||||
"tool", d.ToolName,
|
||||
"field", d.Field,
|
||||
"action", d.Action,
|
||||
"reason", d.Reason)
|
||||
}
|
||||
tr.Mark("context.assemble", "turn", turn, "msgs", len(msgs), "tools", len(toolDefs), "sysprompt_chars", len(staticText)+len(dynamicSuffix), "dur_ms_local", time.Since(phaseStart).Milliseconds())
|
||||
|
||||
// Wait briefly on any in-flight async compaction kicked off by
|
||||
// the previous turn.
|
||||
if turn == 0 && r.Compaction != nil {
|
||||
if res, ok := r.Compaction.WaitForInFlight(r.Session, 8*time.Second); ok && res.Compacted {
|
||||
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
|
||||
history = r.Session.View()
|
||||
msgs = assembleMessages(history)
|
||||
pruneToolResults(msgs, maxToolResultLen, spillCfg)
|
||||
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
|
||||
}
|
||||
}
|
||||
|
||||
compactionAllowed := turn == 0 || r.providerSupportsMidLoopCompaction()
|
||||
if compactionAllowed && r.Compaction != nil && r.Model != "" {
|
||||
if r.calibrator == nil {
|
||||
r.calibrator = tokens.NewCalibrator()
|
||||
}
|
||||
estimate := r.calibrator.Adjust(tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs))
|
||||
window := tokens.ContextWindowFor(r.Model, r.ContextWindow)
|
||||
threshold := 0.6
|
||||
if r.Compaction != nil && r.Compaction.Threshold > 0 {
|
||||
threshold = r.Compaction.Threshold
|
||||
}
|
||||
thresholdHit := window > 0 && estimate > int(threshold*float64(window))
|
||||
msgCap := r.Compaction.MessageCap
|
||||
countHit := msgCap > 0 && len(msgs) > msgCap
|
||||
if thresholdHit || countHit {
|
||||
r.emit(AgentEvent{Type: EventCompactionStart})
|
||||
res, _ := r.Compaction.MaybeCompact(ctx, r.Session, compaction.ReasonPreventive, "")
|
||||
if res.Compacted {
|
||||
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
|
||||
history = r.Session.View()
|
||||
msgs = assembleMessages(history)
|
||||
pruneToolResults(msgs, maxToolResultLen, spillCfg)
|
||||
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
|
||||
} else {
|
||||
r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
req := llm.ChatRequest{
|
||||
Model: r.Model,
|
||||
Messages: msgs,
|
||||
Tools: toolDefs,
|
||||
MaxTokens: 8192,
|
||||
SystemPromptParts: parts,
|
||||
CacheLastMessage: r.providerSupportsCaching(),
|
||||
Reasoning: r.Reasoning,
|
||||
}
|
||||
|
||||
llmStart := time.Now()
|
||||
prefillChars := len(staticText) + len(dynamicSuffix)
|
||||
for _, m := range msgs {
|
||||
prefillChars += len(m.Content)
|
||||
}
|
||||
tr.Mark("llm.request_sent", "turn", turn, "model", r.Model, "prefill_chars", prefillChars)
|
||||
stream, err := r.LLM.ChatStream(ctx, req)
|
||||
if err != nil {
|
||||
if compaction.IsContextOverflow(err) && r.Compaction != nil {
|
||||
r.emit(AgentEvent{Type: EventCompactionStart})
|
||||
res, _ := r.Compaction.MaybeCompact(ctx, r.Session, compaction.ReasonReactive, "")
|
||||
if res.Compacted {
|
||||
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
|
||||
history = r.Session.View()
|
||||
msgs = assembleMessages(history)
|
||||
pruneToolResults(msgs, maxToolResultLen, spillCfg)
|
||||
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
|
||||
req.Messages = msgs
|
||||
stream, err = r.LLM.ChatStream(ctx, req)
|
||||
} else {
|
||||
r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res})
|
||||
}
|
||||
}
|
||||
if err != nil && r.FallbackModel != "" && r.FallbackModel != req.Model && llm.IsRetryableModelError(err) {
|
||||
slog.Info("llm fallback model engaged",
|
||||
"agent", r.AgentID,
|
||||
"primary", req.Model,
|
||||
"fallback", r.FallbackModel,
|
||||
"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)
|
||||
}
|
||||
if err != nil {
|
||||
r.emit(AgentEvent{Type: EventError, Error: fmt.Errorf("llm error: %w", err)})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var textContent strings.Builder
|
||||
var lastUsage *llm.Usage
|
||||
var toolCalls []llm.ToolCall
|
||||
gotFirstToken := false
|
||||
|
||||
streamingOn := r.streamingToolsEnabled()
|
||||
kickoffs := map[string]chan kickoffResult{}
|
||||
kickoffStopped := false
|
||||
|
||||
streamSource := stream
|
||||
retriedNonStreaming := false
|
||||
streamLoop:
|
||||
for {
|
||||
for event := range streamSource {
|
||||
switch event.Type {
|
||||
case llm.EventTextDelta:
|
||||
if !gotFirstToken {
|
||||
gotFirstToken = true
|
||||
tr.Mark("llm.first_token", "turn", turn, "ttft_ms", time.Since(llmStart).Milliseconds())
|
||||
}
|
||||
textContent.WriteString(event.Text)
|
||||
r.emit(AgentEvent{Type: EventTextDelta, Text: event.Text})
|
||||
|
||||
case llm.EventToolCallStart:
|
||||
if !gotFirstToken {
|
||||
gotFirstToken = true
|
||||
tr.Mark("llm.first_token", "turn", turn, "ttft_ms", time.Since(llmStart).Milliseconds(), "kind", "tool_call")
|
||||
}
|
||||
r.emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall})
|
||||
|
||||
case llm.EventToolCallDone:
|
||||
if event.ToolCall == nil {
|
||||
continue
|
||||
}
|
||||
tc := *event.ToolCall
|
||||
toolCalls = append(toolCalls, tc)
|
||||
if !streamingOn || kickoffStopped {
|
||||
continue
|
||||
}
|
||||
if !isCallConcurrencySafe(tc, r.Tools) {
|
||||
kickoffStopped = true
|
||||
continue
|
||||
}
|
||||
ch := make(chan kickoffResult, 1)
|
||||
kickoffs[tc.ID] = ch
|
||||
tcCopy := tc
|
||||
go func() {
|
||||
result, aborted := r.executeToolKickoff(ctx, tcCopy)
|
||||
r.emitToolResult(tr, turn, tcCopy, result, aborted)
|
||||
ch <- kickoffResult{tc: tcCopy, result: result, aborted: aborted}
|
||||
}()
|
||||
|
||||
case llm.EventDone:
|
||||
if event.Usage != nil {
|
||||
lastUsage = event.Usage
|
||||
}
|
||||
if event.Usage != nil && r.calibrator != nil {
|
||||
r.calibrator.Update(event.Usage.InputTokens, tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs))
|
||||
if r.CalibratorStore != nil && r.Session != nil {
|
||||
ratio, count := r.calibrator.Snapshot()
|
||||
r.CalibratorStore.Save(r.AgentID, r.Session.Key, ratio, count)
|
||||
}
|
||||
}
|
||||
|
||||
case llm.EventError:
|
||||
if gotFirstToken && !retriedNonStreaming {
|
||||
if ns, ok := r.LLM.(llm.NonStreamingProvider); ok {
|
||||
slog.Warn("stream died mid-flight; retrying as non-streaming",
|
||||
"agent", r.AgentID, "turn", turn, "err", event.Error)
|
||||
tr.Mark("llm.stream_fallback", "turn", turn, "err", event.Error.Error())
|
||||
textContent.Reset()
|
||||
toolCalls = nil
|
||||
drainKickoffs(kickoffs)
|
||||
kickoffs = map[string]chan kickoffResult{}
|
||||
gotFirstToken = false
|
||||
kickoffStopped = false
|
||||
nsStream, retryErr := ns.ChatNonStreaming(ctx, req)
|
||||
if retryErr != nil {
|
||||
r.emit(AgentEvent{Type: EventError, Error: retryErr})
|
||||
return
|
||||
}
|
||||
retriedNonStreaming = true
|
||||
streamSource = nsStream
|
||||
continue streamLoop
|
||||
}
|
||||
}
|
||||
drainKickoffs(kickoffs)
|
||||
r.emit(AgentEvent{Type: EventError, Error: event.Error})
|
||||
return
|
||||
}
|
||||
}
|
||||
break streamLoop
|
||||
}
|
||||
tr.Mark("llm.stream_end", "turn", turn,
|
||||
"total_ms", time.Since(llmStart).Milliseconds(),
|
||||
"text_chars", textContent.Len(),
|
||||
"tool_calls", len(toolCalls))
|
||||
|
||||
if textContent.Len() > 0 {
|
||||
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
|
||||
if r.KG != nil {
|
||||
r.kgMu.Lock()
|
||||
thread = append(thread, Message{
|
||||
Role: "assistant",
|
||||
Content: textContent.String(),
|
||||
})
|
||||
r.kgMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
if len(toolCalls) == 0 {
|
||||
if len(kickoffs) > 0 {
|
||||
drainKickoffs(kickoffs)
|
||||
}
|
||||
tr.Mark("agent.done", "turn", turn, "reason", "no_tool_calls")
|
||||
r.emit(AgentEvent{Type: EventDone, Usage: lastUsage})
|
||||
r.maybeKickoffAsyncCompaction(msgs, parts, toolDefs)
|
||||
return
|
||||
}
|
||||
|
||||
var pending []llm.ToolCall
|
||||
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()
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
pending = append(pending, tc)
|
||||
}
|
||||
|
||||
batches := partitionToolCalls(pending, r.Tools)
|
||||
for _, b := range batches {
|
||||
if r.runBatch(ctx, b, kgThreadOrNil(r.KG, &thread), turn, tr) {
|
||||
r.emit(AgentEvent{Type: EventAborted})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
r.emit(AgentEvent{
|
||||
Type: EventError,
|
||||
Error: fmt.Errorf("agent exceeded maximum turns (%d)", maxTurns),
|
||||
})
|
||||
}()
|
||||
|
||||
return r.events, nil
|
||||
}
|
||||
|
||||
// RunSync is a convenience method that runs the agent and collects the
|
||||
// full text response.
|
||||
func (r *Runtime) RunSync(ctx context.Context, userMsg string, images []llm.ImageContent) (string, error) {
|
||||
events, err := r.Run(ctx, userMsg, images)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var response strings.Builder
|
||||
for event := range events {
|
||||
switch event.Type {
|
||||
case EventTextDelta:
|
||||
response.WriteString(event.Text)
|
||||
case EventError:
|
||||
return response.String(), event.Error
|
||||
}
|
||||
}
|
||||
|
||||
return response.String(), nil
|
||||
}
|
||||
|
||||
// dispatchTool executes one tool call with strict tool_use ↔ tool_result
|
||||
// pairing. Always appends a ToolCallEntry then exactly one ToolResultEntry
|
||||
// (real, error, denial, or aborted) before returning.
|
||||
func (r *Runtime) dispatchTool(
|
||||
ctx context.Context,
|
||||
tc llm.ToolCall,
|
||||
kgThread *[]Message,
|
||||
) (result tool.ToolResult, aborted bool) {
|
||||
r.Session.Append(session.ToolCallEntry(tc.ID, tc.Name, tc.Input))
|
||||
if kgThread != nil {
|
||||
r.kgMu.Lock()
|
||||
*kgThread = append(*kgThread, Message{
|
||||
Role: "assistant",
|
||||
Content: fmt.Sprintf("[tool: %s]\n%s", tc.Name, string(tc.Input)),
|
||||
})
|
||||
r.kgMu.Unlock()
|
||||
}
|
||||
|
||||
if r.Permission != nil {
|
||||
if d := r.Permission.Check(ctx, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
|
||||
return r.appendDenialResult(tc.ID, d.Reason, kgThread), false
|
||||
}
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return r.appendAbortedResult(tc.ID, kgThread), true
|
||||
}
|
||||
|
||||
result, err := r.Tools.Execute(ctx, tc.Name, tc.Input)
|
||||
if err != nil {
|
||||
result = tool.ToolResult{Error: err.Error()}
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return r.appendAbortedResult(tc.ID, kgThread), true
|
||||
}
|
||||
|
||||
imgData := convertToolResultImages(result.Images)
|
||||
r.Session.Append(session.ToolResultEntry(tc.ID, result.Output, result.Error, imgData))
|
||||
if kgThread != nil {
|
||||
content := result.Output
|
||||
if result.Error != "" {
|
||||
content = "[error] " + result.Error
|
||||
}
|
||||
r.kgMu.Lock()
|
||||
*kgThread = append(*kgThread, Message{Role: "user", Content: content})
|
||||
r.kgMu.Unlock()
|
||||
}
|
||||
|
||||
if result.Error == "" && isFileTool(tc.Name) {
|
||||
r.recordFileTouch(extractPathFromInput(tc.Input))
|
||||
}
|
||||
|
||||
return result, false
|
||||
}
|
||||
|
||||
// executeToolKickoff runs the tool's permission gate, ctx checks, and
|
||||
// Execute call WITHOUT touching session or KG thread. Used by the
|
||||
// streaming kickoff goroutines.
|
||||
func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (result tool.ToolResult, aborted bool) {
|
||||
if r.Permission != nil {
|
||||
if d := r.Permission.Check(ctx, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
|
||||
return tool.ToolResult{Error: d.Reason}, false
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return tool.ToolResult{Error: "aborted by user"}, true
|
||||
}
|
||||
result, err := r.Tools.Execute(ctx, 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
|
||||
}
|
||||
if result.Error == "" && isFileTool(tc.Name) {
|
||||
r.recordFileTouch(extractPathFromInput(tc.Input))
|
||||
}
|
||||
return result, false
|
||||
}
|
||||
|
||||
// appendDenialResult writes the tool-result entry for a denied tool call.
|
||||
func (r *Runtime) appendDenialResult(toolCallID, reason string, kgThread *[]Message) tool.ToolResult {
|
||||
r.Session.Append(session.ToolResultEntry(toolCallID, "", reason, nil))
|
||||
if kgThread != nil {
|
||||
r.kgMu.Lock()
|
||||
*kgThread = append(*kgThread, Message{
|
||||
Role: "user", Content: "[error] " + reason,
|
||||
})
|
||||
r.kgMu.Unlock()
|
||||
}
|
||||
return tool.ToolResult{Error: reason}
|
||||
}
|
||||
|
||||
// appendAbortedResult writes the synthetic abort entry.
|
||||
func (r *Runtime) appendAbortedResult(toolCallID string, kgThread *[]Message) tool.ToolResult {
|
||||
r.Session.Append(session.AbortedToolResultEntry(toolCallID))
|
||||
if kgThread != nil {
|
||||
r.kgMu.Lock()
|
||||
*kgThread = append(*kgThread, Message{
|
||||
Role: "user", Content: "[error] aborted by user",
|
||||
})
|
||||
r.kgMu.Unlock()
|
||||
}
|
||||
return tool.ToolResult{Error: "aborted by user"}
|
||||
}
|
||||
|
||||
// convertToolResultImages adapts tool image attachments to session ImageData.
|
||||
func convertToolResultImages(imgs []llm.ImageContent) []session.ImageData {
|
||||
if len(imgs) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]session.ImageData, 0, len(imgs))
|
||||
for _, img := range imgs {
|
||||
out = append(out, session.ImageData{
|
||||
MimeType: img.MimeType,
|
||||
Data: base64.StdEncoding.EncodeToString(img.Data),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// kgThreadOrNil returns a pointer to the KG thread if KG is enabled, else nil.
|
||||
func kgThreadOrNil(kg KnowledgeGraph, thread *[]Message) *[]Message {
|
||||
if kg == nil {
|
||||
return nil
|
||||
}
|
||||
return thread
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SpillDirForSession returns the absolute path of the spill subdirectory
|
||||
// owned by (workspace, sessionKey). Returns "" if either input is empty,
|
||||
// because we never want to accidentally walk a non-spill location.
|
||||
//
|
||||
// Mirrors the path layout used by spillToolResult in context.go:
|
||||
//
|
||||
// <workspace>/.felix/spill/<sessionKey>/
|
||||
func SpillDirForSession(workspace, sessionKey string) string {
|
||||
if workspace == "" || sessionKey == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(workspace, ".felix", "spill", sessionKey)
|
||||
}
|
||||
|
||||
// RemoveSessionSpill removes the per-session spill directory if it exists.
|
||||
// Safe to call when the directory was never created (no spillover happened).
|
||||
// Logs at warn on unexpected I/O errors but never returns one — spill cleanup
|
||||
// is best-effort and must not block session deletion.
|
||||
func RemoveSessionSpill(workspace, sessionKey string) {
|
||||
dir := SpillDirForSession(workspace, sessionKey)
|
||||
if dir == "" {
|
||||
return
|
||||
}
|
||||
if err := os.RemoveAll(dir); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
slog.Warn("spill cleanup failed", "dir", dir, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// SpillRoot returns the parent directory under which all per-session spill
|
||||
// directories live for the given workspace. Used by the startup janitor.
|
||||
func SpillRoot(workspace string) string {
|
||||
if workspace == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(workspace, ".felix", "spill")
|
||||
}
|
||||
|
||||
// LiveSessionKeysFn returns the set of currently-existing session keys for
|
||||
// the agent that owns the given workspace. The startup janitor uses this
|
||||
// callback to decide which spill dirs are orphans (have no matching
|
||||
// session JSONL on disk).
|
||||
type LiveSessionKeysFn func() (map[string]bool, error)
|
||||
|
||||
// CleanupOrphanedSpills walks <workspace>/.felix/spill/ and removes any
|
||||
// per-session subdirectory whose key is not in the set returned by liveKeys.
|
||||
// Returns the number of directories removed and the first error encountered
|
||||
// (if any). Missing root is not an error — it just means nothing to clean.
|
||||
//
|
||||
// Designed to be called once at startup per agent workspace.
|
||||
func CleanupOrphanedSpills(workspace string, liveKeys LiveSessionKeysFn) (int, error) {
|
||||
root := SpillRoot(workspace)
|
||||
if root == "" {
|
||||
return 0, nil
|
||||
}
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return 0, nil
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
live, err := liveKeys()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
removed := 0
|
||||
var firstErr error
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() {
|
||||
continue
|
||||
}
|
||||
// Defensive: skip anything that doesn't look like a session-key dir
|
||||
// (e.g., a stray dotfile someone dropped here manually).
|
||||
name := e.Name()
|
||||
if name == "" || strings.HasPrefix(name, ".") {
|
||||
continue
|
||||
}
|
||||
if live[name] {
|
||||
continue
|
||||
}
|
||||
full := filepath.Join(root, name)
|
||||
if rerr := os.RemoveAll(full); rerr != nil {
|
||||
if firstErr == nil {
|
||||
firstErr = rerr
|
||||
}
|
||||
slog.Warn("orphan spill cleanup failed", "dir", full, "error", rerr)
|
||||
continue
|
||||
}
|
||||
removed++
|
||||
}
|
||||
if removed > 0 {
|
||||
slog.Info("removed orphan spill directories", "workspace", workspace, "count", removed)
|
||||
}
|
||||
return removed, firstErr
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// streamThenFailProvider emits some text, then EventError mid-stream.
|
||||
// On the non-streaming retry it returns clean text. Used to verify
|
||||
// the runtime discards the partial output and resumes from the retry.
|
||||
type streamThenFailProvider struct {
|
||||
llmtest.Base
|
||||
|
||||
mu sync.Mutex
|
||||
streamCalls atomic.Int64
|
||||
nonstreamCalls atomic.Int64
|
||||
|
||||
// What the failed stream emits before EventError.
|
||||
partialText string
|
||||
streamErr error
|
||||
|
||||
// What the non-streaming retry returns.
|
||||
finalText string
|
||||
}
|
||||
|
||||
func (p *streamThenFailProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.streamCalls.Add(1)
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
if p.partialText != "" {
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: p.partialText}
|
||||
}
|
||||
ch <- llm.ChatEvent{Type: llm.EventError, Error: p.streamErr}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (p *streamThenFailProvider) ChatNonStreaming(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.nonstreamCalls.Add(1)
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: p.finalText}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func TestRuntimeStreamFallbackDiscardsPartialAndRetries(t *testing.T) {
|
||||
prov := &streamThenFailProvider{
|
||||
partialText: "PARTIAL_LOST",
|
||||
streamErr: errors.New("connection reset by peer"),
|
||||
finalText: "RECOVERED_VIA_NONSTREAMING",
|
||||
}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-sonnet-4-5",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 2,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
_, err := rt.RunSync(context.Background(), "do it", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Note: RunSync surfaces ALL EventTextDelta events as they stream,
|
||||
// so the partial text DID hit the user's terminal before we
|
||||
// detected the failure. That's a UX wart but not a correctness
|
||||
// problem — the cache prefix invariant is about what's persisted
|
||||
// to the SESSION, not what flashed past on stdout.
|
||||
require.EqualValues(t, 1, prov.streamCalls.Load(), "streaming endpoint hit once")
|
||||
require.EqualValues(t, 1, prov.nonstreamCalls.Load(), "non-streaming retry hit once")
|
||||
|
||||
// The session's stored assistant message must be the recovered
|
||||
// text only — that is what gets re-played as part of the prefix
|
||||
// on the NEXT turn, and any partial from the failed stream
|
||||
// would invalidate the cache.
|
||||
var assistantText string
|
||||
for _, e := range rt.Session.Entries() {
|
||||
if e.Type == session.EntryTypeMessage {
|
||||
var m session.MessageData
|
||||
require.NoError(t, decodeMessage(e, &m))
|
||||
if m.Text != "" && m.Text != "do it" {
|
||||
assistantText = m.Text
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.Equal(t, "RECOVERED_VIA_NONSTREAMING", assistantText)
|
||||
}
|
||||
|
||||
// alwaysFailStreamProvider implements ChatStream that fires EventError
|
||||
// without ever emitting a token. This is the "pre-flight" failure case
|
||||
// (e.g., 400 Bad Request) — the runtime must NOT retry with
|
||||
// non-streaming, because a different transport won't fix a malformed
|
||||
// request, and a retry would mask the real bug.
|
||||
type alwaysFailStreamProvider struct {
|
||||
llmtest.Base
|
||||
streamCalls atomic.Int64
|
||||
nonstreamCalls atomic.Int64
|
||||
}
|
||||
|
||||
func (p *alwaysFailStreamProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.streamCalls.Add(1)
|
||||
ch := make(chan llm.ChatEvent, 1)
|
||||
ch <- llm.ChatEvent{Type: llm.EventError, Error: errors.New("400 invalid input")}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (p *alwaysFailStreamProvider) ChatNonStreaming(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.nonstreamCalls.Add(1)
|
||||
ch := make(chan llm.ChatEvent, 1)
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func TestRuntimeStreamFallbackSkippedWhenNoTokenReceived(t *testing.T) {
|
||||
prov := &alwaysFailStreamProvider{}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-sonnet-4-5",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 2,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
_, err := rt.RunSync(context.Background(), "do it", nil)
|
||||
require.Error(t, err, "pre-flight stream error must surface to caller")
|
||||
assert.EqualValues(t, 1, prov.streamCalls.Load())
|
||||
assert.EqualValues(t, 0, prov.nonstreamCalls.Load(),
|
||||
"non-streaming retry must NOT engage when no token was received — "+
|
||||
"otherwise pre-flight 4xx errors get silently retried")
|
||||
}
|
||||
|
||||
// streamingOnlyProvider doesn't implement NonStreamingProvider.
|
||||
// Verifies the runtime gracefully surfaces the original error rather
|
||||
// than panicking on the type assertion.
|
||||
type streamingOnlyProvider struct {
|
||||
llmtest.Base
|
||||
streamCalls atomic.Int64
|
||||
}
|
||||
|
||||
func (p *streamingOnlyProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.streamCalls.Add(1)
|
||||
ch := make(chan llm.ChatEvent, 2)
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "started"}
|
||||
ch <- llm.ChatEvent{Type: llm.EventError, Error: errors.New("network broke")}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func TestRuntimeStreamFallbackNoOpWhenProviderLacksNonStreaming(t *testing.T) {
|
||||
prov := &streamingOnlyProvider{}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "x",
|
||||
Provider: "openai", // no NonStreamingProvider impl on streamingOnlyProvider
|
||||
MaxTurns: 2,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
_, err := rt.RunSync(context.Background(), "do it", nil)
|
||||
require.Error(t, err, "provider without NonStreamingProvider must surface mid-stream errors as before")
|
||||
assert.EqualValues(t, 1, prov.streamCalls.Load())
|
||||
}
|
||||
|
||||
// streamFailsAgainProvider fails on stream AND on non-streaming retry.
|
||||
// The runtime must emit the SECOND error and not loop forever.
|
||||
type streamFailsAgainProvider struct {
|
||||
llmtest.Base
|
||||
streamCalls atomic.Int64
|
||||
nonstreamCalls atomic.Int64
|
||||
}
|
||||
|
||||
func (p *streamFailsAgainProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.streamCalls.Add(1)
|
||||
ch := make(chan llm.ChatEvent, 2)
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "x"}
|
||||
ch <- llm.ChatEvent{Type: llm.EventError, Error: errors.New("stream broke")}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (p *streamFailsAgainProvider) ChatNonStreaming(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.nonstreamCalls.Add(1)
|
||||
return nil, errors.New("nonstreaming also broke")
|
||||
}
|
||||
|
||||
func TestRuntimeStreamFallbackBothFail(t *testing.T) {
|
||||
prov := &streamFailsAgainProvider{}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-sonnet-4-5",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 2,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
_, err := rt.RunSync(context.Background(), "do it", nil)
|
||||
require.Error(t, err)
|
||||
assert.EqualValues(t, 1, prov.streamCalls.Load())
|
||||
assert.EqualValues(t, 1, prov.nonstreamCalls.Load(), "must attempt the retry exactly once")
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// streamingToolsEnabled reports whether streaming tool kickoff is on for
|
||||
// this Runtime. Precedence:
|
||||
// 1. Runtime.AgentLoop.StreamingTools == true → on (config wins).
|
||||
// 2. Otherwise HARNESS_STREAMING_TOOLS=="1" → on.
|
||||
// 3. Otherwise off.
|
||||
//
|
||||
// Strict "1" for the env fallback (rather than truthy parsing) keeps the
|
||||
// env contract simple and matches Claude Code's binary-feature-gate posture.
|
||||
// Note: an explicit `false` in JSON5 behaves the same as the field being
|
||||
// absent — to disable, leave both unset.
|
||||
func (r *Runtime) streamingToolsEnabled() bool {
|
||||
if r.AgentLoop.StreamingTools {
|
||||
return true
|
||||
}
|
||||
return os.Getenv("HARNESS_STREAMING_TOOLS") == "1"
|
||||
}
|
||||
|
||||
// kickoffResult is the channel payload sent by a streaming-kickoff goroutine
|
||||
// once executeToolKickoff returns. The goroutine has already emitted the
|
||||
// live EventToolResult (via r.emitToolResult); the main goroutine consumes
|
||||
// this struct post-stream to write the paired session entries (ToolCall +
|
||||
// ToolResult) IN STREAM ORDER, AFTER the assistant text is saved.
|
||||
//
|
||||
// Deferring session writes to the main goroutine preserves the API
|
||||
// invariant that every tool_result message follows an assistant message
|
||||
// containing the matching tool_use. Phase D's parallelism win (tools
|
||||
// running during the stream) is preserved because Execute still happens
|
||||
// inside the kickoff goroutine.
|
||||
type kickoffResult struct {
|
||||
tc llm.ToolCall // the tool call we executed (carried so the main goroutine doesn't have to look it up)
|
||||
result tool.ToolResult
|
||||
aborted bool
|
||||
}
|
||||
|
||||
// drainKickoffs blocks until every kickoff channel has received a value, then
|
||||
// returns. Used on early-return paths (LLM error) so kickoff goroutines
|
||||
// fully settle before Run() returns and r.events closes — preventing leaks.
|
||||
// (The abort path inlines its own walk so it can append paired session
|
||||
// entries in stream order.)
|
||||
func drainKickoffs(kickoffs map[string]chan kickoffResult) {
|
||||
for _, ch := range kickoffs {
|
||||
<-ch
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,821 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestStreamingToolsEnabled_Default(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "")
|
||||
if (&Runtime{}).streamingToolsEnabled() {
|
||||
t.Fatal("expected false when env unset")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamingToolsEnabled_Override(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "1")
|
||||
if !(&Runtime{}).streamingToolsEnabled() {
|
||||
t.Fatal("expected true when env=1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStreamingToolsEnabled_InvalidFallsBack(t *testing.T) {
|
||||
cases := []string{"0", "true", "True", "garbage", " 1 ", "01", "yes"}
|
||||
for _, v := range cases {
|
||||
t.Run(v, func(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", v)
|
||||
if (&Runtime{}).streamingToolsEnabled() {
|
||||
t.Fatalf("expected false for %q", v)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntime_StreamingTools_ConfigTrueWinsOverEnvUnset(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "")
|
||||
r := &Runtime{AgentLoop: LoopConfig{StreamingTools: true}}
|
||||
if !r.streamingToolsEnabled() {
|
||||
t.Fatal("expected true when config sets streamingTools=true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntime_StreamingTools_ConfigTrueWinsOverEnvZero(t *testing.T) {
|
||||
// Env is "0" (off) but config says on — config wins.
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "0")
|
||||
r := &Runtime{AgentLoop: LoopConfig{StreamingTools: true}}
|
||||
if !r.streamingToolsEnabled() {
|
||||
t.Fatal("expected true when config=true even with env=0")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntime_StreamingTools_ConfigFalseFallsBackToEnv(t *testing.T) {
|
||||
// When config bool is false (the zero value, indistinguishable from
|
||||
// "field absent"), fall back to env. Env=1 → on.
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "1")
|
||||
r := &Runtime{AgentLoop: LoopConfig{StreamingTools: false}}
|
||||
if !r.streamingToolsEnabled() {
|
||||
t.Fatal("expected true when config=false but env=1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntime_StreamingTools_BothUnsetIsOff(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "")
|
||||
r := &Runtime{AgentLoop: LoopConfig{}}
|
||||
if r.streamingToolsEnabled() {
|
||||
t.Fatal("expected false when neither config nor env set")
|
||||
}
|
||||
}
|
||||
|
||||
// scriptedStreamEvent is a single event for scriptedStreamLLM to emit.
|
||||
type scriptedStreamEvent struct {
|
||||
typ llm.EventType
|
||||
text string
|
||||
toolCall *llm.ToolCall
|
||||
delay time.Duration // sleep BEFORE emitting this event
|
||||
}
|
||||
|
||||
// scriptedStreamLLM is a fake LLMProvider that emits a fixed sequence of
|
||||
// ChatEvents with optional delays. Use to script "text → tool_use → text → done"
|
||||
// streams for streaming-kickoff tests. After the first call has emitted its
|
||||
// scripted events, subsequent calls just emit EventDone so the agent loop
|
||||
// terminates cleanly.
|
||||
type scriptedStreamLLM struct {
|
||||
llmtest.Base
|
||||
events []scriptedStreamEvent
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (s *scriptedStreamLLM) ChatStream(ctx context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
n := s.calls.Add(1)
|
||||
out := make(chan llm.ChatEvent, len(s.events)+1)
|
||||
go func() {
|
||||
defer close(out)
|
||||
if n != 1 {
|
||||
// Subsequent turns: terminate quickly with no tool calls.
|
||||
out <- llm.ChatEvent{Type: llm.EventDone}
|
||||
return
|
||||
}
|
||||
for _, e := range s.events {
|
||||
if e.delay > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(e.delay):
|
||||
}
|
||||
}
|
||||
ev := llm.ChatEvent{Type: e.typ, Text: e.text, ToolCall: e.toolCall}
|
||||
select {
|
||||
case out <- ev:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// timedExecutor records when each tool call's Execute starts. Each tool call
|
||||
// gets a unique key (toolName_{counter}) so concurrent invocations of the same
|
||||
// tool are tracked separately. Used to assert streaming-kickoff timing.
|
||||
type timedExecutor struct {
|
||||
mu sync.Mutex
|
||||
startTimes []time.Time
|
||||
startNames []string
|
||||
safeNames map[string]bool // tool names that report concurrencySafe
|
||||
blockUntil chan struct{} // tools block until this is closed (or nil for no block)
|
||||
delayPerCall time.Duration // sleep inside Execute (after recording start)
|
||||
toolDefs []llm.ToolDef
|
||||
onExecuteStart func() // optional hook fired at the start of every Execute (before blockUntil/delay)
|
||||
}
|
||||
|
||||
func newTimedExecutor() *timedExecutor {
|
||||
return &timedExecutor{
|
||||
safeNames: map[string]bool{},
|
||||
}
|
||||
}
|
||||
|
||||
func (e *timedExecutor) markSafe(name string) { e.safeNames[name] = true }
|
||||
|
||||
func (e *timedExecutor) addTool(name string) {
|
||||
e.toolDefs = append(e.toolDefs, llm.ToolDef{Name: name})
|
||||
}
|
||||
|
||||
func (e *timedExecutor) starts() []time.Time {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
out := make([]time.Time, len(e.startTimes))
|
||||
copy(out, e.startTimes)
|
||||
return out
|
||||
}
|
||||
|
||||
func (e *timedExecutor) callCount() int {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
return len(e.startTimes)
|
||||
}
|
||||
|
||||
func (e *timedExecutor) Execute(ctx context.Context, name string, _ json.RawMessage) (tool.ToolResult, error) {
|
||||
e.mu.Lock()
|
||||
e.startTimes = append(e.startTimes, time.Now())
|
||||
e.startNames = append(e.startNames, name)
|
||||
bu := e.blockUntil
|
||||
delay := e.delayPerCall
|
||||
hook := e.onExecuteStart
|
||||
e.mu.Unlock()
|
||||
|
||||
if hook != nil {
|
||||
hook()
|
||||
}
|
||||
|
||||
if bu != nil {
|
||||
select {
|
||||
case <-bu:
|
||||
case <-ctx.Done():
|
||||
return tool.ToolResult{}, ctx.Err()
|
||||
}
|
||||
}
|
||||
if delay > 0 {
|
||||
select {
|
||||
case <-time.After(delay):
|
||||
case <-ctx.Done():
|
||||
return tool.ToolResult{}, ctx.Err()
|
||||
}
|
||||
}
|
||||
return tool.ToolResult{Output: "result for " + name}, nil
|
||||
}
|
||||
|
||||
func (e *timedExecutor) Names() []string {
|
||||
out := make([]string, len(e.toolDefs))
|
||||
for i, td := range e.toolDefs {
|
||||
out[i] = td.Name
|
||||
}
|
||||
return out
|
||||
}
|
||||
func (e *timedExecutor) ToolDefs() []llm.ToolDef { return e.toolDefs }
|
||||
func (e *timedExecutor) Get(name string) (tool.Tool, bool) {
|
||||
return &timedExecutorTool{name: name, safe: e.safeNames[name]}, true
|
||||
}
|
||||
|
||||
type timedExecutorTool struct {
|
||||
name string
|
||||
safe bool
|
||||
}
|
||||
|
||||
func (t *timedExecutorTool) Name() string { return t.name }
|
||||
func (t *timedExecutorTool) Description() string { return "" }
|
||||
func (t *timedExecutorTool) Parameters() json.RawMessage { return json.RawMessage(`{}`) }
|
||||
func (t *timedExecutorTool) Execute(_ context.Context, _ json.RawMessage) (tool.ToolResult, error) {
|
||||
return tool.ToolResult{}, nil
|
||||
}
|
||||
func (t *timedExecutorTool) IsConcurrencySafe(_ json.RawMessage) bool { return t.safe }
|
||||
|
||||
// TestRun_StreamingKickoffOverlapsWithLLMStream asserts that with streaming
|
||||
// enabled, a safe tool starts BEFORE the LLM stream ends. The LLM emits a
|
||||
// 200ms delay between EventToolCallDone and the next text delta; if streaming
|
||||
// is off, the tool would only start after EventDone. With streaming on, the
|
||||
// tool starts shortly after EventToolCallDone — well before the stream ends.
|
||||
func TestRun_StreamingKickoffOverlapsWithLLMStream(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "1")
|
||||
|
||||
exec := newTimedExecutor()
|
||||
exec.markSafe("safe_read")
|
||||
exec.addTool("safe_read")
|
||||
exec.delayPerCall = 50 * time.Millisecond
|
||||
|
||||
tcID := "tc_a"
|
||||
tc := &llm.ToolCall{ID: tcID, Name: "safe_read", Input: json.RawMessage(`{}`)}
|
||||
|
||||
scriptedLLM := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventTextDelta, text: "thinking..."},
|
||||
{typ: llm.EventToolCallStart, toolCall: tc},
|
||||
{typ: llm.EventToolCallDone, toolCall: tc},
|
||||
{delay: 200 * time.Millisecond, typ: llm.EventTextDelta, text: "more text"},
|
||||
{typ: llm.EventDone},
|
||||
}}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: scriptedLLM, Tools: exec,
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a", Model: "test", MaxTurns: 2,
|
||||
}
|
||||
events, err := rt.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Stream-end timestamp is when EventDone arrives on the channel. The
|
||||
// runtime emits EventDone only after the LLM stream completes (and the
|
||||
// post-stream pending-tool resolution finishes). For the overlap check
|
||||
// we want the LLM stream-end moment, which lines up with when the post-
|
||||
// stream block starts running.
|
||||
var streamEnd time.Time
|
||||
var sawToolResult bool
|
||||
for ev := range events {
|
||||
switch ev.Type {
|
||||
case EventToolResult:
|
||||
sawToolResult = true
|
||||
case EventDone, EventAborted:
|
||||
streamEnd = time.Now()
|
||||
}
|
||||
}
|
||||
require.True(t, sawToolResult, "expected an EventToolResult for the kicked-off tool")
|
||||
|
||||
starts := exec.starts()
|
||||
require.Len(t, starts, 1, "exactly one tool execution expected")
|
||||
toolStart := starts[0]
|
||||
gap := streamEnd.Sub(toolStart)
|
||||
// Tool started shortly after EventToolCallDone; stream ends ~200ms later
|
||||
// (after the scripted delay before the final text delta). Gap should
|
||||
// comfortably exceed 100ms even with scheduler jitter.
|
||||
require.Greater(t, gap, 100*time.Millisecond,
|
||||
"tool should have started well before stream end (gap=%v)", gap)
|
||||
}
|
||||
|
||||
// TestRun_StreamingStopsAtFirstUnsafe streams [safe1, safe2, unsafe1, safe3].
|
||||
// Asserts: safe1 + safe2 ran in parallel mid-stream (start times within a
|
||||
// small window); unsafe1 and safe3 ran post-stream via the batcher.
|
||||
func TestRun_StreamingStopsAtFirstUnsafe(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "1")
|
||||
|
||||
exec := newTimedExecutor()
|
||||
exec.markSafe("safe1")
|
||||
exec.markSafe("safe2")
|
||||
exec.markSafe("safe3")
|
||||
exec.addTool("safe1")
|
||||
exec.addTool("safe2")
|
||||
exec.addTool("unsafe1")
|
||||
exec.addTool("safe3")
|
||||
exec.delayPerCall = 30 * time.Millisecond
|
||||
|
||||
mk := func(id, name string) *llm.ToolCall {
|
||||
return &llm.ToolCall{ID: id, Name: name, Input: json.RawMessage(`{}`)}
|
||||
}
|
||||
scriptedLLM := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventToolCallDone, toolCall: mk("tc_safe1", "safe1")},
|
||||
{typ: llm.EventToolCallDone, toolCall: mk("tc_safe2", "safe2")},
|
||||
{typ: llm.EventToolCallDone, toolCall: mk("tc_unsafe1", "unsafe1")},
|
||||
{typ: llm.EventToolCallDone, toolCall: mk("tc_safe3", "safe3")},
|
||||
// Hold the stream open briefly so the safe kickoffs definitely overlap.
|
||||
{delay: 100 * time.Millisecond, typ: llm.EventDone},
|
||||
}}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: scriptedLLM, Tools: exec,
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a", Model: "test", MaxTurns: 2,
|
||||
}
|
||||
events, err := rt.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
|
||||
// All four tools must have run.
|
||||
require.Equal(t, 4, exec.callCount(), "all four tools should have executed")
|
||||
|
||||
// The first two starts are safe1 and safe2 (kicked off in stream order).
|
||||
// They must overlap — both started within a window much smaller than
|
||||
// delayPerCall (30ms). 20ms is generous for scheduler jitter while still
|
||||
// proving overlap (vs. >30ms which would indicate sequential execution).
|
||||
exec.mu.Lock()
|
||||
starts := append([]time.Time(nil), exec.startTimes...)
|
||||
names := append([]string(nil), exec.startNames...)
|
||||
exec.mu.Unlock()
|
||||
|
||||
require.Len(t, starts, 4)
|
||||
// First two should be the safe kickoffs (order between them is goroutine-
|
||||
// scheduling dependent, so we just check both names are in the first pair).
|
||||
firstPair := map[string]bool{names[0]: true, names[1]: true}
|
||||
require.True(t, firstPair["safe1"] && firstPair["safe2"],
|
||||
"first two starts should be safe1 and safe2 (got %v, %v)", names[0], names[1])
|
||||
|
||||
gap := starts[1].Sub(starts[0])
|
||||
if gap < 0 {
|
||||
gap = -gap
|
||||
}
|
||||
require.Less(t, gap, 25*time.Millisecond,
|
||||
"safe1 and safe2 should have started concurrently (gap=%v, delayPerCall=30ms)", gap)
|
||||
|
||||
// unsafe1 and safe3 ran post-stream. Their starts must be after both
|
||||
// safe kickoffs FINISHED (i.e., after starts[0]+delayPerCall).
|
||||
postStreamStart := starts[0].Add(exec.delayPerCall)
|
||||
require.True(t, starts[2].After(postStreamStart) || starts[2].Equal(postStreamStart),
|
||||
"unsafe1/safe3 should run after safe1+safe2 finished")
|
||||
|
||||
// Pin the "unsafe runs alone" Phase B contract: unsafe1 must run BEFORE
|
||||
// safe3, and safe3 must wait for unsafe1 to finish (sequential, not
|
||||
// parallel). The post-stream batcher partitions [unsafe1, safe3] into
|
||||
// two batches: an unsafe singleton followed by a safe singleton.
|
||||
require.Equal(t, "unsafe1", names[2], "third tool to start should be unsafe1")
|
||||
require.Equal(t, "safe3", names[3], "fourth tool to start should be safe3")
|
||||
|
||||
unsafeStart := starts[2]
|
||||
safe3Start := starts[3]
|
||||
require.GreaterOrEqual(t, safe3Start.Sub(unsafeStart), exec.delayPerCall-5*time.Millisecond,
|
||||
"safe3 should start at least delayPerCall after unsafe1 (sequential), got gap=%v",
|
||||
safe3Start.Sub(unsafeStart))
|
||||
}
|
||||
|
||||
// TestRun_StreamingDisabledMatchesNonStreaming: same script as test 1 with
|
||||
// HARNESS_STREAMING_TOOLS unset. Tool must start AFTER the LLM stream ends.
|
||||
// Validates the default-off contract.
|
||||
func TestRun_StreamingDisabledMatchesNonStreaming(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "")
|
||||
|
||||
exec := newTimedExecutor()
|
||||
exec.markSafe("safe_read")
|
||||
exec.addTool("safe_read")
|
||||
exec.delayPerCall = 10 * time.Millisecond
|
||||
|
||||
tc := &llm.ToolCall{ID: "tc_a", Name: "safe_read", Input: json.RawMessage(`{}`)}
|
||||
|
||||
scriptedLLM := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventToolCallStart, toolCall: tc},
|
||||
{typ: llm.EventToolCallDone, toolCall: tc},
|
||||
{delay: 100 * time.Millisecond, typ: llm.EventDone},
|
||||
}}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: scriptedLLM, Tools: exec,
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a", Model: "test", MaxTurns: 2,
|
||||
}
|
||||
events, err := rt.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// We track when the LLM stream-end happened by observing when the first
|
||||
// EventToolResult lands. With streaming OFF, no tool result can land
|
||||
// until the post-stream block runs, which is strictly AFTER the stream
|
||||
// loop terminates. We use a sentinel: capture the time of the LAST text
|
||||
// delta + the time of the first tool result. Since the script has a
|
||||
// 100ms delay before EventDone (no text after toolCallDone), the tool
|
||||
// must START at least near that 100ms mark.
|
||||
scriptStart := time.Now()
|
||||
var firstToolResult time.Time
|
||||
for ev := range events {
|
||||
if ev.Type == EventToolResult && firstToolResult.IsZero() {
|
||||
firstToolResult = time.Now()
|
||||
}
|
||||
}
|
||||
require.False(t, firstToolResult.IsZero(), "expected an EventToolResult")
|
||||
|
||||
starts := exec.starts()
|
||||
require.Len(t, starts, 1)
|
||||
// With streaming OFF the tool only runs after the stream completes, which
|
||||
// requires waiting through the 100ms delay before EventDone.
|
||||
elapsed := starts[0].Sub(scriptStart)
|
||||
require.Greater(t, elapsed, 80*time.Millisecond,
|
||||
"tool must start AFTER stream end with streaming disabled (elapsed=%v)", elapsed)
|
||||
}
|
||||
|
||||
// TestRun_StreamingAbortMidKickoffPairsAllEntries: kick off 3 safe tools mid-
|
||||
// stream, then cancel ctx. Asserts: session has 3 paired tool_call/tool_result
|
||||
// entries; exactly one EventAborted; no goroutine leaks.
|
||||
func TestRun_StreamingAbortMidKickoffPairsAllEntries(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "1")
|
||||
|
||||
exec := newTimedExecutor()
|
||||
exec.markSafe("safe_read")
|
||||
exec.addTool("safe_read")
|
||||
exec.blockUntil = make(chan struct{}) // tools block until ctx cancel
|
||||
|
||||
// Deterministic in-flight synchronization: cancel only after all 3
|
||||
// kickoffs have entered Execute. Avoids the timing flake of a fixed
|
||||
// sleep that can lose a race on slow CI.
|
||||
var inFlight sync.WaitGroup
|
||||
inFlight.Add(3)
|
||||
exec.onExecuteStart = func() { inFlight.Done() }
|
||||
|
||||
mk := func(id string) *llm.ToolCall {
|
||||
return &llm.ToolCall{ID: id, Name: "safe_read", Input: json.RawMessage(`{}`)}
|
||||
}
|
||||
scriptedLLM := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventToolCallDone, toolCall: mk("tc_0")},
|
||||
{typ: llm.EventToolCallDone, toolCall: mk("tc_1")},
|
||||
{typ: llm.EventToolCallDone, toolCall: mk("tc_2")},
|
||||
{typ: llm.EventDone},
|
||||
}}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
rt := &Runtime{
|
||||
LLM: scriptedLLM, Tools: exec,
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a", Model: "test", MaxTurns: 2,
|
||||
}
|
||||
|
||||
beforeGoroutines := runtime.NumGoroutine()
|
||||
|
||||
events, err := rt.Run(ctx, "go", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Cancel only once all 3 kickoffs have actually entered Execute.
|
||||
go func() {
|
||||
inFlight.Wait()
|
||||
cancel()
|
||||
}()
|
||||
|
||||
var abortedEvents int
|
||||
for ev := range events {
|
||||
if ev.Type == EventAborted {
|
||||
abortedEvents++
|
||||
}
|
||||
}
|
||||
require.Equal(t, 1, abortedEvents, "exactly one EventAborted expected")
|
||||
|
||||
// Session must contain 3 tool_call/tool_result pairs (paired by ID).
|
||||
entries := rt.Session.Entries()
|
||||
callIDs := map[string]bool{}
|
||||
resultIDs := map[string]bool{}
|
||||
for _, e := range entries {
|
||||
switch e.Type {
|
||||
case session.EntryTypeToolCall:
|
||||
var cd session.ToolCallData
|
||||
require.NoError(t, json.Unmarshal(e.Data, &cd))
|
||||
callIDs[cd.ID] = true
|
||||
case session.EntryTypeToolResult:
|
||||
var trd session.ToolResultData
|
||||
require.NoError(t, json.Unmarshal(e.Data, &trd))
|
||||
resultIDs[trd.ToolCallID] = true
|
||||
}
|
||||
}
|
||||
require.Equal(t, 3, len(callIDs), "expected 3 ToolCall entries")
|
||||
require.Equal(t, 3, len(resultIDs), "expected 3 ToolResult entries")
|
||||
for id := range callIDs {
|
||||
require.True(t, resultIDs[id], "call %s has no matching result", id)
|
||||
}
|
||||
|
||||
// Goroutine leak check: give kickoff goroutines a grace period to finish.
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
afterGoroutines := runtime.NumGoroutine()
|
||||
// Allow some tolerance — runtime/test scheduler can keep transient
|
||||
// goroutines alive briefly. A leak would show up as 3+ extras.
|
||||
require.LessOrEqual(t, afterGoroutines, beforeGoroutines+2,
|
||||
"suspected goroutine leak: before=%d after=%d", beforeGoroutines, afterGoroutines)
|
||||
}
|
||||
|
||||
// TestRun_StreamingResultEmittedBeforeStreamEnds asserts that with streaming
|
||||
// on, a tool's EventToolResult lands on the events channel BEFORE the LLM's
|
||||
// EventDone arrives at the runtime — i.e., the result is live-emitted mid-
|
||||
// stream rather than buffered to post-stream.
|
||||
func TestRun_StreamingResultEmittedBeforeStreamEnds(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "1")
|
||||
|
||||
exec := newTimedExecutor()
|
||||
exec.markSafe("safe_read")
|
||||
exec.addTool("safe_read")
|
||||
exec.delayPerCall = 10 * time.Millisecond
|
||||
|
||||
tc := &llm.ToolCall{ID: "tc_a", Name: "safe_read", Input: json.RawMessage(`{}`)}
|
||||
|
||||
scriptedLLM := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventToolCallStart, toolCall: tc},
|
||||
{typ: llm.EventToolCallDone, toolCall: tc},
|
||||
// LLM stream stays open for 200ms after toolCallDone — tool should
|
||||
// have completed mid-stream and emitted its result well before the
|
||||
// stream end propagates through the post-stream block.
|
||||
{delay: 200 * time.Millisecond, typ: llm.EventTextDelta, text: "tail text"},
|
||||
{typ: llm.EventDone},
|
||||
}}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: scriptedLLM, Tools: exec,
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a", Model: "test", MaxTurns: 2,
|
||||
}
|
||||
events, err := rt.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Track relative ordering of EventToolResult vs the tail EventTextDelta.
|
||||
// With streaming, EventToolResult must precede the tail "tail text"
|
||||
// delta (which is gated behind a 200ms delay). Without streaming, the
|
||||
// delta would arrive first.
|
||||
var sawResult, sawTail bool
|
||||
var resultBeforeTail bool
|
||||
for ev := range events {
|
||||
switch ev.Type {
|
||||
case EventToolResult:
|
||||
sawResult = true
|
||||
if !sawTail {
|
||||
resultBeforeTail = true
|
||||
}
|
||||
case EventTextDelta:
|
||||
if ev.Text == "tail text" {
|
||||
sawTail = true
|
||||
}
|
||||
}
|
||||
}
|
||||
require.True(t, sawResult, "expected EventToolResult")
|
||||
require.True(t, sawTail, "expected tail EventTextDelta")
|
||||
require.True(t, resultBeforeTail,
|
||||
"EventToolResult must land BEFORE the tail text delta (streaming kickoff)")
|
||||
}
|
||||
|
||||
// TestRun_SubagentStreamingForwardsToParent asserts that with streaming on, a
|
||||
// subagent's mid-stream EventToolResult forwards to the parent's events
|
||||
// channel with AgentID set to the subagent's ID — proving the streaming
|
||||
// kickoff inside a subagent runtime cooperates with Phase C's event forwarding.
|
||||
func TestRun_SubagentStreamingForwardsToParent(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "1")
|
||||
|
||||
cfg := newTwoAgentCfg(t)
|
||||
|
||||
subExec := newTimedExecutor()
|
||||
subExec.markSafe("safe_read")
|
||||
subExec.addTool("safe_read")
|
||||
subExec.delayPerCall = 10 * time.Millisecond
|
||||
|
||||
tc := &llm.ToolCall{ID: "tc_sub", Name: "safe_read", Input: json.RawMessage(`{}`)}
|
||||
subLLM := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventTextDelta, text: "sub thinking"},
|
||||
{typ: llm.EventToolCallStart, toolCall: tc},
|
||||
{typ: llm.EventToolCallDone, toolCall: tc},
|
||||
{delay: 100 * time.Millisecond, typ: llm.EventTextDelta, text: "sub done"},
|
||||
{typ: llm.EventDone},
|
||||
}}
|
||||
|
||||
parentLLM := &taskCallingLLM{
|
||||
subagentID: "researcher",
|
||||
prompt: "go",
|
||||
finalText: "parent done",
|
||||
}
|
||||
|
||||
deps := RuntimeDeps{}
|
||||
parent := &Runtime{
|
||||
LLM: parentLLM,
|
||||
Session: session.NewSession("default", "test"),
|
||||
AgentID: "default",
|
||||
Model: "parent",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
|
||||
// Custom subagent builder that gives the subagent the timedExecutor
|
||||
// instead of the default noopExecutor.
|
||||
subBuilder := func(spec AgentSpec) (RuntimeInputs, error) {
|
||||
return RuntimeInputs{
|
||||
Provider: subLLM,
|
||||
Tools: subExec,
|
||||
Session: NewSubagentSession(spec.ID),
|
||||
Compaction: nil,
|
||||
IngestSource: "",
|
||||
}, nil
|
||||
}
|
||||
factory := MakeSubagentFactory(cfg.Resolve, deps, subBuilder, parent)
|
||||
parent.Tools = &taskOnlyExecutor{
|
||||
task: tool.NewTaskTool(factory, parent.Depth, cfg.EligibleSubagents()),
|
||||
}
|
||||
|
||||
events, err := parent.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var subToolResultEvent *AgentEvent
|
||||
timeout := time.After(5 * time.Second)
|
||||
loop:
|
||||
for {
|
||||
select {
|
||||
case ev, ok := <-events:
|
||||
if !ok {
|
||||
break loop
|
||||
}
|
||||
if ev.Type == EventToolResult && ev.AgentID == "researcher" {
|
||||
e := ev
|
||||
subToolResultEvent = &e
|
||||
}
|
||||
case <-timeout:
|
||||
t.Fatal("timed out waiting for parent events")
|
||||
}
|
||||
}
|
||||
|
||||
require.NotNil(t, subToolResultEvent,
|
||||
"expected an EventToolResult forwarded from subagent with AgentID=researcher")
|
||||
require.NotNil(t, subToolResultEvent.ToolCall)
|
||||
require.Equal(t, "safe_read", subToolResultEvent.ToolCall.Name)
|
||||
// Sanity: subagent ran the tool exactly once.
|
||||
require.Equal(t, 1, subExec.callCount())
|
||||
}
|
||||
|
||||
// TestRun_StreamingPreservesSessionOrderForSlowTool ensures session entries
|
||||
// land in [UserMessage, AssistantMessage, ToolCall, ToolResult] order even
|
||||
// when the tool takes longer than the stream. Regression for the bug where
|
||||
// kickoff goroutines wrote ToolCall mid-stream (before the assistant text
|
||||
// was saved), causing assembleMessages to produce a synthetic "(interrupted)"
|
||||
// tool_result and break the Anthropic API on the next turn.
|
||||
//
|
||||
// We deterministically expose the race by:
|
||||
// 1. blocking the tool inside Execute (so the kickoff goroutine has
|
||||
// already appended the ToolCall synchronously inside dispatchTool
|
||||
// before Execute is invoked),
|
||||
// 2. then letting the LLM stream emit its tail assistant-text + EventDone
|
||||
// so the main goroutine appends the AssistantMessage,
|
||||
// 3. then releasing the tool so the kickoff appends the ToolResult.
|
||||
//
|
||||
// On the unfixed code, sess.Entries() ends up [User, ToolCall, Assistant,
|
||||
// ToolResult] which breaks the Anthropic invariant. After the fix, all
|
||||
// session writes are deferred to the main goroutine and the order is
|
||||
// [User, Assistant, ToolCall, ToolResult].
|
||||
func TestRun_StreamingPreservesSessionOrderForSlowTool(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "1")
|
||||
|
||||
exec := newTimedExecutor()
|
||||
exec.markSafe("safe_search")
|
||||
exec.addTool("safe_search")
|
||||
// Block inside Execute so the kickoff goroutine has reached the point
|
||||
// where (under the bug) it has already appended the ToolCall entry, and
|
||||
// hold it there until after the stream emits its assistant text.
|
||||
exec.blockUntil = make(chan struct{})
|
||||
|
||||
var inFlight sync.WaitGroup
|
||||
inFlight.Add(1)
|
||||
exec.onExecuteStart = func() { inFlight.Done() }
|
||||
|
||||
tcID := "tc_slow"
|
||||
tc := &llm.ToolCall{ID: tcID, Name: "safe_search", Input: json.RawMessage(`{}`)}
|
||||
|
||||
sess := session.NewSession("a", "k")
|
||||
rt := &Runtime{
|
||||
LLM: &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventTextDelta, text: "I'll search now."},
|
||||
{typ: llm.EventToolCallStart, toolCall: tc},
|
||||
{typ: llm.EventToolCallDone, toolCall: tc},
|
||||
// Delay the tail text + EventDone so the kickoff goroutine
|
||||
// has time to enter Execute (and, under the bug, append its
|
||||
// ToolCall) before the main goroutine processes EventDone
|
||||
// and appends the AssistantMessage.
|
||||
{delay: 50 * time.Millisecond, typ: llm.EventTextDelta, text: " done."},
|
||||
{typ: llm.EventDone},
|
||||
}},
|
||||
Tools: exec,
|
||||
Session: sess,
|
||||
AgentID: "a",
|
||||
Model: "test",
|
||||
MaxTurns: 1,
|
||||
}
|
||||
|
||||
// Release the tool blocker only after the main goroutine has had time
|
||||
// to process the tail text + EventDone and append the AssistantMessage.
|
||||
// This deterministically pins ToolCall+ToolResult after AssistantMessage
|
||||
// under the fix; under the bug, the ToolCall lands BEFORE the assistant
|
||||
// text (because dispatchTool appends it synchronously before Execute).
|
||||
go func() {
|
||||
inFlight.Wait()
|
||||
time.Sleep(150 * time.Millisecond) // > 50ms tail delay; main loop will save AssistantMessage
|
||||
close(exec.blockUntil)
|
||||
}()
|
||||
|
||||
events, err := rt.Run(context.Background(), "search please", nil)
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
|
||||
entries := sess.Entries()
|
||||
// Expected: UserMessage, AssistantMessage, ToolCall, ToolResult.
|
||||
require.GreaterOrEqual(t, len(entries), 4, "expected at least 4 entries, got %d", len(entries))
|
||||
require.Equal(t, session.EntryTypeMessage, entries[0].Type)
|
||||
require.Equal(t, "user", entries[0].Role)
|
||||
// entries[1] MUST be the AssistantMessage, NOT a ToolCall.
|
||||
require.Equal(t, session.EntryTypeMessage, entries[1].Type,
|
||||
"AssistantMessage must come before ToolCall (bug regression check); got entry type %v at index 1",
|
||||
entries[1].Type)
|
||||
require.Equal(t, "assistant", entries[1].Role)
|
||||
require.Equal(t, session.EntryTypeToolCall, entries[2].Type,
|
||||
"ToolCall must come after AssistantMessage; got entry type %v at index 2", entries[2].Type)
|
||||
require.Equal(t, session.EntryTypeToolResult, entries[3].Type,
|
||||
"ToolResult must come after ToolCall; got entry type %v at index 3", entries[3].Type)
|
||||
}
|
||||
|
||||
// TestRun_StreamingCortexAppendIsRaceClean is the C1 regression test.
|
||||
//
|
||||
// Phase D introduced kickoff goroutines that call dispatchTool mid-stream.
|
||||
// dispatchTool appends to the per-Run cortex thread slice under r.cortexMu.
|
||||
// The main goroutine, after the LLM stream loop ends, also appends the
|
||||
// assistant text to the same slice. Without locking that append, two
|
||||
// writers race on the same slice header.
|
||||
//
|
||||
// This test exercises the race window deterministically: 3 safe tools are
|
||||
// kicked off mid-stream and made to block inside Execute via blockUntil;
|
||||
// the LLM emits assistant text before EventDone; the main goroutine then
|
||||
// runs the assistant-text append while all 3 kickoff goroutines are still
|
||||
// inside dispatchTool. With -race, the unfixed code flags a data race;
|
||||
// the fix (locking the append under r.cortexMu) clears it.
|
||||
//
|
||||
// Cortex setup: a zero-valued *cortex.Cortex is enough — the runtime only
|
||||
// uses it as a non-nil sentinel for the cortex code paths in this test.
|
||||
// Recall is skipped (userMsg "ok" is a trivial phrase per ShouldRecall),
|
||||
// and ingest is skipped (IngestSource="cron" disables ShouldIngest gate).
|
||||
// So no methods are called on the zero-Cortex pointer.
|
||||
func TestRun_StreamingCortexAppendIsRaceClean(t *testing.T) {
|
||||
t.Setenv("HARNESS_STREAMING_TOOLS", "1")
|
||||
|
||||
exec := newTimedExecutor()
|
||||
exec.markSafe("safe_read")
|
||||
exec.addTool("safe_read")
|
||||
|
||||
// Tools block until released. We release AFTER the assistant-text append
|
||||
// has had a chance to fire concurrently with the kickoffs being inside
|
||||
// dispatchTool's locked region.
|
||||
exec.blockUntil = make(chan struct{})
|
||||
|
||||
// Synchronize on all 3 kickoffs being inside Execute (i.e. past the
|
||||
// dispatchTool locked append) before the LLM stream emits its closing
|
||||
// text + EventDone. This guarantees the race window is open when the
|
||||
// main goroutine performs its assistant-text append.
|
||||
var inFlight sync.WaitGroup
|
||||
inFlight.Add(3)
|
||||
exec.onExecuteStart = func() { inFlight.Done() }
|
||||
|
||||
mk := func(id string) *llm.ToolCall {
|
||||
return &llm.ToolCall{ID: id, Name: "safe_read", Input: json.RawMessage(`{}`)}
|
||||
}
|
||||
scriptedLLM := &scriptedStreamLLM{events: []scriptedStreamEvent{
|
||||
{typ: llm.EventToolCallDone, toolCall: mk("tc_0")},
|
||||
{typ: llm.EventToolCallDone, toolCall: mk("tc_1")},
|
||||
{typ: llm.EventToolCallDone, toolCall: mk("tc_2")},
|
||||
// Hold the stream open briefly so the kickoffs all enter Execute
|
||||
// (and are blocked inside it) before assistant text + EventDone.
|
||||
{delay: 50 * time.Millisecond, typ: llm.EventTextDelta, text: "all done"},
|
||||
{typ: llm.EventDone},
|
||||
}}
|
||||
|
||||
rt := &Runtime{
|
||||
LLM: scriptedLLM,
|
||||
Tools: exec,
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test",
|
||||
MaxTurns: 2,
|
||||
KG: neverRecallKG{}, // non-nil sentinel; never invoked
|
||||
IngestSource: "cron", // disables deferred IngestThreadAsync
|
||||
}
|
||||
|
||||
// Trivial userMsg "ok" → ShouldRecall returns false → no Recall call on
|
||||
// the zero Cortex. Combined with IngestSource="cron" (disables ingest),
|
||||
// the zero Cortex is safe to leave dangling for the duration of the run.
|
||||
events, err := rt.Run(context.Background(), "ok", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Release tool blockers only after all 3 kickoffs have entered Execute
|
||||
// AND given the main goroutine time to process the LLM's tail text +
|
||||
// run the assistant-text append concurrently with the in-flight tool
|
||||
// goroutines (which are still holding pointers to `thread`).
|
||||
go func() {
|
||||
inFlight.Wait()
|
||||
// Small grace so the main goroutine reaches its post-stream assistant
|
||||
// append while kickoffs are still parked inside dispatchTool's
|
||||
// post-Execute locked region (or about to enter it after release).
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
close(exec.blockUntil)
|
||||
}()
|
||||
|
||||
// Drain.
|
||||
for range events {
|
||||
}
|
||||
|
||||
require.Equal(t, 3, exec.callCount(), "all 3 kickoffs should have executed")
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// Package runtime — subagent factory + adapter.
|
||||
//
|
||||
// This file wires the per-Runtime task tool: it constructs a tool.SubagentFactory
|
||||
// that builds a fresh Runtime for the named subagent, sets its Parent
|
||||
// pointer (for event forwarding) and Depth (for the recursion cap), and adapts
|
||||
// Runtime.Run to tool.SubagentRunner so the task tool can drain it.
|
||||
//
|
||||
// The factory enforces the depth cap (maxAgentDepth()) before constructing
|
||||
// anything — a subagent that would exceed the limit returns an error that
|
||||
// TaskTool surfaces as a tool result error, which the parent LLM then sees.
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// SubagentBuildFn constructs the per-subagent RuntimeInputs given the resolved
|
||||
// AgentSpec. Each call site provides this closure because tool-registry
|
||||
// construction (file/bash/web tools, MCP, send_message) is environment-specific.
|
||||
//
|
||||
// Implementations MUST:
|
||||
// - Build a fresh tool.Executor for the subagent (workspace = spec.Workspace)
|
||||
// - Resolve the LLM provider from spec.Model
|
||||
// - Create a fresh in-memory Session via NewSubagentSession
|
||||
// - Set IngestSource to "" (subagents are short-lived; no KG ingest)
|
||||
// - Set Compaction to whatever the call site's chat path uses for this agent
|
||||
type SubagentBuildFn func(spec AgentSpec) (RuntimeInputs, error)
|
||||
|
||||
// SubagentSpec carries the per-call-site policy (whether to inherit parent
|
||||
// history, registration check) the framework needs to honour without
|
||||
// importing consumer config types.
|
||||
type SubagentSpec struct {
|
||||
Spec AgentSpec
|
||||
// Registered reports whether the consumer considers this subagent ID
|
||||
// valid for parent-driven invocation. Mirrors Felix's
|
||||
// AgentConfig.Subagent flag.
|
||||
Registered bool
|
||||
// InheritContext, when true, copies the parent session's view into
|
||||
// the child session before BuildRuntime fires.
|
||||
InheritContext bool
|
||||
}
|
||||
|
||||
// MakeSubagentFactory returns a tool.SubagentFactory that builds a Runtime
|
||||
// for the named subagent and adapts it to tool.SubagentRunner. Enforces
|
||||
// the recursion depth cap before constructing anything.
|
||||
//
|
||||
// resolve looks up the subagent's spec at call-time so consumers can
|
||||
// hot-reload registrations.
|
||||
func MakeSubagentFactory(
|
||||
resolve func(agentID string) (SubagentSpec, bool),
|
||||
deps RuntimeDeps,
|
||||
buildInputs SubagentBuildFn,
|
||||
parent *Runtime,
|
||||
) tool.SubagentFactory {
|
||||
return func(ctx context.Context, agentID string, parentDepth int) (tool.SubagentRunner, error) {
|
||||
// Depth-cap enforcement.
|
||||
if parentDepth+1 > parent.maxAgentDepth() {
|
||||
return nil, fmt.Errorf("subagent depth limit %d reached", parent.maxAgentDepth())
|
||||
}
|
||||
ss, ok := resolve(agentID)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("subagent %q not found", agentID)
|
||||
}
|
||||
if !ss.Registered {
|
||||
return nil, fmt.Errorf("agent %q is not registered as a subagent", agentID)
|
||||
}
|
||||
inputs, err := buildInputs(ss.Spec)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("subagent %q: build inputs: %w", agentID, err)
|
||||
}
|
||||
// InheritContext: pre-populate the subagent's fresh session with
|
||||
// copies of parent's session entries. The subagent's first LLM
|
||||
// call then sees the parent's history; the existing
|
||||
// CacheLastMessage path naturally caches the inherited prefix on
|
||||
// the subagent's subsequent turns.
|
||||
if ss.InheritContext && parent != nil && parent.Session != nil && inputs.Session != nil {
|
||||
inheritParentHistory(inputs.Session, parent.Session)
|
||||
}
|
||||
rt, err := BuildRuntime(deps, inputs, ss.Spec)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("subagent %q: build runtime: %w", agentID, err)
|
||||
}
|
||||
rt.Parent = parent
|
||||
rt.Depth = parentDepth + 1
|
||||
return &subagentRunnerAdapter{rt: rt}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// inheritParentHistory copies the parent session's current view (post any
|
||||
// compaction) into the destination subagent session via Append.
|
||||
//
|
||||
// Operates outside Append's normal "stitch into leaf" path: the FIRST
|
||||
// inherited entry gets its ParentID cleared so the subagent's empty leaf
|
||||
// doesn't cause Append to leave a dangling pointer to a parent entry.
|
||||
func inheritParentHistory(dst, src *session.Session) {
|
||||
view := src.View()
|
||||
for i, e := range view {
|
||||
if i == 0 {
|
||||
e.ParentID = ""
|
||||
}
|
||||
dst.Append(e)
|
||||
}
|
||||
}
|
||||
|
||||
// subagentRunnerAdapter satisfies tool.SubagentRunner by adapting Runtime.Run.
|
||||
type subagentRunnerAdapter struct{ rt *Runtime }
|
||||
|
||||
func (s *subagentRunnerAdapter) Run(ctx context.Context, prompt string) (<-chan tool.AgentEventLike, error) {
|
||||
raw, err := s.rt.Run(ctx, prompt, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make(chan tool.AgentEventLike, 16)
|
||||
go func() {
|
||||
defer close(out)
|
||||
for ev := range raw {
|
||||
out <- adaptEvent(ev)
|
||||
}
|
||||
}()
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// adaptEvent translates an AgentEvent into the tool.AgentEventLike shape
|
||||
// that TaskTool understands. Only the fields TaskTool actually inspects
|
||||
// are filled.
|
||||
func adaptEvent(ev AgentEvent) tool.AgentEventLike {
|
||||
return tool.AgentEventLike{
|
||||
Type: int(ev.Type),
|
||||
Text: ev.Text,
|
||||
Done: ev.Type == EventDone,
|
||||
Aborted: ev.Type == EventAborted,
|
||||
Err: ev.Error,
|
||||
}
|
||||
}
|
||||
|
||||
// NewSubagentSession returns a fresh in-memory Session for a subagent run.
|
||||
// SetStore is NOT called — subagent sessions are ephemeral and do not
|
||||
// write JSONL to disk. The parent's session is the durable record.
|
||||
func NewSubagentSession(agentID string) *session.Session {
|
||||
return session.NewSession(agentID, "subagent")
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// scriptedTextLLM emits a single text response then EventDone. Distinct from
|
||||
// fakeLLM only in that it doesn't count an idx — every call gets the same text.
|
||||
// Used as the SUBAGENT's LLM so the parent's task tool result captures it.
|
||||
type scriptedTextLLM struct {
|
||||
llmtest.Base
|
||||
text string
|
||||
}
|
||||
|
||||
func (s *scriptedTextLLM) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
go func() {
|
||||
defer close(ch)
|
||||
// Emit per-character so event-forwarding observability tests can see
|
||||
// multiple deltas with non-empty AgentID forwarded to the parent.
|
||||
for _, r := range s.text {
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: string(r)}
|
||||
}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
}()
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// taskCallingLLM emits exactly one tool_call to the "task" tool on the first
|
||||
// call (delegating to the configured subagent_id with the configured prompt),
|
||||
// then on subsequent calls emits a single text delta + Done so the loop
|
||||
// terminates.
|
||||
type taskCallingLLM struct {
|
||||
llmtest.Base
|
||||
subagentID string
|
||||
prompt string
|
||||
finalText string
|
||||
calls atomic.Int32
|
||||
toolCallID string
|
||||
}
|
||||
|
||||
func (t *taskCallingLLM) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
n := t.calls.Add(1)
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
go func() {
|
||||
defer close(ch)
|
||||
if n == 1 {
|
||||
id := t.toolCallID
|
||||
if id == "" {
|
||||
id = "tc_task_0"
|
||||
}
|
||||
input, _ := json.Marshal(map[string]string{
|
||||
"agent_id": t.subagentID,
|
||||
"prompt": t.prompt,
|
||||
})
|
||||
tc := &llm.ToolCall{
|
||||
ID: id,
|
||||
Name: "task",
|
||||
Input: input,
|
||||
}
|
||||
ch <- llm.ChatEvent{Type: llm.EventToolCallStart, ToolCall: tc}
|
||||
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: tc}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
return
|
||||
}
|
||||
// Second call: parent has the tool result, emit final assistant text.
|
||||
final := t.finalText
|
||||
if final == "" {
|
||||
final = "ok"
|
||||
}
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: final}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
}()
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// taskOnlyExecutor is an Executor that only knows the "task" tool. Anything
|
||||
// else returns a useful error (subagent tests shouldn't hit other tools).
|
||||
type taskOnlyExecutor struct {
|
||||
task *tool.TaskTool
|
||||
}
|
||||
|
||||
func (e *taskOnlyExecutor) Execute(ctx context.Context, name string, input json.RawMessage) (tool.ToolResult, error) {
|
||||
if name == e.task.Name() {
|
||||
return e.task.Execute(ctx, input)
|
||||
}
|
||||
return tool.ToolResult{}, fmt.Errorf("unknown tool: %s", name)
|
||||
}
|
||||
|
||||
func (e *taskOnlyExecutor) ToolDefs() []llm.ToolDef {
|
||||
return []llm.ToolDef{{
|
||||
Name: e.task.Name(),
|
||||
Description: e.task.Description(),
|
||||
Parameters: e.task.Parameters(),
|
||||
}}
|
||||
}
|
||||
|
||||
func (e *taskOnlyExecutor) Names() []string {
|
||||
return []string{e.task.Name()}
|
||||
}
|
||||
|
||||
func (e *taskOnlyExecutor) Get(name string) (tool.Tool, bool) {
|
||||
if name == e.task.Name() {
|
||||
return e.task, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
|
||||
// TestRun_SubagentDelegationProducesFinalText verifies that delegating to a
|
||||
// subagent via the task tool surfaces the subagent's final assistant text as
|
||||
// the tool's output (which the parent session captures as a tool_result).
|
||||
func TestRun_SubagentDelegationProducesFinalText(t *testing.T) {
|
||||
cfg := newTwoAgentCfg(t)
|
||||
subLLM := &scriptedTextLLM{text: "research result"}
|
||||
parentLLM := &taskCallingLLM{
|
||||
subagentID: "researcher",
|
||||
prompt: "look into X",
|
||||
finalText: "done",
|
||||
}
|
||||
|
||||
deps := RuntimeDeps{}
|
||||
parent := &Runtime{
|
||||
LLM: parentLLM,
|
||||
Session: session.NewSession("default", "test"),
|
||||
AgentID: "default",
|
||||
Model: "parent",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
factory := MakeSubagentFactory(cfg.Resolve, deps, subagentBuilderForLLM(subLLM), parent)
|
||||
parent.Tools = &taskOnlyExecutor{
|
||||
task: tool.NewTaskTool(factory, parent.Depth, cfg.EligibleSubagents()),
|
||||
}
|
||||
|
||||
out, err := parent.RunSync(context.Background(), "go research", nil)
|
||||
require.NoError(t, err)
|
||||
// RunSync collects ALL EventTextDelta events, including those forwarded
|
||||
// from the subagent (Runtime.emit forwards subagent deltas to the parent
|
||||
// channel). So the collected output contains both the subagent's text
|
||||
// and the parent's final text.
|
||||
assert.Contains(t, out, "research result", "subagent text was forwarded")
|
||||
assert.Contains(t, out, "done", "parent's final text was emitted")
|
||||
|
||||
// The session should contain a tool_result entry whose Output is the
|
||||
// subagent's text. This is the more rigorous assertion — the session is
|
||||
// the durable record of what the parent's LLM saw as the tool result.
|
||||
var foundResult bool
|
||||
for _, e := range parent.Session.Entries() {
|
||||
if e.Type != session.EntryTypeToolResult {
|
||||
continue
|
||||
}
|
||||
var data session.ToolResultData
|
||||
require.NoError(t, json.Unmarshal(e.Data, &data))
|
||||
if strings.Contains(data.Output, "research result") {
|
||||
foundResult = true
|
||||
break
|
||||
}
|
||||
}
|
||||
require.True(t, foundResult, "parent session should contain the subagent's text as a tool_result")
|
||||
}
|
||||
|
||||
// TestRun_SubagentEventsForwardedToParent asserts that intermediate text
|
||||
// deltas emitted by the subagent are forwarded to the parent's events channel
|
||||
// with AgentID set to the subagent's ID.
|
||||
func TestRun_SubagentEventsForwardedToParent(t *testing.T) {
|
||||
cfg := newTwoAgentCfg(t)
|
||||
subLLM := &scriptedTextLLM{text: "research result"}
|
||||
parentLLM := &taskCallingLLM{
|
||||
subagentID: "researcher",
|
||||
prompt: "look",
|
||||
finalText: "done",
|
||||
}
|
||||
|
||||
deps := RuntimeDeps{}
|
||||
parent := &Runtime{
|
||||
LLM: parentLLM,
|
||||
Session: session.NewSession("default", "test"),
|
||||
AgentID: "default",
|
||||
Model: "parent",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
factory := MakeSubagentFactory(cfg.Resolve, deps, subagentBuilderForLLM(subLLM), parent)
|
||||
parent.Tools = &taskOnlyExecutor{
|
||||
task: tool.NewTaskTool(factory, parent.Depth, cfg.EligibleSubagents()),
|
||||
}
|
||||
|
||||
events, err := parent.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var subagentDeltas []string
|
||||
var sawDone bool
|
||||
timeout := time.After(5 * time.Second)
|
||||
loop:
|
||||
for {
|
||||
select {
|
||||
case ev, ok := <-events:
|
||||
if !ok {
|
||||
break loop
|
||||
}
|
||||
if ev.Type == EventTextDelta && ev.AgentID == "researcher" {
|
||||
subagentDeltas = append(subagentDeltas, ev.Text)
|
||||
}
|
||||
if ev.Type == EventDone && ev.AgentID == "" {
|
||||
sawDone = true
|
||||
}
|
||||
case <-timeout:
|
||||
t.Fatal("timed out waiting for parent events")
|
||||
}
|
||||
}
|
||||
|
||||
assert.True(t, sawDone, "expected parent's own EventDone (AgentID empty)")
|
||||
require.NotEmpty(t, subagentDeltas, "expected at least one text delta forwarded with AgentID=researcher")
|
||||
joined := strings.Join(subagentDeltas, "")
|
||||
assert.Contains(t, joined, "research result",
|
||||
"forwarded subagent text deltas should accumulate to the subagent's final text")
|
||||
}
|
||||
|
||||
// TestRun_SubagentDepthCapEnforced verifies the cap stops construction past
|
||||
// the configured limit. With FELIX_MAX_AGENT_DEPTH=2, a parent at depth 0
|
||||
// can call a subagent (depth 1), and that subagent can call another (depth 2),
|
||||
// but a third-level attempt (depth 3) must fail with the cap error and the
|
||||
// would-be subagent's RuntimeInputs builder must NOT be invoked.
|
||||
//
|
||||
// Note: this test reimplements the factory wiring rather than calling
|
||||
// MakeSubagentFactory directly because production buildSubagentInputs
|
||||
// closures do not register the `task` tool on subagent registries (so
|
||||
// recursion past depth 1 is unreachable from production paths today).
|
||||
// To exercise the cap, this test gives each level its own task tool
|
||||
// pointing at the next level. If production ever registers task tool on
|
||||
// subagent registries, this test should be simplified to use the production
|
||||
// MakeSubagentFactory directly. See subagent.go's depth-cap comment.
|
||||
func TestRun_SubagentDepthCapEnforced(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_AGENT_DEPTH", "2")
|
||||
|
||||
cfg := newTwoAgentCfg(t)
|
||||
|
||||
// Parent emits a task call to "researcher".
|
||||
parentLLM := &taskCallingLLM{
|
||||
subagentID: "researcher",
|
||||
prompt: "go",
|
||||
finalText: "parent done",
|
||||
toolCallID: "tc_parent",
|
||||
}
|
||||
|
||||
// Track build calls. With max depth 2, the parent (depth 0) can build a
|
||||
// subagent at depth 1; that subagent can build one at depth 2; a 3rd-level
|
||||
// build must be blocked BEFORE buildInputs runs.
|
||||
var buildCount atomic.Int32
|
||||
|
||||
deps := RuntimeDeps{}
|
||||
parent := &Runtime{
|
||||
LLM: parentLLM,
|
||||
Session: session.NewSession("default", "test"),
|
||||
AgentID: "default",
|
||||
Model: "parent",
|
||||
MaxTurns: 5,
|
||||
Depth: 0,
|
||||
}
|
||||
|
||||
// Self-referencing factory: every subagent gets a task tool whose factory
|
||||
// is THIS SAME closure, so each level recurses one step deeper. The
|
||||
// tools-executor patch happens AFTER BuildRuntime so the subagent's
|
||||
// task tool captures its own runtime as parent (matching production wiring).
|
||||
var factory tool.SubagentFactory
|
||||
buildInputs := func(spec AgentSpec) (RuntimeInputs, error) {
|
||||
buildCount.Add(1)
|
||||
return RuntimeInputs{
|
||||
Provider: &taskCallingLLM{
|
||||
subagentID: "researcher",
|
||||
prompt: "deeper",
|
||||
finalText: "sub done",
|
||||
toolCallID: fmt.Sprintf("tc_sub_%d", buildCount.Load()),
|
||||
},
|
||||
Session: NewSubagentSession(spec.ID),
|
||||
Compaction: nil,
|
||||
IngestSource: "",
|
||||
}, nil
|
||||
}
|
||||
factory = func(ctx context.Context, agentID string, parentDepth int) (tool.SubagentRunner, error) {
|
||||
if parentDepth+1 > parent.maxAgentDepth() {
|
||||
return nil, fmt.Errorf("subagent depth limit %d reached", parent.maxAgentDepth())
|
||||
}
|
||||
ss, ok := cfg.Resolve(agentID)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("subagent %s not found", agentID)
|
||||
}
|
||||
if !ss.Registered {
|
||||
return nil, fmt.Errorf("agent %s is not a subagent", agentID)
|
||||
}
|
||||
inputs, err := buildInputs(ss.Spec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rt, err := BuildRuntime(deps, inputs, ss.Spec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rt.Parent = parent
|
||||
rt.Depth = parentDepth + 1
|
||||
// Patch the subagent's Tools to include a task tool wired to THIS
|
||||
// same factory so it can recurse one step deeper.
|
||||
rt.Tools = &taskOnlyExecutor{
|
||||
task: tool.NewTaskTool(factory, rt.Depth, cfg.EligibleSubagents()),
|
||||
}
|
||||
return &subagentRunnerAdapter{rt: rt}, nil
|
||||
}
|
||||
|
||||
parent.Tools = &taskOnlyExecutor{
|
||||
task: tool.NewTaskTool(factory, parent.Depth, cfg.EligibleSubagents()),
|
||||
}
|
||||
|
||||
_, err := parent.RunSync(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
// With max depth = 2 we expect at most 2 buildInputs calls:
|
||||
// - depth 1 (parent calls subagent): allowed → builds
|
||||
// - depth 2 (sub calls sub-sub): allowed → builds
|
||||
// - depth 3 (sub-sub tries to call): blocked BEFORE buildInputs runs
|
||||
assert.LessOrEqual(t, int(buildCount.Load()), 2,
|
||||
"buildInputs must not run for a subagent that would exceed the depth cap")
|
||||
assert.GreaterOrEqual(t, int(buildCount.Load()), 1,
|
||||
"at least the first subagent (depth 1) must have been built")
|
||||
|
||||
// At least one tool_result somewhere in the parent's session should be
|
||||
// the deepest subagent's output, which is the depth-limit error string.
|
||||
// The error propagates UP as the deeper subagent's tool result Error.
|
||||
// (We don't see it directly in the parent's session — it lives in the
|
||||
// inner subagent's session — but the buildCount assertion above proves
|
||||
// the cap fired correctly.)
|
||||
}
|
||||
|
||||
// TestRun_SubagentAbortPropagatesFromParent cancels the parent's ctx mid-
|
||||
// subagent execution. The subagent should terminate and the parent session
|
||||
// should still satisfy the tool_call ↔ tool_result pairing invariant.
|
||||
func TestRun_SubagentAbortPropagatesFromParent(t *testing.T) {
|
||||
cfg := newTwoAgentCfg(t)
|
||||
|
||||
// Subagent LLM that takes its time so we can cancel during it.
|
||||
slowSub := &slowLLM{
|
||||
text: "should not finish",
|
||||
delay: 500 * time.Millisecond,
|
||||
}
|
||||
parentLLM := &taskCallingLLM{
|
||||
subagentID: "researcher",
|
||||
prompt: "go",
|
||||
finalText: "shouldn't reach",
|
||||
}
|
||||
|
||||
deps := RuntimeDeps{}
|
||||
parent := &Runtime{
|
||||
LLM: parentLLM,
|
||||
Session: session.NewSession("default", "test"),
|
||||
AgentID: "default",
|
||||
Model: "parent",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
factory := MakeSubagentFactory(cfg.Resolve, deps, subagentBuilderForLLM(slowSub), parent)
|
||||
parent.Tools = &taskOnlyExecutor{
|
||||
task: tool.NewTaskTool(factory, parent.Depth, cfg.EligibleSubagents()),
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
// Cancel after a short delay — the subagent's slow LLM is mid-stream by then.
|
||||
go func() {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
cancel()
|
||||
}()
|
||||
|
||||
events, err := parent.Run(ctx, "go", nil)
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
// drain
|
||||
}
|
||||
|
||||
// Confirm pairing: count tool_calls and tool_results.
|
||||
var calls, results int
|
||||
for _, e := range parent.Session.Entries() {
|
||||
switch e.Type {
|
||||
case session.EntryTypeToolCall:
|
||||
calls++
|
||||
case session.EntryTypeToolResult:
|
||||
results++
|
||||
}
|
||||
}
|
||||
require.Equal(t, calls, results,
|
||||
"every tool_call must have a paired tool_result (no orphans after abort)")
|
||||
}
|
||||
|
||||
// slowLLM streams its text after a delay; used to test cancellation paths.
|
||||
type slowLLM struct {
|
||||
llmtest.Base
|
||||
text string
|
||||
delay time.Duration
|
||||
}
|
||||
|
||||
func (s *slowLLM) ChatStream(ctx context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
go func() {
|
||||
defer close(ch)
|
||||
select {
|
||||
case <-time.After(s.delay):
|
||||
case <-ctx.Done():
|
||||
ch <- llm.ChatEvent{Type: llm.EventError, Error: ctx.Err()}
|
||||
return
|
||||
}
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: s.text}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
}()
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// TestRun_SubagentNotInEligibleListReturnsError verifies that calling a
|
||||
// task tool with an unknown subagent ID returns a tool result error that
|
||||
// names the bad ID and mentions the eligible alternatives.
|
||||
func TestRun_SubagentNotInEligibleListReturnsError(t *testing.T) {
|
||||
cfg := newTwoAgentCfg(t)
|
||||
|
||||
// Parent dispatches to "ghost" — not registered as a subagent.
|
||||
parentLLM := &taskCallingLLM{
|
||||
subagentID: "ghost",
|
||||
prompt: "go",
|
||||
finalText: "parent done",
|
||||
}
|
||||
|
||||
deps := RuntimeDeps{}
|
||||
parent := &Runtime{
|
||||
LLM: parentLLM,
|
||||
Session: session.NewSession("default", "test"),
|
||||
AgentID: "default",
|
||||
Model: "parent",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
factory := MakeSubagentFactory(cfg.Resolve, deps, subagentBuilderForLLM(&scriptedTextLLM{text: "x"}), parent)
|
||||
parent.Tools = &taskOnlyExecutor{
|
||||
task: tool.NewTaskTool(factory, parent.Depth, cfg.EligibleSubagents()),
|
||||
}
|
||||
|
||||
out, err := parent.RunSync(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "parent done", out)
|
||||
|
||||
// Find the tool_result and assert its Error mentions the bad ID and the
|
||||
// eligible list ("researcher" is the only opt-in subagent in cfg).
|
||||
var found bool
|
||||
for _, e := range parent.Session.Entries() {
|
||||
if e.Type != session.EntryTypeToolResult {
|
||||
continue
|
||||
}
|
||||
var data session.ToolResultData
|
||||
require.NoError(t, json.Unmarshal(e.Data, &data))
|
||||
if data.Error == "" {
|
||||
continue
|
||||
}
|
||||
assert.Contains(t, data.Error, "ghost",
|
||||
"error should name the unknown subagent")
|
||||
assert.Contains(t, data.Error, "researcher",
|
||||
"error should list the eligible subagents")
|
||||
found = true
|
||||
break
|
||||
}
|
||||
require.True(t, found, "expected a tool_result entry with an error mentioning the bad subagent")
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package runtime
|
||||
|
||||
import "context"
|
||||
|
||||
// neverRecallKG is a KnowledgeGraph that always declines recall and
|
||||
// silently swallows ingest. Used in tests as a non-nil sentinel where the
|
||||
// runtime should NOT actually invoke the KG (e.g., trivial messages,
|
||||
// IngestSource="cron").
|
||||
type neverRecallKG struct{}
|
||||
|
||||
func (neverRecallKG) ShouldRecall(string) bool { return false }
|
||||
func (neverRecallKG) Recall(context.Context, string) string { return "" }
|
||||
func (neverRecallKG) Ingest(context.Context, []Message) {}
|
||||
|
||||
// recallingKG is a controllable KG fake — tests can set Hint to inspect
|
||||
// the dynamic-suffix injection and Ingested to verify thread capture.
|
||||
type recallingKG struct {
|
||||
Hint string
|
||||
Ingested []Message
|
||||
}
|
||||
|
||||
func (k *recallingKG) ShouldRecall(string) bool { return true }
|
||||
func (k *recallingKG) Recall(context.Context, string) string { return k.Hint }
|
||||
func (k *recallingKG) Ingest(_ context.Context, t []Message) {
|
||||
k.Ingested = append(k.Ingested, t...)
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
// testCfg is the harness test analogue of Felix's *config.Config — bundles
|
||||
// a SubagentResolver with the small accessor helpers (EligibleSubagents,
|
||||
// GetAgent) that subagent tests reach for. Lets the subagent_test.go and
|
||||
// inheritance_test.go call sites keep their `cfg.X()` shape after the
|
||||
// extraction without rewriting every test.
|
||||
type testCfg struct {
|
||||
specs map[string]AgentSpec
|
||||
subagent map[string]bool // id → registered as subagent
|
||||
desc map[string]string // id → description (for EligibleSubagents)
|
||||
}
|
||||
|
||||
func (c *testCfg) Resolve(id string) (SubagentSpec, bool) {
|
||||
spec, ok := c.specs[id]
|
||||
if !ok {
|
||||
return SubagentSpec{}, false
|
||||
}
|
||||
return SubagentSpec{Spec: spec, Registered: c.subagent[id]}, true
|
||||
}
|
||||
|
||||
func (c *testCfg) EligibleSubagents() map[string]string {
|
||||
out := map[string]string{}
|
||||
for id, ok := range c.subagent {
|
||||
if ok {
|
||||
out[id] = c.desc[id]
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *testCfg) GetAgent(id string) (AgentSpec, bool) {
|
||||
s, ok := c.specs[id]
|
||||
return s, ok
|
||||
}
|
||||
|
||||
// newTwoAgentCfg builds a fixture with a parent ("default") and one
|
||||
// subagent ("researcher"). Direct port of Felix's twoAgentConfig fixture.
|
||||
func newTwoAgentCfg(t *testing.T) *testCfg {
|
||||
t.Helper()
|
||||
parent := AgentSpec{
|
||||
ID: "default",
|
||||
Name: "Parent",
|
||||
Workspace: t.TempDir(),
|
||||
Model: "test/parent",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
sub := AgentSpec{
|
||||
ID: "researcher",
|
||||
Name: "Researcher",
|
||||
Workspace: t.TempDir(),
|
||||
Model: "test/researcher",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
return &testCfg{
|
||||
specs: map[string]AgentSpec{"default": parent, "researcher": sub},
|
||||
subagent: map[string]bool{"researcher": true},
|
||||
desc: map[string]string{"researcher": "Investigates topics and reports findings."},
|
||||
}
|
||||
}
|
||||
|
||||
// subagentBuilderForLLM returns a SubagentBuildFn that hands every subagent
|
||||
// the supplied LLM, a fresh in-memory Session, and a noop executor.
|
||||
func subagentBuilderForLLM(subLLM llm.LLMProvider) SubagentBuildFn {
|
||||
return func(spec AgentSpec) (RuntimeInputs, error) {
|
||||
return RuntimeInputs{
|
||||
Provider: subLLM,
|
||||
Tools: noopExecutor{},
|
||||
Session: NewSubagentSession(spec.ID),
|
||||
Compaction: nil,
|
||||
IngestSource: "",
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// otelTracer is the package-level tracer used for OTel span emission
|
||||
// alongside the existing slog perf logs. nil → no OTel emission. Set
|
||||
// once at startup via SetOTelTracer; not safe to swap mid-flight.
|
||||
var otelTracer trace.Tracer
|
||||
|
||||
// SetOTelTracer installs a tracer for the agent package. Call once
|
||||
// from startup wiring after building the OTel provider; thereafter
|
||||
// every NewTrace creates an OTel root span and each Mark adds a span
|
||||
// event. Pass nil to disable.
|
||||
func SetOTelTracer(t trace.Tracer) { otelTracer = t }
|
||||
|
||||
// Trace records phase timings across a single chat request so we can spot
|
||||
// where latency comes from. Designed to be cheap: each Mark allocates a small
|
||||
// struct and emits one slog.Info record. A typical request produces ~10 lines.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// tr := agent.NewTrace(agentID, model)
|
||||
// ctx = agent.WithTrace(ctx, tr)
|
||||
// tr.Mark("ws.received")
|
||||
// ... runtime calls tr.Mark("llm.first_token", "turn", n) ...
|
||||
// tr.Summary()
|
||||
type Trace struct {
|
||||
ID string
|
||||
AgentID string
|
||||
Model string
|
||||
Started time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
last time.Time
|
||||
phases []phaseRecord
|
||||
|
||||
// onMark, when set, is invoked synchronously on every Mark call so
|
||||
// the gateway WebSocket can forward live phase events to subscribed
|
||||
// clients (the chat-UI trace panel). Nil means no live forwarding,
|
||||
// which preserves the original "slog only" behavior for tests and
|
||||
// non-gateway call paths.
|
||||
onMark func(phase string, durMs, atMs int64, attrs []any)
|
||||
|
||||
// span is the root OTel span for this Trace, created by NewTrace
|
||||
// when otelTracer is non-nil. Each Mark adds an event to this span
|
||||
// and Summary ends it. nil when OTel is disabled — every method on
|
||||
// trace.Span is nil-safe so no extra guards needed at call sites.
|
||||
span trace.Span
|
||||
}
|
||||
|
||||
// SetOnMark registers a callback fired on every Mark. Safe to call once
|
||||
// before the trace is shared with a goroutine; later calls overwrite the
|
||||
// previous callback. The callback is invoked under the trace's lock so
|
||||
// receivers must be quick (e.g., non-blocking channel send).
|
||||
func (t *Trace) SetOnMark(fn func(phase string, durMs, atMs int64, attrs []any)) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
t.onMark = fn
|
||||
}
|
||||
|
||||
type phaseRecord struct {
|
||||
Name string
|
||||
DurMs int64 // since previous Mark
|
||||
AtMs int64 // since trace start
|
||||
}
|
||||
|
||||
// NewTrace creates a Trace seeded with the start time. Returns nil-safe value;
|
||||
// all methods are no-ops on a nil receiver so callers don't need nil checks.
|
||||
//
|
||||
// When the package-level otelTracer is set, NewTrace also starts a root
|
||||
// OTel span "agent.run" tagged with trace_id, agent.id, and llm.model.
|
||||
// The span is ended by Summary().
|
||||
func NewTrace(agentID, model string) *Trace {
|
||||
now := time.Now()
|
||||
id := newTraceID()
|
||||
t := &Trace{
|
||||
ID: id,
|
||||
AgentID: agentID,
|
||||
Model: model,
|
||||
Started: now,
|
||||
last: now,
|
||||
}
|
||||
if otelTracer != nil {
|
||||
_, t.span = otelTracer.Start(context.Background(), "agent.run",
|
||||
trace.WithAttributes(
|
||||
attribute.String("felix.trace_id", id),
|
||||
attribute.String("agent.id", agentID),
|
||||
attribute.String("llm.model", model),
|
||||
),
|
||||
)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// Mark records a phase boundary and emits a slog.Info entry tagged "perf".
|
||||
// extraAttrs are key/value pairs appended to the log record (e.g. "turn", 3).
|
||||
//
|
||||
// When the Trace has an attached OTel span (because otelTracer was set
|
||||
// at construction time), Mark also adds a span event so the phase
|
||||
// timeline is visible in OTel UIs (Tempo / Jaeger / etc).
|
||||
func (t *Trace) Mark(phase string, extraAttrs ...any) {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
t.mu.Lock()
|
||||
now := time.Now()
|
||||
dur := now.Sub(t.last).Milliseconds()
|
||||
at := now.Sub(t.Started).Milliseconds()
|
||||
t.phases = append(t.phases, phaseRecord{Name: phase, DurMs: dur, AtMs: at})
|
||||
t.last = now
|
||||
cb := t.onMark
|
||||
span := t.span
|
||||
t.mu.Unlock()
|
||||
|
||||
attrs := []any{
|
||||
"trace_id", t.ID,
|
||||
"agent", t.AgentID,
|
||||
"phase", phase,
|
||||
"dur_ms", dur,
|
||||
"at_ms", at,
|
||||
}
|
||||
attrs = append(attrs, extraAttrs...)
|
||||
slog.Info("perf", attrs...)
|
||||
|
||||
if cb != nil {
|
||||
cb(phase, dur, at, extraAttrs)
|
||||
}
|
||||
|
||||
if span != nil && span.IsRecording() {
|
||||
span.AddEvent(phase, trace.WithAttributes(buildOTelAttrs(dur, at, extraAttrs)...))
|
||||
}
|
||||
}
|
||||
|
||||
// buildOTelAttrs converts the slog-style key/value pairs used throughout
|
||||
// the trace package into the typed attribute.KeyValue slice the OTel
|
||||
// SDK wants. Unknown types fall through to fmt.Sprint so the attribute
|
||||
// always lands as a string rather than being dropped.
|
||||
func buildOTelAttrs(dur, at int64, kvs []any) []attribute.KeyValue {
|
||||
out := make([]attribute.KeyValue, 0, 2+len(kvs)/2)
|
||||
out = append(out, attribute.Int64("dur_ms", dur), attribute.Int64("at_ms", at))
|
||||
for i := 0; i+1 < len(kvs); i += 2 {
|
||||
key, ok := kvs[i].(string)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch v := kvs[i+1].(type) {
|
||||
case string:
|
||||
out = append(out, attribute.String(key, v))
|
||||
case bool:
|
||||
out = append(out, attribute.Bool(key, v))
|
||||
case int:
|
||||
out = append(out, attribute.Int(key, v))
|
||||
case int64:
|
||||
out = append(out, attribute.Int64(key, v))
|
||||
case float64:
|
||||
out = append(out, attribute.Float64(key, v))
|
||||
default:
|
||||
out = append(out, attribute.String(key, fmt.Sprint(v)))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Summary emits one final slog.Info "perf summary" line with the total
|
||||
// elapsed time and the top three slowest phases. Useful for at-a-glance
|
||||
// triage without grep.
|
||||
func (t *Trace) Summary() {
|
||||
if t == nil {
|
||||
return
|
||||
}
|
||||
t.mu.Lock()
|
||||
total := time.Since(t.Started).Milliseconds()
|
||||
// Aggregate dur by phase name (some phases recur per turn).
|
||||
agg := map[string]int64{}
|
||||
for _, p := range t.phases {
|
||||
agg[p.Name] += p.DurMs
|
||||
}
|
||||
type kv struct {
|
||||
Name string
|
||||
Dur int64
|
||||
}
|
||||
flat := make([]kv, 0, len(agg))
|
||||
for k, v := range agg {
|
||||
flat = append(flat, kv{k, v})
|
||||
}
|
||||
t.mu.Unlock()
|
||||
sort.Slice(flat, func(i, j int) bool { return flat[i].Dur > flat[j].Dur })
|
||||
top := flat
|
||||
if len(top) > 3 {
|
||||
top = top[:3]
|
||||
}
|
||||
attrs := []any{
|
||||
"trace_id", t.ID,
|
||||
"agent", t.AgentID,
|
||||
"model", t.Model,
|
||||
"total_ms", total,
|
||||
"phase_count", len(t.phases),
|
||||
}
|
||||
for i, kv := range top {
|
||||
attrs = append(attrs,
|
||||
"top"+itoa(i+1)+"_phase", kv.Name,
|
||||
"top"+itoa(i+1)+"_ms", kv.Dur,
|
||||
)
|
||||
}
|
||||
slog.Info("perf summary", attrs...)
|
||||
|
||||
if t.span != nil {
|
||||
t.span.SetAttributes(
|
||||
attribute.Int64("felix.total_ms", total),
|
||||
attribute.Int("felix.phase_count", len(t.phases)),
|
||||
)
|
||||
t.span.End()
|
||||
}
|
||||
}
|
||||
|
||||
type traceKey struct{}
|
||||
|
||||
// WithTrace stashes the Trace in ctx so deeper layers can call Mark.
|
||||
func WithTrace(ctx context.Context, t *Trace) context.Context {
|
||||
return context.WithValue(ctx, traceKey{}, t)
|
||||
}
|
||||
|
||||
// TraceFrom retrieves the Trace from ctx, or nil if none. nil is safe — all
|
||||
// Trace methods tolerate a nil receiver.
|
||||
func TraceFrom(ctx context.Context) *Trace {
|
||||
if v := ctx.Value(traceKey{}); v != nil {
|
||||
if t, ok := v.(*Trace); ok {
|
||||
return t
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newTraceID() string {
|
||||
var b [4]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
func itoa(n int) string {
|
||||
if n == 0 {
|
||||
return "0"
|
||||
}
|
||||
var buf [4]byte
|
||||
i := len(buf)
|
||||
for n > 0 {
|
||||
i--
|
||||
buf[i] = byte('0' + n%10)
|
||||
n /= 10
|
||||
}
|
||||
return string(buf[i:])
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package runtime
|
||||
|
||||
import "context"
|
||||
|
||||
// AgentSpec is the framework's view of an agent. Consumers convert their
|
||||
// own agent-config types into this struct before invoking BuildRuntime.
|
||||
//
|
||||
// Mirrors the fields Runtime actually consumes; Felix-specific options
|
||||
// (per-agent tool policies, MCP server bindings, channel routing,
|
||||
// inheritContext flag, subagent registration, identity files) live in the
|
||||
// consumer's config and are resolved before this struct is filled in.
|
||||
type AgentSpec struct {
|
||||
// ID identifies the agent for logging, session paths, and subagent
|
||||
// resolution. Used as session.Session.AgentID.
|
||||
ID string
|
||||
// Name is the human-readable display name (shown in chat UIs).
|
||||
Name string
|
||||
// Model is the "provider/model" string parsed by ParseProviderModel
|
||||
// (e.g., "anthropic/claude-haiku-4-5"). The provider portion is exposed
|
||||
// on Runtime.Provider for caching capability checks.
|
||||
Model string
|
||||
// FallbackModel is the bare model name used on transient model errors
|
||||
// (Anthropic 429/529, OpenAI 429/5xx). Same provider as Model.
|
||||
FallbackModel string
|
||||
// Workspace is the agent's working directory — the root for the
|
||||
// post-compact file-restore path and the spill directory.
|
||||
Workspace string
|
||||
// SystemPrompt overrides the built-in default identity. Empty ⇒
|
||||
// BuildStaticSystemPrompt composes a default identity string from
|
||||
// the registered tool names.
|
||||
SystemPrompt string
|
||||
// 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
|
||||
// Reasoning maps to each provider's native reasoning knob. Use
|
||||
// llm.ReasoningOff (zero value), Low, Medium, or High.
|
||||
Reasoning string
|
||||
// Loop controls the runtime's tool-execution behavior (concurrency
|
||||
// cap, depth cap, streaming-tools toggle). Zero value ⇒ env-var
|
||||
// fallback then compiled-in defaults.
|
||||
Loop LoopConfig
|
||||
}
|
||||
|
||||
// LoopConfig tunes the agent runtime's tool-execution behavior. Mirrors
|
||||
// Felix's AgentLoopConfig with framework-side env-var fallbacks
|
||||
// (HARNESS_MAX_TOOL_CONCURRENCY, HARNESS_MAX_AGENT_DEPTH,
|
||||
// HARNESS_STREAMING_TOOLS) — Felix consumers may set the FELIX_* env vars
|
||||
// instead by setting these fields explicitly from their own config block.
|
||||
type LoopConfig struct {
|
||||
// MaxToolConcurrency caps parallel tool dispatch within a safe batch.
|
||||
// 0 ⇒ env fallback then default 10.
|
||||
MaxToolConcurrency int
|
||||
// MaxAgentDepth caps subagent recursion depth. 0 ⇒ env fallback
|
||||
// then default 3.
|
||||
MaxAgentDepth int
|
||||
// StreamingTools enables mid-stream concurrency-safe tool kickoff.
|
||||
// false ⇒ env fallback (HARNESS_STREAMING_TOOLS=1) then off.
|
||||
StreamingTools bool
|
||||
}
|
||||
|
||||
// SkillProvider lets the runtime advertise the available skills in the
|
||||
// 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
|
||||
// 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.
|
||||
type SkillProvider interface {
|
||||
FormatIndex() string
|
||||
Get(name string) (body string, ok bool)
|
||||
}
|
||||
|
||||
// MemoryProvider mirrors SkillProvider for an on-demand memory-entries
|
||||
// store. FormatIndex contributes to the static prompt; Get backs the
|
||||
// load_memory tool. Optional.
|
||||
type MemoryProvider interface {
|
||||
FormatIndex() string
|
||||
Get(id string) (body string, ok bool)
|
||||
}
|
||||
|
||||
// Message is a minimal conversation tuple the runtime hands to the
|
||||
// KnowledgeGraph. The runtime accumulates these inside Run as the LLM
|
||||
// produces text, calls tools, and consumes results. Implementations may
|
||||
// translate to their own domain types.
|
||||
type Message struct {
|
||||
Role string // "user" | "assistant"
|
||||
Content string
|
||||
}
|
||||
|
||||
// KnowledgeGraph is the optional plug point for a long-term memory /
|
||||
// knowledge-graph backend. Felix wires this to its cortex adapter.
|
||||
//
|
||||
// - ShouldRecall is called synchronously at the start of every Run
|
||||
// before scheduling the recall goroutine. Cheap; should return
|
||||
// false for trivial messages ("ok", "thanks", greetings) where
|
||||
// recall would not help.
|
||||
//
|
||||
// - Recall runs in a background goroutine. The runtime caps the wait
|
||||
// at 800ms; implementations should respect ctx cancellation. The
|
||||
// returned string is concatenated verbatim into the dynamic system
|
||||
// prompt suffix — return "" for no hint, or a pre-formatted block
|
||||
// ready for the prompt.
|
||||
//
|
||||
// - Ingest fires deferred-async at the end of Run with the full
|
||||
// conversation thread. The runtime calls it with a fresh
|
||||
// context.Background — the request ctx may already be cancelled.
|
||||
// Implementations decide sync/async batching internally.
|
||||
//
|
||||
// Pass nil on Deps.KG to disable the entire pathway.
|
||||
type KnowledgeGraph interface {
|
||||
ShouldRecall(query string) bool
|
||||
Recall(ctx context.Context, query string) string
|
||||
Ingest(ctx context.Context, thread []Message)
|
||||
}
|
||||
|
||||
// SubagentResolver resolves a subagent ID to its AgentSpec. The runtime
|
||||
// calls this inside MakeSubagentFactory before constructing a
|
||||
// child Runtime. Returning ok=false makes TaskTool surface a "subagent
|
||||
// %q not found" error to the parent LLM.
|
||||
//
|
||||
// Implementations typically read from a live config so subagent
|
||||
// definitions hot-reload (Felix reads through *config.Config).
|
||||
type SubagentResolver func(agentID string) (spec AgentSpec, registered bool, ok bool)
|
||||
Reference in new issue
Block a user