diff --git a/e2e/api/69-assistant-sessions.test.mjs b/e2e/api/69-assistant-sessions.test.mjs index 723647960..0b277b213 100644 --- a/e2e/api/69-assistant-sessions.test.mjs +++ b/e2e/api/69-assistant-sessions.test.mjs @@ -107,10 +107,30 @@ test('archive flags the conversation and can be undone', async () => { }); test('generation endpoints answer for an idle conversation', async () => { - await api('GET', `${S}/${session.id}/generation`, undefined, { expect: 404 }); - await api('POST', `${S}/${session.id}/generation/cancel`, {}, { expect: [404, 409] }); + const path = `${S}/${session.id}`; + await get(`${path}/generation`, { expect: 404 }); + await post(`${path}/generation/cancel`, {}, { expect: [404, 409] }); + const steer = await post(`${path}/generation/steer`, { content: 'This should require a running turn' }, { expect: 409 }); + assert.match(steer.error, /没有进行中的回复/); + const diagnostics = await get(`${path}/generations/${newId('missing-generation')}/diagnostics`, { expect: 404 }); + assert.match(diagnostics.error, /没有可用的诊断记录/); + assert.deepEqual((await get(path)).messages, session.messages); // No native CLI approvals are pending without a generation. - assert.deepEqual(list(await get(`${S}/${session.id}/native-approvals`)), []); + assert.deepEqual(list(await get(`${path}/native-approvals`)), []); +}); + +test('workspace sandbox selection persists and can return to the project default', async () => { + const path = `${S}/${session.id}`; + const selected = await put(`${path}/sandbox`, { sandboxProfileId: cfg.sandbox }); + assert.equal(selected.sandboxProfileId, cfg.sandbox); + await put(`${path}/sandbox`, { sandboxProfileId: newId('missing-sandbox') }, { expect: 400 }); + const stored = await get(path); + assert.equal(stored.sandboxProfileId, cfg.sandbox); + assert.deepEqual(stored.messages, session.messages); + const reset = await put(`${path}/sandbox`, { sandboxProfileId: '' }); + assert.equal(reset.sandboxProfileId ?? '', ''); + session = await get(path); + assert.equal(session.sandboxProfileId ?? '', ''); }); test('runtime mode: platform is accepted, workspace needs an open workspace, unknown is refused', async () => { diff --git a/internal/engine/sop_executors_test.go b/internal/engine/sop_executors_test.go index 305e9edff..af7bd8704 100644 --- a/internal/engine/sop_executors_test.go +++ b/internal/engine/sop_executors_test.go @@ -443,7 +443,7 @@ func TestExecutorCredentialsFollowTheProjectDefaultRunner(t *testing.T) { check := func(projectID string, want map[string]bool) { t.Helper() execution := domain.TelemetryContext{ProjectID: projectID, ResponsibleUserID: 42} - (&Engine{repo: st}).selectSOPExecutionTarget(&execution) + (&Engine{repo: st}).selectSOPExecutionTarget(&execution, true) hasCredential := ExecutorCredentials(st, 42, projectID) for kind, expected := range want { if got := hasCredential(kind); got != expected { @@ -528,7 +528,7 @@ func TestExecutorCredentialsFollowTheCloudPool(t *testing.T) { // Whatever pool runner a run picks, its login matches a CLI the picker offered. for i := 0; i < 20; i++ { execution := domain.TelemetryContext{ProjectID: "pool-served", ResponsibleUserID: 42} - e.selectSOPExecutionTarget(&execution) + e.selectSOPExecutionTarget(&execution, true) if execution.ExecutionPool != domain.ExecutionModeCloud || execution.ExecutionRunnerID == "" { t.Fatalf("run did not use the pool: %+v", execution) } @@ -553,7 +553,7 @@ func TestExecutorCredentialsFollowTheCloudPool(t *testing.T) { e.ConfigureCloudRunnerPool(CloudRunnerPool{Label: "pool", Projects: []string{"*"}}) check("personal default", "", map[string]bool{"codex": false, "claude-code": true}) execution := domain.TelemetryContext{ResponsibleUserID: 42} - e.selectSOPExecutionTarget(&execution) + e.selectSOPExecutionTarget(&execution, true) if execution.ExecutionRunnerID != own.ID { t.Fatalf("personal SOP ran on %q, want the default machine", execution.ExecutionRunnerID) } diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index 846328088..cebeda676 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -1700,6 +1700,10 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U missingText := "No conversation found with session ID: " + inv.sessionRef var handle func(string) sink := func(event domain.TelemetryEvent) { + if event.Name == runtime.CodeBuddyBackgroundTimeoutEvent { + assistantDiagnosticsFrom(ctx).platform(event.Name, event.Message, user) + return + } attempt.process(event) if event.Name == "process.stderr" { attempt.stderr(event.Message) @@ -1759,6 +1763,9 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U if json.Unmarshal([]byte(line), &result) == nil { switch result.Type { case "result": + if engine == assistantEngineCodeBuddy && result.ParentToolUseID != "" { + break + } final, resultError = result.Result, result.IsError claudeResultText = "" if captureClaudeText && result.ParentToolUseID == "" { @@ -1990,6 +1997,10 @@ func prepareAssistantCommand(opts assistantCommandOpts) (runtime.CommandSpec, er if sys == "" { sys = assistantSystemPromptText() } + workspace := opts.Workspace && !opts.ReviewOnly && !opts.ReportOnly + if workspace { + sys += "\n\n" + runtime.CodeBuddyBackgroundAgentInstructions + } // Use the CLI's unlimited value; omitting the flag retains a finite default. // A turn has no deadline; explicit cancellation still stops execution. args := []string{"-p", "--max-turns", nativeAssistantUnlimitedTurns, "--system-prompt", sys, "--output-format", "stream-json", "--include-partial-messages", "--mcp-config", opts.Config} @@ -2019,7 +2030,7 @@ func prepareAssistantCommand(opts assistantCommandOpts) (runtime.CommandSpec, er command.Argv = replaceArgValue(command.Argv, "--disallowedTools", nativeDisallowedTools+",Read,Grep,Glob,Skill,TodoWrite,AskUserQuestion,EnterPlanMode,ExitPlanMode") command.Argv = replaceArgValue(command.Argv, "--setting-sources", "") command.Argv = appendNativeArgs(command.Argv, "--no-session-persistence") - } else if !opts.Workspace { + } else if !workspace { command.Argv = applyNativeToolSafety(command.Argv, AgentToolAssistant) } else { command.Argv = replaceArgValue(command.Argv, "--setting-sources", "user") @@ -2027,9 +2038,9 @@ func prepareAssistantCommand(opts assistantCommandOpts) (runtime.CommandSpec, er } command.CredentialBindings = []runtime.CredentialBinding{runtime.BindCodeBuddy} command.Telemetry = nil - if len(opts.ImagePaths) > 0 { + if workspace || len(opts.ImagePaths) > 0 { command.Argv = appendNativeArgs(command.Argv, "--verbose") - command, err = withAssistantStreamImageInput(command, opts.Prompt, opts.ImagePaths, 0) + command, err = withAssistantStreamInput(command, opts.Prompt, opts.ImagePaths, 0) if err != nil { return runtime.CommandSpec{}, err } diff --git a/internal/httpapi/assistant_engine_cli.go b/internal/httpapi/assistant_engine_cli.go index 12c6d2c68..76b002498 100644 --- a/internal/httpapi/assistant_engine_cli.go +++ b/internal/httpapi/assistant_engine_cli.go @@ -246,7 +246,7 @@ func prepareAssistantClaudeInvocation(o assistantEngineInvocationOpts) (assistan if o.RunnerLogin { frameLimit = runtime.ClaudeLoginMaxInputLine } - command, err = withAssistantStreamImageInput(command, o.Prompt, o.ImagePaths, frameLimit) + command, err = withAssistantStreamInput(command, o.Prompt, o.ImagePaths, frameLimit) if err != nil { return assistantCLIInvocation{}, err } @@ -259,7 +259,7 @@ func prepareAssistantClaudeInvocation(o assistantEngineInvocationOpts) (assistan }, nil } -func withAssistantStreamImageInput(command runtime.CommandSpec, prompt string, imagePaths []string, frameLimit int) (runtime.CommandSpec, error) { +func withAssistantStreamInput(command runtime.CommandSpec, prompt string, imagePaths []string, frameLimit int) (runtime.CommandSpec, error) { input, err := assistantStreamImageInput(prompt, imagePaths) if err != nil { return runtime.CommandSpec{}, err diff --git a/internal/httpapi/assistant_failure_test.go b/internal/httpapi/assistant_failure_test.go index 43450f752..c63c8514b 100644 --- a/internal/httpapi/assistant_failure_test.go +++ b/internal/httpapi/assistant_failure_test.go @@ -129,6 +129,25 @@ func TestAssistantClaudeRecoversReplyFromEmptySuccessfulResult(t *testing.T) { } } +func TestAssistantWorkspaceCodeBuddyKeepsParentReplyAfterChildResult(t *testing.T) { + reply, _, err := runAssistantCLI(t.Context(), assistantCLIRequest{ + Executor: "codebuddy", Prompt: "test", SessionRoot: t.TempDir(), + Workspace: true, Native: true, RemoteBinary: true, + Execute: func(_ context.Context, _ string, _ runtime.CommandSpec, _ runtime.RunCredentials, sink runtime.EventSink) (string, error) { + for _, line := range []string{ + `{"type":"result","result":"parent reply"}`, + `{"type":"result","parent_tool_use_id":"child","result":"child result","is_error":true}`, + } { + sink(domain.TelemetryEvent{Name: "process.stdout", Message: line}) + } + return "", nil + }, + }, domain.User{ID: 1, CodeBuddyAPIKey: "test"}, nil) + if err != nil || reply != "parent reply" { + t.Fatalf("got reply = %q, error = %v", reply, err) + } +} + func TestAssistantGenerationFailurePreservesCancellationAndDeadline(t *testing.T) { for _, cause := range []error{context.Canceled, context.DeadlineExceeded} { _, err := decodeAssistantCLIResult("", false, cause, []string{"process stopped"}) diff --git a/internal/httpapi/assistant_prompt_stdin_test.go b/internal/httpapi/assistant_prompt_stdin_test.go index 743ea8e2d..9d1d3b11b 100644 --- a/internal/httpapi/assistant_prompt_stdin_test.go +++ b/internal/httpapi/assistant_prompt_stdin_test.go @@ -1,9 +1,11 @@ package httpapi import ( + "encoding/json" "io" "os" "path/filepath" + "slices" "strings" "testing" @@ -42,11 +44,10 @@ func assertPromptOnStdin(t *testing.T, name string, command runtime.CommandSpec, func TestAssistantCodeBuddyOversizedPromptUsesStdin(t *testing.T) { prompt := oversizedAssistantPrompt() cases := map[string]assistantCommandOpts{ - "platform": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true}, - "workspace": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true, Workspace: true}, - "resume": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true, Resume: true}, - "report": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, ReportOnly: true}, - "review": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, ReviewOnly: true}, + "platform": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true}, + "resume": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true, Resume: true}, + "report": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, ReportOnly: true}, + "review": {Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, ReviewOnly: true}, } for name, opts := range cases { command, err := prepareAssistantCommand(opts) @@ -60,6 +61,43 @@ func TestAssistantCodeBuddyOversizedPromptUsesStdin(t *testing.T) { } } +func TestAssistantCodeBuddyWorkspaceStreamsPrompt(t *testing.T) { + for name, prompt := range map[string]string{"short": "你好\n第二行", "oversized": oversizedAssistantPrompt()} { + t.Run(name, func(t *testing.T) { + command, err := prepareAssistantCommand(assistantCommandOpts{ + Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: prompt, SessionID: "s1", Native: true, Workspace: true, + }) + if err != nil { + t.Fatal(err) + } + for _, flag := range []string{"--input-format", "--output-format"} { + i := slices.Index(command.Argv, flag) + if i < 0 || i+1 >= len(command.Argv) || command.Argv[i+1] != "stream-json" { + t.Fatalf("%s must be stream-json", flag) + } + } + if slices.Contains(command.Argv, prompt) || command.Argv[len(command.Argv)-1] != "--" || + !runtime.ConversationCommandFor(command, runtime.RunCredentials{}).Interactive { + t.Fatal("workspace prompt must be sent as interactive stdin") + } + var frame struct { + Type string + Message struct { + Role string + Content []struct{ Type, Text string } + } + } + if err := json.NewDecoder(command.Stdin).Decode(&frame); err != nil { + t.Fatal(err) + } + parts := frame.Message.Content + if frame.Type != "user" || frame.Message.Role != "user" || len(parts) != 1 || parts[0].Type != "text" || parts[0].Text != prompt { + t.Fatal("stream-json frame did not preserve the workspace prompt") + } + }) + } +} + func TestAssistantCodeBuddyShortPromptStaysOnArgv(t *testing.T) { command, err := prepareAssistantCommand(assistantCommandOpts{Bin: "codebuddy", Config: "/tmp/mcp.json", Prompt: "你好", SessionID: "s1", Native: true}) if err != nil { diff --git a/internal/runner/daemon.go b/internal/runner/daemon.go index bc2c87c6b..7f893f834 100644 --- a/internal/runner/daemon.go +++ b/internal/runner/daemon.go @@ -993,13 +993,13 @@ func (d *Daemon) executeInvocation(ctx context.Context, task domain.RunnerTask) argv = runtime.BindMCPCallArgv(sandbox, argv) } var result execResult + command := prepared.Command + command.Argv = argv if sandbox != nil { - command := prepared.Command - command.Argv = argv command = runtime.WithCommandEnvironment(command, commandEnv) result = d.executeSandboxProcess(ctx, task, sandbox, command) } else { - result = d.executeProcess(ctx, task, argv, commandEnv) + result = d.executeHostCommand(ctx, task, command, commandEnv) } result.outputs = collectTaskOutputs(workspace, inv) if result.status != domain.RunnerTaskSuccess { diff --git a/internal/runner/exec.go b/internal/runner/exec.go index 4cb4de710..95bc97c77 100644 --- a/internal/runner/exec.go +++ b/internal/runner/exec.go @@ -49,11 +49,17 @@ type eventBatcher struct { // process events back to the control plane. func (d *Daemon) executeSandboxProcess(ctx context.Context, task domain.RunnerTask, sandbox flowruntime.Sandbox, command flowruntime.CommandSpec) execResult { batcher := newEventBatcher(task, d.client) + command, closeInput, err := batcher.observer.OpenSOPInput(command) + if err != nil { + return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()} + } + defer closeInput() if err := d.client.StartTask(ctx, task.ID); err != nil { return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("start: %v", err)} } execCtx, cancel := context.WithCancel(ctx) defer cancel() + drainDeadline := batcher.observer.CodeBuddySOPDrainDeadline(execCtx) type outcome struct { output string err error @@ -81,6 +87,7 @@ func (d *Daemon) executeSandboxProcess(ctx context.Context, task domain.RunnerTa flushTicker := time.NewTicker(eventFlushInterval) defer flushTicker.Stop() canceled := false + stoppedAfterDrain := false ctxDone := ctx.Done() for { select { @@ -88,19 +95,24 @@ func (d *Daemon) executeSandboxProcess(ctx context.Context, task domain.RunnerTa ctxDone = nil canceled = true cancel() + case <-drainDeadline: + drainDeadline = nil + stoppedAfterDrain = true + cancel() case completed := <-done: - batcher.finalizeProtocol(completed.err == nil) + err := batcher.protocolProcessError(completed.err, stoppedAfterDrain) + batcher.finalizeProtocol(err == nil) batcher.flush(context.Background()) result := execResult{result: batcher.taskResult(completed.output)} - if canceled { + if canceled || (stoppedAfterDrain && ctx.Err() != nil) { result.status = domain.RunnerTaskCanceled result.errMsg = "runner stopped" return result } - result.exitCode = exitCode(completed.err) - if completed.err != nil { + result.exitCode = exitCode(err) + if err != nil { result.status = domain.RunnerTaskFailed - result.errMsg = completed.err.Error() + result.errMsg = err.Error() } else { result.status = domain.RunnerTaskSuccess } @@ -203,6 +215,13 @@ func (b *eventBatcher) finalizeProtocol(success bool) { } } +func (b *eventBatcher) protocolProcessError(err error, stoppedAfterDrain bool) error { + if err == nil || stoppedAfterDrain { + return b.observer.CodeBuddySOPResultError() + } + return err +} + func (b *eventBatcher) flush(ctx context.Context) { b.mu.Lock() pending := b.buf @@ -269,7 +288,16 @@ type execResult struct { // requested through the lease renewal response. extraEnv injects // task-scoped credentials (e.g. CODEBUDDY_API_KEY for CodeBuddy tasks). func (d *Daemon) executeProcess(ctx context.Context, task domain.RunnerTask, argv []string, extraEnv ...map[string]string) execResult { + return d.executeHostCommand(ctx, task, flowruntime.CommandSpec{Argv: argv}, extraEnv...) +} + +func (d *Daemon) executeHostCommand(ctx context.Context, task domain.RunnerTask, command flowruntime.CommandSpec, extraEnv ...map[string]string) execResult { batcher := newEventBatcher(task, d.client) + command, closeInput, err := batcher.observer.OpenSOPInput(command) + if err != nil { + return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()} + } + defer closeInput() if err := d.client.StartTask(ctx, task.ID); err != nil { if err == ErrUnauthorized { return execResult{status: domain.RunnerTaskFailed, errMsg: "runner session rejected"} @@ -282,8 +310,10 @@ func (d *Daemon) executeProcess(ctx context.Context, task domain.RunnerTask, arg return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("workspace %s: %v", dir, err)} } + argv := command.Argv cmd := exec.Command(argv[0], argv[1:]...) cmd.Dir = dir + cmd.Stdin = command.Stdin // Agent CLI credentials live in the user environment on this machine; // the platform additionally injects task-scoped credentials (currently // the CodeBuddy API key, which cannot come from a local CLI login). @@ -342,7 +372,11 @@ func (d *Daemon) executeProcess(ctx context.Context, task domain.RunnerTask, arg flushTicker := time.NewTicker(eventFlushInterval) defer flushTicker.Stop() + drainCtx, stopDrain := context.WithCancel(ctx) + defer stopDrain() + drainDeadline := batcher.observer.CodeBuddySOPDrainDeadline(drainCtx) canceled := false + stoppedAfterDrain := false ctxDone := ctx.Done() for { select { @@ -352,8 +386,15 @@ func (d *Daemon) executeProcess(ctx context.Context, task domain.RunnerTask, arg canceled = true terminateProcessGroup(cmd, processDone) } + case <-drainDeadline: + drainDeadline = nil + if !canceled { + stoppedAfterDrain = true + terminateProcessGroup(cmd, processDone) + } case <-processDone: - err := processErr + err := batcher.protocolProcessError(processErr, stoppedAfterDrain) + canceled = canceled || (stoppedAfterDrain && ctx.Err() != nil) if canceled { err = nil } diff --git a/internal/runner/exec_edges_cases_test.go b/internal/runner/exec_edges_cases_test.go index 184a460bd..ba848f5ea 100644 --- a/internal/runner/exec_edges_cases_test.go +++ b/internal/runner/exec_edges_cases_test.go @@ -122,6 +122,34 @@ func TestExecuteProcessAndSandboxCancellation(t *testing.T) { } } +func TestExecuteCodeBuddySOPStopsAtDrainDeadline(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })) + defer server.Close() + ctx, cancel := context.WithTimeout(t.Context(), 12*time.Second) + defer cancel() + d := &Daemon{cfg: Config{DefaultWorkspaceRoot: t.TempDir()}, client: NewClient(server.URL)} + executor := domain.ExecutorDefinition{Kind: "codebuddy", Binary: "codebuddy", Protocol: "stream-json"} + agent := domain.AgentDefinition{ID: "test", Name: "Test"} + prepared, err := flowruntime.NewExecutorRunner().PrepareRemote(t.TempDir(), flowruntime.RemoteInvocation{ + InvocationID: "test", Executor: executor, Agent: agent, Prompt: "test", + }) + if err != nil { + t.Fatal(err) + } + task := domain.RunnerTask{ID: "codebuddy-drain", Invocation: &domain.RunnerInvocation{Executor: executor}} + command := prepared.Command + command.Argv = []string{"sh", "-c", ` +IFS= read -r prompt || exit 1 +printf '%s\n' '{"type":"result","result":"parent done"}' +if IFS= read -r extra; then exit 1; fi +exec sleep 60 +`} + result := d.executeHostCommand(ctx, task, command) + if result.status != domain.RunnerTaskSuccess || result.result != "parent done" || ctx.Err() != nil { + t.Fatalf("Runner did not preserve the parent result after stopping the process: %+v, context=%v", result, ctx.Err()) + } +} + func TestEventBatcherRequeuesFailedFlush(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "fail", http.StatusInternalServerError) })) defer server.Close() diff --git a/internal/runtime/codebuddy_background_stream.go b/internal/runtime/codebuddy_background_stream.go new file mode 100644 index 000000000..e42cdb62b --- /dev/null +++ b/internal/runtime/codebuddy_background_stream.go @@ -0,0 +1,236 @@ +package runtime + +import ( + "context" + "encoding/json" + "fmt" + "maps" + "os" + "slices" + "strings" + "sync" + "time" + + "agentflow/internal/domain" +) + +const CodeBuddyBackgroundAgentInstructions = `CodeBuddy can run an Agent in the background with run_in_background=true. Continue independent work after dispatch and wait when you need the result. +If the Agent call assigns a team, ask the member to send its result to the leader and wait for the matching inbox message. TaskOutput reports teammate status. +For a standalone background Agent, use TaskOutput with block=true to collect the result.` + +const ( + CodeBuddyBackgroundTimeoutEvent = "agent.background.timeout" + codeBuddyBackgroundResultGrace = 5 * time.Second +) + +// CodeBuddy enables background Agent calls when stdin stays open after the +// initial user frame. A successful parent result allows a short window for +// trailing child notifications. Some CodeBuddy versions stop emitting them +// after the parent finishes, so the wait must expire. +type codeBuddyBackgroundStream struct { + mu sync.Mutex + input *os.File + active map[string]struct{} + parentDone bool + closed bool + drained chan struct{} + graceTimer *time.Timer + timedOut bool +} + +func newCodeBuddyBackgroundStream(input *os.File) *codeBuddyBackgroundStream { + return &codeBuddyBackgroundStream{input: input, active: make(map[string]struct{}), drained: make(chan struct{})} +} + +// OpenSOPInput connects a prepared SOP command to the same stream observer +// that consumes its stdout. The caller closes the pipe after execution, even +// if startup fails or the process exits without a result. +func (o *ProtocolObserver) OpenSOPInput(command CommandSpec) (CommandSpec, func(), error) { + if len(command.codeBuddySOPInput) == 0 { + return command, func() {}, nil + } + if o == nil || o.adapter == nil { + return command, nil, fmt.Errorf("CodeBuddy SOP stdin requires a protocol observer") + } + return o.adapter.openSOPInput(command) +} + +func (a *protocolAdapter) openSOPInput(command CommandSpec) (CommandSpec, func(), error) { + if len(command.codeBuddySOPInput) == 0 { + return command, func() {}, nil + } + reader, writer, err := os.Pipe() + if err != nil { + return command, nil, fmt.Errorf("open CodeBuddy SOP stdin: %w", err) + } + // A file descriptor keeps os/exec independent of the open input stream. + command.Stdin = reader + stream := newCodeBuddyBackgroundStream(writer) + a.codeBuddyStream = stream + go func() { _, _ = writer.Write(command.codeBuddySOPInput) }() + return command, func() { + stream.stop() + _ = reader.Close() + }, nil +} + +func (s *codeBuddyBackgroundStream) observeStdout(line string) { + line = strings.TrimSpace(line) + if line == "" || line[0] != '{' { + return + } + var event map[string]any + if json.Unmarshal([]byte(line), &event) != nil { + return + } + switch stringValue(event["type"]) { + case "result": + if stringValue(event["parent_tool_use_id"]) == "" { + failed, _ := event["is_error"].(bool) + s.finishParent(failed) + } + case "error": + if stringValue(event["parent_tool_use_id"]) == "" { + s.finishParent(true) + } + case "system": + s.observeTask(event, nil) + } +} + +func (s *codeBuddyBackgroundStream) finishParent(failed bool) { + s.mu.Lock() + defer s.mu.Unlock() + if s.closed { + return + } + if failed || len(s.active) == 0 { + s.closeLocked(true) + return + } + if !s.parentDone { + s.parentDone = true + s.graceTimer = time.AfterFunc(codeBuddyBackgroundResultGrace, func() { + s.mu.Lock() + defer s.mu.Unlock() + if !s.closed { + s.timedOut = true + s.closeLocked(true) + } + }) + } +} + +func (s *codeBuddyBackgroundStream) closeLocked(drained bool) { + if s.closed { + return + } + s.closed = true + if s.graceTimer != nil { + s.graceTimer.Stop() + } + // Publish the terminal state before closing the writer so any racing + // input relay can let the buffered terminal event reach the API. + if drained { + close(s.drained) + } + _ = s.input.Close() +} + +func (s *codeBuddyBackgroundStream) stop() { + s.mu.Lock() + defer s.mu.Unlock() + s.closeLocked(false) +} + +func (s *codeBuddyBackgroundStream) isDrained() bool { + select { + case <-s.drained: + return true + default: + return false + } +} + +func (s *codeBuddyBackgroundStream) timeoutEvent() domain.TelemetryEvent { + s.mu.Lock() + defer s.mu.Unlock() + if !s.timedOut { + return domain.TelemetryEvent{} + } + return domain.TelemetryEvent{ + Category: "lifecycle", Name: CodeBuddyBackgroundTimeoutEvent, Phase: "finish", Level: "warn", + Message: fmt.Sprintf("CodeBuddy 父 Agent 已结束,%d 个后台子 Agent 未在 %s 内报告完成,关闭命令输入", len(s.active), codeBuddyBackgroundResultGrace), + Attributes: map[string]any{"taskIds": slices.Sorted(maps.Keys(s.active)), "graceMs": codeBuddyBackgroundResultGrace.Milliseconds()}, + } +} + +func (s *codeBuddyBackgroundStream) observeTask(raw map[string]any, emit EventSink) { + id := stringValue(raw["task_id"]) + if id == "" { + return + } + s.mu.Lock() + phase, status := s.updateTaskLocked(raw, id) + s.mu.Unlock() + if phase == "" || emit == nil { + return + } + message := "CodeBuddy 子 Agent 已后台启动" + attributes := map[string]any{"taskId": id} + if status != "" { + attributes["status"] = status + message = "CodeBuddy 子 Agent 后台任务结束" + } + emit(domain.TelemetryEvent{Category: "lifecycle", Name: "agent.background", Phase: phase, Message: message, + SessionID: stringValue(raw["session_id"]), ToolCallID: stringValue(raw["tool_use_id"]), Attributes: attributes}) +} + +func (s *codeBuddyBackgroundStream) updateTaskLocked(raw map[string]any, id string) (phase, status string) { + if s.closed { + return "", "" + } + switch stringValue(raw["subtype"]) { + case "task_started": + if !strings.EqualFold(stringValue(raw["task_type"]), "Agent") && !strings.HasPrefix(id, "agent-") { + return "", "" + } + s.active[id] = struct{}{} + return "start", "" + case "task_updated", "task_notification": + if _, active := s.active[id]; !active { + return "", "" + } + patch, _ := raw["patch"].(map[string]any) + status = firstNonEmpty(stringValue(raw["status"]), stringValue(patch["status"])) + switch status { + case "completed", "failed", "stopped", "killed", "cancelled": + default: + return "", "" + } + delete(s.active, id) + if s.parentDone && len(s.active) == 0 { + s.closeLocked(true) + } + return "finish", status + default: + return "", "" + } +} + +// CodeBuddySOPDrainDeadline signals when a Runner can stop a CodeBuddy SOP +// process that is still alive after EOF and the usual trailing output drain. +// Other Runner processes retain their existing lifetime. +func (o *ProtocolObserver) CodeBuddySOPDrainDeadline(ctx context.Context) <-chan struct{} { + if o == nil || o.adapter == nil || o.adapter.codeBuddyStream == nil { + return nil + } + drained := o.adapter.codeBuddyStream.drained + stop := make(chan struct{}) + go func() { + if waitForProcessTerminalDrain(ctx, drained, nil) { + close(stop) + } + }() + return stop +} diff --git a/internal/runtime/codebuddy_sop_stream_test.go b/internal/runtime/codebuddy_sop_stream_test.go new file mode 100644 index 000000000..036192db3 --- /dev/null +++ b/internal/runtime/codebuddy_sop_stream_test.go @@ -0,0 +1,129 @@ +package runtime + +import ( + "bufio" + "context" + "encoding/json" + "io" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "agentflow/internal/domain" +) + +func TestCodeBuddySOPInputRemainsOpenForBackgroundAgents(t *testing.T) { + executor := domain.ExecutorDefinition{Kind: "codebuddy", Binary: "codebuddy", Protocol: "stream-json", + Args: []string{"-p", "--input-format=text", "--output-format", "text"}} + prepared, err := NewExecutorRunner().PrepareRemote(t.TempDir(), RemoteInvocation{ + InvocationID: "sop-node", + Executor: executor, + Agent: domain.AgentDefinition{ID: "test-agent", Name: "Test Agent"}, + Prompt: "line 1\nline 2", + Options: InvocationOptions{ResumeSessionID: "session-1"}, + }) + if err != nil { + t.Fatal(err) + } + argv := prepared.Command.Argv + if valueAfter(argv, "--input-format") != "stream-json" || valueAfter(argv, "--output-format") != "stream-json" || + valueAfter(argv, "--resume") != "session-1" || slices.Contains(argv, "line 1\nline 2") { + t.Fatalf("unexpected CodeBuddy argv: %v", argv) + } + + var phases []string + observer := NewProtocolObserver(executor, func(event domain.TelemetryEvent) { + if event.Name == "agent.background" { + phases = append(phases, event.Phase) + } + }) + command, closeInput, err := observer.OpenSOPInput(prepared.Command) + if err != nil { + t.Fatal(err) + } + defer closeInput() + stdin := command.Stdin.(*os.File) + if err := stdin.SetReadDeadline(time.Now().Add(2 * time.Second)); err != nil { + t.Fatal(err) + } + input := bufio.NewReader(stdin) + line, err := input.ReadBytes('\n') + if err != nil { + t.Fatal(err) + } + var frame struct { + Type string + Message struct{ Role, Content string } + } + if err := json.Unmarshal(line, &frame); err != nil || frame.Type != "user" || frame.Message.Role != "user" || frame.Message.Content != "line 1\nline 2" { + t.Fatalf("unexpected input frame: %q, %v", line, err) + } + + handle := func(line string) { + observer.Handle(domain.TelemetryEvent{Name: "process.stdout", Message: line}) + } + handle(`{"type":"system","subtype":"task_started","task_type":"Agent","task_id":"agent-1"}`) + handle(`{"type":"system","subtype":"task_started","task_type":"Agent","task_id":"agent-2"}`) + handle(`{"type":"system","subtype":"task_started","task_type":"Bash","task_id":"bash-1"}`) + handle(`{"type":"result","parent_tool_use_id":"agent-call","result":"child output"}`) + handle(`{"type":"error","parent_tool_use_id":"agent-call","error":"child error"}`) + if observer.adapter.Finished() { + t.Fatal("a child result finished the parent") + } + handle(`{"type":"result","result":"parent output"}`) + handle(`{"type":"system","subtype":"task_updated","task_id":"agent-1","patch":{"status":"completed"}}`) + select { + case <-observer.adapter.Completed(): + t.Fatal("input closed while the second child was active") + default: + } + handle(`{"type":"system","subtype":"task_notification","task_id":"agent-2","status":"completed"}`) + if _, err := input.ReadByte(); err != io.EOF { + t.Fatalf("child completion should close the input stream, got %v", err) + } + if observer.VisibleOutput() != "parent output" || !slices.Equal(phases, []string{"start", "start", "finish", "finish"}) { + t.Fatalf("result %q, background event phases %v", observer.VisibleOutput(), phases) + } +} + +func TestCodeBuddySOPFinishesWhenChildNeverReportsCompletion(t *testing.T) { + t.Setenv("AGENTFLOW_BROWSER", "off") + workspace := t.TempDir() + cli := filepath.Join(t.TempDir(), "codebuddy") + script := `#!/bin/sh +IFS= read -r input || exit 1 +printf '%s\n' '{"type":"system","subtype":"task_started","task_type":"Agent","task_id":"agent-1"}' +printf '%s\n' '{"type":"result","result":"","is_error":false}' +if IFS= read -r extra; then exit 1; fi +touch input-closed +exec sleep 60 +` + if err := os.WriteFile(cli, []byte(script), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("AGENTFLOW_CODEBUDDY_BIN", cli) + ctx, cancel := context.WithTimeout(t.Context(), 12*time.Second) + defer cancel() + ex := domain.ExecutorDefinition{Kind: "codebuddy", Binary: cli, Protocol: "stream-json"} + var warning domain.TelemetryEvent + output, err := NewExecutorRunner().Run(ctx, &localSandbox{workspace: workspace}, "test", ex, + domain.AgentDefinition{ID: "test", Name: "Test"}, domain.AgentAssetBundle{}, "prompt", InvocationOptions{}, + func(event domain.TelemetryEvent) { + if event.Name == CodeBuddyBackgroundTimeoutEvent { + warning = event + } + }) + if err != nil || ctx.Err() != nil || !strings.Contains(output, `"type":"result"`) { + t.Fatalf("successful parent result should finish the SOP, output=%q err=%v context=%v", output, err, ctx.Err()) + } + if _, err := os.Stat(filepath.Join(workspace, "input-closed")); err != nil { + t.Fatalf("CLI never received EOF: %v", err) + } + taskIDs, _ := warning.Attributes["taskIds"].([]string) + if warning.Level != "warn" || !slices.Equal(taskIDs, []string{"agent-1"}) { + t.Fatalf("missing timeout warning for unreported child: %+v", warning) + } +} diff --git a/internal/runtime/conversation_process.go b/internal/runtime/conversation_process.go index 66662d9cb..97c1cc5ea 100644 --- a/internal/runtime/conversation_process.go +++ b/internal/runtime/conversation_process.go @@ -158,23 +158,24 @@ func (p *ConversationProcessPool) lockAssets(ctx context.Context, root string) ( } type conversationProcess struct { - mu sync.Mutex - cancel context.CancelFunc - input *os.File - events []domain.TelemetryEvent - base int64 - done bool - err string - errorCode string - wake chan struct{} - lastPoll time.Time - closeRelay func() - finished chan struct{} - root string - bytes int - notStarted bool - cliVersion string - versionSource string + mu sync.Mutex + cancel context.CancelFunc + input *os.File + codeBuddyStream *codeBuddyBackgroundStream + events []domain.TelemetryEvent + base int64 + done bool + err string + errorCode string + wake chan struct{} + lastPoll time.Time + closeRelay func() + finished chan struct{} + root string + bytes int + notStarted bool + cliVersion string + versionSource string // workspace replaces /ws in stdin under seatbelt, which has no mount // namespace to map that path onto the run workspace. workspace string @@ -299,7 +300,11 @@ func (p *ConversationProcessPool) Handle(ctx context.Context, root, workspace st case "write": proc.mu.Lock() input, workspace := proc.input, proc.workspace + background := proc.codeBuddyStream proc.mu.Unlock() + if background != nil && (req.EOF || background.isDrained()) { + return ConversationProcessResult{}, nil + } if input == nil { return ConversationProcessResult{}, fmt.Errorf("process has no stdin") } @@ -317,6 +322,11 @@ func (p *ConversationProcessPool) Handle(ctx context.Context, root, workspace st } else { data := remapConversationStdin(req.Data, req.SourceRoot, root, workspace, proc.stdinProvider) _, err = io.WriteString(input, data) + if err != nil && background != nil && background.isDrained() { + // A terminal error can race the first prompt write. The + // caller needs the buffered error frame to recover. + err = nil + } } return ConversationProcessResult{}, err case "stop": @@ -492,11 +502,17 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str var release func() var stdin io.Closer var cleanupLogin func() error + var background *codeBuddyBackgroundStream // Set once a terminal result line has been followed by the drain window // and this process is stopped so a lingering CLI cannot pin the turn. var stopAfterTerminalResult atomic.Bool finish := func(runErr error, notStarted bool) { cancel() + var backgroundWarning domain.TelemetryEvent + if background != nil { + background.stop() + backgroundWarning = background.timeoutEvent() + } if req.SourceRoot != "" && req.SourceRoot != root { _ = os.RemoveAll(filepath.Join(root, conversationPromptInputDir)) } @@ -523,6 +539,10 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str if proc.input != nil { _ = proc.input.Close() } + if backgroundWarning.Name != "" { + proc.events = append(proc.events, backgroundWarning) + proc.bytes += len(backgroundWarning.Message) + } if credentialCleanupErr != nil { proc.err = "清理 CLI 临时凭证失败" proc.notStarted = notStarted @@ -744,8 +764,16 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str if err != nil { return ConversationProcessResult{}, err } + // The API relays one user frame. CodeBuddy needs this pipe to stay + // open through asynchronous Agents even after that frame reaches EOF. + if spec != nil && command.Provider == "codebuddy" && + valueAfter(nativeArgv, "--input-format") == "stream-json" && + valueAfter(nativeArgv, "--output-format") == "stream-json" { + background = newCodeBuddyBackgroundStream(writer) + } proc.mu.Lock() proc.input = writer + proc.codeBuddyStream = background proc.mu.Unlock() stdin = input command.Stdin = input @@ -783,22 +811,16 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str // it has already emitted its terminal result. Same drain as // ExecutorRunner: let the trailing output land, then stop the process // so the turn can be marked finished and a queued follow-up can send. + // For CodeBuddy background work, wait for stdin to close before draining. terminalResult := make(chan struct{}) + if background != nil { + terminalResult = background.drained + } var terminalOnce sync.Once go func() { - select { - case <-terminalResult: - timer := time.NewTimer(ConversationTerminalResultDrain) - defer timer.Stop() - select { - case <-timer.C: - stopAfterTerminalResult.Store(true) - cancel() - case <-watchDone: - case <-procCtx.Done(): - } - case <-watchDone: - case <-procCtx.Done(): + if waitForProcessTerminalDrain(procCtx, terminalResult, watchDone) { + stopAfterTerminalResult.Store(true) + cancel() } }() sink := func(ev domain.TelemetryEvent) { @@ -814,8 +836,12 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str cancel() } proc.mu.Unlock() - if ev.Name == "process.stdout" && conversationStdoutTerminal(ev.Message) { - terminalOnce.Do(func() { close(terminalResult) }) + if ev.Name == "process.stdout" { + if background != nil { + background.observeStdout(ev.Message) + } else if conversationStdoutTerminal(ev.Message) { + terminalOnce.Do(func() { close(terminalResult) }) + } } select { case proc.wake <- struct{}{}: diff --git a/internal/runtime/conversation_process_test.go b/internal/runtime/conversation_process_test.go index 95a3b91fc..84238df3f 100644 --- a/internal/runtime/conversation_process_test.go +++ b/internal/runtime/conversation_process_test.go @@ -10,6 +10,8 @@ import ( "strings" "testing" "time" + + "agentflow/internal/domain" ) func TestConversationStdinRemapsQuotedCodexWorkspace(t *testing.T) { @@ -171,6 +173,92 @@ func TestConversationProcessStopsAfterTerminalResult(t *testing.T) { } } +func TestConversationCodeBuddyKeepsStdinOpenUntilBackgroundAgentFinishes(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + script := `#!/bin/sh +IFS= read -r prompt || exit 1 +printf '%s\n' '{"type":"system","subtype":"task_started","task_type":"Agent","task_id":"agent-1"}' +printf '%s\n' '{"type":"result","result":"parent result"}' +sleep 3 +IFS= read -r probe || exit 1 +printf 'stdin remained open: %s\n' "$probe" +printf '%s\n' '{"type":"system","subtype":"task_notification","task_id":"agent-1","status":"completed","summary":"child receipt"}' +if IFS= read -r extra; then exit 1; fi +printf 'stdin closed after child receipt\n' +` + pool, root, id := startTestCodeBuddyWorkspace(t, ctx, script) + for _, write := range []ConversationProcessRequest{ + {Data: "{\"type\":\"user\"}\n"}, {EOF: true}, {Data: "probe\n"}, + } { + write.Operation, write.ID = "write", id + if _, err := pool.Handle(ctx, root, "", nil, write, nil); err != nil { + t.Fatal(err) + } + } + output := conversationPoll(t, pool, ctx, root, id) + for _, want := range []string{"parent result", "stdin remained open: probe", `"summary":"child receipt"`, "stdin closed after child receipt"} { + if !strings.Contains(output, want) { + t.Fatalf("missing %q in process output %q", want, output) + } + } +} + +func TestConversationCodeBuddyClosesInputOnEarlyResumeError(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + // Resume can fail before CodeBuddy reads even the first user frame. + script := `#!/bin/sh +printf '%s\n' '{"type":"error","error":"No conversation found with session ID: missing"}' +if IFS= read -r extra; then exit 1; fi +printf 'stdin closed after resume error\n' +` + pool, root, id := startTestCodeBuddyWorkspace(t, ctx, script) + output := conversationPoll(t, pool, ctx, root, id) + for _, req := range []ConversationProcessRequest{{Data: "{\"type\":\"user\"}\n"}, {EOF: true}} { + req.Operation, req.ID = "write", id + if _, err := pool.Handle(ctx, root, "", nil, req, nil); err != nil { + t.Fatalf("input relay masked the resume error: %v", err) + } + } + for _, want := range []string{"No conversation found with session ID: missing", "stdin closed after resume error"} { + if !strings.Contains(output, want) { + t.Fatalf("missing %q in process output %q", want, output) + } + } +} + +func startTestCodeBuddyWorkspace(t *testing.T, ctx context.Context, script string) (*ConversationProcessPool, string, string) { + t.Helper() + root, workspace, install := t.TempDir(), t.TempDir(), t.TempDir() + binary := filepath.Join(install, "codebuddy") + if err := os.WriteFile(binary, []byte(script), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("AGENTFLOW_CODEBUDDY_BIN", binary) + // Exercise the workspace process path without relying on a host sandbox + // binary. The shim executes the test CLI after the seatbelt profile. + shim := filepath.Join(install, "seatbelt-shim") + if err := os.WriteFile(shim, []byte("#!/bin/sh\nshift 2\nexec \"$@\"\n"), 0700); err != nil { + t.Fatal(err) + } + profile := domain.SandboxProfile{Driver: domain.SandboxDriverSeatbelt} + sandbox := &domain.RunnerSandboxSpec{Profile: profile} + factory := func(context.Context, string) (Sandbox, func(), error) { + return &processSandbox{driver: profile.Driver, workspace: workspace, binary: shim}, nil, nil + } + pool := &ConversationProcessPool{} + start, err := pool.Handle(ctx, root, workspace, sandbox, ConversationProcessRequest{ + Operation: "start", + Command: &ConversationCommand{Provider: "codebuddy", Interactive: true, + Argv: []string{binary, "-p", "--input-format", "stream-json", "--output-format", "stream-json"}}, + }, nil, factory) + if err != nil { + t.Fatal(err) + } + return pool, root, start.ID +} + func TestConversationProcessCompletesDuringSlowVersionProbe(t *testing.T) { root := t.TempDir() bin := filepath.Join(t.TempDir(), "codebuddy") diff --git a/internal/runtime/materialize.go b/internal/runtime/materialize.go index 84c70ef24..7108ef748 100644 --- a/internal/runtime/materialize.go +++ b/internal/runtime/materialize.go @@ -115,6 +115,11 @@ func materializeInvocationForDriver(workspace, invocationID string, ex domain.Ex return compiled, err } lines := append([]string{"# " + a.Name, "", "## Rules"}, ruleLines...) + if ex.Kind == "codebuddy" { + lines = append(lines, "", "## Background Agent results", + CodeBuddyBackgroundAgentInstructions, + "Collect results required by this step before submitting the gate decision.") + } selectedSkills := make([]selectedSkill, 0, len(assets.Skills)) for _, skill := range assets.Skills { item, err := compileSelectedSkill(agentRel, skill, assets.SkillFiles[skill.ID]) diff --git a/internal/runtime/process.go b/internal/runtime/process.go index 6312549e2..81a3ca778 100644 --- a/internal/runtime/process.go +++ b/internal/runtime/process.go @@ -3,6 +3,7 @@ package runtime import ( "agentflow/internal/domain" "bytes" + "context" "errors" "fmt" "os/exec" @@ -16,6 +17,26 @@ const processWaitDelay = time.Second var errProcessNotStarted = errors.New("process was not started") +func waitForProcessTerminalDrain(ctx context.Context, terminal, finished <-chan struct{}) bool { + select { + case <-terminal: + case <-ctx.Done(): + return false + case <-finished: + return false + } + timer := time.NewTimer(ConversationTerminalResultDrain) + defer timer.Stop() + select { + case <-timer.C: + return true + case <-ctx.Done(): + return false + case <-finished: + return false + } +} + // runCommand streams process telemetry, coordinating the Claude login callback // and redacting bound credential environment values from process.started. func runCommand(cmd *exec.Cmd, sink EventSink, commands ...CommandSpec) (string, error) { diff --git a/internal/runtime/protocol.go b/internal/runtime/protocol.go index 05d31a1bd..5bd85801b 100644 --- a/internal/runtime/protocol.go +++ b/internal/runtime/protocol.go @@ -26,20 +26,21 @@ const ( ) type protocolAdapter struct { - ex domain.ExecutorDefinition - sink EventSink - parser protocolParser - adapterID string - mu sync.Mutex - result string - lastOutput string - failed bool - reasoningBuf strings.Builder - done chan struct{} - once sync.Once - tools map[string]*toolUseBuf - currentToolID string - translate func(string) []string + ex domain.ExecutorDefinition + sink EventSink + parser protocolParser + adapterID string + mu sync.Mutex + result string + lastOutput string + failed bool + reasoningBuf strings.Builder + done chan struct{} + once sync.Once + tools map[string]*toolUseBuf + currentToolID string + translate func(string) []string + codeBuddyStream *codeBuddyBackgroundStream } // ProtocolObserver normalizes process output from a remotely executed Agent @@ -74,7 +75,11 @@ func (o *ProtocolObserver) VisibleOutput() string { } func (o *ProtocolObserver) Finalize(success bool) { - if o == nil || o.adapter == nil || o.adapter.Finished() { + if o == nil || o.adapter == nil { + return + } + o.adapter.finishCodeBuddyStream() + if o.adapter.Finished() { return } level := "error" @@ -86,6 +91,15 @@ func (o *ProtocolObserver) Finalize(success bool) { o.adapter.emit(domain.TelemetryEvent{Category: "lifecycle", Name: "agent.completed", Phase: "finish", Level: level, Message: message}) } +// CodeBuddySOPResultError preserves a protocol failure when the command exits +// on EOF or when the Runner has to stop it after the output drain. +func (o *ProtocolObserver) CodeBuddySOPResultError() error { + if o == nil || o.adapter == nil || o.adapter.codeBuddyStream == nil || !o.adapter.Failed() { + return nil + } + return executorReportedError(o.adapter.Result(), "") +} + func newProtocolAdapter(ex domain.ExecutorDefinition, sink EventSink) *protocolAdapter { return providerForKind(ex.Kind).Protocol(ex, sink) } @@ -94,7 +108,12 @@ func makeProtocolAdapter(ex domain.ExecutorDefinition, sink EventSink, parser pr return &protocolAdapter{ex: ex, sink: sink, parser: parser, adapterID: adapterID, done: make(chan struct{})} } -func (a *protocolAdapter) Completed() <-chan struct{} { return a.done } +func (a *protocolAdapter) Completed() <-chan struct{} { + if a.codeBuddyStream != nil { + return a.codeBuddyStream.drained + } + return a.done +} func (a *protocolAdapter) Finished() bool { select { @@ -111,6 +130,22 @@ func (a *protocolAdapter) Failed() bool { return a.failed } +func (a *protocolAdapter) recordResult(result string, failed bool) { + a.mu.Lock() + a.result, a.failed = result, failed + a.mu.Unlock() + a.once.Do(func() { close(a.done) }) +} + +func (a *protocolAdapter) finishCodeBuddyStream() { + if stream := a.codeBuddyStream; stream != nil { + stream.stop() + if ev := stream.timeoutEvent(); ev.Name != "" { + a.emit(ev) + } + } +} + func ObservabilitySpec() domain.ObservabilitySpec { return domain.ObservabilitySpec{ Version: domain.ObservabilitySpecVersion, @@ -232,6 +267,9 @@ func (a *protocolAdapter) handleClaudeStream(raw map[string]any) { switch typ { case "system": if stringValue(raw["subtype"]) != "init" { + if stream := a.codeBuddyStream; stream != nil { + stream.observeTask(raw, a.emit) + } return } a.emit(domain.TelemetryEvent{Category: "lifecycle", Name: "agent.initialized", Phase: "start", Message: "agent session initialized", Model: stringValue(raw["model"]), SessionID: sessionID, Attributes: map[string]any{"permissionMode": raw["permissionMode"]}}) @@ -270,6 +308,17 @@ func (a *protocolAdapter) handleClaudeStream(raw map[string]any) { msg := summarizeToolResult(name, failed, content["content"]) a.emit(domain.TelemetryEvent{Category: "tool", Name: "tool.call", Phase: "finish", Level: map[bool]string{true: "error", false: "info"}[failed], Message: msg, SessionID: sessionID, ToolCallID: id, Tool: &domain.ToolObservation{Name: name, Operation: "tool.result", CallID: id, Success: &success}}) } + case "error": + stream := a.codeBuddyStream + if stream == nil || stringValue(raw["parent_tool_use_id"]) != "" { + return + } + if !a.Finished() { + message := firstNonEmpty(stringValue(raw["error"]), stringValue(raw["message"]), "CodeBuddy reported a stream error") + a.recordResult(message, true) + a.emit(domain.TelemetryEvent{Category: "lifecycle", Name: "agent.completed", Phase: "finish", Level: "error", Message: message, SessionID: sessionID}) + } + stream.finishParent(true) case "result": // The root result already includes subagent consumption. A child's // message-scoped result must not reset the session billing cursor. @@ -278,11 +327,7 @@ func (a *protocolAdapter) handleClaudeStream(raw map[string]any) { } result := stringValue(raw["result"]) failed, _ := raw["is_error"].(bool) - a.mu.Lock() - a.result = result - a.failed = failed - a.mu.Unlock() - a.once.Do(func() { close(a.done) }) + a.recordResult(result, failed) usage := tokenUsage(raw["usage"]) usage.CostUSD = float64Value(raw["total_cost_usd"]) // 适配器显式上报成本时标记 reported,用于区分"真实零成本"与"成本未识别"。 @@ -291,6 +336,9 @@ func (a *protocolAdapter) handleClaudeStream(raw map[string]any) { } a.emit(domain.TelemetryEvent{Category: "usage", Name: "usage.final", Phase: "finish", Message: "final model usage", SessionID: sessionID, Usage: &usage, Attributes: map[string]any{"durationMs": raw["duration_ms"], "turns": raw["num_turns"], "isError": raw["is_error"], "usageReported": raw["usage"] != nil}}) a.emit(domain.TelemetryEvent{Category: "lifecycle", Name: "agent.completed", Phase: "finish", Message: result, SessionID: sessionID}) + if stream := a.codeBuddyStream; stream != nil { + stream.finishParent(failed) + } default: // File snapshots and provider-specific housekeeping events are intentionally hidden from the portable view. } diff --git a/internal/runtime/provider.go b/internal/runtime/provider.go index 76b1e59fa..616256924 100644 --- a/internal/runtime/provider.go +++ b/internal/runtime/provider.go @@ -45,6 +45,7 @@ type providerInvocation struct { PromptFile string Driver string Options InvocationOptions + SOP bool } // Provider owns all behavior that varies by executor kind. The runtime remains diff --git a/internal/runtime/provider_codebuddy.go b/internal/runtime/provider_codebuddy.go index 5ebac93c4..0232b705e 100644 --- a/internal/runtime/provider_codebuddy.go +++ b/internal/runtime/provider_codebuddy.go @@ -1,6 +1,7 @@ package runtime import ( + "encoding/json" "path/filepath" "strings" @@ -55,6 +56,13 @@ func (codeBuddyProvider) Prepare(in providerInvocation) (CommandSpec, error) { argv := buildProviderArgs(in) argv = dropArgWithValue(argv, "--resume") argv = isolateCodeBuddyFlagsWithSource(argv, "none") + if in.SOP { + if !hasArg(argv, "-p") && !hasArg(argv, "--print") { + argv = append(argv, "-p") + } + argv = append(dropArgWithValue(argv, "--input-format", "--output-format"), + "--input-format", "stream-json", "--output-format", "stream-json") + } argv = appendEffortArgs(argv, in.Executor.Effort) if in.Compiled.HasMCP { // --tools is a built-in allowlist. CodeBuddy also applies it to MCP @@ -71,17 +79,32 @@ func (codeBuddyProvider) Prepare(in providerInvocation) (CommandSpec, error) { if sessionID := strings.TrimSpace(in.Options.ResumeSessionID); sessionID != "" { argv = append(argv, "--resume", sessionID) } - return CommandSpec{ - // CodeBuddy declares --plugin-dir as variadic (). Terminate - // option parsing explicitly so the positional prompt is not consumed as - // another plugin directory. - Argv: append(argv, "--", positionalPrompt(in)), + command := CommandSpec{ + // End the variadic --plugin-dir list before any positional prompt. + Argv: append(argv, "--"), Provider: "codebuddy", CredentialBindings: []CredentialBinding{BindCodeBuddy, BindGit, BindMCP}, PrivateHome: true, HookOutput: in.Compiled.HookOutput, Telemetry: &options, - }, nil + } + prompt := positionalPrompt(in) + if !in.SOP { + command.Argv = append(command.Argv, prompt) + return command, nil + } + input, err := json.Marshal(map[string]any{ + "type": "user", + "message": map[string]string{ + "role": "user", + "content": prompt, + }, + }) + if err != nil { + return CommandSpec{}, err + } + command.codeBuddySOPInput = append(input, '\n') + return command, nil } func (codeBuddyProvider) Protocol(ex domain.ExecutorDefinition, sink EventSink) *protocolAdapter { diff --git a/internal/runtime/runner.go b/internal/runtime/runner.go index 9fe480f2d..fddc26cfe 100644 --- a/internal/runtime/runner.go +++ b/internal/runtime/runner.go @@ -10,7 +10,7 @@ import ( "path/filepath" "slices" "strings" - "time" + "sync/atomic" "unicode/utf8" ) @@ -69,7 +69,7 @@ func (r *ExecutorRunner) Run(ctx context.Context, sb Sandbox, invocationID strin return "", err } } - command, err := provider.Prepare(providerInvocation{Executor: ex, Compiled: compiled, Prompt: prompt, PromptFile: promptRel, Driver: driver, Options: options}) + command, err := provider.Prepare(providerInvocation{Executor: ex, Compiled: compiled, Prompt: prompt, PromptFile: promptRel, Driver: driver, Options: options, SOP: true}) if err != nil { return "", err } @@ -92,28 +92,29 @@ func (r *ExecutorRunner) Run(ctx context.Context, sb Sandbox, invocationID strin } command = WithCommandEnvironment(command, hookExecutionEnvironment(options.Repositories)) adapter := provider.Protocol(ex, sink) + command, closeInput, err := adapter.openSOPInput(command) + if err != nil { + return "", err + } + defer closeInput() execCtx, cancel := context.WithCancel(ctx) defer cancel() stopObservation := provider.StartObservation(execCtx, compiled, sink) defer stopObservation() stopHookObservation := startHookObservation(execCtx, compiled, sink) defer stopHookObservation() + var stoppedAfterDrain atomic.Bool go func() { - select { - case <-adapter.Completed(): - // Some CLI hook processes stay alive after the protocol has emitted its - // terminal result. Give stdout a short drain window, then stop the process. - timer := time.NewTimer(2500 * time.Millisecond) - defer timer.Stop() - select { - case <-timer.C: - cancel() - case <-execCtx.Done(): - } - case <-execCtx.Done(): + if waitForProcessTerminalDrain(execCtx, adapter.Completed(), nil) { + stoppedAfterDrain.Store(true) + cancel() } }() raw, err := sb.Exec(execCtx, command, adapter.Handle) + adapter.finishCodeBuddyStream() + if adapter.codeBuddyStream != nil && stoppedAfterDrain.Load() && ctx.Err() == nil { + err = nil + } output := strings.TrimSpace(adapter.VisibleOutput()) if adapter.Failed() { if isMaxTurnsBudget(adapter.Result(), raw, err) { @@ -217,7 +218,7 @@ func (r *ExecutorRunner) PrepareRemote(workspace string, inv RemoteInvocation) ( return nil, err } } - command, err := provider.Prepare(providerInvocation{Executor: inv.Executor, Compiled: compiled, Prompt: inv.Prompt, PromptFile: promptRel, Driver: driver, Options: inv.Options}) + command, err := provider.Prepare(providerInvocation{Executor: inv.Executor, Compiled: compiled, Prompt: inv.Prompt, PromptFile: promptRel, Driver: driver, Options: inv.Options, SOP: true}) if err != nil { return nil, err } diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 7dbdb5e09..990f528aa 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -138,6 +138,9 @@ type CommandSpec struct { // Stdin is forwarded by local, Docker and remote conversation execution. Stdin io.Reader environment map[string]string + // codeBuddySOPInput is the first frame of a CodeBuddy SOP's stdin stream. + // The protocol observer opens and owns the pipe on the executing machine. + codeBuddySOPInput []byte // observeOutput receives raw bytes before process telemetry splits lines. observeOutput func(stream string, data []byte) // privateBinds are host directories bwrap binds into this one process diff --git a/internal/runtime/runtime_test.go b/internal/runtime/runtime_test.go index 96421bf0c..be9a15900 100644 --- a/internal/runtime/runtime_test.go +++ b/internal/runtime/runtime_test.go @@ -1763,8 +1763,8 @@ func TestCodeBuddyDropsToolsAllowlistWhenHTTPMCPPresent(t *testing.T) { if !containsArgPair(sb.argv, "--mcp-config", ".agentflow/config/closer/mcp.json") { t.Fatalf("mcp-config must point at the real config file, got %v", sb.argv) } - if sb.argv[len(sb.argv)-1] != "probe" { - t.Fatalf("short prompt must stay on argv, got %v", sb.argv) + if !containsArgPair(sb.argv, "--input-format", "stream-json") || containsArg(sb.argv, "probe") { + t.Fatalf("CodeBuddy SOP prompt must use the JSON input stream, got %v", sb.argv) } }