fix: harden runtime against panics/races, close path-traversal and fail-open gaps

- Runtime.Run rejects concurrent invocations instead of racing on shared state; panics in tools, hooks, and permission checkers are recovered and surfaced as errors/denials instead of crashing the loop
- AgentSpec.Loop now actually overrides RuntimeDeps.AgentLoop per-agent, as documented
- session.Store validates agent ID / session key as single path components, preventing traversal outside the session directory
- ValidatePathInWorkDir resolves symlinks on the target itself, not just its parent, closing a workspace-escape gap
- bash tool now fails closed on an unrecognized ExecPolicy.Level instead of allowing everything
- browser tool rejects unknown actions instead of silently no-op'ing

Bump README to v0.3.4 and document the AgentSpec.Loop override semantics.
This commit is contained in:
sausheong committed 2026-08-02 10:14:20 +08:00
1 parent 445614757b
commit eb4fa67976
15 files changed
+421 -37

No files matched your search

+39 -1
View File
@@ -166,6 +166,8 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
}
}
loop := mergeLoopConfig(deps.AgentLoop, spec.Loop)
rt := &Runtime{
LLM: inputs.Provider,
Tools: inputs.Tools,
@@ -186,7 +188,7 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
Permission: deps.Permission,
Compaction: inputs.Compaction,
IngestSource: inputs.IngestSource,
AgentLoop: deps.AgentLoop,
AgentLoop: loop,
StaticSystemPrompt: staticPrompt,
CalibratorStore: deps.CalibratorStore,
mcpClients: mcpClients,
@@ -206,3 +208,39 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
return rt, nil
}
// mergeLoopConfig applies the per-agent non-zero settings over the shared
// defaults. LoopConfig intentionally uses zero values as "inherit/default",
// so this preserves existing RuntimeDeps.AgentLoop behavior while making the
// documented AgentSpec.Loop override effective.
func mergeLoopConfig(base, override LoopConfig) LoopConfig {
out := base
if override.MaxToolConcurrency > 0 {
out.MaxToolConcurrency = override.MaxToolConcurrency
}
if override.MaxAgentDepth > 0 {
out.MaxAgentDepth = override.MaxAgentDepth
}
if override.StreamingTools {
out.StreamingTools = true
}
if override.MaxToolResultLen > 0 {
out.MaxToolResultLen = override.MaxToolResultLen
}
if override.Hooks.OnUserPromptSubmit != nil {
out.Hooks.OnUserPromptSubmit = override.Hooks.OnUserPromptSubmit
}
if override.Hooks.OnSessionStart != nil {
out.Hooks.OnSessionStart = override.Hooks.OnSessionStart
}
if override.Hooks.BeforeToolUse != nil {
out.Hooks.BeforeToolUse = override.Hooks.BeforeToolUse
}
if override.Hooks.AfterToolUse != nil {
out.Hooks.AfterToolUse = override.Hooks.AfterToolUse
}
if override.Hooks.OnStop != nil {
out.Hooks.OnStop = override.Hooks.OnStop
}
return out
}
+34
View File
@@ -1,6 +1,7 @@
package runtime
import (
"context"
"testing"
"github.com/sausheong/harness/tool"
@@ -38,6 +39,39 @@ func TestBuildRuntimeMinimalSpecSafe(t *testing.T) {
require.NotEmpty(t, rt.StaticSystemPrompt)
}
func TestBuildRuntimeMergesSpecLoopOverSharedDefaults(t *testing.T) {
baseCalled := false
specCalled := false
baseStop := func(context.Context, string) { baseCalled = true }
specStop := func(context.Context, string) { specCalled = true }
rt, err := BuildRuntime(
RuntimeDeps{AgentLoop: LoopConfig{
MaxToolConcurrency: 3,
MaxAgentDepth: 2,
MaxToolResultLen: 8000,
Hooks: LifecycleHooks{OnStop: baseStop},
}},
RuntimeInputs{},
AgentSpec{
ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5",
Loop: LoopConfig{
MaxToolConcurrency: 7,
StreamingTools: true,
Hooks: LifecycleHooks{OnStop: specStop},
},
},
)
require.NoError(t, err)
assert.Equal(t, 7, rt.AgentLoop.MaxToolConcurrency)
assert.Equal(t, 2, rt.AgentLoop.MaxAgentDepth, "zero spec fields inherit shared defaults")
assert.Equal(t, 8000, rt.AgentLoop.MaxToolResultLen)
assert.True(t, rt.AgentLoop.StreamingTools)
require.NotNil(t, rt.AgentLoop.Hooks.OnStop)
rt.AgentLoop.Hooks.OnStop(context.Background(), "completed")
assert.False(t, baseCalled)
assert.True(t, specCalled)
}
func TestBuildRuntimeUsesCallerProvidedMemoryFiles(t *testing.T) {
// Caller composes memoryFiles however they want — typical patterns
// include walking AGENTS.md from workspace + $HOME, building from a
+35 -18
View File
@@ -132,6 +132,11 @@ type Runtime struct {
// AgentSpec.MCPServers. Released by Close. Untouched when MCP is
// not used.
mcpClients []*mcp.Client
// runMu enforces the Runtime contract that one session exchange runs at a
// time. TryLock lets a second caller receive a normal error instead of
// corrupting the shared event channel and run-scoped state.
runMu sync.Mutex
}
// Close releases external resources owned by the Runtime — currently
@@ -272,12 +277,17 @@ func isFileTool(name string) bool {
// Run executes the agent loop for a user message, returning a channel of events.
func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageContent) (<-chan AgentEvent, error) {
r.events = make(chan AgentEvent, 100)
if !r.runMu.TryLock() {
return nil, fmt.Errorf("runtime is already running")
}
events := make(chan AgentEvent, 100)
r.events = events
tr := TraceFrom(ctx)
tr.Mark("agent.run.start", "user_msg_len", len(userMsg), "images", len(images))
go func() {
defer close(r.events)
defer close(events)
defer r.runMu.Unlock()
defer tr.Summary()
// Flush the per-session calibrator once at Run end (all exit paths:
@@ -298,8 +308,15 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
// 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) }()
defer func() { callOnStopHook(ctx, hook, stopReason) }()
}
defer func() {
if recovered := recover(); recovered != nil {
stopReason = "error"
err := recoveredPanicError("runtime", recovered)
r.emit(AgentEvent{Type: EventError, Error: err})
}
}()
// OnUserPromptSubmit may rewrite prompt and/or images BEFORE the
// session sees them. Returning err aborts Run with EventError.
@@ -812,7 +829,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
})
}()
return r.events, nil
return events, nil
}
// recoverFromPreTokenError attempts the same recovery the synchronous
@@ -895,28 +912,28 @@ func (r *Runtime) dispatchTool(
// 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)
d, err := callBeforeToolHook(ctx, hook, 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)
callAfterToolHook(ctx, after, 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)
callAfterToolHook(ctx, after, 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 {
if d := callPermissionCheck(ctx, r.Permission, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
res := r.appendDenialResult(tc.ID, d.Reason, kgThread)
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res)
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
}
return res, false
}
@@ -926,7 +943,7 @@ func (r *Runtime) dispatchTool(
return r.appendAbortedResult(tc.ID, kgThread), true
}
result, err := r.Tools.Execute(ctx, tc.Name, tc.Input)
result, err := callToolExecute(ctx, r.Tools, tc.Name, tc.Input)
if err != nil {
result = tool.ToolResult{Error: err.Error()}
}
@@ -952,7 +969,7 @@ func (r *Runtime) dispatchTool(
}
if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil {
hook(ctx, tc.Name, tc.Input, result)
callAfterToolHook(ctx, hook, tc.Name, tc.Input, result)
}
return result, false
@@ -963,27 +980,27 @@ func (r *Runtime) dispatchTool(
// 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)
d, err := callBeforeToolHook(ctx, hook, 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)
callAfterToolHook(ctx, after, 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)
callAfterToolHook(ctx, after, 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 {
if d := callPermissionCheck(ctx, r.Permission, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
res := tool.ToolResult{Error: d.Reason}
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res)
callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
}
return res, false
}
@@ -991,7 +1008,7 @@ func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (resu
if ctx.Err() != nil {
return tool.ToolResult{Error: "aborted by user"}, true
}
result, err := r.Tools.Execute(ctx, tc.Name, tc.Input)
result, err := callToolExecute(ctx, r.Tools, tc.Name, tc.Input)
if err != nil {
result = tool.ToolResult{Error: err.Error()}
}
@@ -1002,7 +1019,7 @@ func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (resu
r.recordFileTouch(extractPathFromInput(tc.Input))
}
if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil {
hook(ctx, tc.Name, tc.Input, result)
callAfterToolHook(ctx, hook, tc.Name, tc.Input, result)
}
return result, false
}
+62
View File
@@ -0,0 +1,62 @@
package runtime
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"runtime/debug"
"github.com/sausheong/harness/tool"
)
func recoveredPanicError(component string, recovered any) error {
err := fmt.Errorf("%s panicked: %v", component, recovered)
slog.Error("recovered extension panic", "component", component, "error", err, "stack", string(debug.Stack()))
return err
}
func callToolExecute(ctx context.Context, ex tool.Executor, name string, input json.RawMessage) (result tool.ToolResult, err error) {
defer func() {
if recovered := recover(); recovered != nil {
err = recoveredPanicError("tool "+name, recovered)
}
}()
return ex.Execute(ctx, name, input)
}
func callBeforeToolHook(ctx context.Context, hook func(context.Context, string, json.RawMessage) (HookDecision, error), name string, input json.RawMessage) (decision HookDecision, err error) {
defer func() {
if recovered := recover(); recovered != nil {
err = recoveredPanicError("BeforeToolUse hook", recovered)
}
}()
return hook(ctx, name, input)
}
func callAfterToolHook(ctx context.Context, hook func(context.Context, string, json.RawMessage, tool.ToolResult), name string, input json.RawMessage, result tool.ToolResult) {
defer func() {
if recovered := recover(); recovered != nil {
_ = recoveredPanicError("AfterToolUse hook", recovered)
}
}()
hook(ctx, name, input, result)
}
func callOnStopHook(ctx context.Context, hook func(context.Context, string), reason string) {
defer func() {
if recovered := recover(); recovered != nil {
_ = recoveredPanicError("OnStop hook", recovered)
}
}()
hook(ctx, reason)
}
func callPermissionCheck(ctx context.Context, checker tool.PermissionChecker, agentID, name string, input json.RawMessage) (decision tool.Decision) {
defer func() {
if recovered := recover(); recovered != nil {
decision = tool.Decision{Behavior: tool.DecisionDeny, Reason: recoveredPanicError("permission checker", recovered).Error()}
}
}()
return checker.Check(ctx, agentID, name, input)
}
+111
View File
@@ -0,0 +1,111 @@
package runtime
import (
"context"
"encoding/json"
"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"
)
type panickingTool struct{}
func (*panickingTool) Name() string { return "panic_tool" }
func (*panickingTool) Description() string { return "panics for testing" }
func (*panickingTool) Parameters() json.RawMessage { return json.RawMessage(`{"type":"object"}`) }
func (*panickingTool) IsConcurrencySafe(json.RawMessage) bool { return false }
func (*panickingTool) Execute(context.Context, json.RawMessage) (tool.ToolResult, error) {
panic("boom")
}
type panickingPermission struct{}
func (panickingPermission) Check(context.Context, string, string, json.RawMessage) tool.Decision {
panic("permission boom")
}
func (panickingPermission) FilterToolDefs(defs []llm.ToolDef, _ string) []llm.ToolDef {
return defs
}
func TestDispatchToolRecoversExecutePanicAndPreservesPairing(t *testing.T) {
reg := tool.NewRegistry()
reg.Register(&panickingTool{})
rt := &Runtime{Tools: reg, Session: session.NewSession("agent", "key")}
result, aborted := rt.dispatchTool(context.Background(), llm.ToolCall{
ID: "call-1", Name: "panic_tool", Input: json.RawMessage(`{}`),
}, nil)
assert.False(t, aborted)
assert.Contains(t, result.Error, "tool panic_tool panicked: boom")
entries := rt.Session.Entries()
require.Len(t, entries, 2)
assert.Equal(t, session.EntryTypeToolCall, entries[0].Type)
assert.Equal(t, session.EntryTypeToolResult, entries[1].Type)
}
func TestDispatchToolFailsClosedWhenPermissionPanics(t *testing.T) {
reg := tool.NewRegistry()
reg.Register(&mockTool{name: "safe", output: "must not execute"})
rt := &Runtime{
Tools: reg, Session: session.NewSession("agent", "key"),
Permission: panickingPermission{},
}
result, aborted := rt.dispatchTool(context.Background(), llm.ToolCall{
ID: "call-1", Name: "safe", Input: json.RawMessage(`{}`),
}, nil)
assert.False(t, aborted)
assert.Contains(t, result.Error, "permission checker panicked")
assert.NotContains(t, result.Output, "must not execute")
require.Len(t, rt.Session.Entries(), 2)
}
func TestRunRecoversHookPanicAsEventError(t *testing.T) {
rt := hookFixture(t, LifecycleHooks{
OnUserPromptSubmit: func(context.Context, string, []llm.ImageContent) (string, []llm.ImageContent, error) {
panic("hook boom")
},
}, nil, nil)
events, err := rt.Run(context.Background(), "hello", nil)
require.NoError(t, err)
var got error
for event := range events {
if event.Type == EventError {
got = event.Error
}
}
require.Error(t, got)
assert.Contains(t, got.Error(), "runtime panicked: hook boom")
}
func TestRunRejectsConcurrentCall(t *testing.T) {
started := make(chan struct{})
provider := &llmtest.Stub{Text: "done", Delay: 50 * time.Millisecond, Started: started}
rt := &Runtime{
LLM: provider, Tools: tool.NewRegistry(),
Session: session.NewSession("agent", "key"), Model: "mock", MaxTurns: 1,
}
first, err := rt.Run(context.Background(), "first", nil)
require.NoError(t, err)
<-started
second, err := rt.Run(context.Background(), "second", nil)
require.ErrorContains(t, err, "already running")
assert.Nil(t, second)
for range first {
}
third, err := rt.Run(context.Background(), "third", nil)
require.NoError(t, err, "runtime must become available after the first run ends")
for range third {
}
}
+4 -3
View File
@@ -46,9 +46,10 @@ type AgentSpec struct {
// 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 controls the runtime's per-agent tool-execution behavior
// (concurrency cap, depth cap, streaming-tools toggle). Non-zero fields
// and non-nil hooks override RuntimeDeps.AgentLoop; remaining zero values
// inherit the shared setting, then its env/default fallback.
Loop LoopConfig
// MCPServers, when non-empty, are connected by BuildRuntime: each
// server's tools are namespaced ("mcp__<Name>__<tool>") and added