bone-agent 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +184 -0
  3. package/bin/npm-wrapper.js +235 -0
  4. package/bin/rg +0 -0
  5. package/bin/rg.exe +0 -0
  6. package/config.yaml.example +133 -0
  7. package/package.json +53 -0
  8. package/requirements.txt +9 -0
  9. package/src/__init__.py +11 -0
  10. package/src/core/__init__.py +1 -0
  11. package/src/core/agentic.py +1054 -0
  12. package/src/core/chat_manager.py +1552 -0
  13. package/src/core/config_manager.py +247 -0
  14. package/src/core/cron.py +527 -0
  15. package/src/core/cron_allowlist.py +118 -0
  16. package/src/core/memory.py +232 -0
  17. package/src/core/retry.py +71 -0
  18. package/src/core/sub_agent.py +326 -0
  19. package/src/core/tool_approval.py +220 -0
  20. package/src/core/tool_feedback.py +778 -0
  21. package/src/exceptions.py +79 -0
  22. package/src/llm/__init__.py +1 -0
  23. package/src/llm/client.py +171 -0
  24. package/src/llm/config.py +466 -0
  25. package/src/llm/prompts.py +735 -0
  26. package/src/llm/providers.py +417 -0
  27. package/src/llm/streaming.py +163 -0
  28. package/src/llm/token_tracker.py +368 -0
  29. package/src/tools/__init__.py +212 -0
  30. package/src/tools/constants.py +59 -0
  31. package/src/tools/create_file.py +136 -0
  32. package/src/tools/directory.py +389 -0
  33. package/src/tools/edit.py +543 -0
  34. package/src/tools/file_reader.py +322 -0
  35. package/src/tools/helpers/__init__.py +105 -0
  36. package/src/tools/helpers/base.py +550 -0
  37. package/src/tools/helpers/converters.py +44 -0
  38. package/src/tools/helpers/file_helpers.py +189 -0
  39. package/src/tools/helpers/formatters.py +411 -0
  40. package/src/tools/helpers/loader.py +231 -0
  41. package/src/tools/helpers/parallel_executor.py +231 -0
  42. package/src/tools/helpers/path_resolver.py +226 -0
  43. package/src/tools/helpers/plugin_manifest.py +156 -0
  44. package/src/tools/obsidian.py +96 -0
  45. package/src/tools/review_sub_agent.py +189 -0
  46. package/src/tools/rg_search.py +393 -0
  47. package/src/tools/search_plugins.py +109 -0
  48. package/src/tools/select_option.py +593 -0
  49. package/src/tools/shell.py +302 -0
  50. package/src/tools/sub_agent.py +139 -0
  51. package/src/tools/task_list.py +269 -0
  52. package/src/tools/web_search.py +61 -0
  53. package/src/ui/__init__.py +1 -0
  54. package/src/ui/banner.py +87 -0
  55. package/src/ui/commands.py +2694 -0
  56. package/src/ui/displays.py +213 -0
  57. package/src/ui/loader.py +284 -0
  58. package/src/ui/main.py +646 -0
  59. package/src/ui/prompt_utils.py +113 -0
  60. package/src/ui/setting_selector.py +590 -0
  61. package/src/ui/setup_wizard.py +294 -0
  62. package/src/ui/sub_agent_panel.py +234 -0
  63. package/src/ui/tool_confirmation.py +215 -0
  64. package/src/utils/__init__.py +1 -0
  65. package/src/utils/citation_parser.py +199 -0
  66. package/src/utils/editor.py +158 -0
  67. package/src/utils/gitignore_filter.py +149 -0
  68. package/src/utils/logger.py +254 -0
  69. package/src/utils/paths.py +30 -0
  70. package/src/utils/result_parsers.py +108 -0
  71. package/src/utils/safe_commands.py +243 -0
  72. package/src/utils/settings.py +174 -0
  73. package/src/utils/validation.py +191 -0
  74. package/src/utils/web_search.py +173 -0
