remdb 0.3.242__py3-none-any.whl

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.

Potentially problematic release.


This version of remdb might be problematic. Click here for more details.

Files changed (235) hide show
  1. rem/__init__.py +129 -0
  2. rem/agentic/README.md +760 -0
  3. rem/agentic/__init__.py +54 -0
  4. rem/agentic/agents/README.md +155 -0
  5. rem/agentic/agents/__init__.py +38 -0
  6. rem/agentic/agents/agent_manager.py +311 -0
  7. rem/agentic/agents/sse_simulator.py +502 -0
  8. rem/agentic/context.py +425 -0
  9. rem/agentic/context_builder.py +360 -0
  10. rem/agentic/llm_provider_models.py +301 -0
  11. rem/agentic/mcp/__init__.py +0 -0
  12. rem/agentic/mcp/tool_wrapper.py +273 -0
  13. rem/agentic/otel/__init__.py +5 -0
  14. rem/agentic/otel/setup.py +240 -0
  15. rem/agentic/providers/phoenix.py +926 -0
  16. rem/agentic/providers/pydantic_ai.py +854 -0
  17. rem/agentic/query.py +117 -0
  18. rem/agentic/query_helper.py +89 -0
  19. rem/agentic/schema.py +737 -0
  20. rem/agentic/serialization.py +245 -0
  21. rem/agentic/tools/__init__.py +5 -0
  22. rem/agentic/tools/rem_tools.py +242 -0
  23. rem/api/README.md +657 -0
  24. rem/api/deps.py +253 -0
  25. rem/api/main.py +460 -0
  26. rem/api/mcp_router/prompts.py +182 -0
  27. rem/api/mcp_router/resources.py +820 -0
  28. rem/api/mcp_router/server.py +243 -0
  29. rem/api/mcp_router/tools.py +1605 -0
  30. rem/api/middleware/tracking.py +172 -0
  31. rem/api/routers/admin.py +520 -0
  32. rem/api/routers/auth.py +898 -0
  33. rem/api/routers/chat/__init__.py +5 -0
  34. rem/api/routers/chat/child_streaming.py +394 -0
  35. rem/api/routers/chat/completions.py +702 -0
  36. rem/api/routers/chat/json_utils.py +76 -0
  37. rem/api/routers/chat/models.py +202 -0
  38. rem/api/routers/chat/otel_utils.py +33 -0
  39. rem/api/routers/chat/sse_events.py +546 -0
  40. rem/api/routers/chat/streaming.py +950 -0
  41. rem/api/routers/chat/streaming_utils.py +327 -0
  42. rem/api/routers/common.py +18 -0
  43. rem/api/routers/dev.py +87 -0
  44. rem/api/routers/feedback.py +276 -0
  45. rem/api/routers/messages.py +620 -0
  46. rem/api/routers/models.py +86 -0
  47. rem/api/routers/query.py +362 -0
  48. rem/api/routers/shared_sessions.py +422 -0
  49. rem/auth/README.md +258 -0
  50. rem/auth/__init__.py +36 -0
  51. rem/auth/jwt.py +367 -0
  52. rem/auth/middleware.py +318 -0
  53. rem/auth/providers/__init__.py +16 -0
  54. rem/auth/providers/base.py +376 -0
  55. rem/auth/providers/email.py +215 -0
  56. rem/auth/providers/google.py +163 -0
  57. rem/auth/providers/microsoft.py +237 -0
  58. rem/cli/README.md +517 -0
  59. rem/cli/__init__.py +8 -0
  60. rem/cli/commands/README.md +299 -0
  61. rem/cli/commands/__init__.py +3 -0
  62. rem/cli/commands/ask.py +549 -0
  63. rem/cli/commands/cluster.py +1808 -0
  64. rem/cli/commands/configure.py +495 -0
  65. rem/cli/commands/db.py +828 -0
  66. rem/cli/commands/dreaming.py +324 -0
  67. rem/cli/commands/experiments.py +1698 -0
  68. rem/cli/commands/mcp.py +66 -0
  69. rem/cli/commands/process.py +388 -0
  70. rem/cli/commands/query.py +109 -0
  71. rem/cli/commands/scaffold.py +47 -0
  72. rem/cli/commands/schema.py +230 -0
  73. rem/cli/commands/serve.py +106 -0
  74. rem/cli/commands/session.py +453 -0
  75. rem/cli/dreaming.py +363 -0
  76. rem/cli/main.py +123 -0
  77. rem/config.py +244 -0
  78. rem/mcp_server.py +41 -0
  79. rem/models/core/__init__.py +49 -0
  80. rem/models/core/core_model.py +70 -0
  81. rem/models/core/engram.py +333 -0
  82. rem/models/core/experiment.py +672 -0
  83. rem/models/core/inline_edge.py +132 -0
  84. rem/models/core/rem_query.py +246 -0
  85. rem/models/entities/__init__.py +68 -0
  86. rem/models/entities/domain_resource.py +38 -0
  87. rem/models/entities/feedback.py +123 -0
  88. rem/models/entities/file.py +57 -0
  89. rem/models/entities/image_resource.py +88 -0
  90. rem/models/entities/message.py +64 -0
  91. rem/models/entities/moment.py +123 -0
  92. rem/models/entities/ontology.py +181 -0
  93. rem/models/entities/ontology_config.py +131 -0
  94. rem/models/entities/resource.py +95 -0
  95. rem/models/entities/schema.py +87 -0
  96. rem/models/entities/session.py +84 -0
  97. rem/models/entities/shared_session.py +180 -0
  98. rem/models/entities/subscriber.py +175 -0
  99. rem/models/entities/user.py +93 -0
  100. rem/py.typed +0 -0
  101. rem/registry.py +373 -0
  102. rem/schemas/README.md +507 -0
  103. rem/schemas/__init__.py +6 -0
  104. rem/schemas/agents/README.md +92 -0
  105. rem/schemas/agents/core/agent-builder.yaml +235 -0
  106. rem/schemas/agents/core/moment-builder.yaml +178 -0
  107. rem/schemas/agents/core/rem-query-agent.yaml +226 -0
  108. rem/schemas/agents/core/resource-affinity-assessor.yaml +99 -0
  109. rem/schemas/agents/core/simple-assistant.yaml +19 -0
  110. rem/schemas/agents/core/user-profile-builder.yaml +163 -0
  111. rem/schemas/agents/examples/contract-analyzer.yaml +317 -0
  112. rem/schemas/agents/examples/contract-extractor.yaml +134 -0
  113. rem/schemas/agents/examples/cv-parser.yaml +263 -0
  114. rem/schemas/agents/examples/hello-world.yaml +37 -0
  115. rem/schemas/agents/examples/query.yaml +54 -0
  116. rem/schemas/agents/examples/simple.yaml +21 -0
  117. rem/schemas/agents/examples/test.yaml +29 -0
  118. rem/schemas/agents/rem.yaml +132 -0
  119. rem/schemas/evaluators/hello-world/default.yaml +77 -0
  120. rem/schemas/evaluators/rem/faithfulness.yaml +219 -0
  121. rem/schemas/evaluators/rem/lookup-correctness.yaml +182 -0
  122. rem/schemas/evaluators/rem/retrieval-precision.yaml +199 -0
  123. rem/schemas/evaluators/rem/retrieval-recall.yaml +211 -0
  124. rem/schemas/evaluators/rem/search-correctness.yaml +192 -0
  125. rem/services/__init__.py +18 -0
  126. rem/services/audio/INTEGRATION.md +308 -0
  127. rem/services/audio/README.md +376 -0
  128. rem/services/audio/__init__.py +15 -0
  129. rem/services/audio/chunker.py +354 -0
  130. rem/services/audio/transcriber.py +259 -0
  131. rem/services/content/README.md +1269 -0
  132. rem/services/content/__init__.py +5 -0
  133. rem/services/content/providers.py +760 -0
  134. rem/services/content/service.py +762 -0
  135. rem/services/dreaming/README.md +230 -0
  136. rem/services/dreaming/__init__.py +53 -0
  137. rem/services/dreaming/affinity_service.py +322 -0
  138. rem/services/dreaming/moment_service.py +251 -0
  139. rem/services/dreaming/ontology_service.py +54 -0
  140. rem/services/dreaming/user_model_service.py +297 -0
  141. rem/services/dreaming/utils.py +39 -0
  142. rem/services/email/__init__.py +10 -0
  143. rem/services/email/service.py +522 -0
  144. rem/services/email/templates.py +360 -0
  145. rem/services/embeddings/__init__.py +11 -0
  146. rem/services/embeddings/api.py +127 -0
  147. rem/services/embeddings/worker.py +435 -0
  148. rem/services/fs/README.md +662 -0
  149. rem/services/fs/__init__.py +62 -0
  150. rem/services/fs/examples.py +206 -0
  151. rem/services/fs/examples_paths.py +204 -0
  152. rem/services/fs/git_provider.py +935 -0
  153. rem/services/fs/local_provider.py +760 -0
  154. rem/services/fs/parsing-hooks-examples.md +172 -0
  155. rem/services/fs/paths.py +276 -0
  156. rem/services/fs/provider.py +460 -0
  157. rem/services/fs/s3_provider.py +1042 -0
  158. rem/services/fs/service.py +186 -0
  159. rem/services/git/README.md +1075 -0
  160. rem/services/git/__init__.py +17 -0
  161. rem/services/git/service.py +469 -0
  162. rem/services/phoenix/EXPERIMENT_DESIGN.md +1146 -0
  163. rem/services/phoenix/README.md +453 -0
  164. rem/services/phoenix/__init__.py +46 -0
  165. rem/services/phoenix/client.py +960 -0
  166. rem/services/phoenix/config.py +88 -0
  167. rem/services/phoenix/prompt_labels.py +477 -0
  168. rem/services/postgres/README.md +757 -0
  169. rem/services/postgres/__init__.py +49 -0
  170. rem/services/postgres/diff_service.py +599 -0
  171. rem/services/postgres/migration_service.py +427 -0
  172. rem/services/postgres/programmable_diff_service.py +635 -0
  173. rem/services/postgres/pydantic_to_sqlalchemy.py +562 -0
  174. rem/services/postgres/register_type.py +353 -0
  175. rem/services/postgres/repository.py +481 -0
  176. rem/services/postgres/schema_generator.py +661 -0
  177. rem/services/postgres/service.py +802 -0
  178. rem/services/postgres/sql_builder.py +355 -0
  179. rem/services/rate_limit.py +113 -0
  180. rem/services/rem/README.md +318 -0
  181. rem/services/rem/__init__.py +23 -0
  182. rem/services/rem/exceptions.py +71 -0
  183. rem/services/rem/executor.py +293 -0
  184. rem/services/rem/parser.py +180 -0
  185. rem/services/rem/queries.py +196 -0
  186. rem/services/rem/query.py +371 -0
  187. rem/services/rem/service.py +608 -0
  188. rem/services/session/README.md +374 -0
  189. rem/services/session/__init__.py +13 -0
  190. rem/services/session/compression.py +488 -0
  191. rem/services/session/pydantic_messages.py +310 -0
  192. rem/services/session/reload.py +85 -0
  193. rem/services/user_service.py +130 -0
  194. rem/settings.py +1877 -0
  195. rem/sql/background_indexes.sql +52 -0
  196. rem/sql/migrations/001_install.sql +983 -0
  197. rem/sql/migrations/002_install_models.sql +3157 -0
  198. rem/sql/migrations/003_optional_extensions.sql +326 -0
  199. rem/sql/migrations/004_cache_system.sql +282 -0
  200. rem/sql/migrations/005_schema_update.sql +145 -0
  201. rem/sql/migrations/migrate_session_id_to_uuid.sql +45 -0
  202. rem/utils/AGENTIC_CHUNKING.md +597 -0
  203. rem/utils/README.md +628 -0
  204. rem/utils/__init__.py +61 -0
  205. rem/utils/agentic_chunking.py +622 -0
  206. rem/utils/batch_ops.py +343 -0
  207. rem/utils/chunking.py +108 -0
  208. rem/utils/clip_embeddings.py +276 -0
  209. rem/utils/constants.py +97 -0
  210. rem/utils/date_utils.py +228 -0
  211. rem/utils/dict_utils.py +98 -0
  212. rem/utils/embeddings.py +436 -0
  213. rem/utils/examples/embeddings_example.py +305 -0
  214. rem/utils/examples/sql_types_example.py +202 -0
  215. rem/utils/files.py +323 -0
  216. rem/utils/markdown.py +16 -0
  217. rem/utils/mime_types.py +158 -0
  218. rem/utils/model_helpers.py +492 -0
  219. rem/utils/schema_loader.py +649 -0
  220. rem/utils/sql_paths.py +146 -0
  221. rem/utils/sql_types.py +350 -0
  222. rem/utils/user_id.py +81 -0
  223. rem/utils/vision.py +325 -0
  224. rem/workers/README.md +506 -0
  225. rem/workers/__init__.py +7 -0
  226. rem/workers/db_listener.py +579 -0
  227. rem/workers/db_maintainer.py +74 -0
  228. rem/workers/dreaming.py +502 -0
  229. rem/workers/engram_processor.py +312 -0
  230. rem/workers/sqs_file_processor.py +193 -0
  231. rem/workers/unlogged_maintainer.py +463 -0
  232. remdb-0.3.242.dist-info/METADATA +1632 -0
  233. remdb-0.3.242.dist-info/RECORD +235 -0
  234. remdb-0.3.242.dist-info/WHEEL +4 -0
  235. remdb-0.3.242.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,5 @@
