From 449994f1201effe454fc185cd06386aab2c182b0 Mon Sep 17 00:00:00 2001 From: Siddhant Choudhary <28786196+i-m-sid@users.noreply.github.com> Date: Wed, 24 Sep 2025 02:49:32 +0530 Subject: [PATCH] feat: output-format flag to stream json output (#2471) Co-authored-by: Siddhant Choudhary Co-authored-by: rekram1-node --- packages/opencode/src/cli/cmd/run.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/packages/opencode/src/cli/cmd/run.ts b/packages/opencode/src/cli/cmd/run.ts index e5aa7010..07cc10a7 100644 --- a/packages/opencode/src/cli/cmd/run.ts +++ b/packages/opencode/src/cli/cmd/run.ts @@ -64,6 +64,12 @@ export const RunCommand = cmd({ type: "string", describe: "agent to use", }) + .option("format", { + type: "string", + choices: ["default", "json"], + default: "default", + describe: "format: default (formatted) or json (raw JSON events)", + }) }, handler: async (args) => { let message = args.message.join(" ") @@ -144,6 +150,20 @@ export const RunCommand = cmd({ ) } + function outputJsonEvent(type: string, data: any) { + if (args.format === "json") { + const jsonEvent = { + type, + timestamp: Date.now(), + sessionID: session?.id, + ...data, + } + process.stdout.write(JSON.stringify(jsonEvent) + "\n") + return true + } + return false + } + let text = "" Bus.subscribe(MessageV2.Event.PartUpdated, async (evt) => { @@ -152,6 +172,7 @@ export const RunCommand = cmd({ const part = evt.properties.part if (part.type === "tool" && part.state.status === "completed") { + if (outputJsonEvent("tool_use", { part })) return const [tool, color] = TOOL[part.tool] ?? [part.tool, UI.Style.TEXT_INFO_BOLD] const title = part.state.title || @@ -169,6 +190,7 @@ export const RunCommand = cmd({ text = part.text if (part.time?.end) { + if (outputJsonEvent("text", { part })) return UI.empty() UI.println(UI.markdown(text)) UI.empty() @@ -189,6 +211,7 @@ export const RunCommand = cmd({ } errorMsg = errorMsg ? errorMsg + "\n" + err : err + if (outputJsonEvent("error", { error })) return UI.error(err) }) @@ -225,6 +248,7 @@ export const RunCommand = cmd({ const isPiped = !process.stdout.isTTY if (isPiped) { const match = result.parts.findLast((x: any) => x.type === "text") as any + if (outputJsonEvent("text", { text: match })) return if (match) process.stdout.write(UI.markdown(match.text)) if (errorMsg) process.stdout.write(errorMsg) }