@@ -14,7 +14,9 @@ import {
1414 promptIdContext ,
1515 OutputFormat ,
1616 JsonFormatter ,
17+ StreamJsonFormatter ,
1718 uiTelemetryService ,
19+ streamingTelemetryService ,
1820} from '@blocksuser/gemini-cli-core' ;
1921import type { Content , Part } from '@google/genai' ;
2022
@@ -41,6 +43,18 @@ export async function runNonInteractive(
4143
4244 try {
4345 consolePatcher . patch ( ) ;
46+
47+ // Set up streaming telemetry for stream-json format
48+ const isStreamJsonFormat = config . getOutputFormat ( ) === OutputFormat . STREAM_JSON ;
49+ let streamJsonFormatter : StreamJsonFormatter | undefined ;
50+
51+ if ( isStreamJsonFormat ) {
52+ streamJsonFormatter = new StreamJsonFormatter ( ) ;
53+ streamingTelemetryService . enable ( ) ;
54+ streamingTelemetryService . addTelemetryListener ( ( event ) => {
55+ process . stdout . write ( streamJsonFormatter ! . formatTelemetryBlock ( event ) + '\n' ) ;
56+ } ) ;
57+ }
4458 // Handle EPIPE errors when the output is piped to a command that closes early.
4559 process . stdout . on ( 'error' , ( err : NodeJS . ErrnoException ) => {
4660 if ( err . code === 'EPIPE' ) {
@@ -123,6 +137,11 @@ export async function runNonInteractive(
123137 if ( event . type === GeminiEventType . Content ) {
124138 if ( config . getOutputFormat ( ) === OutputFormat . JSON ) {
125139 responseText += event . value ;
140+ } else if ( config . getOutputFormat ( ) === OutputFormat . STREAM_JSON ) {
141+ responseText += event . value ;
142+ if ( streamJsonFormatter ) {
143+ process . stdout . write ( streamJsonFormatter . formatContentBlock ( event . value ) + '\n' ) ;
144+ }
126145 } else {
127146 process . stdout . write ( event . value ) ;
128147 }
@@ -162,6 +181,11 @@ export async function runNonInteractive(
162181 const formatter = new JsonFormatter ( ) ;
163182 const stats = uiTelemetryService . getMetrics ( ) ;
164183 process . stdout . write ( formatter . format ( responseText , stats ) ) ;
184+ } else if ( config . getOutputFormat ( ) === OutputFormat . STREAM_JSON ) {
185+ if ( streamJsonFormatter ) {
186+ const stats = uiTelemetryService . getMetrics ( ) ;
187+ process . stdout . write ( streamJsonFormatter . formatFinalBlock ( responseText , stats ) + '\n' ) ;
188+ }
165189 } else {
166190 process . stdout . write ( '\n' ) ; // Ensure a final newline
167191 }
@@ -172,6 +196,9 @@ export async function runNonInteractive(
172196 handleError ( error , config ) ;
173197 } finally {
174198 consolePatcher . cleanup ( ) ;
199+ if ( config . getOutputFormat ( ) === OutputFormat . STREAM_JSON ) {
200+ streamingTelemetryService . disable ( ) ;
201+ }
175202 if ( isTelemetrySdkInitialized ( ) ) {
176203 await shutdownTelemetry ( config ) ;
177204 }
0 commit comments