Run tool in a daemon thread. Returns background task ID.
(block)
| 298 | |
| 299 | |
| 300 | def start_background_task(block) -> str: |
| 301 | """Run tool in a daemon thread. Returns background task ID.""" |
| 302 | global _bg_counter |
| 303 | _bg_counter += 1 |
| 304 | bg_id = f"bg_{_bg_counter:04d}" |
| 305 | cmd = block.input.get("command", block.name) |
| 306 | |
| 307 | def worker(): |
| 308 | result = execute_tool(block) |
| 309 | with background_lock: |
| 310 | background_tasks[bg_id]["status"] = "completed" |
| 311 | background_results[bg_id] = result |
| 312 | |
| 313 | with background_lock: |
| 314 | background_tasks[bg_id] = { |
| 315 | "tool_use_id": block.id, |
| 316 | "command": cmd, |
| 317 | "status": "running", |
| 318 | } |
| 319 | threading.Thread(target=worker, daemon=True).start() |
| 320 | print(f" \033[33m[background] dispatched {bg_id}: {cmd[:40]}\033[0m") |
| 321 | return bg_id |
| 322 | |
| 323 | |
| 324 | def collect_background_results() -> list[str]: |