Run tool in a daemon thread. Returns background task ID.
(block)
| 342 | |
| 343 | |
| 344 | def start_background_task(block) -> str: |
| 345 | """Run tool in a daemon thread. Returns background task ID.""" |
| 346 | global _bg_counter |
| 347 | _bg_counter += 1 |
| 348 | bg_id = f"bg_{_bg_counter:04d}" |
| 349 | cmd = block.input.get("command", block.name) |
| 350 | |
| 351 | def worker(): |
| 352 | result = execute_tool(block) |
| 353 | with background_lock: |
| 354 | background_tasks[bg_id]["status"] = "completed" |
| 355 | background_results[bg_id] = result |
| 356 | |
| 357 | with background_lock: |
| 358 | background_tasks[bg_id] = { |
| 359 | "tool_use_id": block.id, |
| 360 | "command": cmd, |
| 361 | "status": "running", |
| 362 | } |
| 363 | thread = threading.Thread(target=worker, daemon=True) |
| 364 | thread.start() |
| 365 | print(f" \033[33m[background] dispatched {bg_id}: {cmd[:40]}\033[0m") |
| 366 | return bg_id |
| 367 | |
| 368 | |
| 369 | def collect_background_results() -> list[str]: |