From 6aa61a54e1e3a3793957786adea2f8f2c5d67803 Mon Sep 17 00:00:00 2001 From: Andrew Fribush <9288738+AndrewFribush@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:16:29 -0600 Subject: [PATCH] shelley/loop: report a tool panic as that call's error executeToolCall runs each tool on its own goroutine with no recover, so a panic in any tool, including an MCP wrapper or a tool someone adds later, ends the server process and every conversation running in it, not just the turn that hit the bug. Recover on that goroutine, log where it panicked, and send the panic back as the call's error. The model sees "tool NAME panicked (TYPE)", the rest of the batch runs, and the bug stays loud in the logs. A panic unwinds past the tool's secret redaction, so the result and the log carry the panic's type and call sites (function, file and line) but never its value or debug.Stack's raw frame arguments. Panics on goroutines a tool starts itself are not covered; those are the tool's to handle. The new test runs a batch of a tool that indexes past a nil slice and a tool that succeeds, then a tool that panics with a string. Against the old code the first panic ends the test binary. --- loop/loop_test.go | 54 +++++++++++++++++++++++++++++++++++++++++++++++ loop/run.go | 23 +++++++++++++++++++- 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/loop/loop_test.go b/loop/loop_test.go index 1cc4c70c1..240f26221 100644 --- a/loop/loop_test.go +++ b/loop/loop_test.go @@ -2947,6 +2947,60 @@ func TestExecuteToolCallsCancelActiveSuccessWins(t *testing.T) { } } +// TestExecuteToolCallsRecoversToolPanic verifies that a panicking tool +// becomes an error result for that call and the rest of the batch still +// runs, instead of the panic ending the process. +func TestExecuteToolCallsRecoversToolPanic(t *testing.T) { + t.Parallel() + var recorded []llm.Message + recordFunc := func(ctx context.Context, message llm.Message, _ string, usage llm.Usage, otherUsage []llm.PurposedUsage) error { + recorded = append(recorded, message) + return nil + } + schema := llm.MustSchema(`{"type": "object", "properties": {}}`) + panics := &llm.Tool{Name: "panics", InputSchema: schema, Run: func(context.Context, json.RawMessage) llm.ToolOut { + var lines []string + return llm.ToolOut{LLMContent: llm.TextContent(lines[3])} + }} + works := &llm.Tool{Name: "works", InputSchema: schema, Run: func(context.Context, json.RawMessage) llm.ToolOut { + return llm.ToolOut{LLMContent: llm.TextContent("ok")} + }} + loop := NewLoop(Config{LLM: predictable.NewService(), Tools: []*llm.Tool{panics, works}, RecordMessage: recordFunc}) + + content := []llm.Content{ + {ID: "tc_1", Type: llm.ContentTypeToolUse, ToolName: "panics", ToolInput: json.RawMessage(`{}`)}, + {ID: "tc_2", Type: llm.ContentTypeToolUse, ToolName: "works", ToolInput: json.RawMessage(`{}`)}, + } + if err := loop.executeToolCalls(t.Context(), content); err != nil { + t.Fatalf("executeToolCalls: %v", err) + } + if len(recorded) != 1 || len(recorded[0].Content) != 2 { + t.Fatalf("expected one message with two results, got %+v", recorded) + } + r1, r2 := recorded[0].Content[0], recorded[0].Content[1] + if !r1.ToolError || r1.ToolResult[0].Text != "tool panics panicked (runtime.boundsError); the stack is in the server log" { + t.Errorf("panicking tool result wrong: %+v", r1) + } + if r2.ToolError || r2.ToolResult[0].Text != "ok" { + t.Errorf("later tool in the batch should still run: %+v", r2) + } + + // The panic value never passed through the tool's secret redaction, so + // only its type may reach the transcript. + leaks := &llm.Tool{Name: "leaks", InputSchema: schema, Run: func(context.Context, json.RawMessage) llm.ToolOut { + panic("token=hunter2") + }} + recorded = nil + loop = NewLoop(Config{LLM: predictable.NewService(), Tools: []*llm.Tool{leaks}, RecordMessage: recordFunc}) + call := []llm.Content{{ID: "tc_3", Type: llm.ContentTypeToolUse, ToolName: "leaks", ToolInput: json.RawMessage(`{}`)}} + if err := loop.executeToolCalls(t.Context(), call); err != nil { + t.Fatalf("executeToolCalls: %v", err) + } + if got := recorded[0].Content[0].ToolResult[0].Text; got != "tool leaks panicked (string); the stack is in the server log" { + t.Errorf("panic value reached the result: %q", got) + } +} + // TestExecuteToolCallsAbandonsContextIgnoringTool verifies that a cancelled // tool which ignores its context cannot persist a late result. The loop waits // toolCancelGrace, records an abandoned-tool result, and drops whatever the diff --git a/loop/run.go b/loop/run.go index 9bde837dd..c11b70bb0 100644 --- a/loop/run.go +++ b/loop/run.go @@ -8,6 +8,7 @@ import ( "fmt" "log/slog" "path/filepath" + "runtime" "slices" "strings" "time" @@ -869,7 +870,27 @@ func (l *RunConfig) executeToolCall(ctx context.Context, call llm.Content, tool startTime := time.Now() resultCh := make(chan llm.ToolOut, 1) - go func() { resultCh <- tool.Run(toolCtx, call.ToolInput) }() + go func() { + // A panic on this goroutine would end the process and every + // conversation in it; report it as this call's error instead. The + // panic skipped the tool's secret redaction, so only its type and + // call sites are passed on, never its value or frame arguments. + defer func() { + if r := recover(); r != nil { + var stack strings.Builder + pcs := make([]uintptr, 64) + frames := runtime.CallersFrames(pcs[:runtime.Callers(1, pcs)]) + for more := true; more; { + var f runtime.Frame + f, more = frames.Next() + fmt.Fprintf(&stack, "%s\n\t%s:%d\n", f.Function, f.File, f.Line) + } + l.Logger.Error("tool panicked", "name", call.ToolName, "id", call.ID, "type", fmt.Sprintf("%T", r), "stack", stack.String()) + resultCh <- llm.ToolOut{Error: fmt.Errorf("tool %s panicked (%T); the stack is in the server log", call.ToolName, r)} + } + }() + resultCh <- tool.Run(toolCtx, call.ToolInput) + }() var result llm.ToolOut abandoned := false