xonecas.io
64875
Mc

mini-coder / commit d30923b

refactor: deduplicate code and flatten subagent error handling

- Remove tools/shared.ts (dead re-export of resolvePath)
- Export extractObjectMessage from error-utils.ts, import in error-parse.ts
  (eliminates jscpd-flagged 15-line clone)
- Extract parseSubagentOutput() pure function from subagent-runner.ts,
  collapsing 4 separate resolveDiagnostics() calls into 1
- Add tests for parseSubagentOutput covering all branches
- Duplication down from 0.21% to 0.12%, tests 392→397

xonecas2026-03-18 d30923b4c5491c7528de4736c28cc1b1766ed1c9 parent 896bd9d

6 files changed

src/agent/subagent-runner.test.ts+55−1
@@ -1,5 +1,9 @@
11 import { describe, expect, test } from "bun:test";
2-import { resolveMcCommand, tailTextFromChunks } from "./subagent-runner.ts";
2+import {
3+ parseSubagentOutput,
4+ resolveMcCommand,
5+ tailTextFromChunks,
6+} from "./subagent-runner.ts";
37
48 describe("tailTextFromChunks", () => {
59 test("keeps only the byte tail without buffering everything", () => {
@@ -47,3 +51,53 @@ describe("resolveMcCommand", () => {
4751 ]);
4852 });
4953 });
54+
55+describe("parseSubagentOutput", () => {
56+ test("returns error string for empty output", () => {
57+ const result = parseSubagentOutput("", 0);
58+ expect(typeof result).toBe("string");
59+ expect(result).toContain("no output");
60+ });
61+
62+ test("returns error string for non-JSON output", () => {
63+ const result = parseSubagentOutput("not json", 0);
64+ expect(typeof result).toBe("string");
65+ expect(result).toContain("non-JSON");
66+ });
67+
68+ test("returns error string when parsed JSON has error field", () => {
69+ const result = parseSubagentOutput(
70+ JSON.stringify({
71+ error: "something broke",
72+ result: "",
73+ inputTokens: 0,
74+ outputTokens: 0,
75+ }),
76+ 0,
77+ );
78+ expect(typeof result).toBe("string");
79+ expect(result).toContain("something broke");
80+ });
81+
82+ test("returns error string for non-zero exit code", () => {
83+ const result = parseSubagentOutput(
84+ JSON.stringify({ result: "ok", inputTokens: 10, outputTokens: 5 }),
85+ 1,
86+ );
87+ expect(typeof result).toBe("string");
88+ expect(result).toContain("exit");
89+ });
90+
91+ test("returns parsed summary on success", () => {
92+ const result = parseSubagentOutput(
93+ JSON.stringify({ result: "done", inputTokens: 100, outputTokens: 50 }),
94+ 0,
95+ );
96+ expect(typeof result).toBe("object");
97+ expect(result).toEqual({
98+ result: "done",
99+ inputTokens: 100,
100+ outputTokens: 50,
101+ });
102+ });
103+});
src/agent/subagent-runner.ts+33−35
@@ -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 = {
src/agent/tools.test.ts+1−1
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
22 import { mkdtempSync, rmSync } from "node:fs";
33 import { homedir, tmpdir } from "node:os";
44 import { join } from "node:path";
5-import { resolvePath } from "../tools/shared.ts";
5+import { resolvePath } from "../internal/file-edit/path.ts";
66 import { buildToolSet } from "./tools.ts";
77
88 let cwd = "";
src/cli/error-parse.ts+1−16
@@ -5,6 +5,7 @@ import {
55 NoSuchModelError,
66 RetryError,
77 } from "ai";
8+import { extractObjectMessage } from "../llm-api/error-utils.ts";
89
910 function safeStringifyErrorObject(value: object): string {
1011 try {
@@ -19,22 +20,6 @@ function safeStringifyErrorObject(value: object): string {
1920 }
2021 }
2122
22-function extractObjectMessage(err: object): string | null {
23- const record = err as Record<string, unknown>;
24- const direct = record.message;
25- if (typeof direct === "string" && direct.trim()) return direct.trim();
26-
27- const nested = record.error;
28- if (typeof nested === "object" && nested !== null) {
29- const nestedMessage = (nested as Record<string, unknown>).message;
30- if (typeof nestedMessage === "string" && nestedMessage.trim()) {
31- return nestedMessage.trim();
32- }
33- }
34-
35- return null;
36-}
37-
3823 function toUserErrorMessage(err: unknown): string {
3924 if (err instanceof Error) {
4025 const msg = err.message.trim();
src/llm-api/error-utils.ts+1−1
@@ -1,4 +1,4 @@
1-function extractObjectMessage(error: object): string | null {
1+export function extractObjectMessage(error: object): string | null {
22 const record = error as Record<string, unknown>;
33 const direct = record.message;
44 if (typeof direct === "string" && direct.trim()) return direct.trim();
src/tools/shared.ts+0−3
@@ -1,3 +0,0 @@
1-import { resolvePath } from "../internal/file-edit/path.ts";
2-
3-export { resolvePath };