Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agent): fail a Pi task when Pi ends the turn on an error without retrying (#7059)
adai4383497898a3
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.goindex 3943e3ecda..59cc7c827b 100644--- a/server/pkg/agent/pi.go+++ b/server/pkg/agent/pi.go@@ -297,6 +297,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptionsvar output strings.BuilderfinalStatus := "completed"var finalError string+ var lastTurnError stringusage := make(map[string]TokenUsage)// Pi message_update events can be large (they embed the full message@@ -321,6 +322,7 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptionscase "turn_start":output.Reset()textBuffer.Reset()+ lastTurnError = ""case "message_update":if evt.AssistantMessageEvent == nil {@@ -358,7 +360,11 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions})case "turn_end":- if msg := decodePiMessage(evt.Message); msg != nil && msg.Usage != nil {+ msg := decodePiMessage(evt.Message)+ if msg == nil {+ continue+ }+ if msg.Usage != nil {model := msg.Modelif model == "" {model = opts.Model@@ -373,6 +379,16 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptionsu.CacheWriteTokens += msg.Usage.CacheWriteusage[model] = u}+ // A turn Pi ends on an error is only terminal when nothing+ // follows it. Pi emits the same stopReason before an automatic+ // retry, and turn_start clears this, so a later successful turn+ // leaves nothing behind.+ if msg.StopReason == "error" {+ lastTurnError = msg.ErrorMessage+ if lastTurnError == "" {+ lastTurnError = label + " ended the turn with an error"+ }+ }case "error":errText := decodePiString(evt.Message)@@ -417,6 +433,12 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions} else if writeErr != nil && finalStatus == "completed" {finalStatus = "failed"finalError = fmt.Sprintf("%s prompt write failed: %v", label, writeErr)+ } else if lastTurnError != "" && finalStatus == "completed" {+ // Pi exits 0 after a turn it could not complete and did not retry,+ // and emits neither an `error` event nor `auto_retry_end`. Without+ // this the run reports success with no output.+ finalStatus = "failed"+ finalError = lastTurnError}b.cfg.Logger.Info(label+" finished", "pid", cmd.Process.Pid, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())@@ -470,6 +492,12 @@ type piMessage struct {Role string `json:"role,omitempty"`Model string `json:"model,omitempty"`Usage *piUsage `json:"usage,omitempty"`++ // turn_end carries the terminal state of the turn. Pi sets StopReason to+ // "error" for a provider call it could not complete, whether or not it+ // goes on to retry, and puts the provider's message in ErrorMessage.+ StopReason string `json:"stopReason,omitempty"`+ ErrorMessage string `json:"errorMessage,omitempty"`}type piUsage struct {diff --git a/server/pkg/agent/pi_test.go b/server/pkg/agent/pi_test.goindex fc1948d41a..82fc6931be 100644--- a/server/pkg/agent/pi_test.go+++ b/server/pkg/agent/pi_test.go@@ -298,6 +298,104 @@ func TestPiExecuteRetainsOnlyLastTurnOutput(t *testing.T) {}}+func TestPiExecuteFailsOnUnretriedTurnError(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ // Pi ends the turn with stopReason=error and declines to retry (401, 429+ // and friends). It emits no `error` event and no auto_retry_end, and exits+ // 0, so the terminal state lives only on turn_end.+ events := []string{+ `{"type":"agent_start"}`,+ `{"type":"turn_start"}`,+ `{"type":"turn_end","message":{"role":"assistant","content":[],"model":"test","usage":{"input":0,"output":0},"stopReason":"error","errorMessage":"OpenAI API error (401): invalid token"}}`,+ `{"type":"agent_end","messages":[],"willRetry":false}`,+ }+ fakePath := filepath.Join(t.TempDir(), "pi")+ writeTestExecutable(t, fakePath, []byte(piEventStreamScript(events)))++ backend, err := New("pi", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new pi backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Timeout: 5 * time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result := <-session.Result:+ if result.Status != "failed" {+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "invalid token") {+ t.Fatalf("Error: got %q, want it to carry the provider message", result.Error)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }+}++func TestPiExecuteSucceedsWhenRetryFollowsTurnError(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ // The same stopReason=error precedes an automatic retry. The retry+ // succeeds, so the run must not inherit the first turn's failure.+ events := []string{+ `{"type":"agent_start"}`,+ `{"type":"turn_start"}`,+ `{"type":"turn_end","message":{"role":"assistant","content":[],"model":"test","usage":{"input":0,"output":0},"stopReason":"error","errorMessage":"OpenAI API error (503): no available channel"}}`,+ `{"type":"agent_end","messages":[],"willRetry":true}`,+ `{"type":"auto_retry_start","attempt":1,"maxAttempts":3,"delayMs":1}`,+ `{"type":"agent_start"}`,+ `{"type":"turn_start"}`,+ `{"type":"message_update","assistantMessageEvent":{"type":"text_delta","delta":"recovered"}}`,+ `{"type":"turn_end","message":{"role":"assistant","model":"test","usage":{"input":2,"output":2}}}`,+ }+ fakePath := filepath.Join(t.TempDir(), "pi")+ writeTestExecutable(t, fakePath, []byte(piEventStreamScript(events)))++ backend, err := New("pi", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("new pi backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Timeout: 5 * time.Second})+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ select {+ case result := <-session.Result:+ if result.Status != "completed" {+ t.Fatalf("expected status=completed, got %q (error=%q)", result.Status, result.Error)+ }+ if result.Output != "recovered" {+ t.Fatalf("Output: got %q, want %q", result.Output, "recovered")+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for result")+ }+}+func TestStripPiToolCallMarkup(t *testing.T) {tests := map[string]string{`before call:bash{command:<|"|>cd repo/path && ls -F<|"|>}<tool_call|> after`: "before after",