@@ -0,0 +1,417 @@
1
+ """Provider-specific request/response handlers.
2
+
3
+ This module isolates provider-specific API quirks into handler classes.
4
+ """
5
+
6
+ import json
7
+ from typing import Optional, Dict, Any, Iterator
8
+ import requests
9
+
10
+ from exceptions import LLMResponseError
11
+
12
+
13
+ class OpenAIHandler:
14
+ """Handler for OpenAI-compatible providers.
15
+
16
+ Supports: OpenAI, OpenRouter, GLM, Gemini, Kimi, MiniMax
17
+ """
18
+
19
+ def build_headers(self, config: Dict[str, Any]) -> Dict[str, str]:
20
+ """Build request headers."""
21
+ headers = {"Content-Type": "application/json"}
22
+ if config.get("type") == "api" and config.get("api_key"):
23
+ headers["Authorization"] = f"Bearer {config['api_key']}"
24
+ if "headers_extra" in config:
25
+ headers.update(config["headers_extra"])
26
+ return headers
27
+
28
+ def build_payload(self, config: Dict[str, Any], messages: list,
29
+ tools: Optional[list] = None, stream: bool = True) -> Dict[str, Any]:
30
+ """Build request payload."""
31
+ payload = {**config.get("payload", {}), "messages": messages, "stream": stream}
32
+
33
+ # Ensure model is set from config if not in payload
34
+ if "model" not in payload:
35
+ model_name = config.get("api_model") or config.get("model")
36
+ if model_name:
37
+ payload["model"] = model_name
38
+
39
+ # Add tools if provided (OpenAI format)
40
+ if tools:
41
+ payload["tools"] = tools
42
+
43
+ # Set default parameters if not in config
44
+ if "temperature" not in payload and config.get("allow_temperature", True):
45
+ payload["temperature"] = config.get("default_temperature", 0.1)
46
+ if "top_p" not in payload and config.get("allow_top_p", True):
47
+ payload["top_p"] = config.get("default_top_p", 0.9)
48
+
49
+ return payload
50
+
51
+ def parse_response(self, response_json: Dict[str, Any]) -> Dict[str, Any]:
52
+ """Parse non-streaming response (already in OpenAI format)."""
53
+ return response_json
54
+
55
+ def parse_stream(self, response: requests.Response) -> Iterator[Dict[str, Any]]:
56
+ """Parse streaming response.
57
+
58
+ Yields text chunks, and finally yields a dict with __usage__ key.
59
+ """
60
+ usage_data = None
61
+
62
+ for line in response.iter_lines():
63
+ if line:
64
+ line = line.decode('utf-8')
65
+
66
+ # Skip OpenRouter comments (start with ':')
67
+ if line.startswith(':'):
68
+ continue
69
+
70
+ if line.startswith('data: '):
71
+ data_str = line[6:]
72
+ if data_str.strip() == '[DONE]':
73
+ break
74
+
75
+ try:
76
+ data = json.loads(data_str)
77
+
78
+ # Check for mid-stream errors
79
+ if 'error' in data:
80
+ error_msg = data.get('error', {}).get('message', 'Unknown streaming error')
81
+ raise LLMResponseError(
82
+ f"Streaming error: {error_msg}",
83
+ details={"error_data": data.get('error')}
84
+ )
85
+
86
+ # Capture usage data if present (usually in final chunk)
87
+ if 'usage' in data:
88
+ usage_data = dict(data['usage'])
89
+ # Promote top-level cost into usage dict (OpenRouter places it here)
90
+ if 'cost' in data:
91
+ usage_data['cost'] = data['cost']
92
+
93
+ choices = data.get('choices', [])
94
+ if choices:
95
+ delta = choices[0].get('delta', {})
96
+ content = delta.get('content')
97
+ if content is not None:
98
+ yield content
99
+
100
+ except json.JSONDecodeError as e:
101
+ raise LLMResponseError(
102
+ f"Failed to decode streaming response",
103
+ details={"original_error": str(e)}
104
+ )
105
+
106
+ # Yield usage data as final item if captured
107
+ if usage_data:
108
+ yield {'__usage__': usage_data}
109
+
110
+
111
+ class AnthropicHandler:
112
+ """Handler for Anthropic API.
113
+
114
+ Anthropic has significant differences from OpenAI:
115
+ - Different endpoint (/messages vs /chat/completions)
116
+ - Different message format (content arrays vs strings)
117
+ - Different tool format (flat vs nested)
118
+ - Different streaming (SSE with event types vs data: lines)
119
+ - Different headers (x-api-key vs Authorization: Bearer)
120
+ - Different parameters (requires max_tokens, forbids top_p with temperature)
121
+ """
122
+
123
+ def build_headers(self, config: Dict[str, Any]) -> Dict[str, str]:
124
+ """Build request headers (Anthropic uses x-api-key)."""
125
+ headers = {"Content-Type": "application/json"}
126
+ if config.get("type") == "api" and config.get("api_key"):
127
+ headers["x-api-key"] = config['api_key']
128
+ if "headers_extra" in config:
129
+ headers.update(config["headers_extra"])
130
+ return headers
131
+
132
+ def build_payload(self, config: Dict[str, Any], messages: list,
133
+ tools: Optional[list] = None, stream: bool = True) -> Dict[str, Any]:
134
+ """Build request payload (Anthropic format)."""
135
+ # Extract system messages to top-level parameter
136
+ system_messages = [msg["content"] for msg in messages if msg.get("role") == "system"]
137
+ system_content = "\n".join(system_messages) if system_messages else None
138
+ non_system_messages = [msg for msg in messages if msg.get("role") != "system"]
139
+
140
+ # Convert messages and tools to Anthropic format
141
+ anthropic_messages = self._convert_messages_to_anthropic(non_system_messages)
142
+ anthropic_tools = self._convert_tools_to_anthropic(tools) if tools else None
143
+
144
+ payload = {**config.get("payload", {}), "messages": anthropic_messages, "stream": stream}
145
+
146
+ # Ensure model is set from config if not in payload
147
+ if "model" not in payload:
148
+ model_name = config.get("api_model") or config.get("model")
149
+ if model_name:
150
+ payload["model"] = model_name
151
+
152
+ if system_content:
153
+ payload["system"] = system_content
154
+ if anthropic_tools:
155
+ payload["tools"] = anthropic_tools
156
+
157
+ # Set default parameters (Anthropic requires max_tokens)
158
+ if "temperature" not in payload and config.get("allow_temperature", True):
159
+ payload["temperature"] = config.get("default_temperature", 0.1)
160
+ if "max_tokens" not in payload:
161
+ payload["max_tokens"] = config.get("max_tokens", 4096)
162
+
163
+ # Anthropic doesn't allow both temperature and top_p
164
+ # Only set top_p if temperature is not set
165
+ if "temperature" not in payload and "top_p" not in payload:
166
+ payload["top_p"] = config.get("default_top_p", 0.9)
167
+
168
+ return payload
169
+
170
+ def parse_response(self, response_json: Dict[str, Any]) -> Dict[str, Any]:
171
+ """Convert Anthropic response format to OpenAI-style format."""
172
+ # Anthropic format: {"content": [{"type": "text", "text": "..."}], "usage": {...}}
173
+ # OpenAI format: {"choices": [{"message": {"content": "..."}}], "usage": {...}}
174
+
175
+ # Convert Anthropic usage format (input_tokens/output_tokens) to OpenAI format (prompt_tokens/completion_tokens)
176
+ anthropic_usage = response_json.get("usage", {})
177
+ openai_format_usage = {
178
+ 'prompt_tokens': anthropic_usage.get('input_tokens', 0),
179
+ 'completion_tokens': anthropic_usage.get('output_tokens', 0),
180
+ 'total_tokens': anthropic_usage.get('input_tokens', 0) + anthropic_usage.get('output_tokens', 0),
181
+ }
182
+ # Preserve Anthropic cache token fields for the token tracker
183
+ if 'cache_read_input_tokens' in anthropic_usage:
184
+ openai_format_usage['cache_read_input_tokens'] = anthropic_usage['cache_read_input_tokens']
185
+ if 'cache_creation_input_tokens' in anthropic_usage:
186
+ openai_format_usage['cache_creation_input_tokens'] = anthropic_usage['cache_creation_input_tokens']
187
+
188
+ result = {
189
+ "choices": [],
190
+ "usage": openai_format_usage
191
+ }
192
+
193
+ # Extract content from Anthropic's content array
194
+ content_blocks = response_json.get("content", [])
195
+ text_parts = []
196
+ tool_calls = []
197
+
198
+ for block in content_blocks:
199
+ if block.get("type") == "text":
200
+ text_parts.append(block.get("text", ""))
201
+ elif block.get("type") == "tool_use":
202
+ # Convert Anthropic tool_use to OpenAI tool_calls format
203
+ tool_calls.append({
204
+ "id": block.get("id"),
205
+ "type": "function",
206
+ "function": {
207
+ "name": block.get("name"),
208
+ "arguments": json.dumps(block.get("input", {}))
209
+ }
210
+ })
211
+
212
+ # Build OpenAI-style message
213
+ message = {"role": "assistant"}
214
+
215
+ # Include either text content or tool calls
216
+ if tool_calls:
217
+ message["content"] = None
218
+ message["tool_calls"] = tool_calls
219
+ else:
220
+ message["content"] = "".join(text_parts)
221
+
222
+ result["choices"].append({"message": message})
223
+
224
+ return result
225
+
226
+ def parse_stream(self, response: requests.Response) -> Iterator[Dict[str, Any]]:
227
+ """Parse Anthropic's SSE-based streaming response.
228
+
229
+ Yields text chunks, and finally yields a dict with __usage__ key.
230
+
231
+ Anthropic splits usage across two events:
232
+ - message_start: contains input_tokens
233
+ - message_delta: contains output_tokens
234
+ We merge both and convert to OpenAI format (prompt_tokens/completion_tokens).
235
+ """
236
+ usage_data = {}
237
+
238
+ for line in response.iter_lines():
239
+ if line:
240
+ line = line.decode('utf-8')
241
+
242
+ # Anthropic uses SSE format: "event: <type>" followed by "data: <json>"
243
+ if line.startswith('data: '):
244
+ data_str = line[6:]
245
+ try:
246
+ data = json.loads(data_str)
247
+
248
+ # Check for errors
249
+ if data.get('type') == 'error':
250
+ error_msg = data.get('error', {}).get('message', 'Unknown error')
251
+ raise LLMResponseError(
252
+ f"Anthropic streaming error: {error_msg}",
253
+ details={"error_data": data.get('error')}
254
+ )
255
+
256
+ # Capture input_tokens from message_start events
257
+ if data.get('type') == 'message_start':
258
+ message_usage = data.get('message', {}).get('usage', {})
259
+ if message_usage:
260
+ usage_data.update(message_usage)
261
+
262
+ # Capture output_tokens from message_delta events
263
+ if data.get('type') == 'message_delta' and 'usage' in data:
264
+ usage_data.update(data['usage'])
265
+
266
+ # Extract text from content_block_delta events
267
+ if data.get('type') == 'content_block_delta':
268
+ delta = data.get('delta', {})
269
+ if delta.get('type') == 'text_delta':
270
+ text = delta.get('text', '')
271
+ if text:
272
+ yield text
273
+
274
+ except json.JSONDecodeError as e:
275
+ raise LLMResponseError(
276
+ f"Failed to decode Anthropic streaming response",
277
+ details={"original_error": str(e)}
278
+ )
279
+
280
+ # Yield usage data as final item if captured
281
+ # Convert Anthropic format (input_tokens/output_tokens) to OpenAI format (prompt_tokens/completion_tokens)
282
+ if usage_data:
283
+ openai_format_usage = {
284
+ 'prompt_tokens': usage_data.get('input_tokens', 0),
285
+ 'completion_tokens': usage_data.get('output_tokens', 0),
286
+ 'total_tokens': usage_data.get('input_tokens', 0) + usage_data.get('output_tokens', 0),
287
+ }
288
+ # Preserve Anthropic cache token fields for the token tracker
289
+ if 'cache_read_input_tokens' in usage_data:
290
+ openai_format_usage['cache_read_input_tokens'] = usage_data['cache_read_input_tokens']
291
+ if 'cache_creation_input_tokens' in usage_data:
292
+ openai_format_usage['cache_creation_input_tokens'] = usage_data['cache_creation_input_tokens']
293
+ yield {'__usage__': openai_format_usage}
294
+
295
+ @staticmethod
296
+ def _convert_tools_to_anthropic(openai_tools: list) -> list:
297
+ """Convert OpenAI-style tool definitions to Anthropic format.
298
+
299
+ OpenAI format: {"type": "function", "function": {"name": "...", "parameters": {...}}}
300
+ Anthropic format: {"name": "...", "description": "...", "input_schema": {...}}
301
+ """
302
+ anthropic_tools = []
303
+
304
+ for openai_tool in openai_tools:
305
+ if openai_tool.get("type") == "function":
306
+ func = openai_tool.get("function", {})
307
+ anthropic_tool = {
308
+ "name": func.get("name"),
309
+ "description": func.get("description", ""),
310
+ "input_schema": func.get("parameters", {"type": "object", "properties": {}})
311
+ }
312
+ anthropic_tools.append(anthropic_tool)
313
+
314
+ return anthropic_tools
315
+
316
+ @staticmethod
317
+ def _convert_messages_to_anthropic(openai_messages: list) -> list:
318
+ """Convert OpenAI-style messages to Anthropic format.
319
+
320
+ Anthropic requires all content to be an array, not a string.
321
+
322
+ OpenAI format:
323
+ {"role": "user", "content": "text"}
324
+ {"role": "tool", "content": "...", "tool_call_id": "..."}
325
+
326
+ Anthropic format:
327
+ {"role": "user", "content": [{"type": "text", "text": "..."}]}
328
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "...", "content": "..."}]}
329
+ """
330
+ anthropic_messages = []
331
+
332
+ for msg in openai_messages:
333
+ # Handle tool result messages
334
+ if msg.get("role") == "tool":
335
+ anthropic_msg = {
336
+ "role": "user",
337
+ "content": [
338
+ {
339
+ "type": "tool_result",
340
+ "tool_use_id": msg.get("tool_call_id"),
341
+ "content": msg.get("content", "")
342
+ }
343
+ ]
344
+ }
345
+ anthropic_messages.append(anthropic_msg)
346
+ # Handle user and assistant messages - convert string content to array
347
+ elif msg.get("role") in ("user", "assistant"):
348
+ content = msg.get("content", "")
349
+ tool_calls = msg.get("tool_calls")
350
+
351
+ # Build content blocks array
352
+ content_blocks = []
353
+
354
+ # Add text content if present
355
+ if isinstance(content, str) and content.strip():
356
+ content_blocks.append({
357
+ "type": "text",
358
+ "text": content
359
+ })
360
+ elif isinstance(content, list):
361
+ # Already an array (Anthropic format), use as-is
362
+ anthropic_messages.append(msg)
363
+ continue
364
+
365
+ # Add tool_use blocks if present (for assistant messages with tool calls)
366
+ if tool_calls:
367
+ for tool_call in tool_calls:
368
+ content_blocks.append({
369
+ "type": "tool_use",
370
+ "id": tool_call.get("id"),
371
+ "name": tool_call.get("function", {}).get("name"),
372
+ "input": json.loads(tool_call.get("function", {}).get("arguments", "{}"))
373
+ })
374
+
375
+ # Only add message if we have content blocks (text or tool_use)
376
+ if content_blocks:
377
+ anthropic_msg = {
378
+ "role": msg.get("role"),
379
+ "content": content_blocks
380
+ }
381
+ anthropic_messages.append(anthropic_msg)
382
+ else:
383
+ # Other message types, pass through
384
+ anthropic_messages.append(msg)
385
+
386
+ return anthropic_messages
387
+
388
+
389
+ # Handler registry - maps provider names to handler classes
390
+ HANDLER_REGISTRY = {
391
+ "openai": OpenAIHandler,
392
+ "openrouter": OpenAIHandler,
393
+ "glm": OpenAIHandler,
394
+ "glm_plan": OpenAIHandler,
395
+ "gemini": OpenAIHandler,
396
+ "minimax": AnthropicHandler,
397
+ "minimax_plan": AnthropicHandler,
398
+ "kimi": OpenAIHandler,
399
+ "anthropic": AnthropicHandler,
400
+ "local": OpenAIHandler,
401
+ }
402
+
403
+
404
+ def get_handler(provider_name: str):
405
+ """Get handler instance for the given provider.
406
+
407
+ Args:
408
+ provider_name: Name of the provider
409
+
410
+ Returns:
411
+ Handler instance for the provider
412
+ """
413
+ handler_class = HANDLER_REGISTRY.get(provider_name.lower(), OpenAIHandler)
414
+ return handler_class()
415
+
416
+
417
+ __all__ = ['OpenAIHandler', 'AnthropicHandler', 'get_handler']
@@ -0,0 +1,163 @@
1
+ """Streaming response assembler for agentic mode.
2
+
3
+ Consumes a StreamWrapper yielding mixed delta dicts and assembles them into
4
+ a complete message dict (content + tool_calls), matching the format that
5
+ non-streaming responses already produce.
6
+
7
+ Usage:
8
+ stream = client.chat_completion(messages, stream=True, tools=tools)
9
+ assembler = StreamingResponse(stream, console, debug_mode=False)
10
+ message = assembler.consume() # iterates stream, prints text, assembles tool_calls
11
+ tool_calls = message.get("tool_calls")
12
+ usage = assembler.usage
13
+ """
14
+
15
+ import json
16
+ import sys
17
+ from typing import Any, Dict, List, Optional
18
+
19
+ from rich.text import Text
20
+
21
+
22
+ class StreamingResponse:
23
+ """Assemble streaming deltas into a complete message dict.
24
+
25
+ Text deltas are printed to stderr immediately (raw, no formatting).
26
+ Tool call deltas are buffered and reassembled across chunks.
27
+ """
28
+
29
+ def __init__(self, stream, console=None, debug_mode: bool = False,
30
+ on_text=None, live=None):
31
+ """
32
+ Args:
33
+ stream: StreamWrapper (or any iterable yielding deltas / __usage__ dicts).
34
+ console: Rich Console instance (used for debug logging only).
35
+ debug_mode: If True, log assembly details.
36
+ on_text: Optional callback(str) invoked for each text token.
37
+ Defaults to printing to stderr.
38
+ live: Optional Rich Live context. When set, streaming text is
39
+ rendered through Live (raw during streaming, swappable to
40
+ Markdown on completion) instead of raw stderr.
41
+ """
42
+ self._stream = stream
43
+ self._console = console
44
+ self._debug = debug_mode
45
+ self._on_text = on_text
46
+ self._live = live
47
+
48
+ # Accumulated state
49
+ self._text_parts: List[str] = []
50
+ self._tool_calls: Dict[int, Dict[str, Any]] = {} # index -> partial tool call
51
+ self._usage: Optional[Dict[str, Any]] = None
52
+
53
+ def consume(self) -> Dict[str, Any]:
54
+ """Iterate the stream, print text tokens, assemble tool calls.
55
+
56
+ Returns:
57
+ A message dict with 'role', 'content', and optionally 'tool_calls'
58
+ — same shape as a non-streaming response["choices"][0]["message"].
59
+ """
60
+ for item in self._stream:
61
+ if isinstance(item, dict) and '__usage__' in item:
62
+ self._usage = item['__usage__']
63
+ continue
64
+
65
+ # OpenAI-style delta: {"content": "...", "tool_calls": [...]}
66
+ if isinstance(item, dict):
67
+ self._process_delta(item)
68
+ elif isinstance(item, str):
69
+ # Fallback: plain text string (legacy parse_stream behavior)
70
+ self._print(item)
71
+ self._text_parts.append(item)
72
+
73
+ return self._build_message()
74
+
75
+ @property
76
+ def usage(self) -> Optional[Dict[str, Any]]:
77
+ """Usage data captured from the stream's final chunk."""
78
+ return self._usage
79
+
80
+ def _process_delta(self, delta: Dict[str, Any]):
81
+ """Process a single streaming delta dict.
82
+
83
+ Expected shapes (OpenAI format):
84
+ {"content": "some text"}
85
+ {"tool_calls": [{"index": 0, "id": "call_xxx", "function": {"name": "f"}}]}
86
+ {"tool_calls": [{"index": 0, "function": {"arguments": "{..."}}]}
87
+ {"content": "text", "tool_calls": [...]}
88
+ """
89
+ # Handle text content
90
+ content = delta.get("content")
91
+ if content is not None:
92
+ self._print(content)
93
+ self._text_parts.append(content)
94
+
95
+ # Handle tool call fragments
96
+ tool_calls = delta.get("tool_calls")
97
+ if tool_calls:
98
+ for tc_delta in tool_calls:
99
+ idx = tc_delta.get("index", 0)
100
+ if idx not in self._tool_calls:
101
+ self._tool_calls[idx] = {
102
+ "id": "",
103
+ "type": "function",
104
+ "function": {"name": "", "arguments": ""},
105
+ }
106
+
107
+ entry = self._tool_calls[idx]
108
+
109
+ # Tool call id (sent once at the start)
110
+ if tc_delta.get("id"):
111
+ entry["id"] = tc_delta["id"]
112
+
113
+ # Function name (sent once at the start)
114
+ func = tc_delta.get("function", {})
115
+ if func.get("name"):
116
+ entry["function"]["name"] = func["name"]
117
+
118
+ # Arguments (sent incrementally, concatenated)
119
+ if func.get("arguments"):
120
+ entry["function"]["arguments"] += func["arguments"]
121
+
122
+ def _build_message(self) -> Dict[str, Any]:
123
+ """Build the final message dict from assembled parts."""
124
+ message: Dict[str, Any] = {"role": "assistant"}
125
+
126
+ # Collect assembled tool calls in index order
127
+ assembled_tool_calls = []
128
+ if self._tool_calls:
129
+ for idx in sorted(self._tool_calls.keys()):
130
+ assembled_tool_calls.append(self._tool_calls[idx])
131
+
132
+ if assembled_tool_calls:
133
+ message["tool_calls"] = assembled_tool_calls
134
+ # Content may be None or a string alongside tool calls
135
+ text = "".join(self._text_parts).strip()
136
+ message["content"] = text if text else None
137
+ else:
138
+ message["content"] = "".join(self._text_parts)
139
+
140
+ return message
141
+
142
+ def _print(self, text: str):
143
+ """Output text token via the configured callback (default: stderr).
144
+
145
+ When a Rich Live context is provided, text is rendered through Live
146
+ for atomic screen updates (raw text during streaming, swappable to
147
+ Markdown on completion).
148
+ """
149
+ if self._live is not None:
150
+ # Render through Rich Live — update with accumulated text so far
151
+ self._live.update(Text("".join(self._text_parts) + text))
152
+ elif self._on_text is None:
153
+ # Default: print to stderr
154
+ sys.stderr.write(text)
155
+ sys.stderr.flush()
156
+ elif callable(self._on_text):
157
+ self._on_text(text)
158
+ # If on_text is False, silently drop output (subagent mode)
159
+
160
+ def close(self):
161
+ """Close the underlying stream."""
162
+ if hasattr(self._stream, 'close'):
163
+ self._stream.close()