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 workflow and budget operators

z2tngbcc368d4449e
diff --git a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/SKILL.md
index 14c169c8bf..9245b0bc9b 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.5"
+version: "0.6"
---
# Swarm Skill Creator
@@ -161,7 +161,11 @@ 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.
+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.
+
+Choose composition by asset boundary: use `workflow(...)` only to reuse an existing persisted child workflow whose independent journal namespace is useful; keep ordinary code reuse in local helpers. The template is canonical for call shape, one-level composition, shared Runtime resources, and failure behavior.
+
+Choose budget behavior only when the user requests token-budget scaling: use dynamic depth for uncertain work, static fan-out for divisible work, or graceful completion when synthesis capacity must be reserved. The template is canonical for guards, read-only access, shared-ledger behavior, and exhaustion handling.
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.
@@ -221,7 +225,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, human/session call discipline, schema permissiveness, and blocked runtime patterns
+- **SwarmFlow script safety envelope**: standalone script shape, inline prompts, safe imports, phase/agent consistency, human/session call discipline, workflow composition, budget guard 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/reference/compliance-checklist.md b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/reference/compliance-checklist.md
index 32fc23703b..50ce94d555 100644
--- a/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/reference/compliance-checklist.md
+++ b/jiuwenswarm/resources/agent/workspace/skills/swarmskill-creator/reference/compliance-checklist.md
@@ -195,6 +195,28 @@ For every integration/final result, verify:
Schema shape only proves the container exists; it does not prove the answer is useful.
+### B13. Child workflow composition is justified
+
+For every `workflow(...)` call, verify:
+
+- The referenced child script already exists and its independent journal namespace is useful.
+- The child does not call another workflow; recursive designs have been flattened.
+- Ordinary shared code remains a helper function instead of becoming a child workflow.
+- Parallel children either tolerate shared-budget competition or receive explicit per-child limits through args.
+
+Sub-workflows are execution boundaries, not a general-purpose code reuse mechanism.
+
+### B14. Budget scaling leaves room to finish
+
+For every budget-dependent loop or fan-out, verify:
+
+- The no-budget fallback is bounded independently and cannot create an unbounded loop or fan-out.
+- The remaining-token threshold reserves enough capacity for integration and the final report.
+- Work skipped because of the budget is visible in the returned result.
+- Child workflows rely on the shared parent ledger rather than inventing a second budget source.
+
+A syntactically guarded budget policy can still spend everything before producing a usable answer.
+
---
## Part C: Cross-Swarm-Skill consistency (only when publishing multiple together)
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 ff21744b1f..47392ed52d 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
@@ -32,8 +32,8 @@ What this script catches (deterministic):
- scripts/workflow.py, when present, satisfies the executable SwarmFlow
safety envelope: standalone shape, literal META, inline prompts, safe
imports, phase/agent consistency, human/session call discipline,
- permissive schemas, and blocked runtime patterns. The full authoring
- constraint list lives in
+ workflow composition, budget access 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):
@@ -495,10 +495,12 @@ SUPPORTED_SWARMFLOW_OPERATORS = {
"phase",
"pipeline",
"pmap",
+ "workflow",
}
SUPPORTED_SWARMFLOW_TYPES = {"AgentSession", "HumanSession"}
PROTECTED_SWARMFLOW_NAMES = SUPPORTED_SWARMFLOW_OPERATORS
+DEFERRED_THUNK_OPERATORS = {"map_parallel", "parallel", "pipeline", "pmap"}
NON_DETERMINISTIC_IMPORTS = {"random", "time", "datetime"}
FILESYSTEM_CALLS = {"open"}
PATH_IO_METHODS = {"read_text", "write_text", "read_bytes", "write_bytes", "open"}
@@ -552,7 +554,7 @@ def _call_name(node: ast.Call) -> str | None:
return None
-def _is_inside_parallel_lambda(node: ast.AST) -> bool:
+def _is_inside_deferred_lambda(node: ast.AST) -> bool:
current = _parent(node)
while current is not None:
if isinstance(current, ast.Lambda):
@@ -560,7 +562,7 @@ def _is_inside_parallel_lambda(node: ast.AST) -> bool:
container = _parent(lambda_node)
while container is not None:
if isinstance(container, ast.Call):
- return _call_name(container) == "parallel"
+ return _call_name(container) in DEFERRED_THUNK_OPERATORS
if isinstance(container, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
return False
container = _parent(container)
@@ -893,6 +895,114 @@ def _has_notify_schema_conflict(node: ast.Call) -> bool:
return not _is_literal_none(schema_kw.value)
+def _workflow_path_argument(node: ast.Call) -> ast.AST | None:
+ if node.args:
+ return node.args[0]
+ keyword = _keyword(node, "name_or_path")
+ return keyword.value if keyword is not None else None
+
+
+def _workflow_path_is_missing_or_empty(node: ast.AST | None) -> bool:
+ if node is None:
+ return True
+ if not isinstance(node, ast.Constant):
+ return False
+ return not isinstance(node.value, str) or not node.value.strip()
+
+
+def _is_budget_attribute(node: ast.AST, name: str) -> bool:
+ return (
+ isinstance(node, ast.Attribute)
+ and node.attr == name
+ and isinstance(node.value, ast.Name)
+ and node.value.id == "budget"
+ )
+
+
+def _is_none_literal(node: ast.AST) -> bool:
+ return isinstance(node, ast.Constant) and node.value is None
+
+
+def _proves_budget_total_available(node: ast.AST) -> bool:
+ if _is_budget_attribute(node, "total"):
+ return True
+ if isinstance(node, ast.BoolOp) and isinstance(node.op, ast.And):
+ return any(_proves_budget_total_available(value) for value in node.values)
+ if not isinstance(node, ast.Compare) or len(node.ops) != 1:
+ return False
+
+ op = node.ops[0]
+ comparator = node.comparators[0]
+ if not isinstance(op, (ast.IsNot, ast.NotEq)):
+ return False
+ return (
+ _is_budget_attribute(node.left, "total") and _is_none_literal(comparator)
+ ) or (
+ _is_none_literal(node.left) and _is_budget_attribute(comparator, "total")
+ )
+
+
+def _is_guarded_by_budget_total(node: ast.AST) -> bool:
+ current = node
+ parent = _parent(current)
+ while parent is not None:
+ if isinstance(parent, ast.BoolOp) and isinstance(parent.op, ast.And):
+ current_index = parent.values.index(current)
+ if any(
+ _proves_budget_total_available(value)
+ for value in parent.values[:current_index]
+ ):
+ return True
+ elif isinstance(parent, (ast.If, ast.While)):
+ if current in parent.body and _proves_budget_total_available(parent.test):
+ return True
+ elif isinstance(parent, ast.IfExp):
+ if current is parent.body and _proves_budget_total_available(parent.test):
+ return True
+ current = parent
+ parent = _parent(current)
+ return False
+
+
+def _budget_remaining_is_numeric(node: ast.Call) -> bool:
+ current: ast.AST = node
+ parent = _parent(current)
+ while isinstance(parent, (ast.UnaryOp, ast.BinOp)):
+ current = parent
+ parent = _parent(current)
+ if isinstance(parent, ast.Compare):
+ return any(
+ isinstance(op, (ast.Lt, ast.LtE, ast.Gt, ast.GtE))
+ for op in parent.ops
+ )
+ return isinstance(current, (ast.UnaryOp, ast.BinOp))
+
+
+def _has_guarded_budget_remaining(test: ast.AST) -> bool:
+ return any(
+ isinstance(candidate, ast.Call)
+ and _call_name(candidate) == "budget.remaining"
+ and _budget_remaining_is_numeric(candidate)
+ and _is_guarded_by_budget_total(candidate)
+ for candidate in ast.walk(test)
+ )
+
+
+def _caught_exception_names(node: ast.AST | None) -> set[str]:
+ if node is None:
+ return {"<bare>"}
+ if isinstance(node, ast.Name):
+ return {node.id}
+ if isinstance(node, ast.Attribute):
+ return {node.attr}
+ if isinstance(node, ast.Tuple):
+ names: set[str] = set()
+ for element in node.elts:
+ names.update(_caught_exception_names(element))
+ return names
+ return set()
+
+
def _is_asyncio_orchestration_alias_call(node: ast.Call, asyncio_modules: set[str]) -> bool:
if not isinstance(node.func, ast.Attribute):
return False
@@ -927,7 +1037,7 @@ def _runtime_call_issues(tree: ast.Module) -> tuple[list[str], list[str]]:
f"line {getattr(node, 'lineno', '?')}: imports non-deterministic module "
f"{module!r}; pass values via args"
)
- elif isinstance(node, ast.While):
+ elif isinstance(node, ast.While) and not _has_guarded_budget_remaining(node.test):
warnings.append(
f"line {getattr(node, 'lineno', '?')}: loop must document a stop condition "
"(max_rounds, dry_count, budget guard, or input cap)"
@@ -938,6 +1048,13 @@ def _runtime_call_issues(tree: ast.Module) -> tuple[list[str], list[str]]:
f"line {getattr(node, 'lineno', '?')}: avoid module-level mutable state; "
"keep run state inside run(args)"
)
+ elif isinstance(node, ast.ExceptHandler):
+ caught = _caught_exception_names(node.type)
+ if caught & {"<bare>", "BaseException", "BudgetExhausted"}:
+ warnings.append(
+ f"line {getattr(node, 'lineno', '?')}: exception handler may catch "
+ "budget exhaustion; use finally for cleanup and let BudgetExhausted propagate"
+ )
elif isinstance(node, ast.Call):
line = getattr(node, "lineno", "?")
call_name = _call_name(node)
@@ -951,18 +1068,53 @@ def _runtime_call_issues(tree: ast.Module) -> tuple[list[str], list[str]]:
errors.append(f"line {line}: use swarmflow.log(), not print()")
elif call_name == "budget":
errors.append(f"line {line}: budget is an imported singleton; use budget.remaining(), not budget()")
+ elif call_name == "budget.total":
+ errors.append(f"line {line}: budget.total is a property; do not call it")
+ elif call_name == "budget.remaining":
+ if _budget_remaining_is_numeric(node) and not _is_guarded_by_budget_total(node):
+ errors.append(
+ f"line {line}: guard budget.remaining() numeric use with "
+ "budget.total or `budget.total is not None`"
+ )
+ elif call_name == "workflow":
+ path_argument = _workflow_path_argument(node)
+ path_literal = (
+ _string_literal(path_argument)
+ if path_argument is not None
+ else None
+ )
+ if _workflow_path_is_missing_or_empty(path_argument):
+ errors.append(
+ f"line {line}: workflow() requires a non-empty child workflow name/path"
+ )
+ elif path_literal is None:
+ warnings.append(
+ f"line {line}: dynamic child workflow path cannot be validated; "
+ "prefer a stable string literal and validate external input"
+ )
+ if not _is_directly_awaited(node) and not _is_inside_deferred_lambda(node):
+ errors.append(
+ f"line {line}: workflow() must be awaited or returned from a "
+ "deferred SwarmFlow thunk"
+ )
elif call_name == "agent":
if node.args and _string_literal(node.args[0]) == "":
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")
+ if not _is_directly_awaited(node) and not _is_inside_deferred_lambda(node):
+ errors.append(
+ f"line {line}: agent() must be awaited or returned from a "
+ "deferred SwarmFlow 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")
+ if not _is_directly_awaited(node) and not _is_inside_deferred_lambda(node):
+ errors.append(
+ f"line {line}: human() must be awaited or returned from a "
+ "deferred SwarmFlow 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")
@@ -1006,6 +1158,24 @@ def _runtime_call_issues(tree: ast.Module) -> tuple[list[str], list[str]]:
warnings.append(
f"line {line}: avoid direct filesystem access via Path.{node.func.attr} in workflow.py"
)
+ elif isinstance(node, ast.Attribute):
+ line = getattr(node, "lineno", "?")
+ if _is_budget_attribute(node, "total") and isinstance(
+ node.ctx,
+ (ast.Store, ast.Del),
+ ):
+ errors.append(f"line {line}: budget.total is read-only")
+ elif (
+ node.attr in {"remaining", "spent"}
+ and _is_budget_attribute(node, node.attr)
+ and isinstance(node.ctx, ast.Load)
+ ):
+ parent = _parent(node)
+ if not (isinstance(parent, ast.Call) and parent.func is node):
+ errors.append(
+ f"line {line}: budget.{node.attr} is a method; "
+ f"use budget.{node.attr}()"
+ )
return sorted(set(errors)), sorted(set(warnings))
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 c3628563f1..6b66210358 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
@@ -211,15 +211,38 @@ async def run(args):
# that reference undefined names.
# - 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(...): 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.
+# dynamic import/importlib/getattr(sys.modules[...]) lookup. The supported
+# operators are agent, agent_session, budget, compact, flatten_filter, human,
+# human_session, log, map_parallel, parallel, phase, pipeline, pmap, and
+# workflow. 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 workflow(...) only to reuse a child workflow script that already exists
+# and needs its own journal namespace. Await direct serial calls. For sibling
+# fan-out, return workflow(...) from each parallel thunk and bind loop
+# variables in lambda defaults. Prefer a stable string-literal name or path;
+# validate any path selected from args.
+# - Workflow composition is capped at one level. A child script's run() MUST NOT
+# call workflow(...) again; flatten recursive designs into one script with
+# loops, parallel, or pipeline. The child shares the parent Runtime,
+# concurrency permits, abort signal, and budget ledger, so do not pass or
+# allocate a separate budget object.
+# - Generate budget-dependent control flow only when the user requests a token
+# budget or budget-based scaling. budget.total is None when no cap is set, so
+# guard every numeric use of budget.remaining(): for example,
+# `while budget.total and budget.remaining() > threshold`.
+# - For evenly divisible work, size static fan-out with
+# `budget.total // per_agent if budget.total else default`. For graceful
+# completion, poll remaining() inside the same total guard and reserve enough
+# budget for integration or reporting.
+# - budget is read-only. Read budget.total as a property; call budget.spent()
+# and budget.remaining() as methods. Never assign to budget.total. Let
+# BudgetExhausted propagate; use finally for cleanup instead of catching
+# BaseException or BudgetExhausted.
+# - Parallel child workflows compete for the same token ledger. If fairness is
+# required, calculate per-child limits in the parent and pass them through
+# child args; workflow(...) itself does not consume tokens.
# - Use JSON Schema literals for structured agent outputs. Keep schema but
# REMOVE schema-object keywords "additionalProperties": False and "required"
# — both are too strict for LLM outputs and can cause agent() to silently