1
+ """Chat completions router with OpenAI-compatible API."""
2
+
3
+ from .completions import router
4
+
5
+ __all__ = ["router"]
@@ -0,0 +1,394 @@
1
+ """
2
+ Child Agent Event Handling.
3
+
4
+ Handles events from child agents during multi-agent orchestration.
5
+
6
+ Event Flow:
7
+ ```
8
+ Parent Agent (Siggy)
9
+
10
+
11
+ ask_agent tool
12
+
13
+ ├──────────────────────────────────┐
14
+ ▼ │
15
+ Child Agent (intake_diverge) │
16
+ │ │
17
+ ├── child_tool_start ──────────────┼──► Event Sink (Queue)
18
+ ├── child_content ─────────────────┤
19
+ └── child_tool_result ─────────────┘
20
+
21
+
22
+ drain_child_events()
23
+
24
+ ├── SSE to client
25
+ └── DB persistence
26
+ ```
27
+
28
+ IMPORTANT: When child_content is streamed, parent text output should be SKIPPED
29
+ to prevent content duplication.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import asyncio
35
+ import json
36
+ import uuid
37
+ from typing import TYPE_CHECKING, Any, AsyncGenerator
38
+
39
+ from loguru import logger
40
+
41
+ from .streaming_utils import StreamingState, build_content_chunk
42
+ from .sse_events import MetadataEvent, ToolCallEvent, format_sse_event
43
+ from ....services.session import SessionMessageStore
44
+ from ....settings import settings
45
+ from ....utils.date_utils import to_iso, utc_now
46
+
47
+ if TYPE_CHECKING:
48
+ from ....agentic.context import AgentContext
49
+
50
+
51
+ async def handle_child_tool_start(
52
+ state: StreamingState,
53
+ child_agent: str,
54
+ tool_name: str,
55
+ arguments: dict | str | None,
56
+ session_id: str | None,
57
+ user_id: str | None,
58
+ ) -> AsyncGenerator[str, None]:
59
+ """
60
+ Handle child_tool_start event.
61
+
62
+ Actions:
63
+ 1. Log the tool call
64
+ 2. Emit SSE event
65
+ 3. Save to database (with tool_arguments in metadata for consistency with parent)
66
+ """
67
+ full_tool_name = f"{child_agent}:{tool_name}"
68
+ tool_id = f"call_{uuid.uuid4().hex[:8]}"
69
+
70
+ # Normalize arguments - may come as JSON string from ToolCallPart.args
71
+ if isinstance(arguments, str):
72
+ try:
73
+ arguments = json.loads(arguments)
74
+ except json.JSONDecodeError:
75
+ arguments = None
76
+ elif not isinstance(arguments, dict):
77
+ arguments = None
78
+
79
+ # 1. LOG
80
+ logger.info(f"🔧 {full_tool_name}")
81
+
82
+ # 2. EMIT SSE
83
+ yield format_sse_event(ToolCallEvent(
84
+ tool_name=full_tool_name,
85
+ tool_id=tool_id,
86
+ status="started",
87
+ arguments=arguments,
88
+ ))
89
+
90
+ # 3. SAVE TO DB - content contains args as JSON (pydantic_messages.py parses it)
91
+ if session_id and settings.postgres.enabled:
92
+ try:
93
+ store = SessionMessageStore(
94
+ user_id=user_id or settings.test.effective_user_id
95
+ )
96
+ tool_msg = {
97
+ "role": "tool",
98
+ # Content is the tool call args as JSON - this is what the agent sees on reload
99
+ # and what pydantic_messages.py parses for ToolCallPart.args
100
+ "content": json.dumps(arguments) if arguments else "",
101
+ "timestamp": to_iso(utc_now()),
102
+ "tool_call_id": tool_id,
103
+ "tool_name": full_tool_name,
104
+ }
105
+ await store.store_session_messages(
106
+ session_id=session_id,
107
+ messages=[tool_msg],
108
+ user_id=user_id,
109
+ compress=False,
110
+ )
111
+ except Exception as e:
112
+ logger.warning(f"Failed to save child tool call: {e}")
113
+
114
+
115
+ def handle_child_content(
116
+ state: StreamingState,
117
+ child_agent: str,
118
+ content: str,
119
+ ) -> str | None:
120
+ """
121
+ Handle child_content event.
122
+
123
+ CRITICAL: Sets state.child_content_streamed = True
124
+ This flag is used to skip parent text output and prevent duplication.
125
+
126
+ Returns:
127
+ SSE chunk or None if content is empty
128
+ """
129
+ if not content:
130
+ return None
131
+
132
+ # Track that child content was streamed
133
+ # Parent text output should be SKIPPED when this is True
134
+ state.child_content_streamed = True
135
+ state.responding_agent = child_agent
136
+
137
+ return build_content_chunk(state, content)
138
+
139
+
140
+ async def handle_child_tool_result(
141
+ state: StreamingState,
142
+ child_agent: str,
143
+ result: Any,
144
+ message_id: str | None,
145
+ session_id: str | None,
146
+ agent_schema: str | None,
147
+ ) -> AsyncGenerator[str, None]:
148
+ """
149
+ Handle child_tool_result event.
150
+
151
+ Actions:
152
+ 1. Log metadata if present
153
+ 2. Emit metadata event if present
154
+ 3. Emit tool completion event
155
+ """
156
+ # Check for metadata registration
157
+ if isinstance(result, dict) and result.get("_metadata_event"):
158
+ risk = result.get("risk_level", "")
159
+ conf = result.get("confidence", "")
160
+ logger.info(f"📊 {child_agent} metadata: risk={risk}, confidence={conf}")
161
+
162
+ # Update responding agent from child
163
+ if result.get("agent_schema"):
164
+ state.responding_agent = result.get("agent_schema")
165
+
166
+ # Build extra dict with risk fields
167
+ extra_data = {}
168
+ if risk:
169
+ extra_data["risk_level"] = risk
170
+
171
+ yield format_sse_event(MetadataEvent(
172
+ message_id=message_id,
173
+ session_id=session_id,
174
+ agent_schema=agent_schema,
175
+ responding_agent=state.responding_agent,
176
+ confidence=result.get("confidence"),
177
+ extra=extra_data if extra_data else None,
178
+ ))
179
+
180
+ # Emit tool completion
181
+ # Preserve full result dict if it contains an artifact (e.g. finalize_intake)
182
+ # This is needed for frontend to extract artifact URLs for download
183
+ if isinstance(result, dict) and result.get("artifact"):
184
+ result_for_sse = result # Full dict with artifact
185
+ else:
186
+ result_for_sse = str(result)[:200] if result else None
187
+
188
+ yield format_sse_event(ToolCallEvent(
189
+ tool_name=f"{child_agent}:tool",
190
+ tool_id=f"call_{uuid.uuid4().hex[:8]}",
191
+ status="completed",
192
+ result=result_for_sse,
193
+ ))
194
+
195
+
196
+ async def drain_child_events(
197
+ event_sink: asyncio.Queue,
198
+ state: StreamingState,
199
+ session_id: str | None = None,
200
+ user_id: str | None = None,
201
+ message_id: str | None = None,
202
+ agent_schema: str | None = None,
203
+ ) -> AsyncGenerator[str, None]:
204
+ """
205
+ Drain all pending child events from the event sink.
206
+
207
+ This is called during tool execution to process events
208
+ pushed by child agents via ask_agent.
209
+
210
+ IMPORTANT: When child_content events are processed, this sets
211
+ state.child_content_streamed = True. Callers should check this
212
+ flag and skip parent text output to prevent duplication.
213
+ """
214
+ while not event_sink.empty():
215
+ try:
216
+ child_event = event_sink.get_nowait()
217
+ async for chunk in process_child_event(
218
+ child_event, state, session_id, user_id, message_id, agent_schema
219
+ ):
220
+ yield chunk
221
+ except Exception as e:
222
+ logger.warning(f"Error processing child event: {e}")
223
+
224
+
225
+ async def process_child_event(
226
+ child_event: dict,
227
+ state: StreamingState,
228
+ session_id: str | None = None,
229
+ user_id: str | None = None,
230
+ message_id: str | None = None,
231
+ agent_schema: str | None = None,
232
+ ) -> AsyncGenerator[str, None]:
233
+ """Process a single child event and yield SSE chunks."""
234
+ event_type = child_event.get("type", "")
235
+ child_agent = child_event.get("agent_name", "child")
236
+
237
+ if event_type == "child_tool_start":
238
+ async for chunk in handle_child_tool_start(
239
+ state=state,
240
+ child_agent=child_agent,
241
+ tool_name=child_event.get("tool_name", "tool"),
242
+ arguments=child_event.get("arguments"),
243
+ session_id=session_id,
244
+ user_id=user_id,
245
+ ):
246
+ yield chunk
247
+
248
+ elif event_type == "child_content":
249
+ chunk = handle_child_content(
250
+ state=state,
251
+ child_agent=child_agent,
252
+ content=child_event.get("content", ""),
253
+ )
254
+ if chunk:
255
+ yield chunk
256
+
257
+ elif event_type == "child_tool_result":
258
+ async for chunk in handle_child_tool_result(
259
+ state=state,
260
+ child_agent=child_agent,
261
+ result=child_event.get("result"),
262
+ message_id=message_id,
263
+ session_id=session_id,
264
+ agent_schema=agent_schema,
265
+ ):
266
+ yield chunk
267
+
268
+
269
+ async def stream_with_child_events(
270
+ tools_stream,
271
+ child_event_sink: asyncio.Queue,
272
+ state: StreamingState,
273
+ session_id: str | None = None,
274
+ user_id: str | None = None,
275
+ message_id: str | None = None,
276
+ agent_schema: str | None = None,
277
+ ) -> AsyncGenerator[tuple[str, Any], None]:
278
+ """
279
+ Multiplex tool events with child events using asyncio.wait().
280
+
281
+ This is the key fix for child agent streaming - instead of draining
282
+ the queue synchronously during tool event iteration, we concurrently
283
+ listen to both sources and yield events as they arrive.
284
+
285
+ Yields:
286
+ Tuples of (event_type, event_data) where event_type is either
287
+ "tool" or "child", allowing the caller to handle each appropriately.
288
+ """
289
+ tool_iter = tools_stream.__aiter__()
290
+
291
+ # Create initial tasks
292
+ pending_tool: asyncio.Task | None = None
293
+ pending_child: asyncio.Task | None = None
294
+
295
+ try:
296
+ pending_tool = asyncio.create_task(tool_iter.__anext__())
297
+ except StopAsyncIteration:
298
+ # No tool events, just drain any remaining child events
299
+ while not child_event_sink.empty():
300
+ try:
301
+ child_event = child_event_sink.get_nowait()
302
+ yield ("child", child_event)
303
+ except asyncio.QueueEmpty:
304
+ break
305
+ return
306
+
307
+ # Start listening for child events with a short timeout
308
+ pending_child = asyncio.create_task(
309
+ _get_child_event_with_timeout(child_event_sink, timeout=0.05)
310
+ )
311
+
312
+ try:
313
+ while True:
314
+ # Wait for either source to produce an event
315
+ tasks = {t for t in [pending_tool, pending_child] if t is not None}
316
+ if not tasks:
317
+ break
318
+
319
+ done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
320
+
321
+ for task in done:
322
+ try:
323
+ result = task.result()
324
+ except asyncio.TimeoutError:
325
+ # Child queue timeout - restart listener
326
+ if task is pending_child:
327
+ pending_child = asyncio.create_task(
328
+ _get_child_event_with_timeout(child_event_sink, timeout=0.05)
329
+ )
330
+ continue
331
+ except StopAsyncIteration:
332
+ # Tool stream exhausted
333
+ if task is pending_tool:
334
+ pending_tool = None
335
+ # Final drain of any remaining child events
336
+ if pending_child:
337
+ pending_child.cancel()
338
+ try:
339
+ await pending_child
340
+ except asyncio.CancelledError:
341
+ pass
342
+ while not child_event_sink.empty():
343
+ try:
344
+ child_event = child_event_sink.get_nowait()
345
+ yield ("child", child_event)
346
+ except asyncio.QueueEmpty:
347
+ break
348
+ return
349
+ continue
350
+
351
+ if task is pending_child and result is not None:
352
+ # Got a child event
353
+ yield ("child", result)
354
+ # Restart child listener
355
+ pending_child = asyncio.create_task(
356
+ _get_child_event_with_timeout(child_event_sink, timeout=0.05)
357
+ )
358
+ elif task is pending_tool:
359
+ # Got a tool event
360
+ yield ("tool", result)
361
+ # Get next tool event
362
+ try:
363
+ pending_tool = asyncio.create_task(tool_iter.__anext__())
364
+ except StopAsyncIteration:
365
+ pending_tool = None
366
+ elif task is pending_child and result is None:
367
+ # Timeout with no event - restart listener
368
+ pending_child = asyncio.create_task(
369
+ _get_child_event_with_timeout(child_event_sink, timeout=0.05)
370
+ )
371
+ finally:
372
+ # Cleanup any pending tasks
373
+ for task in [pending_tool, pending_child]:
374
+ if task and not task.done():
375
+ task.cancel()
376
+ try:
377
+ await task
378
+ except asyncio.CancelledError:
379
+ pass
380
+
381
+
382
+ async def _get_child_event_with_timeout(
383
+ queue: asyncio.Queue, timeout: float = 0.05
384
+ ) -> dict | None:
385
+ """
386
+ Get an event from the queue with a timeout.
387
+
388
+ Returns None on timeout (no event available).
389
+ This allows the multiplexer to check for tool events regularly.
390
+ """
391
+ try:
392
+ return await asyncio.wait_for(queue.get(), timeout=timeout)
393
+ except asyncio.TimeoutError:
394
+ return None