power-loop 6.47.0__tar.gz → 6.49.0__tar.gz

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.
Files changed (114) hide show
  1. {power_loop-6.47.0 → power_loop-6.49.0}/PKG-INFO +1 -1
  2. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/__init__.py +1 -1
  3. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/agent/stateful_loop.py +1 -1
  4. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/core/pipeline.py +8 -4
  5. power_loop-6.49.0/power_loop/runtime/background.py +42 -0
  6. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/representation.py +1 -1
  7. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/runtime_state.py +25 -3
  8. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/tools/default_manifest.py +3 -1
  9. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/tools/default_tools.py +89 -25
  10. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/workflow/engine.py +43 -2
  11. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/workflow/journal.py +4 -0
  12. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop.egg-info/PKG-INFO +1 -1
  13. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop.egg-info/SOURCES.txt +1 -0
  14. {power_loop-6.47.0 → power_loop-6.49.0}/LICENSE +0 -0
  15. {power_loop-6.47.0 → power_loop-6.49.0}/README.md +0 -0
  16. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/_vendor/__init__.py +0 -0
  17. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/_vendor/llm_client/__init__.py +0 -0
  18. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/_vendor/llm_client/anthropic_factory.py +0 -0
  19. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/_vendor/llm_client/capabilities.py +0 -0
  20. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/_vendor/llm_client/interface.py +0 -0
  21. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/_vendor/llm_client/llm_factory.py +0 -0
  22. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/_vendor/llm_client/llm_tooling.py +0 -0
  23. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/_vendor/llm_client/llm_utils.py +0 -0
  24. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/_vendor/llm_client/multimodal.py +0 -0
  25. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/_vendor/llm_client/proxy_fallback.py +0 -0
  26. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/agent/__init__.py +0 -0
  27. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/agent/follow_up.py +0 -0
  28. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/agent/sink.py +0 -0
  29. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/agent/system_prompt.py +0 -0
  30. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/agent/types.py +0 -0
  31. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contracts/__init__.py +0 -0
  32. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contracts/errors.py +0 -0
  33. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contracts/event_payloads.py +0 -0
  34. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contracts/events.py +0 -0
  35. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contracts/handlers.py +0 -0
  36. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contracts/hook_contexts.py +0 -0
  37. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contracts/hooks.py +0 -0
  38. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contracts/messages.py +0 -0
  39. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contracts/protocols.py +0 -0
  40. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contracts/tools.py +0 -0
  41. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contrib/__init__.py +0 -0
  42. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contrib/_redact.py +0 -0
  43. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contrib/jsonl_sink.py +0 -0
  44. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contrib/logging_sink.py +0 -0
  45. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contrib/mcp.py +0 -0
  46. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contrib/metrics_sink.py +0 -0
  47. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/contrib/otel_sink.py +0 -0
  48. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/core/agent_context.py +0 -0
  49. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/core/events.py +0 -0
  50. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/core/hooks.py +0 -0
  51. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/core/phase.py +0 -0
  52. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/core/runner.py +0 -0
  53. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/core/state.py +0 -0
  54. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/py.typed +0 -0
  55. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/blackboard.py +0 -0
  56. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/budget.py +0 -0
  57. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/cancellation.py +0 -0
  58. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/capability_probe.py +0 -0
  59. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/compact.py +0 -0
  60. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/env.py +0 -0
  61. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/exec_backend.py +0 -0
  62. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/fold.py +0 -0
  63. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/fold_adapter.py +0 -0
  64. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/history_projector.py +0 -0
  65. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/history_sanitize.py +0 -0
  66. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/human_input.py +0 -0
  67. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/image_recall.py +0 -0
  68. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/memory.py +0 -0
  69. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/notes.py +0 -0
  70. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/provider.py +0 -0
  71. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/retry.py +0 -0
  72. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/session_store.py +0 -0
  73. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/skills.py +0 -0
  74. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/spec.py +0 -0
  75. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/steer.py +0 -0
  76. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/stop_policy.py +0 -0
  77. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/store/__init__.py +0 -0
  78. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/store/backends/__init__.py +0 -0
  79. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/store/backends/mysql.py +0 -0
  80. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/store/backends/postgres.py +0 -0
  81. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/store/backends/sqlite.py +0 -0
  82. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/store/capabilities.py +0 -0
  83. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/store/db.py +0 -0
  84. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/store/dialect.py +0 -0
  85. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/store/factory.py +0 -0
  86. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/store/schema.py +0 -0
  87. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/store/store.py +0 -0
  88. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/store/types.py +0 -0
  89. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/structured.py +0 -0
  90. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/stub_provider.py +0 -0
  91. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/timers.py +0 -0
  92. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/todos.py +0 -0
  93. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/runtime/usage_estimate.py +0 -0
  94. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/tools/__init__.py +0 -0
  95. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/tools/blackboard.py +0 -0
  96. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/tools/command_policy.py +0 -0
  97. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/tools/command_rules.py +0 -0
  98. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/tools/registry.py +0 -0
  99. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/tools/spawn_agent.py +0 -0
  100. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/workflow/__init__.py +0 -0
  101. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/workflow/api.py +0 -0
  102. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/workflow/introspect.py +0 -0
  103. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/workflow/result.py +0 -0
  104. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/workflow/resume.py +0 -0
  105. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/workflow/runner.py +0 -0
  106. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/workflow/spec.py +0 -0
  107. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/workflow/subprocess_executor.py +0 -0
  108. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/workflow/tool.py +0 -0
  109. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop/workflow/worker.py +0 -0
  110. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop.egg-info/dependency_links.txt +0 -0
  111. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop.egg-info/requires.txt +0 -0
  112. {power_loop-6.47.0 → power_loop-6.49.0}/power_loop.egg-info/top_level.txt +0 -0
  113. {power_loop-6.47.0 → power_loop-6.49.0}/pyproject.toml +0 -0
  114. {power_loop-6.47.0 → power_loop-6.49.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: power-loop
3
- Version: 6.47.0
3
+ Version: 6.49.0
4
4
  Summary: Embeddable agent execution kernel — LLM loop, hooks, events, tools, dynamic sub-agents.
5
5
  Author-email: zhangran <zhangran24@126.com>
6
6
  License: MIT
@@ -15,7 +15,7 @@ Stability tiers
15
15
  无版本承诺,可随时变更或删除。
16
16
  """
17
17
 
18
- __version__ = "6.47.0"
18
+ __version__ = "6.49.0"
19
19
 
20
20
  # Public LLM contract (SDK-free) re-exported so callers (e.g. writing llm.* hooks or
21
21
  # a custom LLMService) don't reach into the internal vendored transport package (H3.4).
@@ -1272,7 +1272,7 @@ class StatefulAgentLoop:
1272
1272
  jobs.append({"id": "send", "kind": "foreground", "title": "当前这一轮",
1273
1273
  "status": "running", "started_at": None, "origin": ""})
1274
1274
  for t in await store.list_background_tasks(session_id):
1275
- if t.status != "running":
1275
+ if t.status not in ("queued", "running"):
1276
1276
  continue
1277
1277
  jobs.append({"id": f"bg:{t.task_id}", "kind": "background",
1278
1278
  "title": str(t.command or "")[:80], "status": t.status,
@@ -1128,9 +1128,9 @@ class AgentPipeline:
1128
1128
  async def _runtime_messages_for_round(self, round_index: int) -> list[LoopMessage]:
1129
1129
  """Build transient runtime-state messages for the next LLM call.
1130
1130
 
1131
- These messages are deliberately not appended through ``_append_message``:
1132
- the store's runtime state is the authority, and the message is just the
1133
- current projection the model needs for this round.
1131
+ Current state projections are ephemeral. Completed background tool results
1132
+ opt into durable history with ``_persist`` so later sends retain their
1133
+ original-tool summary after the notification is acknowledged.
1134
1134
  """
1135
1135
  if self.store is None or self.session_id is None:
1136
1136
  todo_snap = self.ctx.todo.snapshot_for_prompt()
@@ -1153,7 +1153,11 @@ class AgentPipeline:
1153
1153
  ack = m.pop("_ack", None)
1154
1154
  if ack is not None and hasattr(projector, "acknowledge"):
1155
1155
  self._pending_acks.append((projector, ack))
1156
- messages.append(m)
1156
+ if m.pop("_persist", False):
1157
+ if not any(_persist_key(old) == _persist_key(m) for old in self.history):
1158
+ await self._append_message(m, round_index=round_index)
1159
+ else:
1160
+ messages.append(m)
1157
1161
  return messages
1158
1162
 
1159
1163
  async def _acknowledge_runtime(self) -> None:
@@ -0,0 +1,42 @@
1
+ """Durable identity and results of background tool calls; no schema migration needed."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from typing import Any
6
+
7
+ ACTIVE_STATUSES = frozenset({'queued', 'pending', 'running'})
8
+ RESULT_PREFIX = '[background_tool_results]\n'
9
+
10
+
11
+ def record_key(task_id: str) -> str:
12
+ return 'background_tool:' + task_id
13
+
14
+
15
+ def encode_results(tasks: list[dict[str, Any]]) -> str:
16
+ return RESULT_PREFIX + json.dumps({'version': 1, 'tasks': tasks}, ensure_ascii=False)
17
+
18
+
19
+ async def load_record(store: Any, sid: str | None, task_id: str) -> dict[str, Any] | None:
20
+ if store is None or sid is None or not hasattr(store, 'get_runtime_state'):
21
+ return None
22
+ value = await store.get_runtime_state(sid, record_key(task_id), default=None)
23
+ return value if isinstance(value, dict) else None
24
+
25
+
26
+ def summarize_record(record: dict[str, Any]) -> dict[str, Any]:
27
+ from power_loop.core.agent_context import get_current_loop
28
+
29
+ loop = get_current_loop()
30
+ config = getattr(loop, 'config', None)
31
+ rep = getattr(config, 'representation', None)
32
+ distill = getattr(rep, 'distill_tool_call', None)
33
+ result = str(record.get('result') or '')
34
+ summary = result[:750]
35
+ if callable(distill):
36
+ try:
37
+ summary = distill(record['tool'], record.get('args') or {}, result,
38
+ getattr(loop, 'tool_registry', None))
39
+ except Exception:
40
+ # The canonical result stays available even if a host distiller fails.
41
+ pass
42
+ return {k: record.get(k) for k in ('task_id', 'tool', 'status', 'result_ref')} | {'summary': summary}
@@ -363,7 +363,7 @@ class ProjectedRepresentation:
363
363
  seen_assistant = False
364
364
  for r in send_rows:
365
365
  if r.role == "user":
366
- if seen_assistant:
366
+ if seen_assistant or getattr(r, "name", None) == "background_tool_results":
367
367
  # Verbatim like the input (conversation content, not tool output).
368
368
  tools.append({
369
369
  "name": "__user__",
@@ -107,8 +107,30 @@ class BackgroundRuntimeProjector(RuntimeProjector):
107
107
  updates = await store.list_unseen_background_updates(session_id)
108
108
  if not updates:
109
109
  return []
110
- chunks: list[str] = ["<background_updates>"]
110
+ from power_loop.runtime.background import ACTIVE_STATUSES, encode_results, load_record, summarize_record
111
+ durable = []
112
+ legacy = []
111
113
  for task in updates:
114
+ record = await load_record(store, session_id, task.task_id)
115
+ if record is not None and task.status not in ACTIVE_STATUSES:
116
+ if "result" not in record:
117
+ record = {**record, "result": "(完整结果未保存,以下为台账预览)\n" + (task.output_tail or "")}
118
+ durable.append(summarize_record({**record, "status": task.status}))
119
+ else:
120
+ legacy.append(task)
121
+ messages = []
122
+ for record in durable:
123
+ # Stable per-task messages remain deduplicable if another task finishes
124
+ # between a failed model request and its retry.
125
+ message = {"role": "user", "name": "background_tool_results",
126
+ "content": encode_results([record]), "_persist": True}
127
+ if self.mark_seen:
128
+ message["_ack"] = ("background_seen", [record["task_id"]])
129
+ messages.append(message)
130
+ if not legacy:
131
+ return messages
132
+ chunks: list[str] = ["<background_updates>"]
133
+ for task in legacy:
112
134
  output = (task.output_tail or "(running)").strip()
113
135
  chunks.append(
114
136
  "\n".join(
@@ -132,8 +154,8 @@ class BackgroundRuntimeProjector(RuntimeProjector):
132
154
  # succeeded. The pipeline strips this private marker before the request and calls
133
155
  # :meth:`acknowledge` only after a successful call — a failed / degraded / aborted
134
156
  # call must not swallow the updates (design/124 Z7).
135
- msg["_ack"] = ("background_seen", [task.task_id for task in updates])
136
- return [msg]
157
+ msg["_ack"] = ("background_seen", [task.task_id for task in legacy])
158
+ return [*messages, msg]
137
159
 
138
160
  async def acknowledge(self, *, store: Any, session_id: str, ack: Any) -> None:
139
161
  """Mark the projected tasks seen — called by the pipeline once the model saw them."""
@@ -357,7 +357,9 @@ DEFAULT_TOOL_DEFINITIONS: list[ToolDefinition] = [
357
357
  "task_id immediately. action=tool runs one async-capable TOOL in the background "
358
358
  "(tool=<name>, args={…}) and returns a task_id at once — use it for long, "
359
359
  "side-effect-free calls (image generation, web fetches) whose result you do not "
360
- "need immediately. **Results are delivered to you automatically on completion "
360
+ "need immediately. Up to 8 submitted tools execute per session; excess calls are accepted "
361
+ "as queued and start automatically in submission order when a slot opens. No check is needed "
362
+ "to release a slot. **Results are delivered to you automatically on completion "
361
363
  "(in the background updates block or a wake message) — do not poll for them.** "
362
364
  "While a task runs, do other work, or pass_turn if there is nothing else to do. "
363
365
  "action=check is a fallback: call it only when a wake message explicitly asks you to, "
@@ -1262,6 +1262,7 @@ class BackgroundManager:
1262
1262
  # agent when they settle — the user said stop).
1263
1263
  self._stop_tokens: dict[str, Any] = {}
1264
1264
  self._stopped: set[str] = set()
1265
+ self._tool_slots: dict[tuple[Any, int, str | None], tuple[asyncio.Semaphore, int]] = {}
1265
1266
  # Live daemon threads (so shutdown can drain them) and terminal write-backs that
1266
1267
  # could not be delivered to their owning loop (so a later check / shutdown can
1267
1268
  # still persist them instead of leaving the row stuck at 'running' forever).
@@ -1274,7 +1275,7 @@ class BackgroundManager:
1274
1275
  Running tasks are never evicted. Caller must hold ``self._lock``."""
1275
1276
  while len(self.tasks) > _MAX_BG_TASKS:
1276
1277
  for tid, t in self.tasks.items(): # insertion order = oldest first
1277
- if t.get("status") != "running":
1278
+ if t.get("status") not in ("queued", "running"):
1278
1279
  del self.tasks[tid]
1279
1280
  self._threads.pop(tid, None)
1280
1281
  break
@@ -1527,9 +1528,9 @@ class BackgroundManager:
1527
1528
  计费/活动打标上下文天然跟着走,不需要捕获重播。结果持久化进同一张
1528
1529
  background 任务表(command 字段以 ``tool:`` 前缀区分);完成后调用宿主注册的
1529
1530
  ``on_tool_task_complete``(best-effort),由宿主决定要不要唤醒睡着的 agent。
1530
- 进程重启 = 任务丢失,行卡 running,由 check 的 flush_orphaned 语义外**另行**
1531
- 诚实兜底:这里在启动时登记 in-memory,check 未命中 in-memory 且行仍 running
1532
- 时按孤儿报告(复用 shell 分支已有的自愈路径)。
1531
+ 每个 store/sid 的新调用最多 8 个同时执行,超出后按接收顺序等待。
1532
+ 队列驻留当前进程;宿主重启时应把旧 queued/running 行标为 interrupted,
1533
+ 不自动重放可能已经产生外部副作用的调用。adopt 接管已经执行的调用,不重新排队。
1533
1534
  """
1534
1535
  from power_loop.core.agent_context import get_current_loop
1535
1536
 
@@ -1579,21 +1580,25 @@ class BackgroundManager:
1579
1580
  + ("\n可以后台跑的是:" + "、".join(_others) if _others else "")
1580
1581
  )
1581
1582
  store, sid = _current_store_and_session()
1582
- if store is not None and sid is not None:
1583
- rows = await store.list_background_tasks(sid)
1584
- running = sum(1 for r in rows if r.status == "running" and r.command.startswith("tool:"))
1585
- if running >= 8:
1586
- raise ValueError("后台工具任务已达并发上限(8)——先 check 收结果再发新的。")
1587
1583
  task_id = str(uuid.uuid4())[:8]
1588
1584
  args = dict(args or {})
1589
1585
  label = f"tool:{name} " + json.dumps(args, ensure_ascii=False)[:160]
1590
- with self._lock:
1591
- self.tasks[task_id] = {"command": label, "status": "running", "result": None}
1586
+ record = {"task_id": task_id, "tool": name, "args": args, "status": "queued",
1587
+ "result_ref": "background_tool:" + task_id}
1588
+ if store is not None and sid is not None and hasattr(store, "set_runtime_state"):
1589
+ await store.set_runtime_state(sid, record["result_ref"], record)
1592
1590
  if store is not None and sid is not None:
1593
1591
  await store.upsert_background_task(
1594
- sid, task_id=task_id, command=label, status="running",
1595
- return_code=None, output_tail="(running)",
1592
+ sid, task_id=task_id, command=label, status="queued",
1593
+ return_code=None, output_tail="(queued)",
1596
1594
  )
1595
+ with self._lock:
1596
+ self.tasks[task_id] = {"command": label, "status": "queued", "result": None, "tool_record": record}
1597
+ # One FIFO admission gate per store/session/event loop. No await between lookup
1598
+ # and registration: concurrent submissions cannot oversubscribe the limit.
1599
+ key = (asyncio.get_running_loop(), id(store), sid)
1600
+ gate, users = self._tool_slots.get(key, (asyncio.Semaphore(8), 0))
1601
+ self._tool_slots[key] = (gate, users + 1)
1597
1602
 
1598
1603
  # Its own ROOT stop token: a background task outlives the send that started it (the
1599
1604
  # UI stop button stops the foreground, not this); only a stop by id reaches it.
@@ -1609,13 +1614,34 @@ class BackgroundManager:
1609
1614
  async def _invoke() -> Any:
1610
1615
  ctok = set_current_cancel_token(tok)
1611
1616
  try:
1612
- return await registry.invoke_async(name, args)
1617
+ async with gate:
1618
+ if store is not None and sid is not None:
1619
+ await store.upsert_background_task(
1620
+ sid, task_id=task_id, command=label, status="running",
1621
+ return_code=None, output_tail="(running)",
1622
+ )
1623
+ with self._lock:
1624
+ self.tasks[task_id]["status"] = "running"
1625
+ return await registry.invoke_async(name, args)
1613
1626
  finally:
1614
1627
  reset_current_cancel_token(ctok)
1615
1628
 
1616
- self._supervise(task_id, label, store, sid, _invoke())
1629
+ worker = self._supervise(task_id, label, store, sid, _invoke())
1630
+
1631
+ def release_pool(_task: Any) -> None:
1632
+ semaphore, count = self._tool_slots[key]
1633
+ if count == 1:
1634
+ del self._tool_slots[key]
1635
+ else:
1636
+ self._tool_slots[key] = (semaphore, count - 1)
1637
+
1638
+ worker.add_done_callback(release_pool)
1639
+ # Start supervision before exposing the id, including for immediate cancellation.
1640
+ await asyncio.sleep(0)
1617
1641
  return (
1618
- f"后台任务已启动:task_id={task_id}({label[:80]})。"
1642
+ f"后台任务已接收:task_id={task_id}({label[:80]})。"
1643
+ f"当前状态:{self.tasks[task_id]['status']}。"
1644
+ "同一会话最多同时执行 8 个后台工具,超出的自动排队,空出名额后自动执行,无需 check 释放名额。"
1619
1645
  "**完成时结果会自动送到你面前,不用去取。** 现在去做别的;"
1620
1646
  "手上没有别的可做就 pass_turn 停轮等它——用 check 反复问「好了没」只会空烧回合,"
1621
1647
  "任务不会因此快一点,用户还得等你。"
@@ -1644,14 +1670,15 @@ class BackgroundManager:
1644
1670
  status = "failed"
1645
1671
  else:
1646
1672
  output = str(result if result is not None else "")
1647
- output = output[:8000]
1673
+ if output.lstrip().lower().startswith("error:"):
1674
+ status = "failed"
1648
1675
  except asyncio.CancelledError:
1649
1676
  status, output = "cancelled", "(cancelled)"
1650
1677
  await self._settle(task_id, label, store, sid, status, output, notify=False)
1651
1678
  raise
1652
1679
  except Exception as exc: # noqa: BLE001 — 失败是任务结果,不是崩溃
1653
1680
  status = "failed"
1654
- output = f"{type(exc).__name__}: {exc}"[:2000]
1681
+ output = f"{type(exc).__name__}: {exc}"
1655
1682
  await self._settle(task_id, label, store, sid, status, output, notify=True)
1656
1683
 
1657
1684
  task = asyncio.ensure_future(_worker())
@@ -1671,12 +1698,21 @@ class BackgroundManager:
1671
1698
  if task is not None:
1672
1699
  task["status"] = status
1673
1700
  task["result"] = output or "(no output)"
1701
+ record = (task or {}).get("tool_record")
1702
+ if record is not None and task is not None:
1703
+ record = {**record, "status": status, "result": output}
1704
+ task["tool_record"] = record
1705
+ if store is not None and sid is not None and hasattr(store, "set_runtime_state"):
1706
+ try:
1707
+ await store.set_runtime_state(sid, record["result_ref"], record)
1708
+ except Exception: # noqa: BLE001 — still settle the task and notify the host
1709
+ logger.warning("tool task %s: full result write-back failed", task_id, exc_info=True)
1674
1710
  if store is not None and sid is not None:
1675
1711
  try:
1676
1712
  await store.upsert_background_task(
1677
1713
  sid, task_id=task_id, command=label, status=status,
1678
1714
  return_code=0 if status == "completed" else 1,
1679
- output_tail=output or "(no output)",
1715
+ output_tail=output[:8000] or "(no output)",
1680
1716
  )
1681
1717
  except Exception: # noqa: BLE001
1682
1718
  logger.warning("tool task %s: status write-back failed", task_id, exc_info=True)
@@ -1699,8 +1735,12 @@ class BackgroundManager:
1699
1735
  store, sid = _current_store_and_session()
1700
1736
  task_id = str(uuid.uuid4())[:8]
1701
1737
  label = f"tool:{tool_name} " + json.dumps(dict(args or {}), ensure_ascii=False)[:160]
1738
+ record = {"task_id": task_id, "tool": tool_name, "args": dict(args or {}),
1739
+ "status": "running", "result_ref": "background_tool:" + task_id}
1740
+ if store is not None and sid is not None and hasattr(store, "set_runtime_state"):
1741
+ await store.set_runtime_state(sid, record["result_ref"], record)
1702
1742
  with self._lock:
1703
- self.tasks[task_id] = {"command": label, "status": "running", "result": None}
1743
+ self.tasks[task_id] = {"command": label, "status": "running", "result": None, "tool_record": record}
1704
1744
  if store is not None and sid is not None:
1705
1745
  await store.upsert_background_task(
1706
1746
  sid, task_id=task_id, command=label, status="running",
@@ -1752,6 +1792,10 @@ class BackgroundManager:
1752
1792
  if worker.done():
1753
1793
  return "finished"
1754
1794
  self._stopped.add(task_id)
1795
+ if self.tasks.get(task_id, {}).get("status") == "queued":
1796
+ worker.cancel()
1797
+ await asyncio.wait({worker}, timeout=5)
1798
+ return "stopped"
1755
1799
  tok = self._stop_tokens.get(task_id)
1756
1800
  if tok is not None and hasattr(tok, "cancel"):
1757
1801
  tok.cancel("stopped")
@@ -1762,6 +1806,19 @@ class BackgroundManager:
1762
1806
  await asyncio.wait({worker}, timeout=5)
1763
1807
  return "forced"
1764
1808
 
1809
+ async def _tool_result(self, store: Any, sid: str | None, task_id: str) -> dict[str, Any] | None:
1810
+ from power_loop.runtime.background import load_record
1811
+ record = await load_record(store, sid, task_id)
1812
+ memory_record = self.tasks.get(task_id, {}).get("tool_record")
1813
+ if record is None or ("result" not in record and memory_record and "result" in memory_record):
1814
+ record = memory_record
1815
+ if record is not None:
1816
+ status, tail = await self._status_of(store, sid, task_id)
1817
+ if status not in ("queued", "pending", "running") and "result" not in record:
1818
+ record = {**record, "result": tail, "legacy": True}
1819
+ return {**record, "status": status}
1820
+ return None
1821
+
1765
1822
  async def _status_of(self, store: Any, sid: str | None, task_id: str) -> tuple[str, str]:
1766
1823
  """(status, 输出尾巴):优先读 store 里这个会话的行,没有就读进程内记录。"""
1767
1824
  if store is not None and sid is not None:
@@ -1784,10 +1841,10 @@ class BackgroundManager:
1784
1841
  ids = [str(x) for x in (task_ids or []) if str(x).strip()]
1785
1842
  if not ids:
1786
1843
  if store is not None and sid is not None:
1787
- ids = [r.task_id for r in await store.list_background_tasks(sid) if str(r.status) == "running"]
1844
+ ids = [r.task_id for r in await store.list_background_tasks(sid) if str(r.status) in ("queued", "running")]
1788
1845
  else:
1789
1846
  with self._lock:
1790
- ids = [tid for tid, tk in self.tasks.items() if tk.get("status") == "running"]
1847
+ ids = [tid for tid, tk in self.tasks.items() if tk.get("status") in ("queued", "running")]
1791
1848
  if not ids:
1792
1849
  return "没有在跑的后台任务。"
1793
1850
  timeout_s = max(1.0, min(float(timeout_s or 600.0), 3600.0))
@@ -1797,7 +1854,7 @@ class BackgroundManager:
1797
1854
  end = loop.time() + timeout_s
1798
1855
  while loop.time() < end:
1799
1856
  states = [(await self._status_of(store, sid, tid))[0] for tid in ids]
1800
- if all(s not in ("running", "unknown") for s in states):
1857
+ if all(s not in ("queued", "running", "unknown") for s in states):
1801
1858
  return
1802
1859
  futs = {self._workers[tid] for tid in ids if tid in self._workers and not self._workers[tid].done()}
1803
1860
  await asyncio.wait(futs or {asyncio.ensure_future(asyncio.sleep(1.0))}, timeout=1.0,
@@ -1810,15 +1867,22 @@ class BackgroundManager:
1810
1867
  pending = 0
1811
1868
  for tid in ids:
1812
1869
  status, tail = await self._status_of(store, sid, tid)
1813
- pending += status == "running"
1870
+ pending += status in ("queued", "running")
1814
1871
  lines.append(f"{tid}: [{status}] {tail[-1500:] if tail else ''}".rstrip())
1815
1872
  head = ("等的时候来了新消息,先停下来等(任务照常在跑)。" if steered
1816
1873
  else f"还有 {pending} 件没做完(等了 {int(timeout_s)} 秒,任务照常在跑)。" if pending
1817
1874
  else "都做完了。")
1818
- return head + "\n" + "\n".join(lines)
1875
+ from power_loop.runtime.background import encode_results
1876
+ records = [r for tid in ids if (r := await self._tool_result(store, sid, tid)) is not None]
1877
+ return head + "\n" + "\n".join(lines) + ("\n" + encode_results(records) if records else "")
1819
1878
 
1820
1879
  async def check(self, task_id: str | None = None) -> str:
1821
1880
  store, sid = _current_store_and_session()
1881
+ if task_id:
1882
+ record = await self._tool_result(store, sid, task_id)
1883
+ if record is not None:
1884
+ from power_loop.runtime.background import encode_results
1885
+ return f"[{record['status']}] {record['tool']}\n" + encode_results([record])
1822
1886
  if store is not None and sid is not None:
1823
1887
  # Recover any terminal status a daemon thread couldn't deliver to a now-gone
1824
1888
  # loop, so a stuck 'running' row self-heals on the next read.
@@ -122,6 +122,8 @@ def _loop_prompt(lc: dict[str, Any], user_input: str) -> str:
122
122
  return (f"第 {lc['iteration']}/{lc['max']} 轮:上一轮没通过({lc.get('why') or ''})。\n"
123
123
  f"上一轮的意见:\n{lc.get('feedback') or ''}\n\n"
124
124
  "按意见改。你上一轮做的都还在(会话、文件),在已有成果上改,不要从头重做。改完照原来的要求交卷。\n\n"
125
+ "先用 todo 列出本轮审核意见对应的修复与复验任务;上一轮已完成待办只代表历史成果。"
126
+ "完成待办后还需提交本轮最终结果;若审核缺少具体问题,先读取审核报告核实。\n\n"
125
127
  f"(这一轮的任务输入照旧附在下面)\n{user_input}")
126
128
 
127
129
 
@@ -802,6 +804,7 @@ class WorkflowEngine:
802
804
  and lc["prev"].get(node.id)):
803
805
  prev_sid = lc["prev"][node.id]
804
806
  try:
807
+ await self._prepare_rework(prev_sid, node.id, lc)
805
808
  resumed_raw = await self._continue_leaf(
806
809
  prev_sid, _loop_prompt(lc, user_input), extra_rounds=max(int(node.spec.max_rounds or 30), 10), stop=node_tok)
807
810
  resumed_raw.setdefault("session_id", prev_sid)
@@ -1037,6 +1040,27 @@ class WorkflowEngine:
1037
1040
  except Exception: # noqa: BLE001
1038
1041
  return []
1039
1042
 
1043
+ async def _prepare_rework(self, session_id: str, node_id: str, lc: dict[str, Any]) -> None:
1044
+ """Archive the previous todo only for a new review iteration, never for a budget continuation."""
1045
+ from power_loop.runtime.todos import render_todos, todo_counts, validate_todos
1046
+
1047
+ if not hasattr(self._loop, "ensure_store"):
1048
+ return
1049
+ store = await self._loop.ensure_store()
1050
+ key = f"workflow_rework:{lc['loop_id']}:{node_id}:{lc['iteration']}"
1051
+ if await store.get_runtime_state(session_id, key, default=None):
1052
+ return
1053
+ old = await store.get_runtime_state(session_id, "todo", default={})
1054
+ await store.set_runtime_state(session_id, key + ":previous_todo", old)
1055
+ items = validate_todos([{"text": f"第 {lc['iteration']} 轮:核实审核意见,列出修复与复验任务", "status": "in_progress"}])
1056
+ await store.set_runtime_state(session_id, "todo", {
1057
+ "items": items, "rendered": render_todos(items), "counts": todo_counts(items),
1058
+ })
1059
+ state = {"iteration": lc["iteration"], "node_id": node_id, "loop_id": lc["loop_id"],
1060
+ "reason": lc.get("why"), "previous_todo_ref": key + ":previous_todo"}
1061
+ await store.set_runtime_state(session_id, "workflow_rework", state)
1062
+ await store.set_runtime_state(session_id, key, state)
1063
+
1040
1064
  async def _continue_leaf(self, session_id: str, prompt: str, *, extra_rounds: int,
1041
1065
  stop: CancellationToken | None = None) -> dict[str, Any]:
1042
1066
  """原会话补轮。走 executor 的 ``continue_agent``(host 可换实现,如加自己的 guards);
@@ -1044,8 +1068,25 @@ class WorkflowEngine:
1044
1068
  fn = getattr(self._executor, "continue_agent", None)
1045
1069
  if fn is None:
1046
1070
  fn = InProcessExecutor().continue_agent
1047
- return await fn(session_id, prompt, parent_loop=self._loop,
1048
- extra_rounds=extra_rounds, stop_event=stop or self._cancel)
1071
+ from power_loop.contracts.event_payloads import SubagentCompletedPayload, SubagentTaskStartPayload
1072
+ from power_loop.contracts.events import AgentEventType
1073
+ from power_loop.core.agent_context import get_session_id
1074
+ from power_loop.runtime.spec import _publish_subagent_event
1075
+
1076
+ parent_sid = get_session_id()
1077
+ _publish_subagent_event(self._loop, parent_sid, AgentEventType.SUBAGENT_TASK_START,
1078
+ SubagentTaskStartPayload(task=prompt, preset="core", sub_session_id=session_id, depth=1))
1079
+ result = None
1080
+ try:
1081
+ result = await fn(session_id, prompt, parent_loop=self._loop,
1082
+ extra_rounds=extra_rounds, stop_event=stop or self._cancel)
1083
+ return result
1084
+ finally:
1085
+ _publish_subagent_event(self._loop, parent_sid, AgentEventType.SUBAGENT_COMPLETED,
1086
+ SubagentCompletedPayload(sub_session_id=session_id,
1087
+ status=(result or {}).get("status", "failed"),
1088
+ rounds=int((result or {}).get("rounds") or 0),
1089
+ final_text=str((result or {}).get("final_text") or "")))
1049
1090
 
1050
1091
  @staticmethod
1051
1092
  def _should_retry(raw: dict[str, Any], triggers: set[str]) -> bool:
@@ -181,6 +181,10 @@ async def node_start(
181
181
  if jn is None or _is_terminal(jn.get("status")):
182
182
  return MUTATE_SKIP
183
183
  live = dict(jn.get("live") or {})
184
+ if node_id not in live:
185
+ attempts = dict(jn.get("node_attempts") or {})
186
+ attempts[node_id] = int(attempts.get(node_id) or 0) + 1
187
+ jn["node_attempts"] = attempts
184
188
  live[node_id] = _now_ms()
185
189
  jn["live"] = live
186
190
  jn["updated_at_ms"] = _now_ms()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: power-loop
3
- Version: 6.47.0
3
+ Version: 6.49.0
4
4
  Summary: Embeddable agent execution kernel — LLM loop, hooks, events, tools, dynamic sub-agents.
5
5
  Author-email: zhangran <zhangran24@126.com>
6
6
  License: MIT
@@ -48,6 +48,7 @@ power_loop/core/phase.py
48
48
  power_loop/core/pipeline.py
49
49
  power_loop/core/runner.py
50
50
  power_loop/core/state.py
51
+ power_loop/runtime/background.py
51
52
  power_loop/runtime/blackboard.py
52
53
  power_loop/runtime/budget.py
53
54
  power_loop/runtime/cancellation.py
File without changes
File without changes
File without changes
File without changes