Files
cp1-agents/scripts/kab_import_workflow.py
Jonathan Boniface 416c66ced4
All checks were successful
check agents / check (push) Successful in 10s
Add CP1 Discovery agents in both patterns
ALZ-F01 Discovery as a sub-agent orchestrator (sub-agents/) and as eight
individual declarative agents (individual-agents/), with their KAB workflow
exports. Shared check, render and import scripts, the alz-discovery-sample
MCP server, the crucible-kab-dev deploy profile, deployment docs, platform
issue reports and the source material. Agent steps time out at 20 minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:25:57 +00:00

123 lines
5.8 KiB
Python

#!/usr/bin/env python3
"""Build a Feature's KAB workflow export and apply it to the platform.
Builds the export with the Feature's own scripts/build_workflow.py (the same JSON as its workflows/, with the chosen
front steps), then:
validate POST {api}/api/workflows/import/validate-json always; changes nothing
import POST {api}/api/workflows/import only with --apply
The run form KAB shows for the imported workflow asks for `engagement_id`, `run_id` and, with the upload step, the
files to upload. Artifact ids given here are fixed in the workflow's Artifacts step.
Authentication: your KAB session's OIDC access token, read from --token-file (default ~/.kab_token) or the KAB_TOKEN
variable. It is sent only as the Authorization header and never printed. Importing needs the Editor role in KAB.
Standard library only.
Usage (from the repository root; quote the Feature folder, its name has spaces):
python3 scripts/kab_import_workflow.py "sub-agents/ALZ-F01: Discovery Workflow Agent" --project-id <id> # validate only
python3 scripts/kab_import_workflow.py "<Feature folder>" --project-id <id> --apply # import as a draft
python3 scripts/kab_import_workflow.py "<Feature folder>" --project-id <id> --artifact-id <id> --apply # with an Artifacts step
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import sys
import urllib.error
import urllib.request
from pathlib import Path
DEFAULT_API = "https://api.kab-dev.kyndemo.live"
def _token(path: Path) -> str:
token = os.environ.get("KAB_TOKEN", "").strip()
if not token and path.is_file():
token = path.read_text().strip()
if token.lower().startswith("bearer "):
token = token[7:].strip()
if not token:
raise SystemExit(f"no KAB token: put your session's access token in {path} (or KAB_TOKEN)")
return token
def _builder(feature: Path):
"""The Feature's own build() from <feature>/scripts/build_workflow.py."""
script = feature / "scripts" / "build_workflow.py"
if not script.is_file():
raise SystemExit(f"{feature}: no scripts/build_workflow.py; pass a Feature folder such as "
"'sub-agents/ALZ-F01: Discovery Workflow Agent'")
spec = importlib.util.spec_from_file_location(f"build_workflow_{abs(hash(script))}", script)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module.build
def _post(api: str, path: str, token: str, body: dict) -> dict:
request = urllib.request.Request(
f"{api.rstrip('/')}{path}", data=json.dumps(body).encode("utf-8"), method="POST",
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"})
try:
with urllib.request.urlopen(request, timeout=60) as response:
return json.loads(response.read() or b"{}")
except urllib.error.HTTPError as error:
detail = error.read().decode("utf-8", "replace")[:800]
hint = {401: "the token is missing, wrong or expired: copy a fresh one",
403: "your KAB account lacks the role this needs (Editor to import)"}.get(error.code, "")
raise SystemExit(f"{path}: HTTP {error.code} {hint}\n{detail}")
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("feature", type=Path, help="the Feature folder whose workflow is imported")
parser.add_argument("--project-id", required=True, help="the KAB project the workflow is imported into")
parser.add_argument("--api", default=DEFAULT_API)
parser.add_argument("--token-file", type=Path, default=Path.home() / ".kab_token")
parser.add_argument("--no-upload", action="store_true", help="leave out the file upload step")
parser.add_argument("--artifact-id", action="append", default=[], help="add an Artifacts step with this id")
parser.add_argument("--name", help="import under another name")
parser.add_argument("--published", action="store_true", help="import as published (default: draft)")
parser.add_argument("--apply", action="store_true", help="import; without it the export is only validated")
parser.add_argument("--save", type=Path, help="also write the export to this file")
args = parser.parse_args(argv)
export = _builder(args.feature)(not args.no_upload, args.artifact_id)
if args.save:
args.save.write_text(json.dumps(export, indent=2) + "\n")
steps = export["template"]["steps"]
print(f"workflow: {export['workflow']['name']} ({len(steps)} steps: "
+ ", ".join(f"{s['id']}={s['agent']}" for s in steps) + ")")
token = _token(args.token_file)
check = _post(args.api, "/api/workflows/import/validate-json", token, export)
print(f"validate: valid={check.get('valid')}")
for item in check.get("agents", []) + check.get("activities", []):
print(" ", json.dumps(item)[:200])
for error in check.get("errors", []):
print(" error:", error)
for warning in check.get("warnings", []):
print(" warning:", warning)
if not check.get("valid"):
return 1
if not args.apply:
print("validated only; add --apply to import")
return 0
mappings = [{"source_name": a["name"], "target_url": a["source_url"]} for a in export["dependencies"]["agents"]]
result = _post(args.api, "/api/workflows/import", token, {
"export_data": export, "agent_mappings": mappings, "import_as_draft": not args.published,
"new_name": args.name, "project_id": args.project_id})
print(f"imported: workflow_id={result.get('workflow_id')} status={result.get('status')} "
f"steps={result.get('step_count')}")
for warning in result.get("warnings", []):
print(" warning:", warning)
return 0 if result.get("success") else 1
if __name__ == "__main__":
raise SystemExit(main())