@@ -124,6 +124,36 @@ async function resolveDiagnostics(opts: {
124124 return formatSubagentDiagnostics(stdout, stderr);
125125 }
126126
127+/**
128+ * Parse the structured output from a subagent subprocess.
129+ * Returns the parsed summary on success, or an error message string on failure.
130+ */
131+export function parseSubagentOutput(
132+ rawText: string,
133+ exitCode: number | null,
134+): SubagentSummary | string {
135+ const trimmed = rawText.trim();
136+ if (!trimmed) {
137+ return `Subagent subprocess produced no output (exit code ${String(exitCode)})`;
138+ }
139+
140+ let parsed: SubagentSummary & { error?: string };
141+ try {
142+ parsed = JSON.parse(trimmed) as SubagentSummary & { error?: string };
143+ } catch {
144+ return `Subagent subprocess wrote non-JSON output (exit code ${String(exitCode)}): ${trimmed.slice(0, 200)}`;
145+ }
146+
147+ if (parsed.error) {
148+ return `Subagent failed: ${parsed.error}`;
149+ }
150+ if (exitCode !== 0) {
151+ return `Subagent process exited with code ${String(exitCode)}`;
152+ }
153+
154+ return parsed;
155+}
156+
127157 export function createSubagentRunner(
128158 cwd: string,
129159 getCurrentModel: () => string,
@@ -214,45 +244,13 @@ export function createSubagentRunner(
214244 );
215245 }
216246
217- const trimmed = text.trim();
218- if (!trimmed) {
219- const diagnostics = await resolveDiagnostics({
220- stdoutTail,
221- stderrTail,
222- });
223- throw new Error(
224- `Subagent subprocess produced no output (exit code ${String(proc.exitCode)})${diagnostics}`,
225- );
226- }
227-
228- let parsed: SubagentSummary & { error?: string };
229- try {
230- parsed = JSON.parse(trimmed) as SubagentSummary & { error?: string };
231- } catch {
247+ const parsed = parseSubagentOutput(text, proc.exitCode);
248+ if (typeof parsed === "string") {
232249 const diagnostics = await resolveDiagnostics({
233250 stdoutTail,
234251 stderrTail,
235252 });
236- throw new Error(
237- `Subagent subprocess wrote non-JSON output (exit code ${String(proc.exitCode)}): ${trimmed.slice(0, 200)}${diagnostics}`,
238- );
239- }
240-
241- if (parsed.error) {
242- const diagnostics = await resolveDiagnostics({
243- stdoutTail,
244- stderrTail,
245- });
246- throw new Error(`Subagent failed: ${parsed.error}${diagnostics}`);
247- }
248- if (proc.exitCode !== 0) {
249- const diagnostics = await resolveDiagnostics({
250- stdoutTail,
251- stderrTail,
252- });
253- throw new Error(
254- `Subagent process exited with code ${String(proc.exitCode)}${diagnostics}`,
255- );
253+ throw new Error(`${parsed}${diagnostics}`);
256254 }
257255
258256 const output: SubagentOutput = {