Add hooks and MCP as first-class components; expand docs
Promotes the two remaining "deliberately not in scope" components from the harness model to first-class subsystems, and overhauls the docs. Hooks (runtime/types.go, runtime/runtime.go, runtime/hooks_test.go): - New runtime.LifecycleHooks struct on LoopConfig.Hooks with five Go callbacks: OnUserPromptSubmit (may rewrite prompt), OnSessionStart, BeforeToolUse (gating with same shape as PermissionChecker), AfterToolUse (observe), OnStop (with reason: completed/max_turns/error/aborted). - Wired into Run, dispatchTool, executeToolKickoff at all 8 exit points + both tool-execution paths. - 8 tests covering each hook firing. MCP (tools/mcp/, runtime/builder.go, runtime/types.go): - New tools/mcp package using the official github.com/modelcontextprotocol/go-sdk v1.5.0. Stdio and Streamable HTTP transports. - ServerConfig now exposes Headers + HTTPClient for HTTP auth (static bearer, OAuth via oauth2.NewClient, mTLS, custom RoundTripper). Header injection clones requests so SDK retries see clean params. - First-class AgentSpec.MCPServers — BuildRuntime connects each server, registers adapter tools (mcp__<server>__<tool>), stashes clients on Runtime. - New Runtime.Close() releases sessions; idempotent. - 14 tests including end-to-end header propagation through the SDK via httptest.Server. Examples: - support-agent now demonstrates Skills + Permission + LifecycleHooks together. Audit log via AfterToolUse + OnStop, JSONL output. - defer rt.Close() added to all four examples (no-op without MCP, idiomatic). Docs: - README expanded: Why harness, Requirements, Install, Examples table, Configuration (env vars), Non-goals, Testing, expanded Status. Quick Start fixed to use real BuildRuntime API. - developer.md mental-model diagram replaced with two correct ones: composition (how a Runtime is wired) and per-Run sequence (what rt.Run actually does, including hook fan-out and the tool batch loop). - developer.md gains Lifecycle hooks + MCP servers subsections with full snippets, including Streamable HTTP auth and OAuth recipes (clientcredentials + authcode flows via golang.org/x/oauth2). - LICENSE file added (MIT). All 18 packages build and test green.
This commit is contained in:
1 parent
4b2f645f16
commit
76c03019c8
19 files changed
+1926
-59
No files matched your search
@@ -1,6 +1,8 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/sausheong/harness/compaction"
|
||||
@@ -8,6 +10,7 @@ import (
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tokens"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/sausheong/harness/tools/mcp"
|
||||
)
|
||||
|
||||
// RuntimeDeps holds the long-lived dependencies that every Runtime in this
|
||||
@@ -87,6 +90,7 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
// *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).
|
||||
var mcpClients []*mcp.Client
|
||||
if reg, ok := inputs.Tools.(*tool.Registry); ok {
|
||||
if deps.Skills != nil {
|
||||
skills := deps.Skills
|
||||
@@ -104,6 +108,24 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
},
|
||||
})
|
||||
}
|
||||
// Connect declared MCP servers and register their adapter tools.
|
||||
// On any failure, close everything connected so far before
|
||||
// returning — a partially-built Runtime would leak processes.
|
||||
for _, srv := range spec.MCPServers {
|
||||
cli, err := mcp.Connect(context.Background(), srv)
|
||||
if err != nil {
|
||||
for _, c := range mcpClients {
|
||||
_ = c.Close()
|
||||
}
|
||||
return nil, fmt.Errorf("mcp server %q: %w", srv.Name, err)
|
||||
}
|
||||
for _, t := range cli.Tools() {
|
||||
reg.Register(t)
|
||||
}
|
||||
mcpClients = append(mcpClients, cli)
|
||||
}
|
||||
} else if len(spec.MCPServers) > 0 {
|
||||
return nil, fmt.Errorf("AgentSpec.MCPServers requires inputs.Tools to be *tool.Registry")
|
||||
}
|
||||
|
||||
// Pre-compute the static portion of the system prompt so the per-turn
|
||||
@@ -167,6 +189,7 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
AgentLoop: deps.AgentLoop,
|
||||
StaticSystemPrompt: staticPrompt,
|
||||
CalibratorStore: deps.CalibratorStore,
|
||||
mcpClients: mcpClients,
|
||||
}
|
||||
|
||||
// Seed the calibrator from prior (ratio, count) for this session so a
|
||||
|
||||
@@ -3,6 +3,9 @@ package runtime
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/sausheong/harness/tools/mcp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -51,3 +54,49 @@ func TestBuildRuntimeUsesCallerProvidedMemoryFiles(t *testing.T) {
|
||||
require.Contains(t, rt.StaticSystemPrompt, sentinel)
|
||||
require.Contains(t, rt.StaticSystemPrompt, "## Project memory:")
|
||||
}
|
||||
|
||||
// TestBuildRuntime_MCPServers_BadConfigErrors confirms BuildRuntime
|
||||
// surfaces MCP connection failures (here: invalid empty ServerConfig)
|
||||
// rather than returning a partially-built Runtime.
|
||||
func TestBuildRuntime_MCPServers_BadConfigErrors(t *testing.T) {
|
||||
reg := tool.NewRegistry()
|
||||
rt, err := BuildRuntime(
|
||||
RuntimeDeps{},
|
||||
RuntimeInputs{Tools: reg},
|
||||
AgentSpec{
|
||||
ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5",
|
||||
MCPServers: []mcp.ServerConfig{{Name: ""}}, // invalid: name missing
|
||||
},
|
||||
)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, rt)
|
||||
assert.Contains(t, err.Error(), "mcp server")
|
||||
}
|
||||
|
||||
// TestBuildRuntime_MCPServers_RequiresRegistry confirms that declaring
|
||||
// MCPServers when inputs.Tools is not a *tool.Registry is a clean error
|
||||
// rather than a silent no-op.
|
||||
func TestBuildRuntime_MCPServers_RequiresRegistry(t *testing.T) {
|
||||
rt, err := BuildRuntime(
|
||||
RuntimeDeps{},
|
||||
RuntimeInputs{Tools: nil}, // not a *tool.Registry
|
||||
AgentSpec{
|
||||
ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5",
|
||||
MCPServers: []mcp.ServerConfig{{Name: "x", Command: "true"}},
|
||||
},
|
||||
)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, rt)
|
||||
assert.Contains(t, err.Error(), "*tool.Registry")
|
||||
}
|
||||
|
||||
// TestRuntime_Close_NoOpWithoutMCP confirms Close on a runtime with no
|
||||
// MCP clients is a safe no-op (returns nil, doesn't panic).
|
||||
func TestRuntime_Close_NoOpWithoutMCP(t *testing.T) {
|
||||
rt, err := BuildRuntime(RuntimeDeps{}, RuntimeInputs{}, AgentSpec{
|
||||
ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.NoError(t, rt.Close())
|
||||
assert.NoError(t, rt.Close(), "second Close must also be a no-op")
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// hookFixture builds a Runtime wired to a mock LLM that emits the given
|
||||
// canned event stream. Returns the Runtime and the session so tests can
|
||||
// assert on session entries.
|
||||
func hookFixture(t *testing.T, hooks LifecycleHooks, events []llm.ChatEvent, reg *tool.Registry) *Runtime {
|
||||
t.Helper()
|
||||
if reg == nil {
|
||||
reg = tool.NewRegistry()
|
||||
}
|
||||
return &Runtime{
|
||||
LLM: &mockLLMProvider{events: events},
|
||||
Tools: reg,
|
||||
Session: session.NewSession("test-agent", "test-key"),
|
||||
Model: "mock-model",
|
||||
Workspace: t.TempDir(),
|
||||
MaxTurns: 3,
|
||||
AgentLoop: LoopConfig{Hooks: hooks},
|
||||
}
|
||||
}
|
||||
|
||||
// drainEvents consumes the channel and returns any error events seen.
|
||||
func drainEvents(t *testing.T, events <-chan AgentEvent) {
|
||||
t.Helper()
|
||||
for e := range events {
|
||||
if e.Type == EventError {
|
||||
t.Fatalf("unexpected error: %v", e.Error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHook_OnSessionStart_FiresOnce(t *testing.T) {
|
||||
var fires int32
|
||||
var sawSession *session.Session
|
||||
hooks := LifecycleHooks{
|
||||
OnSessionStart: func(_ context.Context, s *session.Session) {
|
||||
atomic.AddInt32(&fires, 1)
|
||||
sawSession = s
|
||||
},
|
||||
}
|
||||
rt := hookFixture(t, hooks, []llm.ChatEvent{
|
||||
{Type: llm.EventTextDelta, Text: "hi"},
|
||||
{Type: llm.EventDone},
|
||||
}, nil)
|
||||
|
||||
events, err := rt.Run(context.Background(), "ping", nil)
|
||||
require.NoError(t, err)
|
||||
drainEvents(t, events)
|
||||
|
||||
assert.Equal(t, int32(1), atomic.LoadInt32(&fires))
|
||||
assert.Same(t, rt.Session, sawSession, "hook receives the runtime's own session")
|
||||
}
|
||||
|
||||
func TestHook_OnUserPromptSubmit_RewritesPrompt(t *testing.T) {
|
||||
hooks := LifecycleHooks{
|
||||
OnUserPromptSubmit: func(_ context.Context, prompt string, imgs []llm.ImageContent) (string, []llm.ImageContent, error) {
|
||||
return "REWRITTEN: " + prompt, imgs, nil
|
||||
},
|
||||
}
|
||||
rt := hookFixture(t, hooks, []llm.ChatEvent{
|
||||
{Type: llm.EventTextDelta, Text: "ok"},
|
||||
{Type: llm.EventDone},
|
||||
}, nil)
|
||||
|
||||
events, err := rt.Run(context.Background(), "original", nil)
|
||||
require.NoError(t, err)
|
||||
drainEvents(t, events)
|
||||
|
||||
// First session entry is the user message — assert the rewritten one
|
||||
// landed there.
|
||||
view := rt.Session.View()
|
||||
require.NotEmpty(t, view)
|
||||
first := view[0]
|
||||
require.Equal(t, session.EntryTypeMessage, first.Type)
|
||||
require.Equal(t, "user", first.Role)
|
||||
var md session.MessageData
|
||||
require.NoError(t, json.Unmarshal(first.Data, &md))
|
||||
assert.Equal(t, "REWRITTEN: original", md.Text)
|
||||
}
|
||||
|
||||
func TestHook_OnUserPromptSubmit_ErrorAbortsRun(t *testing.T) {
|
||||
hooks := LifecycleHooks{
|
||||
OnUserPromptSubmit: func(_ context.Context, _ string, _ []llm.ImageContent) (string, []llm.ImageContent, error) {
|
||||
return "", nil, errors.New("rejected")
|
||||
},
|
||||
}
|
||||
rt := hookFixture(t, hooks, []llm.ChatEvent{{Type: llm.EventDone}}, nil)
|
||||
|
||||
events, err := rt.Run(context.Background(), "x", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var sawError bool
|
||||
for e := range events {
|
||||
if e.Type == EventError {
|
||||
sawError = true
|
||||
require.Error(t, e.Error)
|
||||
assert.Contains(t, e.Error.Error(), "rejected")
|
||||
}
|
||||
}
|
||||
assert.True(t, sawError, "expected EventError when OnUserPromptSubmit returns err")
|
||||
}
|
||||
|
||||
func TestHook_BeforeToolUse_DenialBlocksExecute(t *testing.T) {
|
||||
var executed int32
|
||||
reg := tool.NewRegistry()
|
||||
reg.Register(&countingTool{name: "noop", executed: &executed})
|
||||
|
||||
callCount := 0
|
||||
llmMock := &statefulMockLLMProvider{
|
||||
responses: [][]llm.ChatEvent{
|
||||
{
|
||||
{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{
|
||||
ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`),
|
||||
}},
|
||||
{Type: llm.EventDone},
|
||||
},
|
||||
{{Type: llm.EventTextDelta, Text: "after"}, {Type: llm.EventDone}},
|
||||
},
|
||||
callCount: &callCount,
|
||||
}
|
||||
|
||||
hooks := LifecycleHooks{
|
||||
BeforeToolUse: func(_ context.Context, name string, _ json.RawMessage) (HookDecision, error) {
|
||||
return HookDecision{Allow: false, Reason: "policy: " + name + " forbidden"}, nil
|
||||
},
|
||||
}
|
||||
rt := &Runtime{
|
||||
LLM: llmMock,
|
||||
Tools: reg,
|
||||
Session: session.NewSession("a", "k"),
|
||||
Model: "m",
|
||||
Workspace: t.TempDir(),
|
||||
MaxTurns: 3,
|
||||
AgentLoop: LoopConfig{Hooks: hooks},
|
||||
}
|
||||
events, err := rt.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
drainEvents(t, events)
|
||||
|
||||
assert.Equal(t, int32(0), atomic.LoadInt32(&executed),
|
||||
"tool Execute must not run when BeforeToolUse denies")
|
||||
|
||||
// Walk the session for the tool_result entry — it should carry the
|
||||
// denial reason.
|
||||
var foundDenial bool
|
||||
for _, e := range rt.Session.View() {
|
||||
if e.Type != session.EntryTypeToolResult {
|
||||
continue
|
||||
}
|
||||
var tr session.ToolResultData
|
||||
require.NoError(t, json.Unmarshal(e.Data, &tr))
|
||||
if tr.Error == "policy: noop forbidden" {
|
||||
foundDenial = true
|
||||
break
|
||||
}
|
||||
}
|
||||
assert.True(t, foundDenial, "denial reason must surface in the tool_result entry")
|
||||
}
|
||||
|
||||
func TestHook_BeforeToolUse_AllowsThroughToPermission(t *testing.T) {
|
||||
var executed int32
|
||||
reg := tool.NewRegistry()
|
||||
reg.Register(&countingTool{name: "noop", executed: &executed})
|
||||
|
||||
callCount := 0
|
||||
llmMock := &statefulMockLLMProvider{
|
||||
responses: [][]llm.ChatEvent{
|
||||
{
|
||||
{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{
|
||||
ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`),
|
||||
}},
|
||||
{Type: llm.EventDone},
|
||||
},
|
||||
{{Type: llm.EventTextDelta, Text: "done"}, {Type: llm.EventDone}},
|
||||
},
|
||||
callCount: &callCount,
|
||||
}
|
||||
|
||||
var permissionConsulted int32
|
||||
perm := &countingPermission{calls: &permissionConsulted}
|
||||
|
||||
hooks := LifecycleHooks{
|
||||
BeforeToolUse: func(_ context.Context, _ string, _ json.RawMessage) (HookDecision, error) {
|
||||
return HookDecision{Allow: true}, nil
|
||||
},
|
||||
}
|
||||
rt := &Runtime{
|
||||
LLM: llmMock,
|
||||
Tools: reg,
|
||||
Session: session.NewSession("a", "k"),
|
||||
Model: "m",
|
||||
Workspace: t.TempDir(),
|
||||
MaxTurns: 3,
|
||||
Permission: perm,
|
||||
AgentLoop: LoopConfig{Hooks: hooks},
|
||||
}
|
||||
|
||||
events, err := rt.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
drainEvents(t, events)
|
||||
|
||||
assert.Equal(t, int32(1), atomic.LoadInt32(&permissionConsulted),
|
||||
"PermissionChecker.Check must still run when BeforeToolUse allows")
|
||||
assert.Equal(t, int32(1), atomic.LoadInt32(&executed),
|
||||
"tool must execute when both BeforeToolUse and PermissionChecker allow")
|
||||
}
|
||||
|
||||
func TestHook_AfterToolUse_ObservesResult(t *testing.T) {
|
||||
reg := tool.NewRegistry()
|
||||
reg.Register(&mockTool{name: "noop", output: "tool-said-this"})
|
||||
|
||||
callCount := 0
|
||||
llmMock := &statefulMockLLMProvider{
|
||||
responses: [][]llm.ChatEvent{
|
||||
{
|
||||
{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{
|
||||
ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`),
|
||||
}},
|
||||
{Type: llm.EventDone},
|
||||
},
|
||||
{{Type: llm.EventTextDelta, Text: "fin"}, {Type: llm.EventDone}},
|
||||
},
|
||||
callCount: &callCount,
|
||||
}
|
||||
|
||||
var capturedName string
|
||||
var capturedOutput string
|
||||
hooks := LifecycleHooks{
|
||||
AfterToolUse: func(_ context.Context, name string, _ json.RawMessage, res tool.ToolResult) {
|
||||
capturedName = name
|
||||
capturedOutput = res.Output
|
||||
},
|
||||
}
|
||||
rt := &Runtime{
|
||||
LLM: llmMock,
|
||||
Tools: reg,
|
||||
Session: session.NewSession("a", "k"),
|
||||
Model: "m",
|
||||
Workspace: t.TempDir(),
|
||||
MaxTurns: 3,
|
||||
AgentLoop: LoopConfig{Hooks: hooks},
|
||||
}
|
||||
|
||||
events, err := rt.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
drainEvents(t, events)
|
||||
|
||||
assert.Equal(t, "noop", capturedName)
|
||||
assert.Equal(t, "tool-said-this", capturedOutput)
|
||||
}
|
||||
|
||||
func TestHook_OnStop_FiresWithCompletedReason(t *testing.T) {
|
||||
var captured string
|
||||
hooks := LifecycleHooks{
|
||||
OnStop: func(_ context.Context, reason string) { captured = reason },
|
||||
}
|
||||
rt := hookFixture(t, hooks, []llm.ChatEvent{
|
||||
{Type: llm.EventTextDelta, Text: "hi"},
|
||||
{Type: llm.EventDone},
|
||||
}, nil)
|
||||
|
||||
events, err := rt.Run(context.Background(), "ping", nil)
|
||||
require.NoError(t, err)
|
||||
drainEvents(t, events)
|
||||
|
||||
assert.Equal(t, "completed", captured)
|
||||
}
|
||||
|
||||
func TestHook_OnStop_FiresWithAbortedReason(t *testing.T) {
|
||||
var captured string
|
||||
hooks := LifecycleHooks{
|
||||
OnStop: func(_ context.Context, reason string) { captured = reason },
|
||||
}
|
||||
// Cancel ctx before Run starts → first turn's ctx.Err() check trips
|
||||
// immediately and we emit Aborted.
|
||||
rt := hookFixture(t, hooks, []llm.ChatEvent{{Type: llm.EventDone}}, nil)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
events, err := rt.Run(ctx, "ping", nil)
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
|
||||
assert.Equal(t, "aborted", captured)
|
||||
}
|
||||
|
||||
func TestHook_NilHooks_NoChange(t *testing.T) {
|
||||
// Sanity: zero LifecycleHooks behaves identically to current behavior.
|
||||
rt := hookFixture(t, LifecycleHooks{}, []llm.ChatEvent{
|
||||
{Type: llm.EventTextDelta, Text: "hello"},
|
||||
{Type: llm.EventDone},
|
||||
}, nil)
|
||||
events, err := rt.Run(context.Background(), "x", nil)
|
||||
require.NoError(t, err)
|
||||
var got string
|
||||
for e := range events {
|
||||
if e.Type == EventTextDelta {
|
||||
got += e.Text
|
||||
}
|
||||
}
|
||||
assert.Equal(t, "hello", got)
|
||||
}
|
||||
|
||||
// --- test fixtures ---
|
||||
|
||||
type countingTool struct {
|
||||
name string
|
||||
executed *int32
|
||||
}
|
||||
|
||||
func (t *countingTool) Name() string { return t.name }
|
||||
func (t *countingTool) Description() string { return "counting" }
|
||||
func (t *countingTool) Parameters() json.RawMessage { return json.RawMessage(`{"type":"object"}`) }
|
||||
func (t *countingTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
|
||||
func (t *countingTool) Execute(_ context.Context, _ json.RawMessage) (tool.ToolResult, error) {
|
||||
atomic.AddInt32(t.executed, 1)
|
||||
return tool.ToolResult{Output: "ok"}, nil
|
||||
}
|
||||
|
||||
type countingPermission struct {
|
||||
calls *int32
|
||||
}
|
||||
|
||||
func (p *countingPermission) Check(_ context.Context, _, _ string, _ json.RawMessage) tool.Decision {
|
||||
atomic.AddInt32(p.calls, 1)
|
||||
return tool.Decision{Behavior: tool.DecisionAllow}
|
||||
}
|
||||
|
||||
func (p *countingPermission) FilterToolDefs(defs []llm.ToolDef, _ string) []llm.ToolDef {
|
||||
return defs
|
||||
}
|
||||
+112
-2
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tokens"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/sausheong/harness/tools/mcp"
|
||||
)
|
||||
|
||||
// EventType identifies the kind of agent event.
|
||||
@@ -112,6 +113,28 @@ type Runtime struct {
|
||||
CalibratorStore *tokens.CalibratorStore
|
||||
|
||||
calibrator *tokens.Calibrator
|
||||
|
||||
// mcpClients holds the MCP client sessions resolved from
|
||||
// AgentSpec.MCPServers. Released by Close. Untouched when MCP is
|
||||
// not used.
|
||||
mcpClients []*mcp.Client
|
||||
}
|
||||
|
||||
// Close releases external resources owned by the Runtime — currently
|
||||
// just the MCP client sessions resolved from AgentSpec.MCPServers.
|
||||
// Optional: callers who never use MCP can skip it. Safe to call
|
||||
// multiple times; safe to call before or after Run completes.
|
||||
// Returns the first Close error encountered, if any; remaining
|
||||
// clients are still closed.
|
||||
func (r *Runtime) Close() error {
|
||||
var firstErr error
|
||||
for _, c := range r.mcpClients {
|
||||
if err := c.Close(); err != nil && firstErr == nil {
|
||||
firstErr = err
|
||||
}
|
||||
}
|
||||
r.mcpClients = nil
|
||||
return firstErr
|
||||
}
|
||||
|
||||
// emit sends ev to this runtime's events channel and forwards a copy to
|
||||
@@ -219,6 +242,28 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
defer close(r.events)
|
||||
defer tr.Summary()
|
||||
|
||||
// stopReason is read by the OnStop deferred hook below. Each early
|
||||
// return path reassigns it before returning. Default is "max_turns"
|
||||
// so the natural fall-through (loop exhausted MaxTurns) records the
|
||||
// right reason without an explicit assignment at that exit.
|
||||
stopReason := "max_turns"
|
||||
if hook := r.AgentLoop.Hooks.OnStop; hook != nil {
|
||||
defer func() { hook(ctx, stopReason) }()
|
||||
}
|
||||
|
||||
// OnUserPromptSubmit may rewrite prompt and/or images BEFORE the
|
||||
// session sees them. Returning err aborts Run with EventError.
|
||||
if hook := r.AgentLoop.Hooks.OnUserPromptSubmit; hook != nil {
|
||||
newMsg, newImgs, err := hook(ctx, userMsg, images)
|
||||
if err != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: err})
|
||||
return
|
||||
}
|
||||
userMsg = newMsg
|
||||
images = newImgs
|
||||
}
|
||||
|
||||
if len(images) > 0 {
|
||||
var imgData []session.ImageData
|
||||
for _, img := range images {
|
||||
@@ -232,6 +277,10 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
r.Session.Append(session.UserMessageEntry(userMsg))
|
||||
}
|
||||
|
||||
if hook := r.AgentLoop.Hooks.OnSessionStart; hook != nil {
|
||||
hook(ctx, r.Session)
|
||||
}
|
||||
|
||||
// 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)
|
||||
@@ -279,6 +328,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
|
||||
for turn := 0; turn < maxTurns; turn++ {
|
||||
if ctx.Err() != nil {
|
||||
stopReason = "aborted"
|
||||
r.emit(AgentEvent{Type: EventAborted})
|
||||
return
|
||||
}
|
||||
@@ -418,6 +468,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
stream, err = r.LLM.ChatStream(ctx, req)
|
||||
}
|
||||
if err != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: fmt.Errorf("llm error: %w", err)})
|
||||
return
|
||||
}
|
||||
@@ -501,6 +552,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
kickoffStopped = false
|
||||
nsStream, retryErr := ns.ChatNonStreaming(ctx, req)
|
||||
if retryErr != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: retryErr})
|
||||
return
|
||||
}
|
||||
@@ -510,6 +562,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
}
|
||||
}
|
||||
drainKickoffs(kickoffs)
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: event.Error})
|
||||
return
|
||||
}
|
||||
@@ -538,6 +591,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
drainKickoffs(kickoffs)
|
||||
}
|
||||
tr.Mark("agent.done", "turn", turn, "reason", "no_tool_calls")
|
||||
stopReason = "completed"
|
||||
r.emit(AgentEvent{Type: EventDone, Usage: lastUsage})
|
||||
r.maybeKickoffAsyncCompaction(msgs, parts, toolDefs)
|
||||
return
|
||||
@@ -584,6 +638,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
r.kgMu.Unlock()
|
||||
}
|
||||
}
|
||||
stopReason = "aborted"
|
||||
r.emit(AgentEvent{Type: EventAborted})
|
||||
return
|
||||
}
|
||||
@@ -606,12 +661,15 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
batches := partitionToolCalls(pending, r.Tools)
|
||||
for _, b := range batches {
|
||||
if r.runBatch(ctx, b, kgThreadOrNil(r.KG, &thread), turn, tr) {
|
||||
stopReason = "aborted"
|
||||
r.emit(AgentEvent{Type: EventAborted})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stopReason already "max_turns" by default — fall through to
|
||||
// the EventError below records "agent exceeded maximum turns".
|
||||
r.emit(AgentEvent{
|
||||
Type: EventError,
|
||||
Error: fmt.Errorf("agent exceeded maximum turns (%d)", maxTurns),
|
||||
@@ -660,9 +718,33 @@ func (r *Runtime) dispatchTool(
|
||||
r.kgMu.Unlock()
|
||||
}
|
||||
|
||||
// BeforeToolUse fires before the PermissionChecker. A hook denial
|
||||
// has the same observable shape as a Permission.Check denial.
|
||||
if hook := r.AgentLoop.Hooks.BeforeToolUse; hook != nil {
|
||||
d, err := hook(ctx, tc.Name, tc.Input)
|
||||
if err != nil {
|
||||
res := r.appendDenialResult(tc.ID, err.Error(), kgThread)
|
||||
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
|
||||
after(ctx, tc.Name, tc.Input, res)
|
||||
}
|
||||
return res, false
|
||||
}
|
||||
if !d.Allow {
|
||||
res := r.appendDenialResult(tc.ID, d.Reason, kgThread)
|
||||
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
|
||||
after(ctx, tc.Name, tc.Input, res)
|
||||
}
|
||||
return res, false
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
res := r.appendDenialResult(tc.ID, d.Reason, kgThread)
|
||||
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
|
||||
after(ctx, tc.Name, tc.Input, res)
|
||||
}
|
||||
return res, false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -695,6 +777,10 @@ func (r *Runtime) dispatchTool(
|
||||
r.recordFileTouch(extractPathFromInput(tc.Input))
|
||||
}
|
||||
|
||||
if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil {
|
||||
hook(ctx, tc.Name, tc.Input, result)
|
||||
}
|
||||
|
||||
return result, false
|
||||
}
|
||||
|
||||
@@ -702,9 +788,30 @@ func (r *Runtime) dispatchTool(
|
||||
// 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 hook := r.AgentLoop.Hooks.BeforeToolUse; hook != nil {
|
||||
d, err := hook(ctx, tc.Name, tc.Input)
|
||||
if err != nil {
|
||||
res := tool.ToolResult{Error: err.Error()}
|
||||
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
|
||||
after(ctx, tc.Name, tc.Input, res)
|
||||
}
|
||||
return res, false
|
||||
}
|
||||
if !d.Allow {
|
||||
res := tool.ToolResult{Error: d.Reason}
|
||||
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
|
||||
after(ctx, tc.Name, tc.Input, res)
|
||||
}
|
||||
return res, false
|
||||
}
|
||||
}
|
||||
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
|
||||
res := tool.ToolResult{Error: d.Reason}
|
||||
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
|
||||
after(ctx, tc.Name, tc.Input, res)
|
||||
}
|
||||
return res, false
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
@@ -720,6 +827,9 @@ func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (resu
|
||||
if result.Error == "" && isFileTool(tc.Name) {
|
||||
r.recordFileTouch(extractPathFromInput(tc.Input))
|
||||
}
|
||||
if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil {
|
||||
hook(ctx, tc.Name, tc.Input, result)
|
||||
}
|
||||
return result, false
|
||||
}
|
||||
|
||||
|
||||
+61
-1
@@ -1,6 +1,14 @@
|
||||
package runtime
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/sausheong/harness/tools/mcp"
|
||||
)
|
||||
|
||||
// AgentSpec is the framework's view of an agent. Consumers convert their
|
||||
// own agent-config types into this struct before invoking BuildRuntime.
|
||||
@@ -42,6 +50,11 @@ type AgentSpec struct {
|
||||
// cap, depth cap, streaming-tools toggle). Zero value ⇒ env-var
|
||||
// fallback then compiled-in defaults.
|
||||
Loop LoopConfig
|
||||
// MCPServers, when non-empty, are connected by BuildRuntime: each
|
||||
// server's tools are namespaced ("mcp__<Name>__<tool>") and added
|
||||
// to the agent's tool registry. Runtime.Close releases the
|
||||
// underlying sessions. Connection failures abort BuildRuntime.
|
||||
MCPServers []mcp.ServerConfig
|
||||
}
|
||||
|
||||
// LoopConfig tunes the agent runtime's tool-execution behavior. Each
|
||||
@@ -58,6 +71,53 @@ type LoopConfig struct {
|
||||
// StreamingTools enables mid-stream concurrency-safe tool kickoff.
|
||||
// false ⇒ env fallback (HARNESS_STREAMING_TOOLS=1) then off.
|
||||
StreamingTools bool
|
||||
// Hooks are optional callbacks the runtime fires at well-known
|
||||
// points in the loop. Zero value (all nil fields) disables every
|
||||
// hook with no overhead.
|
||||
Hooks LifecycleHooks
|
||||
}
|
||||
|
||||
// HookDecision is the outcome of a BeforeToolUse hook. Mirrors
|
||||
// tool.Decision so callers familiar with PermissionChecker get a
|
||||
// consistent shape: Allow=true permits the call to continue (still
|
||||
// subject to PermissionChecker); Allow=false denies it with Reason
|
||||
// surfaced as the tool result error.
|
||||
type HookDecision struct {
|
||||
Allow bool
|
||||
Reason string
|
||||
}
|
||||
|
||||
// LifecycleHooks bundles optional callbacks the runtime fires at
|
||||
// well-known points. All fields are nil-safe — leave a field nil and
|
||||
// that hook is skipped. Hooks run synchronously on the runtime
|
||||
// goroutine; expensive work should be deferred by the implementation.
|
||||
type LifecycleHooks struct {
|
||||
// OnUserPromptSubmit fires once at the top of Run, BEFORE the
|
||||
// user message is appended to the session. The hook may rewrite
|
||||
// the prompt and/or images; the rewritten values are what the
|
||||
// session and the LLM see. Returning err != nil aborts Run with
|
||||
// EventError.
|
||||
OnUserPromptSubmit func(ctx context.Context, prompt string, images []llm.ImageContent) (string, []llm.ImageContent, error)
|
||||
|
||||
// OnSessionStart fires once at the top of Run, AFTER the user
|
||||
// message is appended to the session. Observe-only.
|
||||
OnSessionStart func(ctx context.Context, sess *session.Session)
|
||||
|
||||
// BeforeToolUse fires inside dispatchTool / executeToolKickoff
|
||||
// BEFORE PermissionChecker. Returning Allow=false denies the call
|
||||
// with the given Reason (same shape as a PermissionChecker
|
||||
// denial). Returning err != nil treats the call as a denial with
|
||||
// err.Error() as the reason. nil → no-op (call proceeds).
|
||||
BeforeToolUse func(ctx context.Context, toolName string, input json.RawMessage) (HookDecision, error)
|
||||
|
||||
// AfterToolUse fires after the tool's Execute returns (including
|
||||
// on error or denial). Observe-only — no result rewrite.
|
||||
AfterToolUse func(ctx context.Context, toolName string, input json.RawMessage, result tool.ToolResult)
|
||||
|
||||
// OnStop fires exactly once at the end of Run, regardless of
|
||||
// outcome. reason is one of: "completed", "max_turns", "error",
|
||||
// "aborted". Observe-only.
|
||||
OnStop func(ctx context.Context, reason string)
|
||||
}
|
||||
|
||||
// SkillProvider lets the runtime advertise the available skills in the
|
||||
|
||||
Reference in new issue
Block a user