@@ -120,16 +120,30 @@ def main() -> None:
120120
121121 try :
122122 client = Anthropic (api_key = api_key )
123- response = client .messages .create (
123+ with client .messages .stream (
124124 model = os .environ .get ("AUTOCMD_MODEL" , DEFAULT_MODEL ),
125125 max_tokens = 200 ,
126126 messages = [{"role" : "user" , "content" : f"Convert to { os .environ .get ('SHELL' , 'bash' )} command (no markdown): { ' ' .join (sys .argv [1 :])} " }]
127- )
128- cmd = re .sub (r'^```\w*\n?|```$' , '' , response .content [0 ].text ).strip ()
129- if not cmd :
130- print ("No command generated" , file = sys .stderr )
131- sys .exit (1 )
132- print (cmd )
127+ ) as stream :
128+ full_response = ""
129+ for text in stream .text_stream :
130+ print (text , end = "" , flush = True , file = sys .stderr )
131+ full_response += text
132+
133+ # Clear the stderr line so the final command is clean on stdout
134+ # \r goes to start of line, \033[K clears line
135+ if sys .stderr .isatty ():
136+ print ("\r \033 [K" , end = "" , file = sys .stderr , flush = True )
137+ else :
138+ # If not a TTY, just print a newline
139+ print ("" , file = sys .stderr )
140+
141+ cmd = re .sub (r'^```\w*\n?|```$' , '' , full_response ).strip ()
142+ if not cmd :
143+ print ("No command generated" , file = sys .stderr )
144+ sys .exit (1 )
145+ print (cmd )
146+
133147 except KeyboardInterrupt :
134148 print ("\n Cancelled" , file = sys .stderr )
135149 sys .exit (130 )
0 commit comments