Skip to content

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

fix(swarmskill-creator): support human and session operators

z2tngdd7c6ef46a90
diff --git a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md
index 2019c2d166..14c169c8bf 100644
--- a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md
+++ b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md
@@ -4,7 +4,7 @@ description: |
Creates, converts, or modifies Swarm Skills — the multi-role (多角色团队) extension of the Skills standard, optionally with an executable SwarmFlow orchestration script.
Use when building or refactoring a multi-agent team, generating workflow (工作流/编排) orchestration code, or upgrading a single-agent skill into a collaborating team.
Do NOT use for ordinary single-agent skills — use create-skill instead.
-version: "0.4"
+version: "0.5"
---
# Swarm Skill Creator
@@ -161,6 +161,8 @@ Do not let the script invent a different workflow from `workflow.md`; do not let
Generate `scripts/workflow.py` from [templates/scripts/workflow.py.template](templates/scripts/workflow.py.template). Before editing, read that template's `TEMPLATE AUTHORING CONSTRAINTS` block; it is the single full source for executable SwarmFlow script constraints. Keep this stage focused on routing and topology synchronization rather than restating those rules.
+Choose the interaction primitive from the requested participant and memory semantics: one-shot human input uses `human`, stateful multi-turn human or agent interaction uses the corresponding session primitive, and one-shot agent work continues to use `agent`. The template remains the canonical source for call, lifecycle, and resource rules. Nested `workflow(...)` composition remains outside the supported surface and must not be generated.
+
For the full Markdown spec + SwarmFlow shape, the final script must match the topology in `workflow.md` and the executable constraints in `bind.md`: same phases, same parallel or sequential structure, same integration point, and no extra hidden workflow that the Markdown spec does not describe.
For script-only mode, derive the script directly from the user's requested orchestration. Keep `SKILL.md` minimal but explicit: describe when to invoke the skill, state that `scripts/workflow.py` is the execution definition, and list the script under `## Files`.
@@ -219,7 +221,7 @@ The validator checks two output shapes:
**Script-only SwarmFlow**
- **Structural**: exactly `SKILL.md` + `scripts/workflow.py`; no `roles/`, `workflow.md`, `bind.md`, `dependencies.yaml`, or `prompts/`
- **SKILL.md**: valid frontmatter plus `## Workflow` and `## Files`; `roles:` omitted or empty
-- **SwarmFlow script safety envelope**: standalone script shape, inline prompts, safe imports, phase/agent consistency, schema permissiveness, and blocked runtime patterns
+- **SwarmFlow script safety envelope**: standalone script shape, inline prompts, safe imports, phase/agent consistency, human/session call discipline, schema permissiveness, and blocked runtime patterns
**Exit code 0 = compliant**. Non-zero exit prints the failing checks with file:line references.
diff --git a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/scripts/validate_swarmskill.py b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/scripts/validate_swarmskill.py
index 4a400bccd7..ff21744b1f 100644
--- a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/scripts/validate_swarmskill.py
+++ b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/scripts/validate_swarmskill.py
@@ -31,8 +31,9 @@ What this script catches (deterministic):
- Every roles[].skills / roles[].tools in SKILL.md appears in dependencies.yaml
- scripts/workflow.py, when present, satisfies the executable SwarmFlow
safety envelope: standalone shape, literal META, inline prompts, safe
- imports, phase/agent consistency, permissive schemas, and blocked runtime
- patterns. The full authoring constraint list lives in
+ imports, phase/agent consistency, human/session call discipline,
+ permissive schemas, and blocked runtime patterns. The full authoring
+ constraint list lives in
templates/scripts/workflow.py.template.
What this script does NOT catch (judgment calls — see reference/compliance-checklist.md):
@@ -482,9 +483,12 @@ def validate_dependencies_yaml(path: Path, report: Report) -> dict[str, list[str
SUPPORTED_SWARMFLOW_OPERATORS = {
"agent",
+ "agent_session",
"budget",
"compact",
"flatten_filter",
+ "human",
+ "human_session",
"log",
"map_parallel",
"parallel",
@@ -493,6 +497,7 @@ SUPPORTED_SWARMFLOW_OPERATORS = {
"pmap",
}
+SUPPORTED_SWARMFLOW_TYPES = {"AgentSession", "HumanSession"}
PROTECTED_SWARMFLOW_NAMES = SUPPORTED_SWARMFLOW_OPERATORS
NON_DETERMINISTIC_IMPORTS = {"random", "time", "datetime"}
FILESYSTEM_CALLS = {"open"}
@@ -836,6 +841,58 @@ def _is_module_level_mutable_assignment(node: ast.Assign | ast.AnnAssign) -> boo
return is_mutable_literal or is_set_call
+def _session_variable_names(tree: ast.Module) -> set[str]:
+ names: set[str] = set()
+ for node in ast.walk(tree):
+ if not isinstance(node, (ast.Assign, ast.AnnAssign)):
+ continue
+ value = node.value
+ if not isinstance(value, ast.Call):
+ continue
+ if _call_name(value) not in {"agent_session", "human_session"}:
+ continue
+ targets = [node.target] if isinstance(node, ast.AnnAssign) else list(node.targets)
+ names.update(target.id for target in targets if isinstance(target, ast.Name))
+ return names
+
+
+def _session_method_name(node: ast.Call, session_names: set[str]) -> str | None:
+ func = node.func
+ if not isinstance(func, ast.Attribute):
+ return None
+ if not isinstance(func.value, ast.Name):
+ return None
+ if func.value.id not in session_names:
+ return None
+ if func.attr not in {"send", "aclose"}:
+ return None
+ return func.attr
+
+
+def _keyword(node: ast.Call, name: str) -> ast.keyword | None:
+ return next((keyword for keyword in node.keywords if keyword.arg == name), None)
+
+
+def _is_literal_true(node: ast.AST) -> bool:
+ return isinstance(node, ast.Constant) and node.value is True
+
+
+def _is_literal_none(node: ast.AST) -> bool:
+ return isinstance(node, ast.Constant) and node.value is None
+
+
+def _has_notify_schema_conflict(node: ast.Call) -> bool:
+ notify_kw = _keyword(node, "notify")
+ if notify_kw is None or not _is_literal_true(notify_kw.value):
+ return False
+
+ schema_kw = _keyword(node, "schema")
+ if schema_kw is None:
+ return False
+
+ return not _is_literal_none(schema_kw.value)
+
+
def _is_asyncio_orchestration_alias_call(node: ast.Call, asyncio_modules: set[str]) -> bool:
if not isinstance(node.func, ast.Attribute):
return False
@@ -850,6 +907,8 @@ def _runtime_call_issues(tree: ast.Module) -> tuple[list[str], list[str]]:
errors: list[str] = []
warnings: list[str] = []
asyncio_modules, asyncio_functions = _asyncio_orchestration_aliases(tree)
+ session_names = _session_variable_names(tree)
+ imported_swarmflow_types = _swarmflow_imported_names(tree) & SUPPORTED_SWARMFLOW_TYPES
for node in ast.walk(tree):
if isinstance(node, ast.Import):
@@ -897,6 +956,21 @@ def _runtime_call_issues(tree: ast.Module) -> tuple[list[str], list[str]]:
errors.append(f"line {line}: agent prompt must not be an empty string")
if not _is_directly_awaited(node) and not _is_inside_parallel_lambda(node):
errors.append(f"line {line}: agent() must be awaited or returned from a parallel thunk")
+ elif call_name == "human":
+ if node.args and _string_literal(node.args[0]) == "":
+ errors.append(f"line {line}: human prompt must not be an empty string")
+ if _keyword(node, "notify") is not None:
+ errors.append(f"line {line}: human() does not accept notify; use human_session().send()")
+ if not _is_directly_awaited(node) and not _is_inside_parallel_lambda(node):
+ errors.append(f"line {line}: human() must be awaited or returned from a parallel thunk")
+ elif call_name in {"agent_session", "human_session"}:
+ if _is_directly_awaited(node):
+ errors.append(f"line {line}: {call_name}() is synchronous and must not be awaited")
+ elif call_name in imported_swarmflow_types:
+ errors.append(
+ f"line {line}: do not construct {call_name} directly; "
+ "use agent_session() or human_session()"
+ )
elif call_name in {"map_parallel", "pmap"}:
warnings.append(
f"line {line}: dynamic fan-out should declare an item cap and log skipped work "
@@ -917,6 +991,17 @@ def _runtime_call_issues(tree: ast.Module) -> tuple[list[str], list[str]]:
elif call_name in {"time.time", "datetime.now", "datetime.utcnow"}:
warnings.append(f"line {line}: current time access is non-deterministic; pass values via args")
+ method_name = _session_method_name(node, session_names)
+ if method_name is not None:
+ if not _is_directly_awaited(node):
+ errors.append(
+ f"line {line}: session.{method_name}() must be awaited"
+ )
+ if method_name == "send" and _has_notify_schema_conflict(node):
+ errors.append(
+ f"line {line}: session.send(notify=True) must not also pass schema"
+ )
+
if isinstance(node.func, ast.Attribute) and node.func.attr in PATH_IO_METHODS:
warnings.append(
f"line {line}: avoid direct filesystem access via Path.{node.func.attr} in workflow.py"
@@ -955,7 +1040,10 @@ def _swarmflow_import_issues(tree: ast.Module) -> list[str]:
if alias.name == "*":
issues.append(f"line {line}: import * from swarmflow is not allowed")
continue
- if alias.name not in SUPPORTED_SWARMFLOW_OPERATORS:
+ if (
+ alias.name not in SUPPORTED_SWARMFLOW_OPERATORS
+ and alias.name not in SUPPORTED_SWARMFLOW_TYPES
+ ):
issues.append(f"line {line}: unsupported swarmflow operator {alias.name!r}")
if alias.asname:
issues.append(f"line {line}: import swarmflow.{alias.name} without aliasing it")
diff --git a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/templates/scripts/workflow.py.template b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/templates/scripts/workflow.py.template
index 1d2cb3dcd9..c3628563f1 100644
--- a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/templates/scripts/workflow.py.template
+++ b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/templates/scripts/workflow.py.template
@@ -212,9 +212,12 @@ async def run(args):
# - Use top-level explicit `from swarmflow import ...` imports for the operators
# this script actually uses. Do not use import *, delayed imports, aliases, or
# dynamic import/importlib/getattr(sys.modules[...]) lookup. Do not import or
-# call workflow(...): sub-workflow composition is not part of this template's
-# supported surface. The supported operators are agent, budget, compact,
-# flatten_filter, log, map_parallel, parallel, phase, pipeline, and pmap.
+# call workflow(...): nested workflow composition remains outside this
+# template's supported surface. The supported operators are agent,
+# agent_session, budget, compact, flatten_filter, human, human_session, log,
+# map_parallel, parallel, phase, pipeline, and pmap. AgentSession and
+# HumanSession are type-only imports; import them only for annotations and
+# never construct them directly.
# - Do not define variables, functions, parameters, or classes named like
# SwarmFlow operators. They shadow the imported runtime primitives.
# - Use JSON Schema literals for structured agent outputs. Keep schema but
@@ -226,6 +229,22 @@ async def run(args):
# with extract_json(..., fallback={...}). agent() may return None (schema
# validation failed) or a raw string (no schema match); extract_json handles
# both gracefully.
+# - Use human(...) for one-shot human input. Await it outside parallel thunks,
+# never pass notify=..., and handle None just as deliberately as an agent
+# failure. Use a schema when the human answer must be structured.
+# - Use human_session(...) or agent_session(...) only when the same participant
+# needs multiple turns with persistent context. The factories are synchronous:
+# assign their return value without await. Await every session.send(...) and
+# session.aclose() call, keep sends on one session sequential, and close the
+# session in a finally block. send(notify=True) is one-way and returns None;
+# never combine notify=True with schema=....
+# - An agent_session consumes one spawn slot when first opened and its turns use
+# the agent concurrency permit. A human_session consumes neither while waiting
+# for a person. Account for the former in budgets, and handle None returned by
+# either session instead of assuming every turn succeeds.
+# - Give human and session interactions stable literal labels. An active phase()
+# call overrides a session's default phase, so one session may intentionally
+# continue across multiple workflow phases.
# - After extract_json(...), verify semantic key fields before treating a
# result as successful. Missing or empty key fields should trigger fallback,
# retry, or degraded handling.