@@ -64,6 +64,12 @@ export const RunCommand = cmd({
6464 type : "string" ,
6565 describe : "agent to use" ,
6666 } )
67+ . option ( "format" , {
68+ type : "string" ,
69+ choices : [ "default" , "json" ] ,
70+ default : "default" ,
71+ describe : "format: default (formatted) or json (raw JSON events)" ,
72+ } )
6773 } ,
6874 handler : async ( args ) => {
6975 let message = args . message . join ( " " )
@@ -144,6 +150,20 @@ export const RunCommand = cmd({
144150 )
145151 }
146152
153+ function outputJsonEvent ( type : string , data : any ) {
154+ if ( args . format === "json" ) {
155+ const jsonEvent = {
156+ type,
157+ timestamp : Date . now ( ) ,
158+ sessionID : session ?. id ,
159+ ...data ,
160+ }
161+ process . stdout . write ( JSON . stringify ( jsonEvent ) + "\n" )
162+ return true
163+ }
164+ return false
165+ }
166+
147167 let text = ""
148168
149169 Bus . subscribe ( MessageV2 . Event . PartUpdated , async ( evt ) => {
@@ -152,6 +172,7 @@ export const RunCommand = cmd({
152172 const part = evt . properties . part
153173
154174 if ( part . type === "tool" && part . state . status === "completed" ) {
175+ if ( outputJsonEvent ( "tool_use" , { part } ) ) return
155176 const [ tool , color ] = TOOL [ part . tool ] ?? [ part . tool , UI . Style . TEXT_INFO_BOLD ]
156177 const title =
157178 part . state . title ||
@@ -169,6 +190,7 @@ export const RunCommand = cmd({
169190 text = part . text
170191
171192 if ( part . time ?. end ) {
193+ if ( outputJsonEvent ( "text" , { part } ) ) return
172194 UI . empty ( )
173195 UI . println ( UI . markdown ( text ) )
174196 UI . empty ( )
@@ -189,6 +211,7 @@ export const RunCommand = cmd({
189211 }
190212 errorMsg = errorMsg ? errorMsg + "\n" + err : err
191213
214+ if ( outputJsonEvent ( "error" , { error } ) ) return
192215 UI . error ( err )
193216 } )
194217
@@ -225,6 +248,7 @@ export const RunCommand = cmd({
225248 const isPiped = ! process . stdout . isTTY
226249 if ( isPiped ) {
227250 const match = result . parts . findLast ( ( x : any ) => x . type === "text" ) as any
251+ if ( outputJsonEvent ( "text" , { text : match } ) ) return
228252 if ( match ) process . stdout . write ( UI . markdown ( match . text ) )
229253 if ( errorMsg ) process . stdout . write ( errorMsg )
230254 }
0 commit comments