langchain-agentx-python 2.4.9__py3-none-any.whl → 2.5.0__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.
@@ -11,7 +11,7 @@ from langchain_agentx import create_loop_agent
11
11
  ```
12
12
  """
13
13
 
14
- __version__ = "2.4.9"
14
+ __version__ = "2.5.0"
15
15
 
16
16
  from .mcp.call import McpToolCaller
17
17
  from .mcp.client_manager import McpClientManager, McpConnectedClient
@@ -143,6 +143,7 @@ class WorkflowToolBackend:
143
143
  run_id=effective_run_id,
144
144
  workflow_name=workflow_name,
145
145
  script_path=source.script_path,
146
+ args=inp.args,
146
147
  )
147
148
  effective_worker = worker if worker is not None else getattr(
148
149
  self._coordinator, "_worker", None
@@ -164,6 +165,7 @@ class WorkflowToolBackend:
164
165
  script_path=source.script_path or "",
165
166
  task_id=record.task_id,
166
167
  abort_event=abort_event,
168
+ task_bridge=self._tasks,
167
169
  )
168
170
  self._spawn(
169
171
  record.task_id,
@@ -4,7 +4,7 @@ tools/workflow/engine/coordinator.py — WorkflowRunCoordinator
4
4
  职责:Gate → Paths/Journal/Registry → Hooks → Executor;resume 复用 runId。
5
5
  链路位置:Backend 后台 task 调用。
6
6
  当前裁剪:假 Port 默认;真 KernelBridge 由调用方注入 worker;
7
- CancelledError → registry cancelled(非 failed)。
7
+ CancelledError → registry killed(非 failed;对齐 host-panel 终态)。
8
8
  """
9
9
 
10
10
  from __future__ import annotations
@@ -37,6 +37,7 @@ class WorkflowRunRequest:
37
37
  script_path: str = ""
38
38
  task_id: str | None = None
39
39
  abort_event: asyncio.Event | None = field(default=None, repr=False)
40
+ task_bridge: Any | None = field(default=None, repr=False)
40
41
 
41
42
 
42
43
  @dataclass(frozen=True)
@@ -105,6 +106,8 @@ class WorkflowRunCoordinator:
105
106
 
106
107
  def on_progress(event: dict[str, Any]) -> None:
107
108
  progress_buf.append(event)
109
+ if req.task_bridge is not None and req.task_id is not None:
110
+ req.task_bridge.apply_progress(req.task_id, [event])
108
111
  if registry is not None:
109
112
  registry.apply_progress([event])
110
113
  if event.get("type") == "workflow_agent" and event.get("tokens"):
@@ -128,6 +131,8 @@ class WorkflowRunCoordinator:
128
131
  nesting=NestingGuard(depth=0),
129
132
  cpu_count=req.cpu_count,
130
133
  on_progress=on_progress,
134
+ task_bridge=req.task_bridge,
135
+ task_id=req.task_id,
131
136
  )
132
137
  )
133
138
  try:
@@ -152,8 +157,8 @@ class WorkflowRunCoordinator:
152
157
  agent_count = hooks.get_agent_count() if hooks is not None else 0
153
158
  if registry is not None:
154
159
  registry.finalize(
155
- status="cancelled",
156
- error="cancelled",
160
+ status="killed",
161
+ error="killed",
157
162
  agent_count=agent_count,
158
163
  )
159
164
  raise
@@ -10,6 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  import asyncio
12
12
  import os
13
+ import time
13
14
  from collections.abc import Awaitable, Callable, Sequence
14
15
  from dataclasses import dataclass, field
15
16
  from typing import Any
@@ -24,8 +25,18 @@ from langchain_agentx.tools.workflow.engine.concurrency import (
24
25
  workflow_concurrency,
25
26
  )
26
27
  from langchain_agentx.tools.workflow.engine.nested import NestingGuard
27
- from langchain_agentx.tools.workflow.errors import AgentCapError, BudgetExceededError, NestingError
28
- from langchain_agentx.tools.workflow.models import AgentSpec
28
+ from langchain_agentx.tools.workflow.errors import (
29
+ AgentAbandonedError,
30
+ AgentCapError,
31
+ AgentStalledSignal,
32
+ BudgetExceededError,
33
+ NestingError,
34
+ )
35
+ from langchain_agentx.tools.workflow.models import AgentRunResult, AgentSpec
36
+ from langchain_agentx.tools.workflow.observe.previews import truncate_preview
37
+
38
+ STALL_RETRY_CAP = 5 # CC K5u
39
+ _SKIPPED = object()
29
40
 
30
41
 
31
42
  ProgressCallback = Callable[[dict[str, Any]], None]
@@ -90,6 +101,8 @@ class HooksDeps:
90
101
  nesting: NestingGuard = field(default_factory=NestingGuard)
91
102
  args: Any = None
92
103
  cpu_count: int | None = None
104
+ task_bridge: Any | None = None # WorkflowTaskBridge | None
105
+ task_id: str | None = None
93
106
 
94
107
 
95
108
  class WorkflowHooks:
@@ -160,21 +173,41 @@ class WorkflowHooks:
160
173
  label = options.get("label")
161
174
 
162
175
  key = self._cache.next_key(prompt, options)
176
+ model = options.get("model")
177
+ isolation = options.get("isolation")
178
+ agent_type = options.get("agent_type") or options.get("agentType")
179
+ prompt_preview = truncate_preview(prompt)
163
180
  cached = self._cache.lookup(key)
164
181
  if cached is not None:
165
- self._emit(
166
- {
167
- "type": "workflow_agent",
168
- "index": agent_index,
169
- "label": label,
170
- **phase,
171
- "state": "done",
172
- "cached": True,
173
- }
174
- )
182
+ now_ms = int(time.time() * 1000)
183
+ cached_agent_id = cached.get("agentId")
184
+ event: dict[str, Any] = {
185
+ "type": "workflow_agent",
186
+ "index": agent_index,
187
+ "label": label,
188
+ **phase,
189
+ "state": "done",
190
+ "cached": True,
191
+ "model": model,
192
+ "promptPreview": prompt_preview,
193
+ "resultPreview": truncate_preview(
194
+ cached.get("result") if not isinstance(cached.get("result"), (dict, list))
195
+ else str(cached.get("result"))
196
+ ),
197
+ "startedAt": now_ms,
198
+ "lastProgressAt": now_ms,
199
+ }
200
+ if cached_agent_id:
201
+ event["agentId"] = cached_agent_id
202
+ if isolation:
203
+ event["isolation"] = isolation
204
+ if agent_type:
205
+ event["agentType"] = agent_type
206
+ self._emit(event)
175
207
  return cached["result"]
176
208
 
177
- started = asyncio.get_running_loop().time()
209
+ queued_at = int(time.time() * 1000)
210
+ # 入队(槽前):无 agentId
178
211
  self._emit(
179
212
  {
180
213
  "type": "workflow_agent",
@@ -182,12 +215,164 @@ class WorkflowHooks:
182
215
  "label": label,
183
216
  **phase,
184
217
  "state": "start",
218
+ "queuedAt": queued_at,
219
+ "lastProgressAt": queued_at,
220
+ "promptPreview": prompt_preview,
221
+ "model": model,
222
+ **({"isolation": isolation} if isolation else {}),
223
+ **({"agentType": agent_type} if agent_type else {}),
185
224
  }
186
225
  )
187
226
  await self._slots.acquire(aborted=self._aborted())
227
+ try:
228
+ return await self._agent_attempts(
229
+ prompt=prompt,
230
+ options=options,
231
+ key=key,
232
+ agent_index=agent_index,
233
+ label=label,
234
+ phase=phase,
235
+ model=model,
236
+ isolation=isolation,
237
+ agent_type=agent_type,
238
+ prompt_preview=prompt_preview,
239
+ queued_at=queued_at,
240
+ )
241
+ finally:
242
+ self._slots.release()
243
+
244
+ async def _agent_attempts(
245
+ self,
246
+ *,
247
+ prompt: str,
248
+ options: dict[str, Any],
249
+ key: str,
250
+ agent_index: int,
251
+ label: str | None,
252
+ phase: dict[str, Any],
253
+ model: Any,
254
+ isolation: Any,
255
+ agent_type: Any,
256
+ prompt_preview: str,
257
+ queued_at: int,
258
+ ) -> Any:
259
+ """外层环:attempt=1 + stalled/user-retry ≤ K5u;同槽同 cache key。"""
260
+ cum_tokens = 0
261
+ cum_tools = 0
262
+ reasons: list[str] = []
263
+ base_label = label
264
+
265
+ async def _once(
266
+ attempt: int, last_reason: str | None, attempt_label: str | None
267
+ ) -> Any:
268
+ nonlocal cum_tokens, cum_tools
269
+ return await self._one_attempt(
270
+ prompt=prompt,
271
+ options=options,
272
+ key=key,
273
+ agent_index=agent_index,
274
+ label=attempt_label,
275
+ phase=phase,
276
+ model=model,
277
+ isolation=isolation,
278
+ agent_type=agent_type,
279
+ prompt_preview=prompt_preview,
280
+ queued_at=queued_at,
281
+ attempt=attempt,
282
+ last_attempt_reason=last_reason,
283
+ cum_tokens=cum_tokens,
284
+ cum_tools=cum_tools,
285
+ )
286
+
287
+ try:
288
+ value, tokens, tools = await _once(1, None, base_label)
289
+ cum_tokens += tokens
290
+ cum_tools += tools
291
+ return None if value is _SKIPPED else value
292
+ except AgentStalledSignal as first:
293
+ # reasons = 每次失败尝试的 reason(含首次);循环内仅在再次 stalled 时追加
294
+ reasons.append(first.reason)
295
+ stalled_reason: str | None = first.reason
296
+ for i in range(1, STALL_RETRY_CAP + 1):
297
+ if self._aborted():
298
+ raise RuntimeError("Workflow aborted") from first
299
+ r = stalled_reason or "stalled"
300
+ suffix = f" (retry {i})"
301
+ next_label = f"{base_label}{suffix}" if base_label else f"retry {i}"
302
+ try:
303
+ value, tokens, tools = await _once(i + 1, r, next_label)
304
+ cum_tokens += tokens
305
+ cum_tools += tools
306
+ return None if value is _SKIPPED else value
307
+ except AgentStalledSignal as again:
308
+ reasons.append(again.reason)
309
+ stalled_reason = again.reason
310
+ continue
311
+ # 耗尽(reasons 长度 = 实际失败尝试数)
312
+ n = len(reasons)
313
+ all_retry = bool(reasons) and all(x == "user-retry" for x in reasons)
314
+ all_stall = bool(reasons) and all(x == "stalled" for x in reasons)
315
+ if all_retry:
316
+ msg = f"agent abandoned: user requested retry on all {n} attempts"
317
+ elif all_stall:
318
+ msg = f"agent stalled on all {n} attempts (no progress for stall each)"
319
+ else:
320
+ msg = f"agent abandoned after {n} attempts ({' → '.join(reasons)})"
321
+ raise AgentAbandonedError(msg) from first
322
+
323
+ async def _one_attempt(
324
+ self,
325
+ *,
326
+ prompt: str,
327
+ options: dict[str, Any],
328
+ key: str,
329
+ agent_index: int,
330
+ label: str | None,
331
+ phase: dict[str, Any],
332
+ model: Any,
333
+ isolation: Any,
334
+ agent_type: Any,
335
+ prompt_preview: str,
336
+ queued_at: int,
337
+ attempt: int,
338
+ last_attempt_reason: str | None,
339
+ cum_tokens: int,
340
+ cum_tools: int,
341
+ ) -> tuple[Any, int, int]:
188
342
  agent_id = new_agent_id()
343
+ started_mono = asyncio.get_running_loop().time()
344
+ started_at = int(time.time() * 1000)
345
+ bridge = self._deps.task_bridge
346
+ task_id = self._deps.task_id
347
+ abort_ev: asyncio.Event | None = None
348
+ if bridge is not None and task_id is not None:
349
+ abort_ev = bridge.register_agent_controller(task_id, agent_id)
189
350
  try:
190
351
  await self._cache.persist_start(key, agent_id)
352
+ start_event: dict[str, Any] = {
353
+ "type": "workflow_agent",
354
+ "index": agent_index,
355
+ "label": label,
356
+ **phase,
357
+ "agentId": agent_id,
358
+ "state": "start",
359
+ "queuedAt": queued_at,
360
+ "startedAt": started_at,
361
+ "lastProgressAt": started_at,
362
+ "promptPreview": prompt_preview,
363
+ "model": model,
364
+ "attempt": attempt,
365
+ "tokens": cum_tokens or None,
366
+ "toolCalls": cum_tools or None,
367
+ **({"isolation": isolation} if isolation else {}),
368
+ **({"agentType": agent_type} if agent_type else {}),
369
+ }
370
+ if last_attempt_reason:
371
+ start_event["lastAttemptReason"] = last_attempt_reason
372
+ # 清 None 可选字段
373
+ start_event = {k: v for k, v in start_event.items() if v is not None}
374
+ self._emit(start_event)
375
+
191
376
  spec = AgentSpec(
192
377
  prompt=prompt,
193
378
  label=label,
@@ -198,10 +383,15 @@ class WorkflowHooks:
198
383
  isolation=options.get("isolation") or "none",
199
384
  agent_type=options.get("agent_type") or options.get("agentType"),
200
385
  )
201
- result = await self._deps.worker.run(spec, agent_index)
202
- duration_ms = int((asyncio.get_running_loop().time() - started) * 1000)
203
- if result.tokens:
204
- self.budget.add(result.tokens)
386
+ result = await self._run_worker_raced(
387
+ spec, agent_index, abort_ev=abort_ev, task_id=task_id, agent_id=agent_id
388
+ )
389
+ duration_ms = int((asyncio.get_running_loop().time() - started_mono) * 1000)
390
+ now_ms = int(time.time() * 1000)
391
+ tokens = int(result.tokens or 0)
392
+ tools = int(result.tool_calls or 0)
393
+ if tokens:
394
+ self.budget.add(tokens)
205
395
  if result.skipped:
206
396
  self._emit(
207
397
  {
@@ -209,41 +399,140 @@ class WorkflowHooks:
209
399
  "index": agent_index,
210
400
  "label": label,
211
401
  **phase,
402
+ "agentId": agent_id,
212
403
  "state": "error",
213
404
  "error": "skipped by user",
405
+ "skipped": True,
406
+ "queuedAt": queued_at,
407
+ "startedAt": started_at,
408
+ "lastProgressAt": now_ms,
409
+ "promptPreview": prompt_preview,
410
+ "model": model,
214
411
  "durationMs": duration_ms,
412
+ "attempt": attempt,
215
413
  }
216
414
  )
217
- return None
415
+ # 用特殊返回:上层用 None;这里 raise 不如直接用 sentinel
416
+ return _SKIPPED, tokens, tools # type: ignore[return-value]
218
417
  self._emit(
219
418
  {
220
419
  "type": "workflow_agent",
221
420
  "index": agent_index,
222
421
  "label": label,
223
422
  **phase,
423
+ "agentId": agent_id,
224
424
  "state": "done",
225
- "tokens": result.tokens,
226
- "toolCalls": result.tool_calls,
425
+ "queuedAt": queued_at,
426
+ "startedAt": started_at,
427
+ "lastProgressAt": now_ms,
428
+ "promptPreview": prompt_preview,
429
+ "resultPreview": truncate_preview(
430
+ result.value
431
+ if not isinstance(result.value, (dict, list))
432
+ else str(result.value)
433
+ ),
434
+ "model": model,
435
+ "tokens": tokens,
436
+ "toolCalls": tools,
227
437
  "durationMs": duration_ms,
438
+ "attempt": attempt,
228
439
  }
229
440
  )
230
441
  await self._cache.persist_result(key, agent_id, result.value)
231
- return result.value
442
+ return result.value, tokens, tools
443
+ except AgentStalledSignal as sig:
444
+ duration_ms = int((asyncio.get_running_loop().time() - started_mono) * 1000)
445
+ now_ms = int(time.time() * 1000)
446
+ self._emit(
447
+ {
448
+ "type": "workflow_agent",
449
+ "index": agent_index,
450
+ "label": label,
451
+ **phase,
452
+ "agentId": agent_id,
453
+ "state": "error",
454
+ "error": str(sig),
455
+ "queuedAt": queued_at,
456
+ "startedAt": started_at,
457
+ "lastProgressAt": now_ms,
458
+ "promptPreview": prompt_preview,
459
+ "model": model,
460
+ "durationMs": duration_ms,
461
+ "attempt": attempt,
462
+ "skipped": False,
463
+ }
464
+ )
465
+ raise
232
466
  except Exception as exc:
467
+ now_ms = int(time.time() * 1000)
233
468
  self._emit(
234
469
  {
235
470
  "type": "workflow_agent",
236
471
  "index": agent_index,
237
472
  "label": label,
238
473
  **phase,
474
+ "agentId": agent_id,
239
475
  "state": "error",
240
476
  "error": str(exc),
241
- "durationMs": int((asyncio.get_running_loop().time() - started) * 1000),
477
+ "queuedAt": queued_at,
478
+ "startedAt": started_at,
479
+ "lastProgressAt": now_ms,
480
+ "promptPreview": prompt_preview,
481
+ "model": model,
482
+ "durationMs": int(
483
+ (asyncio.get_running_loop().time() - started_mono) * 1000
484
+ ),
485
+ "attempt": attempt,
242
486
  }
243
487
  )
244
488
  raise
245
489
  finally:
246
- self._slots.release()
490
+ if bridge is not None and task_id is not None:
491
+ bridge.unregister_agent_controller(task_id, agent_id)
492
+
493
+ async def _run_worker_raced(
494
+ self,
495
+ spec: AgentSpec,
496
+ agent_index: int,
497
+ *,
498
+ abort_ev: asyncio.Event | None,
499
+ task_id: str | None,
500
+ agent_id: str,
501
+ ) -> AgentRunResult:
502
+ if abort_ev is None:
503
+ return await self._deps.worker.run(spec, agent_index)
504
+ worker_task = asyncio.create_task(self._deps.worker.run(spec, agent_index))
505
+ abort_task = asyncio.create_task(abort_ev.wait())
506
+ done, pending = await asyncio.wait(
507
+ {worker_task, abort_task},
508
+ return_when=asyncio.FIRST_COMPLETED,
509
+ )
510
+ for task in pending:
511
+ task.cancel()
512
+ try:
513
+ await task
514
+ except asyncio.CancelledError:
515
+ pass
516
+ except Exception: # noqa: BLE001
517
+ pass
518
+ if abort_ev.is_set() and (
519
+ worker_task not in done or worker_task.cancelled() or not worker_task.done()
520
+ ):
521
+ reason = "user-skip"
522
+ if self._deps.task_bridge is not None and task_id is not None:
523
+ reason = (
524
+ self._deps.task_bridge.get_agent_abort_reason(task_id, agent_id)
525
+ or "user-skip"
526
+ )
527
+ if reason == "user-skip":
528
+ return AgentRunResult(value=None, skipped=True)
529
+ msg = (
530
+ "retry requested by user"
531
+ if reason == "user-retry"
532
+ else f"stalled — no progress ({reason})"
533
+ )
534
+ raise AgentStalledSignal(reason, message=msg)
535
+ return await worker_task
247
536
 
248
537
  async def parallel(self, thunks: Sequence[Any]) -> list[Any]:
249
538
  if self._aborted():
@@ -1,9 +1,9 @@
1
1
  """
2
2
  tools/workflow/engine/run_registry.py — 每 run 元数据 JSON
3
3
 
4
- 职责:五态 status;applyProgress 按 type:index 合并;log 帽 500。
4
+ 职责:五态 status(running|paused|completed|failed|killed);applyProgress 按 type:index 合并;log 帽 500。
5
5
  链路位置:Coordinator 终态写盘;resume 原地更新。
6
- 当前裁剪:字段对齐 CC RunRecord 子集。
6
+ 当前裁剪:字段对齐 CC RunRecord 子集;无持久化 interrupted/cancelled。
7
7
  """
8
8
 
9
9
  from __future__ import annotations
@@ -16,7 +16,7 @@ from typing import Any, Literal
16
16
 
17
17
  from langchain_agentx.tools.workflow.constants import MAX_LOG_EVENTS
18
18
 
19
- RunStatus = Literal["running", "completed", "failed", "cancelled", "interrupted"]
19
+ RunStatus = Literal["running", "paused", "completed", "failed", "killed"]
20
20
 
21
21
 
22
22
  @dataclass
@@ -51,3 +51,15 @@ class BudgetExceededError(WorkflowError):
51
51
  self.name = "WorkflowBudgetExceededError"
52
52
  self.spent = spent
53
53
  self.total = total
54
+
55
+
56
+ class AgentStalledSignal(WorkflowError):
57
+ """单次尝试因 stalled/user-retry 中止;外层环重入 vr(非槽 null)。"""
58
+
59
+ def __init__(self, reason: str, *, message: str) -> None:
60
+ super().__init__(message)
61
+ self.reason = reason
62
+
63
+
64
+ class AgentAbandonedError(WorkflowError):
65
+ """重试环耗尽后 throw(parallel/pipeline → null 槽)。"""
@@ -1 +1,59 @@
1
- """tools/workflow/observe — 进度事件与 task 桥(L5);Phase 1 仅占位。"""
1
+ """
2
+ tools/workflow/observe — 进度事件、折叠与宿主面板控制面
3
+
4
+ 职责:merge 规则、fold(Cfr/JLo/BE_)、display_status、HostPanelFacade、TaskBridge。
5
+ 链路位置:engine → observe;CLI 只消费 Facade(跨仓)。
6
+ 当前裁剪:P0 list/fold/kill;P1 skip/retry/pause/save/transcript。
7
+ """
8
+
9
+ from langchain_agentx.tools.workflow.observe.display_status import (
10
+ agent_display_name,
11
+ agent_display_status,
12
+ attempt_reason_label,
13
+ )
14
+ from langchain_agentx.tools.workflow.observe.events import merge_workflow_progress
15
+ from langchain_agentx.tools.workflow.observe.fold import (
16
+ FoldedAgent,
17
+ FoldedPhase,
18
+ WorkflowPhasesView,
19
+ fold_progress,
20
+ )
21
+ from langchain_agentx.tools.workflow.observe.host_panel import (
22
+ ResumeHint,
23
+ WorkflowHostPanelFacade,
24
+ WorkflowRunDetail,
25
+ WorkflowRunSummary,
26
+ )
27
+ from langchain_agentx.tools.workflow.observe.task_bridge import (
28
+ WorkflowTaskBridge,
29
+ WorkflowTaskRecord,
30
+ get_default_task_bridge,
31
+ spawn_background,
32
+ )
33
+ from langchain_agentx.tools.workflow.observe.transcript_view import (
34
+ AgentTranscriptView,
35
+ ToolCallSummary,
36
+ WorkflowAgentTranscriptReader,
37
+ )
38
+
39
+ __all__ = [
40
+ "AgentTranscriptView",
41
+ "FoldedAgent",
42
+ "FoldedPhase",
43
+ "ResumeHint",
44
+ "ToolCallSummary",
45
+ "WorkflowAgentTranscriptReader",
46
+ "WorkflowHostPanelFacade",
47
+ "WorkflowPhasesView",
48
+ "WorkflowRunDetail",
49
+ "WorkflowRunSummary",
50
+ "WorkflowTaskBridge",
51
+ "WorkflowTaskRecord",
52
+ "agent_display_name",
53
+ "agent_display_status",
54
+ "attempt_reason_label",
55
+ "fold_progress",
56
+ "get_default_task_bridge",
57
+ "merge_workflow_progress",
58
+ "spawn_background",
59
+ ]
@@ -0,0 +1,69 @@
1
+ """
2
+ tools/workflow/observe/display_status.py — agent 显示态($Se)
3
+
4
+ 职责:由 workflow_agent 事件 + run_active 派生 UI 显示名(非持久化态)。
5
+ 链路位置:HostPanel / CLI 投影共用;禁止第二套判定。
6
+ 当前裁剪:不渲染字形/色(留给宿主)。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any, Literal
12
+
13
+ DisplayStatus = Literal[
14
+ "done",
15
+ "skipped",
16
+ "blocked",
17
+ "failed",
18
+ "interrupted",
19
+ "queued",
20
+ "running",
21
+ ]
22
+
23
+ _DISPLAY_NAME: dict[DisplayStatus, str] = {
24
+ "done": "Completed",
25
+ "skipped": "Skipped",
26
+ "blocked": "Blocked",
27
+ "failed": "Failed",
28
+ "interrupted": "Stopped",
29
+ "queued": "Queued",
30
+ "running": "Running",
31
+ }
32
+
33
+
34
+ def agent_display_status(event: dict[str, Any], *, run_active: bool) -> DisplayStatus:
35
+ """对齐设计 §8.1 $Se。"""
36
+ state = event.get("state")
37
+ if state == "done":
38
+ return "done"
39
+ if state == "error":
40
+ if event.get("skipped"):
41
+ return "skipped"
42
+ if event.get("blocked"):
43
+ return "blocked"
44
+ err = event.get("error")
45
+ if err == "skipped by user":
46
+ return "skipped"
47
+ return "failed"
48
+ if not run_active:
49
+ return "interrupted"
50
+ if event.get("queuedAt") is not None and event.get("startedAt") is None:
51
+ return "queued"
52
+ return "running"
53
+
54
+
55
+ def agent_display_name(status: DisplayStatus) -> str:
56
+ return _DISPLAY_NAME[status]
57
+
58
+
59
+ def attempt_reason_label(attempt: int | None, reason: str | None) -> str | None:
60
+ """VAa:attempt N (throttled|user retry|stalled)。"""
61
+ if attempt is None or not reason:
62
+ return None
63
+ mapping = {
64
+ "throttled": "throttled",
65
+ "user-retry": "user retry",
66
+ "stalled": "stalled",
67
+ }
68
+ shown = mapping.get(reason, reason)
69
+ return f"attempt {attempt} ({shown})"