|
| 1 | +import { exec } from "node:child_process"; |
| 2 | +import { prompts } from "@getpochi/common"; |
| 3 | +import { extractWorkflowBashCommands } from "@getpochi/common/message-utils"; |
| 4 | +import type { UIMessage } from "ai"; |
| 5 | + |
| 6 | +export function createOnOverrideMessages(cwd: string) { |
| 7 | + return async function onOverrideMessages({ |
| 8 | + messages, |
| 9 | + }: { messages: UIMessage[] }) { |
| 10 | + const lastMessage = messages.at(-1); |
| 11 | + if (lastMessage?.role === "user") { |
| 12 | + await appendWorkflowBashOutputs(cwd, lastMessage); |
| 13 | + } |
| 14 | + }; |
| 15 | +} |
| 16 | + |
| 17 | +async function appendWorkflowBashOutputs(cwd: string, message: UIMessage) { |
| 18 | + if (message.role !== "user") return; |
| 19 | + |
| 20 | + const commands = extractWorkflowBashCommands(message); |
| 21 | + if (!commands.length) return []; |
| 22 | + |
| 23 | + const bashCommandResults: { |
| 24 | + command: string; |
| 25 | + output: string; |
| 26 | + error?: string; |
| 27 | + }[] = []; |
| 28 | + for (const command of commands) { |
| 29 | + try { |
| 30 | + const { output, error } = await executeBashCommand(cwd, command); |
| 31 | + bashCommandResults.push({ command, output, error }); |
| 32 | + } catch (e) { |
| 33 | + const error = e instanceof Error ? e.message : String(e); |
| 34 | + bashCommandResults.push({ command, output: "", error }); |
| 35 | + // The AbortError is a specific error that should stop the whole process. |
| 36 | + if (e instanceof Error && e.name === "AbortError") { |
| 37 | + break; |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + if (bashCommandResults.length) { |
| 43 | + prompts.injectBashOutputs(message, bashCommandResults); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +function executeBashCommand( |
| 48 | + cwd: string, |
| 49 | + command: string, |
| 50 | +): Promise<{ output: string; error?: string }> { |
| 51 | + return new Promise((resolve) => { |
| 52 | + exec(command, { cwd }, (error, stdout, stderr) => { |
| 53 | + if (error) { |
| 54 | + resolve({ output: stdout, error: stderr || error.message }); |
| 55 | + } else { |
| 56 | + resolve({ output: stdout }); |
| 57 | + } |
| 58 | + }); |
| 59 | + }); |
| 60 | +} |
0 commit comments