Merge main into fix/micro-compact-latest-batch

This commit is contained in:
Haoran
2026-08-16 17:25:14 +08:00
3 changed files with 276 additions and 58 deletions

View File

@@ -2109,8 +2109,6 @@ def should_run_background(tool_name: str, tool_input: dict) -> bool:
def start_background_task(block, handlers: dict) -> str:
global _bg_counter
_bg_counter += 1
bg_id = f"bg_{_bg_counter:04d}"
command = block.input.get("command", block.name)
cwd, cwd_error = _agent_cwd()
@@ -2127,19 +2125,36 @@ def start_background_task(block, handlers: dict) -> str:
except Exception as exc:
result = f"Error: {type(exc).__name__}: {exc}"
status = "failed"
trigger_hooks("PostToolUse", block, result)
try:
trigger_hooks("PostToolUse", block, result)
except Exception as exc:
result = (f"Error: PostToolUse hook failed: "
f"{type(exc).__name__}: {exc}\n{result}")
status = "failed"
with background_lock:
background_tasks[bg_id]["status"] = status
task = background_tasks.get(bg_id)
if task is None:
return
task["status"] = status
background_results[bg_id] = str(result)
with background_lock:
_bg_counter += 1
bg_id = f"bg_{_bg_counter:04d}"
background_tasks[bg_id] = {
"tool_use_id": block.id,
"command": command,
"status": "running",
"cwd": str(cwd) if cwd else None,
}
threading.Thread(target=worker, daemon=True).start()
thread = threading.Thread(target=worker, daemon=True)
try:
thread.start()
except Exception:
with background_lock:
background_tasks.pop(bg_id, None)
background_results.pop(bg_id, None)
raise
print(f" \033[33m[background] {bg_id}: {str(command)[:60]}\033[0m")
return bg_id
@@ -2148,11 +2163,13 @@ def collect_background_results() -> list[str]:
with background_lock:
ready = [bg_id for bg_id, task in background_tasks.items()
if task["status"] in {"completed", "failed"}]
completed = [
(bg_id, background_tasks.pop(bg_id),
background_results.pop(bg_id, ""))
for bg_id in ready
]
notifications = []
for bg_id in ready:
with background_lock:
task = background_tasks.pop(bg_id)
output = background_results.pop(bg_id, "")
for bg_id, task, output in completed:
summary = output[:200] if len(output) > 200 else output
notifications.append(
f"<task_notification>\n"
@@ -2998,9 +3015,13 @@ def agent_loop(messages: list, context: dict, active_request: str):
continue
if should_run_background(block.name, block.input):
bg_id = start_background_task(block, handlers)
output = (f"[Background task {bg_id} started] "
"Result will arrive as a task_notification.")
try:
bg_id = start_background_task(block, handlers)
output = (f"[Background task {bg_id} started] "
"Result will arrive as a task_notification.")
except Exception as exc:
output = (f"Error: Failed to start background task: "
f"{type(exc).__name__}: {exc}")
results.append({"type": "tool_result",
"tool_use_id": block.id,
"content": output})