JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(skill_turbo): 多交付物清单编排与串行契约,修复 taskProgress 槽位泄漏与 fresh 守卫后续交付物误拦/收紧
dufengyang81bab636a6ff
diff --git a/jiuwenswarm/agents/harness/common/rails/skill_protocol_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/skill_protocol_prompt_rail.pyindex 5fa3ee6758..cdcb3d8ed7 100644--- a/jiuwenswarm/agents/harness/common/rails/skill_protocol_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/skill_protocol_prompt_rail.py@@ -41,6 +41,7 @@ _CN_PROTOCOL = """## 技能执行规范(强制)1. **声明步骤**:默认情况下,每次行动前必须在回复开头声明当前所在步骤,格式:`[当前步骤: <步骤名称>]`。**无需调用任何工具来"开始"步骤**——声明本身即代表进入该步。若 SKILL.md 明确声明“阶段状态和阶段消息由工具事件唯一生成”,则以该声明为准,禁止自行输出 `[当前步骤: ...]` 或其他步骤声明。2. **必须使用 todo**:在执行 skill 步骤前,必须先创建 todo 列表。+ - **加速通道例外(单份交付物)**:若任务直接交给 `skill_acceleration_exec` 加速通道执行、且本单轮只需产出**一份交付物**,**不要创建 todo**——加速通道内部会通过 Stage 步骤事件自行在前端展示进度,无需也不应再建外层 todo(建了会导致前端任务列表异常)。**仅当单轮需产出多份交付物**(需多次调用 `skill_acceleration_exec`)时,才必须先建外层待办清单(规则见「技能加速通道」段的「多交付物待办清单」)。- **创建时搭便车**:`todo_create` **必须**和第一个工作工具在同一轮发出,禁止 `todo_create` 独占一轮。- **更新时搭便车(强制)**:`todo_modify` **必须**和下一个任务的工作工具在同一轮发出,禁止 `todo_modify` 独占一轮。系统会在工作工具被调用时自动将 pending 推进为 in_progress,你只需要用 `todo_modify` 标记 completed/cancelled。- ✅ 正确:`[write_file(...), todo_modify(action="update", todos=[{"id":"step1","status":"completed"}])]`@@ -82,6 +83,7 @@ Then execute the workflow; the rules below govern execution.1. **Declare step**: By default, before each action, state your current step at the start of your reply: `[Current Step: <step name>]`. **You do NOT call any tool to "start" a step** — the declaration itself enters the step. If SKILL.md explicitly states that stage status and stage messages are emitted exclusively by tool events, follow that rule and you must not declare `[Current Step: ...]` or any other step message yourself.2. **Use todo (mandatory)**: For skills, you MUST create a todo list before executing the skill steps.+ - **Acceleration-channel exception (single deliverable)**: If the task is handed directly to the `skill_acceleration_exec` acceleration channel and this turn needs to produce exactly **one deliverable**, do **NOT** create a todo — the channel emits its own Stage step events that render as the frontend task list, so no outer todo is needed (creating one causes the frontend task list to display incorrectly). **Only** when a single turn must produce **multiple deliverables** (multiple `skill_acceleration_exec` calls) must you first build an outer todo list (see the "Multiple-deliverable todo list" in the acceleration-channel section).- **Piggyback on creation**: `todo_create` **MUST** be called in the same response as the first work tool — never in a standalone todo-only round.- **Piggyback on updates (MANDATORY)**: `todo_modify` **MUST** be called alongside the next task's work tool in the same response — never alone. The system auto-advances pending tasks to in_progress when work tools are called, so you only need `todo_modify` to mark tasks completed/cancelled.- ✅ CORRECT: `[write_file(...), todo_modify(action="update", todos=[{"id":"step1","status":"completed"}])]`diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.pyindex 59992ce076..580705c591 100644--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py@@ -56,6 +56,7 @@ from jiuwenswarm.agents.harness.common.rails.read_file_validation import ()from jiuwenswarm.agents.harness.common.rails.task_execution_rail import (SKILL_TURBO_OUTER_TODO_ACTIVE_EXTRA_KEY,+ SKILL_TURBO_OUTER_TODO_COMPLETED_BEFORE_EXTRA_KEY,SKILL_TURBO_OUTER_TODO_PENDING_EXTRA_KEY,is_todo_close_nudge,)@@ -1265,8 +1266,9 @@ class JiuSwarmStreamEventRail(DeepAgentRail):}# SkillTurbo 专用 ContextVar 统一绑定(adapter / metadata / workspace /- # interactive_ask / outer_todo / outer_todo_pending / subagent_parent /- # resume_answers 共 8 个,条件语义与绑定实现见+ # interactive_ask / outer_todo / outer_todo_pending /+ # outer_todo_completed_before / subagent_parent / resume_answers+ # 共 9 个,条件语义与绑定实现见# context_binding.bind_skill_turbo_context)try:_resume_answers = None@@ -1277,9 +1279,13 @@ class JiuSwarmStreamEventRail(DeepAgentRail):_resume_answers = extra.get(RESUME_USER_INPUT_KEY)_outer_todo_active = None_outer_todo_pending = None+ _outer_todo_completed_before = Noneif isinstance(extra, dict):_outer_todo_active = extra.get(SKILL_TURBO_OUTER_TODO_ACTIVE_EXTRA_KEY)_outer_todo_pending = extra.get(SKILL_TURBO_OUTER_TODO_PENDING_EXTRA_KEY)+ _outer_todo_completed_before = extra.get(+ SKILL_TURBO_OUTER_TODO_COMPLETED_BEFORE_EXTRA_KEY+ )bind_skill_turbo_context(ctx,adapter=self._skill_turbo_adapter,@@ -1288,6 +1294,7 @@ class JiuSwarmStreamEventRail(DeepAgentRail):resume_answers=_resume_answers,outer_todo_active=_outer_todo_active,outer_todo_pending=_outer_todo_pending,+ outer_todo_completed_before=_outer_todo_completed_before,)except Exception:# metadata / resume_answers 绑定失败意味着 HITL 作答注入静默失效,diff --git a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.pyindex 013cd43d33..af336393cc 100644--- a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py@@ -49,6 +49,9 @@ from jiuwenswarm.server.runtime.agent_adapter.todo_close_text_hold import (TODO_CLOSE_HOLD_STREAM_TYPE,TODO_CLOSE_RELEASE_STREAM_TYPE,)+from jiuwenswarm.server.runtime.skill_turbo.task_slot_guard import (+ release_task_slot,+)_ACTIVE_TASK_ID: ContextVar[str | None] = ContextVar("active_task_id", default=None@@ -59,6 +62,9 @@ SKILL_TURBO_OUTER_TODO_ACTIVE_EXTRA_KEY = (SKILL_TURBO_OUTER_TODO_PENDING_EXTRA_KEY = ("_jiuwenswarm_skill_turbo_outer_todo_pending")+SKILL_TURBO_OUTER_TODO_COMPLETED_BEFORE_EXTRA_KEY = (+ "_jiuwenswarm_skill_turbo_outer_todo_completed_before"+)# 纯文本收尾前插入的一次调用。名字用已注册的 todo_modify,避免下一轮# 请求里出现未注册工具名被模型接口拒绝。id 前缀把它和真改状态分开:# 不执行、不改 todo.json、不向前端发工具卡片,只回一条要求模型自己改状态的说明。@@ -1790,6 +1796,10 @@ class TaskExecutionRail(DeepAgentRail):ctx.extra[SKILL_TURBO_OUTER_TODO_PENDING_EXTRA_KEY] = (self._pending_items_after(_ACTIVE_TASK_ID.get()))+ # B_04:fresh 守卫的后续交付物放行信号——早于绑定项的已完成项数。+ ctx.extra[SKILL_TURBO_OUTER_TODO_COMPLETED_BEFORE_EXTRA_KEY] = (+ self._completed_items_before(_ACTIVE_TASK_ID.get())+ )def _reject_todo_close_nudge(self, ctx: AgentCallbackContext) -> None:"""Skip the internal nudge tool and return the todo_modify instruction."""@@ -2237,6 +2247,40 @@ class TaskExecutionRail(DeepAgentRail):"next_summary": pending[0].get("content", "") if pending else "",}+ def _completed_items_before(self, task_id: str | None) -> int | None:+ """早于当前绑定项的已完成项数;无外层 todo 绑定返回 None。++ B_04 fresh 守卫的后续交付物放行信号:清单推进到第二项及以后(早前+ 项已 completed/cancelled)时,本次 skill_acceleration_exec 是清单+ 推进的新交付物而非同任务重跑,残留产物属于已收尾的上一交付物。+ 迭代纪律与 _pending_items_after 一致(剥 "todo:" 前缀 + index 元组+ 排序 + _TODO_DONE_STATUSES 终态判定),保证两信号同一口径。+ """+ if not task_id:+ return None+ raw_id = task_id[5:] if task_id.startswith("todo:") else task_id+ todo_map = self._todo_map+ if not todo_map:+ return None+ current = todo_map.get(raw_id)+ if not current:+ return None+ try:+ current_index = int(current.get("index", 0))+ except (TypeError, ValueError):+ return None+ completed = 0+ for other_id, task in self._iter_todos_by_index(todo_map):+ try:+ other_index = int(task.get("index", 0))+ except (TypeError, ValueError):+ continue+ if (other_index, other_id) >= (current_index, raw_id):+ continue+ if str(task.get("status", "")).lower() in self._TODO_DONE_STATUSES:+ completed += 1+ return completed+def _overlay_serial_todo_statuses(self,items: list[dict[str, Any]],@@ -2724,6 +2768,11 @@ class TaskExecutionRail(DeepAgentRail):payload=payload,))+ # B_03:外层 todo 快照进流 = taskProgress 槽位被外层夺回,注销+ # skill_turbo 的槽位泄漏登记(若入口 gate 误判 forwarded 曾遗留)。+ # 必须在 write_stream 成功后注销——写失败时槽位未被夺回,保留+ # 登记让 turbo 侧终止性出口仍可关账。+ release_task_slot(session_id)except Exception:logger.debug("[TaskExecutionRail] task.update emit failed",diff --git a/jiuwenswarm/server/runtime/skill_turbo/context_binding.py b/jiuwenswarm/server/runtime/skill_turbo/context_binding.pyindex 4c5952311f..074509fb5f 100644--- a/jiuwenswarm/server/runtime/skill_turbo/context_binding.py+++ b/jiuwenswarm/server/runtime/skill_turbo/context_binding.py@@ -3,8 +3,9 @@"""skill_turbo 专用 ContextVar 的 bind/reset 函数对(单一收口)。``stream_event_rail.before_tool_call`` 调用 ``bind_skill_turbo_context`` 统一绑定-8 个 ContextVar(adapter / request_metadata / workspace_dir / interactive_ask /-resume_answers / outer_todo_active / outer_todo_pending / subagent_parent_session),+9 个 ContextVar(adapter / request_metadata / workspace_dir / interactive_ask /+resume_answers / outer_todo_active / outer_todo_pending /+outer_todo_completed_before / subagent_parent_session),tokens 存在 ctx 的 task-local 属性上;``after_tool_call`` / ``after_invoke`` /``on_model_exception`` 调用 ``reset_skill_turbo_context`` 一处循环复位——消除散落的逐个 reset 与异常路径漏 reset(R5/R8 根源)。@@ -41,8 +42,9 @@ def bind_skill_turbo_context(resume_answers: Any = None,outer_todo_active: Any = None,outer_todo_pending: Any = None,+ outer_todo_completed_before: Any = None,) -> None:- """before_tool_call 调用:统一绑定 8 个 skill_turbo ContextVar。+ """before_tool_call 调用:统一绑定 9 个 skill_turbo ContextVar。各绑定保持原条件语义:值缺失(None / 非 bool)不绑、不产生 token。"""@@ -110,6 +112,16 @@ def bind_skill_turbo_context(tokens["outer_todo_pending"] = set_skill_turbo_outer_todo_pending(outer_todo_pending)+ # B_04:仅 int 绑定(0=绑定项之前无已完成项也是有效信号,None=无绑定不绑)+ if isinstance(outer_todo_completed_before, int):+ from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (+ set_skill_turbo_outer_todo_completed_before,+ )++ tokens["outer_todo_completed_before"] = (+ set_skill_turbo_outer_todo_completed_before(outer_todo_completed_before)+ )+def _reset_adapter(token: Any) -> None:from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (@@ -167,6 +179,14 @@ def _reset_outer_todo_pending(token: Any) -> None:reset_skill_turbo_outer_todo_pending(token)+def _reset_outer_todo_completed_before(token: Any) -> None:+ from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (+ reset_skill_turbo_outer_todo_completed_before,+ )++ reset_skill_turbo_outer_todo_completed_before(token)++def _reset_subagent_parent(token: Any) -> None:from jiuwenswarm.agents.harness.common.tools.subagent_executor.context_vars import (reset_subagent_parent_session,@@ -183,6 +203,7 @@ _RESETTERS = {"resume_answers": _reset_resume_answers,"outer_todo": _reset_outer_todo,"outer_todo_pending": _reset_outer_todo_pending,+ "outer_todo_completed_before": _reset_outer_todo_completed_before,"subagent_parent": _reset_subagent_parent,}diff --git a/jiuwenswarm/server/runtime/skill_turbo/rails/skill_prompt_rail.py b/jiuwenswarm/server/runtime/skill_turbo/rails/skill_prompt_rail.pyindex 851a4b1c47..f399d705a3 100644--- a/jiuwenswarm/server/runtime/skill_turbo/rails/skill_prompt_rail.py+++ b/jiuwenswarm/server/runtime/skill_turbo/rails/skill_prompt_rail.py@@ -5,6 +5,19 @@在每次 LLM 调用前向 system prompt 注入 skill_turbo_guide 段,指导 LLM 何时使用 skill_acceleration_exec 加速通道以及失败后的降级策略。+指南含多交付物强制引导:单轮需要多份交付物(多次调用 skill_acceleration_exec)+时必须先 todo_create 建外层待办清单、逐项执行逐项 todo_modify 标记、全部完成后+统一总结——外层 todo 激活时入口才走 outer_todo 分支(跳过内部 task.*、chat.*+归外层 todo 步骤 segment,见 skill_turbo_tools 入口拦截),无 todo 连跑会让+各次交付的内部任务互相顶替、交付总结挤占主气泡(实证:单轮两份 PPT 无 todo+连跑,交付总结一份被毁一份过时错位)。++清单编排必须**串行**:todo_create / todo_modify 的工具结果返回后才进入加速+通道,严禁同批并行调用——同轮并行 todo_create + skill_acceleration_exec 会让+入口 outer_todo 检测竞态误判(rail 的 _ACTIVE_TASK_ID 尚未设置),turbo 的+Stage 快照顶掉外层 todo 槽位且续跑入口不再补发终态(实证 case 与机制见+docs/bugfix/B_03_leaked-task-slot-settlement.md)。+清单动态化(请求期):外部 turbo 技能目录的可见性依赖请求级上下文(session 绑定目录 / env),sidecar 启动(模块导入)时不可见,工具描述若仅依赖导入期固化值会恒为"暂无"。本 rail 在每次模型调用前调用@@ -49,11 +62,13 @@ def _build_skill_turbo_guide_text(language: str, skill_names: list[str]) -> str:names = "、".join(skill_names)return f"""## 技能加速通道(skill_acceleration_exec)-⚠️ **默认优先**:当用户意图匹配 `skill_acceleration_exec`(当前支持的技能清单以该工具描述中的"当前内部支持"为准,当前:{names}),你的**第一个工具调用必须是 `skill_acceleration_exec`**——它内部会自行完成规划+研究+生成+推送全流程。**唯一例外**:用户**显式**要求先执行某项 `skill_acceleration_exec` 不会自行处理的前置操作,则必须先完成该操作再调用 `skill_acceleration_exec`。搜索、读文件等研究类操作它内部会自己完成,**不构成**例外;其他技能类操作(如加载独立技能流程)它不会自行处理,**构成**例外。**同样例外**:本回合 tool_result 明确提示『检测到上一轮留下的已完成产物』时,不要调用 `skill_acceleration_exec`,改用 skill_tool 或直接编辑产物文件继续。+⚠️ **默认优先**:当用户意图匹配 `skill_acceleration_exec`(当前支持的技能清单以该工具描述中的"当前内部支持"为准,当前:{names}),你的**第一个工具调用必须是 `skill_acceleration_exec`**——它内部会自行完成规划+研究+生成+推送全流程。**唯一例外**:用户**显式**要求先执行某项 `skill_acceleration_exec` 不会自行处理的前置操作,则必须先完成该操作再调用 `skill_acceleration_exec`。搜索、读文件等研究类操作它内部会自己完成,**不构成**例外;其他技能类操作(如加载独立技能流程)它不会自行处理,**构成**例外。**同样例外**:本回合 tool_result 明确提示『检测到上一轮留下的已完成产物』时,不要调用 `skill_acceleration_exec`,改用 skill_tool 或直接编辑产物文件继续。**同样例外**:单轮需要产出**多份交付物**(即需要多次调用 `skill_acceleration_exec`,如一次要两份 PPT)时,必须先按下方「📋 多交付物待办清单」用 `todo_create` 建好清单,**等 `todo_create` 成功返回后**再进入加速通道(**不要把 `todo_create` 和 `skill_acceleration_exec` 放在同一批并行调用**)。若你已先调用了 `skill_tool` 加载了对应技能正文(即**不属于**上述例外,只是误触),**仍须立即调用 `skill_acceleration_exec`**——不要因"已经加载了 SKILL.md"或"已经做了研究"而放弃加速通道。-若 `skill_acceleration_exec` 返回成功(产物已生成),**禁止**再用 `skill_tool` 重复同一任务。若待办仍有 `in_progress`,先单独调 `todo_modify` 把对应步骤标为 `completed`,再向用户总结结果。若 `skill_acceleration_exec` 返回失败或未处理,**必须**继续用 `skill_tool` 加载对应技能走标准流程完成用户任务。+若 `skill_acceleration_exec` 返回成功(产物已生成),**禁止**再用 `skill_tool` 重复同一任务。若待办仍有 `in_progress`,先单独调 `todo_modify` 把对应步骤标为 `completed`;清单还有未完成项时按下方「📋 多交付物待办清单」继续下一项,全部完成后再向用户总结结果。若 `skill_acceleration_exec` 返回失败或未处理,**必须**继续用 `skill_tool` 加载对应技能走标准流程完成用户任务。++📋 **多交付物待办清单(强制)**:单轮需要产出**多份交付物**(如两份 PPT、多份文档,即需要多次调用 `skill_acceleration_exec`)时,**禁止**在无外层待办的情况下连跑加速通道——各次交付的进度与总结会互相顶替、无法归位到各自交付物下。正确流程(**串行推进:每一步都必须等上一步的工具结果返回后再发起下一步,严禁同批并行调用**):先调 `todo_create` 建待办清单(**每份交付物一项**,第一项自动为 `in_progress`)→ **等 `todo_create` 返回成功后**,对当前项调用 `skill_acceleration_exec` 完成交付 → 成功后立即调 `todo_modify`(action=update)把当前项标为 `completed`、下一项标为 `in_progress` → **等 `todo_modify` 返回成功后**再进入下一项,清单仍有未完成项时**继续下一项,不要中途向用户做最终总结** → **全部完成后**再向用户做**一次性统一总结**(逐份说明交付结果)。⏸️ **暂停不是失败**:当 `skill_acceleration_exec` 暂停等待用户回答(返回"技能加速已暂停"类信息,或向用户弹出补充问题卡片,或返回结果中包含 `__skill_turbo_hitl__` 标记时)时,这是任务流的正常提问环节。**必须停止后续工具调用,等待用户回答**;用户回答后加速通道会自动从断点继续。**禁止**把暂停当成失败而改走 `skill_tool` 标准流程,那会丢弃已完成的阶段并从头重跑。@@ -62,11 +77,13 @@ def _build_skill_turbo_guide_text(language: str, skill_names: list[str]) -> str:names = ", ".join(skill_names)return f"""## Skill Acceleration Channel (skill_acceleration_exec)-⚠️ **Default priority**: When the user's intent matches `skill_acceleration_exec` (see the "当前内部支持 / currently supported" list in that tool's description; currently: {names}), your **FIRST tool call MUST be `skill_acceleration_exec`** — it handles planning + research + generation + delivery internally. **Only exception**: the user **explicitly** asks to first perform a preceding action that `skill_acceleration_exec` does not handle internally; then you must complete that action before calling `skill_acceleration_exec`. Research-style actions like `web_search` and file reading are handled internally — they do **NOT** constitute an exception; other skill-type actions (e.g. loading a separate skill flow) are not handled internally and **DO** constitute an exception. **Also excepted**: when this turn's tool_result explicitly indicates completed artifacts from a previous run were detected, do NOT call `skill_acceleration_exec`; continue with skill_tool or by editing the artifact files directly.+⚠️ **Default priority**: When the user's intent matches `skill_acceleration_exec` (see the "当前内部支持 / currently supported" list in that tool's description; currently: {names}), your **FIRST tool call MUST be `skill_acceleration_exec`** — it handles planning + research + generation + delivery internally. **Only exception**: the user **explicitly** asks to first perform a preceding action that `skill_acceleration_exec` does not handle internally; then you must complete that action before calling `skill_acceleration_exec`. Research-style actions like `web_search` and file reading are handled internally — they do **NOT** constitute an exception; other skill-type actions (e.g. loading a separate skill flow) are not handled internally and **DO** constitute an exception. **Also excepted**: when this turn's tool_result explicitly indicates completed artifacts from a previous run were detected, do NOT call `skill_acceleration_exec`; continue with skill_tool or by editing the artifact files directly. **Also excepted**: when a single turn must produce **multiple deliverables** (i.e. multiple `skill_acceleration_exec` calls, e.g. two PPT decks in one request), you must first build the todo list via `todo_create` as required by the "📋 Multiple-deliverable todo list" clause below, and enter the acceleration channel **only after `todo_create` has returned successfully** (**do NOT batch `todo_create` and `skill_acceleration_exec` as parallel calls in the same turn**).If you have already mistakenly called `skill_tool` to load the corresponding skill body (i.e. this does **NOT** fall under the exception above - it was just a misfire), **you MUST still call `skill_acceleration_exec` immediately** - do NOT abandon the acceleration channel because "SKILL.md is already loaded" or "research is already done."-If `skill_acceleration_exec` returns success (the artifact is already generated), you are **forbidden** from calling `skill_tool` again for the same task. If any todo is still `in_progress`, first call `todo_modify` alone to mark that step `completed`, then summarize the result to the user. If `skill_acceleration_exec` returns failure or is not handled, you **MUST** fall back to `skill_tool` to load the corresponding skill and complete the user's task via the standard flow.+If `skill_acceleration_exec` returns success (the artifact is already generated), you are **forbidden** from calling `skill_tool` again for the same task. If any todo is still `in_progress`, first call `todo_modify` alone to mark that step `completed`; if the list still has unfinished items, continue with the next one per the "📋 Multiple-deliverable todo list" clause below, and only summarize to the user after all items are completed. If `skill_acceleration_exec` returns failure or is not handled, you **MUST** fall back to `skill_tool` to load the corresponding skill and complete the user's task via the standard flow.++📋 **Multiple-deliverable todo list (mandatory)**: When a single turn must produce **multiple deliverables** (e.g. two PPT decks, several documents — i.e. multiple `skill_acceleration_exec` calls), you are **forbidden** from running the acceleration channel back-to-back without an outer todo list — each run's progress and delivery summary would overwrite the previous one instead of attaching to its own deliverable. Correct flow (**strictly sequential: every step must wait for the previous tool's result before starting the next; NEVER batch these calls in parallel**): first call `todo_create` to build the list (**one item per deliverable**; the first item automatically becomes `in_progress`) → **after `todo_create` returns success**, call `skill_acceleration_exec` for the current item → on success immediately call `todo_modify` (action=update) to mark the current item `completed` and the next item `in_progress` → **after `todo_modify` returns success**, proceed to the next item; while unfinished items remain, **continue with the next one and do NOT give the user a final summary midway** → after **all items are completed**, give **one unified summary** covering every deliverable.⏸️ **Pause is NOT failure**: When `skill_acceleration_exec` pauses to wait for the user's answer (returning a "skill acceleration paused" style message, showing a follow-up question card to the user, or returning a result containing the `__skill_turbo_hitl__` marker), that is a normal clarification step of the pipeline. You **MUST stop making further tool calls and wait for the user's answer**; the acceleration channel will automatically resume from the breakpoint once answered. **DO NOT** treat the pause as a failure and switch to the `skill_tool` standard flow — that would discard completed stages and rerun from scratch.diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py b/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.pyindex d3aca6aa0e..082c0df02e 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py@@ -19,6 +19,11 @@ from typing import TYPE_CHECKING, Anyfrom openjiuwen.core.foundation.tool import toolfrom jiuwenswarm.agents.harness.common.rails.task_execution_rail import get_current_task_id+from jiuwenswarm.server.runtime.skill_turbo.task_slot_guard import (+ claim_task_slot,+ peek_leaked_task_slot,+ release_task_slot,+)if TYPE_CHECKING:from openjiuwen.core.session.agent import Session@@ -412,6 +417,61 @@ def _without_inner_task_routing(payload: dict[str, Any]) -> dict[str, Any]:return cleaned+def _task_ids_from_snapshot(payload: Any) -> set[str]:+ """从 task.update 快照提取任务集 task_id 集(槽位登记簿的观测值)。"""+ if not isinstance(payload, dict):+ return set()+ tasks = payload.get("tasks")+ if not isinstance(tasks, list):+ return set()+ return {+ str(t.get("task_id")).strip()+ for t in tasks+ if isinstance(t, dict) and str(t.get("task_id") or "").strip()+ }+++def _is_terminal_task_snapshot(payload: Any) -> bool:+ """终态快照判定:tasks 非空且全部状态落在 {completed, failed}。++ 依据 tasks 列表逐项 status,不依赖计数字段(in_progress_tasks 等)——+ 事件构造方(executor)虽有计数,但以逐项判定为唯一口径可容忍缺计数的+ 快照来源。空列表不算终态:无内容可关账。+ """+ if not isinstance(payload, dict):+ return False+ tasks = payload.get("tasks")+ if not isinstance(tasks, list) or not tasks:+ return False+ statuses: set[str] = set()+ for t in tasks:+ if not isinstance(t, dict):+ return False+ statuses.add(str(t.get("status") or "").strip())+ return bool(statuses) and statuses.issubset({"completed", "failed"})+++def _parent_session_slot_key(parent_session: Any) -> str:+ """槽位登记簿键:外层父会话 session_id。++ 与外层 rail 侧(task_execution_rail._emit_task_update_event 的+ session.get_session_id())同一 session 对象、同一 id 口径——两侧键不对齐+ 则外层夺回时的注销永远打不中。+ """+ if parent_session is None:+ return ""+ getter = getattr(parent_session, "get_session_id", None)+ sid = ""+ if callable(getter):+ try:+ sid = str(getter() or "").strip()+ except Exception:+ sid = ""+ if not sid:+ sid = str(getattr(parent_session, "session_id", "") or "").strip()+ return sid++def _prepare_parent_stream_output(event_type: str, payload: dict[str, Any]) -> tuple[str, dict[str, Any]]:@@ -492,6 +552,74 @@ async def _push_task_event_out_of_band()+async def _settle_leaked_task_slot(+ parent_session: Any,+ request_id: Any,+ channel_id: Any,+ external_session_id: Any,+ last_task_update: Any,+) -> None:+ """B_03:skip 入口终止性出口的槽位清算。++ 入口 gate 误判 forwarded 的竞态会让 turbo 任务集顶掉前端唯一的+ taskProgress 槽位;若该轮终态前被打断(HITL),续跑入口判 skip,+ 终态快照被抑制——槽位永驻 in_progress。本函数在**终止性出口**+ (成功 / 未处理 / 普通异常;AbortError 暂停除外,暂停后任务集还要续跑)+ 检查登记簿(task_slot_guard):有未闭合占用且本入口缓存到终态快照时+ 补发关账。++ 只放行 task.update 全量快照(幂等、后到覆盖先到、可 OOB);task.start /+ task.complete 仍禁——skip 语义下放行它们会破坏 chat.* 归段(taskStack+ 嵌套 / segment 分裂,正是 skip 机制要防的)。FIFO 写失败保留登记,+ 下次终止性出口重试;写成功后 OOB 尽力直推(右侧任务列表由 OOB 驱动)。+ """+ if parent_session is None or not isinstance(last_task_update, dict):+ return+ if not _is_terminal_task_snapshot(last_task_update):+ # 非终态快照关不了账(流中途异常等);登记保留,待后续运行治愈。+ return+ slot_key = _parent_session_slot_key(parent_session)+ if not slot_key:+ return+ leaked_ids = peek_leaked_task_slot(slot_key)+ if leaked_ids is None:+ return+ from openjiuwen.core.session.stream.base import OutputSchema++ payload = dict(last_task_update)+ output_type, mapped = _prepare_parent_stream_output("task.update", payload)+ try:+ await parent_session.write_stream(+ OutputSchema(type=output_type, index=0, payload=mapped)+ )+ except Exception:+ logger.warning(+ "[SkillTurboTool] leaked slot settle write_stream failed "+ "session=%s leaked_ids=%s",+ slot_key,+ sorted(leaked_ids),+ exc_info=True,+ )+ return+ release_task_slot(slot_key)+ logger.info(+ "[SkillTurboTool] settled leaked task slot: session=%s "+ "leaked_ids=%s settled_tasks=%d",+ slot_key,+ sorted(leaked_ids),+ len(payload.get("tasks") or []),+ )+ await _push_task_event_out_of_band(+ "task.update",+ mapped,+ request_id=str(request_id or ""),+ channel_id=str(channel_id or ""),+ session_id=_resolve_skill_turbo_resume_session_id(+ external_session_id, parent_session+ ),+ )++# ── ContextVar:在 before_tool_call 中注入,供工具函数读取 ──_current_skill_turbo_adapter: ContextVar[Any] = ContextVar("current_skill_turbo_adapter", default=None@@ -534,6 +662,74 @@ def get_skill_turbo_outer_todo_pending() -> dict[str, Any] | None:def reset_skill_turbo_outer_todo_pending(token: Token) -> None:_skill_turbo_outer_todo_pending.reset(token)++# 外层 todo 当前绑定项之前已完成的项数(B_04 fresh 守卫放行信号)。+# task_execution_rail.before_tool_call 计算导出,context_binding 绑定到此+# ContextVar,_fresh_call_artifacts_guard 读取:≥1 表示本次调用是清单推进+# 的后续交付物(首个交付物已收尾),残留产物属于上一交付物而非本任务——+# 放行 fresh 调用,产物清理交 executor 开跑时的 _clear_stale_node_artifacts。+# 值形态:int(0=绑定项之前无已完成项)或 None(无外层 todo 绑定)。+_skill_turbo_outer_todo_completed_before: ContextVar[int | None] = ContextVar(+ "skill_turbo_outer_todo_completed_before", default=None+)+++def set_skill_turbo_outer_todo_completed_before(count: int | None) -> Token:+ """Bind how many todo items before the bound one are already done."""+ return _skill_turbo_outer_todo_completed_before.set(count)+++def get_skill_turbo_outer_todo_completed_before() -> int | None:+ return _skill_turbo_outer_todo_completed_before.get()+++def reset_skill_turbo_outer_todo_completed_before(token: Token) -> None:+ _skill_turbo_outer_todo_completed_before.reset(token)+++# ── B_05:后续交付物 fresh 放行的「绑定项切换」登记(模块级跨请求单例)──+# completed_before 只是绑定时刻算出的静态计数(绑定项存续期内不变),只表达+# "清单推进到了第 2+ 项",无法区分"清单推进到新交付物的首次调用"与"同一交付物+# 已成功后的盲目重跑"。本登记记录每个会话上次放行时绑定的外层 todo id,守卫放行+# 前比对:绑定项相较上次**切换**才放行,相同(同项盲目重跑)落回产物检查——F_01+# 对"同任务盲目重跑"的保护面对第 2+ 项不放松。键 = 守卫的 sid 口径(外层父会话+# id);值 = 上次放行时的 get_current_task_id()。仅随后续交付物放行分支写;上限+# 淘汰同 task_slot_guard 先例(防长生命周期进程无界增长)。+_SUBSEQUENT_DELIVERABLE_LAST_TODO_ID: dict[str, str | None] = {}+_MAX_TRACKED_SUBSEQUENT_DELIVERABLE_SESSIONS = 4096+++def _release_subsequent_deliverable(+ sid: str, current_todo_id: str | None,+) -> bool:+ """判定并登记"后续交付物 fresh 放行":仅绑定项相较上次放行切换才放行。++ - 拿不到会话键或绑定项 id(含测试桩 / 退化态)→ 退回旧语义无条件放行;+ - 绑定项相同(同项盲目重跑)→ 返回 False,调用方落回产物检查;+ - 绑定项不同 / 首次 → 放行并登记(返回 True)。+ """+ key = str(sid or "").strip()+ if not key or not current_todo_id:+ return True+ if _SUBSEQUENT_DELIVERABLE_LAST_TODO_ID.get(key) == current_todo_id:+ return False+ if (+ key not in _SUBSEQUENT_DELIVERABLE_LAST_TODO_ID+ and len(_SUBSEQUENT_DELIVERABLE_LAST_TODO_ID)+ >= _MAX_TRACKED_SUBSEQUENT_DELIVERABLE_SESSIONS+ ):+ _SUBSEQUENT_DELIVERABLE_LAST_TODO_ID.pop(+ next(iter(_SUBSEQUENT_DELIVERABLE_LAST_TODO_ID))+ )+ _SUBSEQUENT_DELIVERABLE_LAST_TODO_ID[key] = current_todo_id+ return True+++def reset_subsequent_deliverable_registry() -> None:+ """清空后续交付物放行登记(测试隔离用;生产零调用)。"""+ _SUBSEQUENT_DELIVERABLE_LAST_TODO_ID.clear()++# ── ContextVar:SkillTurbo HITL 中断信号 ──# skill_turbo_tools catch AbortError 后提取 ToolInterruptException 存入此 ContextVar,# StreamEventRail.after_tool_call 读取后改写 ctx.inputs.tool_result 为 TIE,@@ -943,6 +1139,12 @@ async def _fresh_call_artifacts_guard(P2-2 hash 继承与后续拦截的数据源,拦截本身不消耗它);- ``fresh_start=True`` → 显式全新任务:清空产物记录后放行(清库失败仅warning,executor 的 _clear_stale_node_artifacts 仍会在 fresh run 兜底清)。++ B_04 后续交付物放行:外层 todo 清单推进到第二项及以后(早于绑定项存在+ 已完成项,``outer_todo_completed_before`` 通道 ≥1)时,残留产物属于已+ 收尾的上一交付物而非本任务——放行且**不在守卫内清库**(executor 开跑时+ ``_clear_stale_node_artifacts`` 按同序兜底清理);无绑定(None)或绑定项+ 之前无已完成项(0)仍拦,F_01 对"同任务盲目重跑"的保护不放松。"""from openjiuwen.core.session.agent import create_agent_sessionfrom jiuwenswarm.server.runtime.skill_turbo.node_artifact_store import (@@ -955,6 +1157,37 @@ async def _fresh_call_artifacts_guard(sid = _resolve_skill_turbo_resume_session_id(external_session_id, parent_session)+ # B_04 后续交付物放行(快路径,免开 session):外层 todo 清单推进到+ # 第二项及以后——早于绑定项存在已完成项时,残留产物属于已收尾的上一+ # 交付物而非本任务,fresh 调用是清单推进的正常流程而非盲目重跑。+ # 仅在未显式携带 fresh_start 时走本分支(fresh_start=true 的显式清库+ # 语义优先,两者都放行但清理时机不同:本分支交 executor 开跑时清理)。+ #+ # B_05 收紧:completed_before 是绑定时刻算出的静态计数,绑定项存续期内+ # 不变,无法区分"清单推进到新交付物(应放行)"与"同一交付物已成功后的+ # 盲目重跑(应拦)"。故仅在绑定项相较上次放行**切换**时放行;同绑定项+ # 重复 fresh 调用落回下方产物检查——命中残留产物即拦并提示 fresh_start+ # (F_01 对"同任务盲目重跑"的保护面对第 2+ 项不放松)。+ if not fresh_start:+ completed_before = get_skill_turbo_outer_todo_completed_before()+ if isinstance(completed_before, int) and completed_before > 0:+ if _release_subsequent_deliverable(sid, get_current_task_id()):+ logger.info(+ "[SkillTurboTool] fresh guard bypassed by outer todo "+ "progression (subsequent deliverable, bound item switched) "+ "sid=%s completed_before=%d",+ sid,+ completed_before,+ )+ return None+ logger.info(+ "[SkillTurboTool] fresh guard same-bound-item re-invoke "+ "(subsequent deliverable blind rerun) sid=%s completed_before=%d; "+ "falling through to artifact check",+ sid,+ completed_before,+ )+card = getattr(getattr(adapter, "_instance", None), "card", None)guard_session = Nonetry:@@ -1147,6 +1380,12 @@ async def skill_turbo(query: str, fresh_start: bool = False) -> dict[str, Any] |"skipped" if has_outer_todo else "forwarded as-is",)+ # B_03 槽位登记簿键 + skip 抑制快照缓存:转发分支放行 task.update 时按此键+ # 登记"槽位被本任务集占用";skip 分支被抑制的 task.update 缓存最后一条,+ # 终止性出口(_settle_leaked_task_slot)用它关账。+ slot_key = _parent_session_slot_key(parent_session)+ last_suppressed_task_update: dict[str, Any] | None = None+# metadata:通过 ContextVar 读取(_update_runtime_config 中设置,无并发覆盖风险)request_metadata = get_current_request_metadata()request_id = request_metadata.get("request_id", "") if isinstance(request_metadata, dict) else ""@@ -1378,6 +1617,11 @@ async def skill_turbo(query: str, fresh_start: bool = False) -> dict[str, Any] |# 而该 segment 的 taskId 与外层 todo 不匹配,被 resolveSegmentForRow 丢弃,# PPT 的思考/工具调用全部不显示。跳过后 chat.* 归到外层 todo 的 segment,正常渲染。if has_outer_todo and event_type in _SKILL_TURBO_TASK_EVENT_TYPES:+ # B_03:被抑制的 task.update 仍需缓存最后一条——本入口跑到+ # 终止性出口时若登记簿显示槽位被本引擎任务集占用未闭合,+ # 由 _settle_leaked_task_slot 用它补发关账。+ if event_type == "task.update" and isinstance(chunk.payload, dict):+ last_suppressed_task_update = dict(chunk.payload)continuepayload = chunk.payload@@ -1413,6 +1657,17 @@ async def skill_turbo(query: str, fresh_start: bool = False) -> dict[str, Any] |n_tasks,type(parent_session).__name__,)+ if event_type == "task.update" and slot_key:+ # B_03 槽位登记:转发分支放行快照 = 槽位被本任务集+ # 占用;终态快照(全 completed/failed)= 任务集自然+ # 闭合,即行注销(后续 skip 入口不误清算)。+ if _is_terminal_task_snapshot(chunk.payload):+ release_task_slot(slot_key)+ else:+ claim_task_slot(+ slot_key,+ _task_ids_from_snapshot(chunk.payload),+ )except Exception:logger.warning("[SkillTurboTool] write_stream failed for event_type=%s",@@ -1437,6 +1692,17 @@ async def skill_turbo(query: str, fresh_start: bool = False) -> dict[str, Any] |event_type,)+ # B_03:终止性出口清算——skip 抑制掉的终态快照若对应未闭合的槽位+ # 占用(首入口误判 forwarded 的竞态遗留),在此补发关账。AbortError+ # 暂停不清算(见 except 分支):任务集还要续跑,关账等于谎报终态。+ await _settle_leaked_task_slot(+ parent_session,+ request_id,+ channel_id,+ external_session_id,+ last_suppressed_task_update,+ )+# 过程输出已通过 write_stream 实时推给前端。交付失败时不得返回 success,# 否则外层 LLM / 前端会把「任务已完成」当成 PPT 已生成。release_checkpoint = True@@ -1477,12 +1743,29 @@ async def skill_turbo(query: str, fresh_start: bool = False) -> dict[str, Any] |except SkillTurboNotHandled as exc:logger.info("[SkillTurboTool] SkillTurbo 未处理: %s", exc)release_checkpoint = True+ # 终止性出口(B_03):清算逻辑自守——无登记 / 无终态快照均静默+ await _settle_leaked_task_slot(+ parent_session,+ request_id,+ channel_id,+ external_session_id,+ last_suppressed_task_update,+ )return _wrap_skill_turbo_result({"success": False, "error": f"SkillAccelerationExec 未处理: {exc}"},artifact_holder=skill_turbo_inst.artifact_holder,)except Exception as exc:logger.warning("[SkillTurboTool] 执行失败: %s", exc, exc_info=True)+ # 终止性出口(B_03):executor 异常分支已 flush task 事件(S_08 约束 6),+ # 缓存快照可能已带 failed 终态——仍尝试关账;非终态则登记保留+ await _settle_leaked_task_slot(+ parent_session,+ request_id,+ channel_id,+ external_session_id,+ last_suppressed_task_update,+ )return _wrap_skill_turbo_result({"success": False, "error": f"执行失败: {exc}"},artifact_holder=skill_turbo_inst.artifact_holder,diff --git a/jiuwenswarm/server/runtime/skill_turbo/task_slot_guard.py b/jiuwenswarm/server/runtime/skill_turbo/task_slot_guard.pynew file mode 100644index 0000000000..b26f05d542--- /dev/null+++ b/jiuwenswarm/server/runtime/skill_turbo/task_slot_guard.py@@ -0,0 +1,102 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""taskProgress 槽位泄漏登记簿(跨请求,模块级单例)。++前端只有唯一的 taskProgress 槽位,由 ``task.update`` 全量快照 last-wins 覆盖。+skill_turbo 入口 gate 误判"无外层 todo"(同轮并行 todo_create ++skill_acceleration_exec 竞态,外层 rail 的 ``_ACTIVE_TASK_ID`` 尚未设置)时,+turbo 的 task.* 事件被整流转发,内部 Stage 快照顶掉外层 todo 列表;若该轮+又在终态前被打断(HITL),续跑入口 gate 判 skip,终态快照被转发层抑制——+槽位永驻最后转发的 in_progress 帧,用户视角"Stage 永远卡住"+(完整定界见 docs/bugfix/B_03_leaked-task-slot-settlement.md)。++本登记簿给这个"无 owner 的真空"补一个 owner:++- ``claim_task_slot``:转发分支放行 task.update 时登记(槽位被该 turbo 任务集占用);+- ``release_task_slot``:两类注销——① 转发分支自己跑到终态快照(任务集自然+ 闭合,见 skill_turbo_tools 转发循环);② 外层 rail 发自身 task.update+ (槽位被外层 todo 夺回,见 task_execution_rail._emit_task_update_event);+- ``peek_leaked_task_slot``:skip 入口终止性出口查询——有登记即槽位仍被本+ 引擎的陈旧任务集占用,调用方放行终态快照关账后自行 release。++键 = 外层父会话 session_id(turbo 的 parent_session 与外层 rail 的+ctx.session 是同一 session 对象,两侧 ``get_session_id()`` 同值)。值 =+占用任务集的 task_id 集,仅用于日志观测与事后诊断;清算判定**不要求** id+交集——槽位已被污染时"最新终态覆盖陈旧 in_progress"优于永驻陈旧(严格+交集匹配会放走"首任务集被弃、次任务集完成"的治愈路径,B_03 记录为拒绝方案)。++⛔ 语义红线:+ - 状态必须模块级跨请求存续——不得改成请求级 ContextVar(泄漏恰恰跨请求:+ 登记在首入口、清算在续跑入口);+ - 只登记"转发分支曾放行 task.update"的事实,不预测 gate 判定、不读 todo.json;+ - 唯一注销时机是"终态快照已实际进流"(FIFO 写成功)或"外层快照已进流"——+ 预测式注销会让健康槽位被二次顶替。+"""++from __future__ import annotations++import logging+from collections.abc import Collection++logger = logging.getLogger(__name__)++__all__ = [+ "claim_task_slot",+ "peek_leaked_task_slot",+ "release_task_slot",+ "reset_task_slot_registry",+]++# 单进程多会话上限:超过后按插入序淘汰最旧条目。条目极小(会话 id → 数十个+# task id),上限只为防长生命周期进程无界增长(先例:类扫描缓存 _scan_cache+# 亦为模块级共享;hitl_dedup 序号表无上限——本处从紧)。+_MAX_TRACKED_SESSIONS = 4096++_leaked_task_slots: dict[str, frozenset[str]] = {}+++def claim_task_slot(session_id: str, task_ids: Collection[str]) -> None:+ """登记槽位被该 turbo 任务集占用(转发分支放行 task.update 时调用)。++ 同会话重复 claim 为覆盖语义(后写胜):并发两条 turbo 流同会话转发时,+ 登记跟随后进快照——该场景本身已属退化态(两套 Stage 快照交错顶替),+ 登记簿不额外仲裁,见 B_03 边界 case。+ """+ sid = str(session_id or "").strip()+ if not sid:+ return+ ids = frozenset(+ str(t).strip()+ for t in task_ids+ if str(t or "").strip()+ )+ if not ids:+ return+ if (+ sid not in _leaked_task_slots+ and len(_leaked_task_slots) >= _MAX_TRACKED_SESSIONS+ ):+ _leaked_task_slots.pop(next(iter(_leaked_task_slots)))+ _leaked_task_slots[sid] = ids+++def release_task_slot(session_id: str) -> None:+ """注销登记:终态快照已进流(自然闭合)或外层 rail 快照夺回槽位。++ 幂等:无登记时静默(外层 rail 每次发 todo 快照都会调,无泄漏会话是常态)。+ """+ _leaked_task_slots.pop(str(session_id or "").strip(), None)+++def peek_leaked_task_slot(session_id: str) -> frozenset[str] | None:+ """查询未闭合的槽位占用;无登记返回 None。++ 只读不删——清算方在终态快照**实际进流后**再调 release_task_slot+ (FIFO 写失败保留登记,下次终止性出口重试)。+ """+ return _leaked_task_slots.get(str(session_id or "").strip())+++def reset_task_slot_registry() -> None:+ """清空登记簿(测试隔离用;生产零调用)。"""+ _leaked_task_slots.clear()