Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7855 fix(pi): fail a run whose agent_end reports an error (#9028)
Ray Walkera5b2c361a9d0
diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.goindex 155a6324dc..2ec0e0a319 100644--- a/server/pkg/agent/pi.go+++ b/server/pkg/agent/pi.go@@ -613,6 +613,23 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptionsturnErrors.clear()}+ case "agent_end":+ // agent_end closes the run, and its last assistant message holds+ // the run's terminal state. Pi 0.74.0 and earlier report a+ // failure raised outside a model stream, such as an API key they+ // cannot resolve, only here: no turn_end, no error event, and+ // print mode still exits 0. Record it like a turn_end error, so+ // an automatic retry or a later successful turn still clears it.+ msg := lastPiAssistantMessage(evt.Messages)+ if msg == nil || msg.StopReason != "error" {+ continue+ }+ runError := msg.ErrorMessage+ if runError == "" {+ runError = label + " ended the run with an error"+ }+ turnErrors.record(runError)+case "error":errText := decodePiString(evt.Message)trySend(msgCh, Message{Type: MessageError, Content: errText})@@ -634,6 +651,13 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions}}}+ scanErr := scanner.Err()+ if scanErr != nil {+ // Scanner stopped consuming stdout. Close the pipe before Wait so Pi,+ // still writing an oversized event, cannot deadlock on the full OS+ // pipe; the scanner error remains the primary failure.+ closePiReadPipe(stdout)+ }if d := flushPiTextBuffer(&textBuffer); d != "" {output.WriteString(d)trySend(msgCh, Message{Type: MessageText, Content: d})@@ -682,6 +706,17 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptionsfinalStatus = "failed"finalError = lastTurnErrorauthoritativeTerminal = true+ } else if scanErr != nil && finalStatus == "completed" {+ // The unread rest of the stream may hold the run's terminal state+ // (agent_end repeats every message of the run, so it is the line+ // most likely to overflow), so the run cannot count as a success.+ // Ranked above waitErr: closing stdout is what made Pi exit.+ authoritativeTerminal = true+ finalStatus = "failed"+ finalError = fmt.Sprintf("%s stdout read error: %v", label, scanErr)+ if lastTurnError != "" {+ finalError = lastTurnError + "; " + finalError+ }} else if waitErr != nil && finalStatus == "completed" {authoritativeTerminal = truefinalStatus = "failed"@@ -843,6 +878,9 @@ type piStreamEvent struct {// error: Message is a string. turn_end: Message is an object.Message json.RawMessage `json:"message,omitempty"`+ // agent_end: the messages the agent run produced, oldest first.+ Messages json.RawMessage `json:"messages,omitempty"`+// auto_retry_endSuccess bool `json:"success,omitempty"`FinalError string `json:"finalError,omitempty"`@@ -858,9 +896,10 @@ type piMessage struct {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.+ // turn_end carries the terminal state of the turn, and agent_end's last+ // assistant message that of the run. 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"`}@@ -884,6 +923,22 @@ func decodePiMessage(raw json.RawMessage) *piMessage {return &m}+// lastPiAssistantMessage returns the newest assistant message in agent_end's+// messages, or nil when there is none. Messages are decoded one at a time so+// an unexpected shape elsewhere in the run cannot hide the last one.+func lastPiAssistantMessage(raw json.RawMessage) *piMessage {+ var messages []json.RawMessage+ if err := json.Unmarshal(raw, &messages); err != nil {+ return nil+ }+ for i := len(messages) - 1; i >= 0; i-- {+ if m := decodePiMessage(messages[i]); m != nil && m.Role == "assistant" {+ return m+ }+ }+ return nil+}+func decodePiString(raw json.RawMessage) string {if len(raw) == 0 {return ""diff --git a/server/pkg/agent/pi_test.go b/server/pkg/agent/pi_test.goindex da8a4c80af..ea395c8743 100644--- a/server/pkg/agent/pi_test.go+++ b/server/pkg/agent/pi_test.go@@ -655,13 +655,14 @@ func TestPiExecuteSucceedsWhenRetryFollowsTurnError(t *testing.T) {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.+ // The same stopReason=error precedes an automatic retry, on turn_end and+ // again on agent_end. 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":"agent_end","messages":[{"role":"assistant","content":[],"model":"test","usage":{"input":0,"output":0},"stopReason":"error","errorMessage":"OpenAI API error (503): no available channel"}],"willRetry":true}`,`{"type":"auto_retry_start","attempt":1,"maxAttempts":3,"delayMs":1}`,`{"type":"agent_start"}`,`{"type":"turn_start"}`,@@ -753,6 +754,151 @@ func TestPiExecuteKeepsTurnErrorWhenProcessExitsNonZero(t *testing.T) {}}+// piKeyErrorAgentEnd is the agent_end Pi 0.74.0 emits when the provider's API+// key command fails: one empty assistant message, and nothing else reports it.+const piKeyErrorAgentEnd = `{"type":"agent_end","messages":[{"role":"assistant","content":[{"type":"text","text":""}],"model":"test","usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0,"totalTokens":0},"stopReason":"error","errorMessage":"Failed to resolve API key for provider \"gateway\" from shell command: key-helper"}]}`++func TestPiExecuteFailsOnAgentEndOnlyError(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ // A failure raised before the first model call reaches the stream only on+ // agent_end: no turn_end, no error event, no auto_retry_end, exit 0.+ tests := []struct {+ name string+ agentEnd string+ want string+ }{+ {+ name: "provider message",+ agentEnd: piKeyErrorAgentEnd,+ want: `Failed to resolve API key for provider "gateway" from shell command: key-helper`,+ },+ {+ name: "empty message",+ agentEnd: `{"type":"agent_end","messages":[{"role":"assistant","content":[],"model":"test","stopReason":"error"}]}`,+ want: "pi ended the run with an error",+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ script := piEventStreamScript([]string{+ `{"type":"agent_start"}`,+ `{"type":"turn_start"}`,+ `{"type":"message_start","message":{"role":"user","content":[{"type":"text","text":"prompt"}]}}`,+ `{"type":"message_end","message":{"role":"user","content":[{"type":"text","text":"prompt"}]}}`,+ tt.agentEnd,+ })+ backend := newPiTestBackend(t, script, 0)+ session, err := backend.Execute(context.Background(), "prompt-ignored", ExecOptions{+ Timeout: 5 * time.Second,+ ResumeSessionID: filepath.Join(t.TempDir(), "session.jsonl"),+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ result := waitPiResult(t, session, 10*time.Second)+ if result.Status != "failed" || result.Error != tt.want {+ t.Fatalf("result = {Status:%q Error:%q}, want failed with %q", result.Status, result.Error, tt.want)+ }+ })+ }+}++func TestPiExecuteFailsOnAgentEndErrorAfterToolWork(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ // Pi resolves the API key again for every model request, so a key that+ // stops resolving mid-run fails the next turn after real work. That turn+ // starts and then only agent_end reports the failure.+ script := piEventStreamScript([]string{+ `{"type":"agent_start"}`,+ `{"type":"turn_start"}`,+ `{"type":"message_update","assistantMessageEvent":{"type":"text_delta","delta":"Checking."}}`,+ `{"type":"tool_execution_start","toolCallId":"call_1","toolName":"bash","args":{"command":"echo hi"}}`,+ `{"type":"tool_execution_end","toolCallId":"call_1","toolName":"bash","result":{"content":[{"type":"text","text":"hi"}]},"isError":false}`,+ `{"type":"turn_end","message":{"role":"assistant","content":[],"model":"test","usage":{"input":5,"output":3,"cacheRead":0,"cacheWrite":0,"totalTokens":8},"stopReason":"toolUse"}}`,+ `{"type":"turn_start"}`,+ piKeyErrorAgentEnd,+ })+ backend := newPiTestBackend(t, script, 0)+ session, err := backend.Execute(context.Background(), "prompt-ignored", ExecOptions{+ Timeout: 5 * time.Second,+ ResumeSessionID: filepath.Join(t.TempDir(), "session.jsonl"),+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ result := waitPiResult(t, session, 10*time.Second)+ want := `Failed to resolve API key for provider "gateway" from shell command: key-helper`+ if result.Status != "failed" || result.Error != want {+ t.Fatalf("result = {Status:%q Error:%q}, want failed with %q", result.Status, result.Error, want)+ }+ if got := result.Usage["test"]; got.InputTokens != 5 || got.OutputTokens != 3 {+ t.Fatalf("Usage[test] = %+v, want the completed turn's usage kept", got)+ }+}++func TestPiExecuteFailsOnScannerOverflow(t *testing.T) {+ t.Parallel()+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ // agent_end repeats every message of the run, so on a long run it is the+ // line most likely to outgrow the shared bound. Once the scanner stops, the+ // run's terminal state is unknown and must not read as success. The line is+ // sized from agentStreamMaxLineBytes so raising the cap keeps this test on+ // the overflow branch.+ script := piEventStreamScript([]string{+ `{"type":"agent_start"}`,+ `{"type":"turn_start"}`,+ `{"type":"message_update","assistantMessageEvent":{"type":"text_delta","delta":"done"}}`,+ `{"type":"turn_end","message":{"role":"assistant","model":"test","usage":{"input":1,"output":1}}}`,+ }) + fmt.Sprintf("dd if=/dev/zero bs=1048576 count=%d 2>/dev/null | tr '\\000' x\nprintf '\\n'\n",+ agentStreamMaxLineBytes/(1024*1024)+1)+ backend := newPiTestBackend(t, script, 0)+ // A generous timeout: without the fix this run hangs until it expires, and+ // a loaded host must not turn the fixed run into a timeout either.+ session, err := backend.Execute(context.Background(), "prompt-ignored", ExecOptions{+ Timeout: 30 * time.Second,+ ResumeSessionID: filepath.Join(t.TempDir(), "session.jsonl"),+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ go func() {+ for range session.Messages {+ }+ }()++ result := waitPiResult(t, session, 40*time.Second)+ if result.Status != "failed" {+ t.Fatalf("result = {Status:%q Error:%q}, want failed", result.Status, result.Error)+ }+ for _, want := range []string{"pi stdout read error", "token too long"} {+ if !strings.Contains(result.Error, want) {+ t.Errorf("Error = %q, want substring %q", result.Error, want)+ }+ }+}+func TestStripPiToolCallMarkup(t *testing.T) {tests := map[string]string{`before call:bash{command:<|"|>cd repo/path && ls -F<|"|>}<tool_call|> after`: "before after",