agent-toolkit-cli 1.11.0__py3-none-win_amd64.whl
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.
- agent_toolkit/__init__.py +4 -0
- agent_toolkit/__main__.py +5 -0
- agent_toolkit/_paths.py +145 -0
- agent_toolkit/bin/.gitkeep +0 -0
- agent_toolkit/bin/agent-toolkit.exe +0 -0
- agent_toolkit/cli/__init__.py +0 -0
- agent_toolkit/cli/__main__.py +5 -0
- agent_toolkit/cli/build.py +278 -0
- agent_toolkit/cli/completion.py +297 -0
- agent_toolkit/cli/context_budget.py +455 -0
- agent_toolkit/cli/devcompanion.py +923 -0
- agent_toolkit/cli/devcompanion_queue.py +235 -0
- agent_toolkit/cli/diff.py +176 -0
- agent_toolkit/cli/doctor.py +1052 -0
- agent_toolkit/cli/insights.py +771 -0
- agent_toolkit/cli/install.py +706 -0
- agent_toolkit/cli/main.py +171 -0
- agent_toolkit/cli/mcp.py +537 -0
- agent_toolkit/cli/memory.py +739 -0
- agent_toolkit/cli/plugin.py +224 -0
- agent_toolkit/cli/project.py +459 -0
- agent_toolkit/cli/release.py +178 -0
- agent_toolkit/cli/skills.py +461 -0
- agent_toolkit/cli/uninstall.py +166 -0
- agent_toolkit/cli/update.py +298 -0
- agent_toolkit/cli/workspace.py +1713 -0
- agent_toolkit/compiler/hook_registry.py +110 -0
- agent_toolkit/compiler/loader.py +338 -0
- agent_toolkit/compiler/mcp_registry.py +87 -0
- agent_toolkit/compiler/model.py +182 -0
- agent_toolkit/compiler/provenance.py +140 -0
- agent_toolkit/compiler/registry_emit.py +263 -0
- agent_toolkit/compiler/target_registry.py +122 -0
- agent_toolkit/compiler/targets/__init__.py +1 -0
- agent_toolkit/compiler/targets/agent_plugins.py +160 -0
- agent_toolkit/compiler/targets/base.py +229 -0
- agent_toolkit/compiler/targets/claude_code.py +241 -0
- agent_toolkit/compiler/targets/codex.py +261 -0
- agent_toolkit/compiler/targets/copilot.py +275 -0
- agent_toolkit/compiler/targets/cursor.py +207 -0
- agent_toolkit/compiler/targets/gemini_cli.py +213 -0
- agent_toolkit/compiler/targets/muse_code.py +113 -0
- agent_toolkit/compiler/targets/opencode.py +204 -0
- agent_toolkit/compiler/targets/pi.py +263 -0
- agent_toolkit/compiler/targets/windsurf.py +267 -0
- agent_toolkit/compiler/tool_mapping.py +83 -0
- agent_toolkit/data/.gitignore +4 -0
- agent_toolkit/data/__init__.py +1 -0
- agent_toolkit/data/agents/agentic-security-reviewer/AGENT.md +60 -0
- agent_toolkit/data/agents/architect/AGENT.md +30 -0
- agent_toolkit/data/agents/assistant/AGENT.md +59 -0
- agent_toolkit/data/agents/build-error-resolver/AGENT.md +30 -0
- agent_toolkit/data/agents/client-workflow-bootstrap/AGENT.md +60 -0
- agent_toolkit/data/agents/code-reviewer/AGENT.md +49 -0
- agent_toolkit/data/agents/database-reviewer/AGENT.md +44 -0
- agent_toolkit/data/agents/docs-lookup/AGENT.md +28 -0
- agent_toolkit/data/agents/e2e-runner/AGENT.md +38 -0
- agent_toolkit/data/agents/performance-optimizer/AGENT.md +52 -0
- agent_toolkit/data/agents/planner/AGENT.md +41 -0
- agent_toolkit/data/agents/refactor-cleaner/AGENT.md +43 -0
- agent_toolkit/data/agents/reference-lookup/AGENT.md +33 -0
- agent_toolkit/data/agents/security-reviewer/AGENT.md +47 -0
- agent_toolkit/data/agents/tdd-guide/AGENT.md +58 -0
- agent_toolkit/data/agents/tech-assistant/AGENT.md +11 -0
- agent_toolkit/data/agents/typescript-reviewer/AGENT.md +61 -0
- agent_toolkit/data/capabilities/hooks/README.md +6 -0
- agent_toolkit/data/capabilities/hooks/pre-commit-validate.yaml +26 -0
- agent_toolkit/data/capabilities/hooks/scripts/pre-commit-validate.sh +41 -0
- agent_toolkit/data/capabilities/hooks/scripts/session-start-context.sh +11 -0
- agent_toolkit/data/capabilities/hooks/session-start-context.yaml +23 -0
- agent_toolkit/data/capabilities/targets/registry.yaml +90 -0
- agent_toolkit/data/capabilities/upstream.lock +118 -0
- agent_toolkit/data/catalogs/agent-catalog.yaml +81 -0
- agent_toolkit/data/catalogs/loop-catalog.yaml +55 -0
- agent_toolkit/data/catalogs/skill-catalog.yaml +520 -0
- agent_toolkit/data/catalogs/skills-layout.json +391 -0
- agent_toolkit/data/distributions/products.yaml +190 -0
- agent_toolkit/data/distributions/targets/claude-code.yaml +47 -0
- agent_toolkit/data/distributions/targets/cursor.yaml +42 -0
- agent_toolkit/data/distributions/targets/opencode.yaml +55 -0
- agent_toolkit/data/loops/changelog-drafter/loop.yaml +40 -0
- agent_toolkit/data/loops/ci-sweeper/loop.yaml +53 -0
- agent_toolkit/data/loops/daily-triage/loop.yaml +47 -0
- agent_toolkit/data/loops/dep-sweeper/loop.yaml +46 -0
- agent_toolkit/data/loops/issue-triage/loop.yaml +40 -0
- agent_toolkit/data/loops/oss-daily-briefing/loop.yaml +65 -0
- agent_toolkit/data/loops/oss-pr-monitor/loop.yaml +86 -0
- agent_toolkit/data/loops/oss-triage/loop.yaml +67 -0
- agent_toolkit/data/loops/post-merge-cleanup/loop.yaml +44 -0
- agent_toolkit/data/loops/pr-babysitter/loop.yaml +46 -0
- agent_toolkit/data/mcp/registry/chrome-devtools.yaml +61 -0
- agent_toolkit/data/mcp/registry/clickup.yaml +48 -0
- agent_toolkit/data/mcp/registry/figma.yaml +44 -0
- agent_toolkit/data/mcp/registry/github.yaml +52 -0
- agent_toolkit/data/mcp/registry/linear.yaml +47 -0
- agent_toolkit/data/mcp/registry/notion.yaml +48 -0
- agent_toolkit/data/mcp/registry/slack.yaml +46 -0
- agent_toolkit/data/mcp/templates/chrome-devtools/README.md +57 -0
- agent_toolkit/data/mcp/templates/chrome-devtools/config.template.json +6 -0
- agent_toolkit/data/mcp/templates/clickup/README.md +45 -0
- agent_toolkit/data/mcp/templates/clickup/config.template.json +8 -0
- agent_toolkit/data/mcp/templates/clickup/wrapper.sh +23 -0
- agent_toolkit/data/mcp/templates/figma/README.md +54 -0
- agent_toolkit/data/mcp/templates/figma/config.template.json +9 -0
- agent_toolkit/data/mcp/templates/github/README.md +16 -0
- agent_toolkit/data/mcp/templates/github/config.template.json +15 -0
- agent_toolkit/data/mcp/templates/github/wrapper.sh +6 -0
- agent_toolkit/data/mcp/templates/linear/README.md +49 -0
- agent_toolkit/data/mcp/templates/linear/config.template.json +10 -0
- agent_toolkit/data/mcp/templates/notion/README.md +7 -0
- agent_toolkit/data/mcp/templates/notion/config.template.json +8 -0
- agent_toolkit/data/mcp/templates/notion/wrapper.sh +23 -0
- agent_toolkit/data/mcp/templates/slack/README.md +8 -0
- agent_toolkit/data/mcp/templates/slack/config.template.json +9 -0
- agent_toolkit/data/mcp/templates/slack/wrapper.sh +23 -0
- agent_toolkit/data/packs/README.md +66 -0
- agent_toolkit/data/packs/agentic-security/README.md +19 -0
- agent_toolkit/data/packs/agentic-security/config.yaml +25 -0
- agent_toolkit/data/packs/architecture/README.md +22 -0
- agent_toolkit/data/packs/architecture/config.yaml +27 -0
- agent_toolkit/data/packs/code-quality/README.md +19 -0
- agent_toolkit/data/packs/code-quality/config.yaml +21 -0
- agent_toolkit/data/packs/delivery-discipline/README.md +19 -0
- agent_toolkit/data/packs/delivery-discipline/config.yaml +42 -0
- agent_toolkit/data/packs/design-engineering/README.md +19 -0
- agent_toolkit/data/packs/design-engineering/config.yaml +41 -0
- agent_toolkit/data/packs/engineering-workflow/README.md +21 -0
- agent_toolkit/data/packs/engineering-workflow/config.yaml +57 -0
- agent_toolkit/data/packs/oss-maintenance/README.md +245 -0
- agent_toolkit/data/packs/oss-maintenance/config.yaml +75 -0
- agent_toolkit/data/profiles/claude-code/CLAUDE.md +110 -0
- agent_toolkit/data/profiles/claude-code/agents/assistant.md +59 -0
- agent_toolkit/data/profiles/claude-code/agents/build-error-resolver.md +30 -0
- agent_toolkit/data/profiles/claude-code/agents/client-workflow-bootstrap.md +60 -0
- agent_toolkit/data/profiles/claude-code/agents/contribution-planner.md +39 -0
- agent_toolkit/data/profiles/claude-code/agents/database-reviewer.md +44 -0
- agent_toolkit/data/profiles/claude-code/agents/docs-lookup.md +28 -0
- agent_toolkit/data/profiles/claude-code/agents/e2e-runner.md +38 -0
- agent_toolkit/data/profiles/claude-code/agents/performance-optimizer.md +52 -0
- agent_toolkit/data/profiles/claude-code/agents/planner.md +41 -0
- agent_toolkit/data/profiles/claude-code/agents/refactor-cleaner.md +43 -0
- agent_toolkit/data/profiles/claude-code/agents/reference-lookup.md +33 -0
- agent_toolkit/data/profiles/claude-code/agents/security-reviewer.md +47 -0
- agent_toolkit/data/profiles/claude-code/agents/tdd-guide.md +58 -0
- agent_toolkit/data/profiles/claude-code/agents/typescript-reviewer.md +61 -0
- agent_toolkit/data/profiles/claude-code/settings.json +86 -0
- agent_toolkit/data/profiles/copilot/copilot-instructions.md +15 -0
- agent_toolkit/data/profiles/cursor/README.md +33 -0
- agent_toolkit/data/profiles/cursor/rules/architect.mdc +23 -0
- agent_toolkit/data/profiles/cursor/rules/assistant.mdc +61 -0
- agent_toolkit/data/profiles/cursor/rules/build-error-resolver.mdc +20 -0
- agent_toolkit/data/profiles/cursor/rules/code-reviewer.mdc +21 -0
- agent_toolkit/data/profiles/cursor/rules/database-reviewer.mdc +29 -0
- agent_toolkit/data/profiles/cursor/rules/docs-lookup.mdc +15 -0
- agent_toolkit/data/profiles/cursor/rules/e2e-runner.mdc +30 -0
- agent_toolkit/data/profiles/cursor/rules/performance-optimizer.mdc +27 -0
- agent_toolkit/data/profiles/cursor/rules/planner.mdc +28 -0
- agent_toolkit/data/profiles/cursor/rules/refactor-cleaner.mdc +26 -0
- agent_toolkit/data/profiles/cursor/rules/reference-lookup.mdc +20 -0
- agent_toolkit/data/profiles/cursor/rules/security-reviewer.mdc +20 -0
- agent_toolkit/data/profiles/cursor/rules/tdd-guide.mdc +26 -0
- agent_toolkit/data/profiles/cursor/rules/typescript-reviewer.mdc +28 -0
- agent_toolkit/data/profiles/muse-code/README.md +35 -0
- agent_toolkit/data/profiles/opencode/README.md +44 -0
- agent_toolkit/data/profiles/opencode/agents/architect.md +30 -0
- agent_toolkit/data/profiles/opencode/agents/assistant.md +96 -0
- agent_toolkit/data/profiles/opencode/agents/build-error-resolver.md +31 -0
- agent_toolkit/data/profiles/opencode/agents/client-workflow-bootstrap.md +66 -0
- agent_toolkit/data/profiles/opencode/agents/code-reviewer.md +47 -0
- agent_toolkit/data/profiles/opencode/agents/contribution-planner.md +44 -0
- agent_toolkit/data/profiles/opencode/agents/database-reviewer.md +43 -0
- agent_toolkit/data/profiles/opencode/agents/docs-lookup.md +28 -0
- agent_toolkit/data/profiles/opencode/agents/e2e-runner.md +33 -0
- agent_toolkit/data/profiles/opencode/agents/performance-optimizer.md +34 -0
- agent_toolkit/data/profiles/opencode/agents/planner.md +27 -0
- agent_toolkit/data/profiles/opencode/agents/refactor-cleaner.md +27 -0
- agent_toolkit/data/profiles/opencode/agents/reference-lookup.md +27 -0
- agent_toolkit/data/profiles/opencode/agents/security-reviewer.md +27 -0
- agent_toolkit/data/profiles/opencode/agents/tdd-guide.md +27 -0
- agent_toolkit/data/profiles/opencode/agents/typescript-reviewer.md +30 -0
- agent_toolkit/data/profiles/opencode/opencode.json +3 -0
- agent_toolkit/data/profiles/pi/skills/architect/skill.md +5 -0
- agent_toolkit/data/profiles/pi/skills/assistant/skill.md +3 -0
- agent_toolkit/data/profiles/pi/skills/code-reviewer/skill.md +5 -0
- agent_toolkit/data/profiles/pi/skills/planner/skill.md +3 -0
- agent_toolkit/data/profiles/pi/skills/security-reviewer/skill.md +3 -0
- agent_toolkit/data/profiles/windsurf/memories/global_rules.md +114 -0
- agent_toolkit/data/profiles/windsurf/rules/architect.mdc +23 -0
- agent_toolkit/data/profiles/windsurf/rules/assistant.mdc +61 -0
- agent_toolkit/data/profiles/windsurf/rules/build-error-resolver.mdc +20 -0
- agent_toolkit/data/profiles/windsurf/rules/code-reviewer.mdc +21 -0
- agent_toolkit/data/profiles/windsurf/rules/database-reviewer.mdc +29 -0
- agent_toolkit/data/profiles/windsurf/rules/docs-lookup.mdc +15 -0
- agent_toolkit/data/profiles/windsurf/rules/e2e-runner.mdc +30 -0
- agent_toolkit/data/profiles/windsurf/rules/performance-optimizer.mdc +27 -0
- agent_toolkit/data/profiles/windsurf/rules/planner.mdc +28 -0
- agent_toolkit/data/profiles/windsurf/rules/refactor-cleaner.mdc +26 -0
- agent_toolkit/data/profiles/windsurf/rules/reference-lookup.mdc +20 -0
- agent_toolkit/data/profiles/windsurf/rules/security-reviewer.mdc +20 -0
- agent_toolkit/data/profiles/windsurf/rules/tdd-guide.mdc +26 -0
- agent_toolkit/data/profiles/windsurf/rules/typescript-reviewer.mdc +28 -0
- agent_toolkit/data/skills/accessibility/review/SKILL.md +116 -0
- agent_toolkit/data/skills/accessibility/review/references/a11y-checklist.md +25 -0
- agent_toolkit/data/skills/accessibility/review/references/a11y-findings-template.md +56 -0
- agent_toolkit/data/skills/accessibility/review/references/research.md +47 -0
- agent_toolkit/data/skills/agentic-security/mcp-audit/SKILL.md +116 -0
- agent_toolkit/data/skills/agentic-security/mcp-audit/references/mcp-audit-template.md +51 -0
- agent_toolkit/data/skills/agentic-security/owasp-agentic-review/SKILL.md +73 -0
- agent_toolkit/data/skills/agentic-security/owasp-agentic-review/references/owasp-agentic-template.md +32 -0
- agent_toolkit/data/skills/agentic-security/supply-chain-audit/SKILL.md +142 -0
- agent_toolkit/data/skills/agentic-security/threat-modeling/SKILL.md +100 -0
- agent_toolkit/data/skills/agentic-security/threat-modeling/references/threat-model-template.md +55 -0
- agent_toolkit/data/skills/architecture/c4-model/SKILL.md +49 -0
- agent_toolkit/data/skills/cloud/aws-well-architected-review/SKILL.md +37 -0
- agent_toolkit/data/skills/cloud/cloud-design-patterns/SKILL.md +38 -0
- agent_toolkit/data/skills/core/assistant/SKILL.md +216 -0
- agent_toolkit/data/skills/core/assistant/references/AGENTS_TEMPLATE.md +0 -0
- agent_toolkit/data/skills/core/assistant/references/ORCHESTRATION.md +0 -0
- agent_toolkit/data/skills/core/assistant/references/REPO_INSPECTION.md +0 -0
- agent_toolkit/data/skills/core/dev-companion/SKILL.md +65 -0
- agent_toolkit/data/skills/core/dev-companion/references/LOOP_GUARDRAILS.md +0 -0
- agent_toolkit/data/skills/core/onboarding/SKILL.md +122 -0
- agent_toolkit/data/skills/core/output-handshake/SKILL.md +26 -0
- agent_toolkit/data/skills/core/pr-fallback/SKILL.md +35 -0
- agent_toolkit/data/skills/core/pr-fallback/references/pr-body-default.md +0 -0
- agent_toolkit/data/skills/core/project/SKILL.md +89 -0
- agent_toolkit/data/skills/core/workspace/SKILL.md +103 -0
- agent_toolkit/data/skills/core/workspace-knowledge-sync/SKILL.md +140 -0
- agent_toolkit/data/skills/data/dbt-validation/SKILL.md +41 -0
- agent_toolkit/data/skills/data/snowflake-validation/SKILL.md +38 -0
- agent_toolkit/data/skills/delivery/adr/SKILL.md +56 -0
- agent_toolkit/data/skills/delivery/adr/references/default-template.md +35 -0
- agent_toolkit/data/skills/delivery/adr/references/example-001-graphql-adoption.md +66 -0
- agent_toolkit/data/skills/delivery/agreement/SKILL.md +24 -0
- agent_toolkit/data/skills/delivery/agreement/references/default-template.md +17 -0
- agent_toolkit/data/skills/delivery/agreement/references/example-api-versioning.md +29 -0
- agent_toolkit/data/skills/delivery/bug/SKILL.md +26 -0
- agent_toolkit/data/skills/delivery/bug/references/default-template.md +26 -0
- agent_toolkit/data/skills/delivery/bug/references/example-search-filter-bug.md +58 -0
- agent_toolkit/data/skills/delivery/decision-log/SKILL.md +28 -0
- agent_toolkit/data/skills/delivery/decision-log/references/default-template.md +17 -0
- agent_toolkit/data/skills/delivery/decision-log/references/example-repository-pattern.md +27 -0
- agent_toolkit/data/skills/delivery/development-workflow/SKILL.md +34 -0
- agent_toolkit/data/skills/delivery/development-workflow/references/default-workflow-checklist.md +44 -0
- agent_toolkit/data/skills/delivery/epic/SKILL.md +22 -0
- agent_toolkit/data/skills/delivery/epic/references/default-template.md +26 -0
- agent_toolkit/data/skills/delivery/epic/references/example-unified-dashboard.md +40 -0
- agent_toolkit/data/skills/delivery/incident/SKILL.md +24 -0
- agent_toolkit/data/skills/delivery/incident/references/default-template.md +29 -0
- agent_toolkit/data/skills/delivery/incident/references/example-payment-outage.md +62 -0
- agent_toolkit/data/skills/delivery/management-unit-assessment/SKILL.md +104 -0
- agent_toolkit/data/skills/delivery/management-unit-assessment/references/default-template.md +24 -0
- agent_toolkit/data/skills/delivery/management-unit-assessment/references/example-team-assessment.md +126 -0
- agent_toolkit/data/skills/delivery/meeting-minutes/SKILL.md +25 -0
- agent_toolkit/data/skills/delivery/meeting-minutes/references/default-template.md +22 -0
- agent_toolkit/data/skills/delivery/meeting-minutes/references/example-weekly-sync.md +72 -0
- agent_toolkit/data/skills/delivery/planning/SKILL.md +31 -0
- agent_toolkit/data/skills/delivery/planning/references/default-template.md +25 -0
- agent_toolkit/data/skills/delivery/planning/references/example-sprint-planning.md +62 -0
- agent_toolkit/data/skills/delivery/prd/SKILL.md +46 -0
- agent_toolkit/data/skills/delivery/prd/references/default-template.md +31 -0
- agent_toolkit/data/skills/delivery/prd/references/example-unified-api.md +71 -0
- agent_toolkit/data/skills/delivery/project-assessment/SKILL.md +90 -0
- agent_toolkit/data/skills/delivery/project-assessment/references/default-template.md +26 -0
- agent_toolkit/data/skills/delivery/project-assessment/references/example-platform-assessment.md +122 -0
- agent_toolkit/data/skills/delivery/project-assessment-evidence/SKILL.md +88 -0
- agent_toolkit/data/skills/delivery/project-assessment-evidence/references/default-template.md +24 -0
- agent_toolkit/data/skills/delivery/project-assessment-evidence/references/example-evidence-map.md +46 -0
- agent_toolkit/data/skills/delivery/spike/SKILL.md +24 -0
- agent_toolkit/data/skills/delivery/spike/references/default-template.md +29 -0
- agent_toolkit/data/skills/delivery/spike/references/example-graphql-federation.md +79 -0
- agent_toolkit/data/skills/delivery/task/SKILL.md +21 -0
- agent_toolkit/data/skills/delivery/task/references/default-template.md +21 -0
- agent_toolkit/data/skills/delivery/task/references/example-nav-system.md +33 -0
- agent_toolkit/data/skills/delivery/technical-unit-assessment/SKILL.md +58 -0
- agent_toolkit/data/skills/delivery/technical-unit-assessment/references/default-template.md +26 -0
- agent_toolkit/data/skills/delivery/technical-unit-assessment/references/example-frontend-assessment.md +112 -0
- agent_toolkit/data/skills/delivery/technical-unit-assessment/references/indicator-groups.md +65 -0
- agent_toolkit/data/skills/delivery/trd/SKILL.md +49 -0
- agent_toolkit/data/skills/delivery/trd/references/default-template.md +31 -0
- agent_toolkit/data/skills/delivery/trd/references/example-api-migration.md +122 -0
- agent_toolkit/data/skills/delivery/user-story/SKILL.md +21 -0
- agent_toolkit/data/skills/delivery/user-story/references/default-template.md +21 -0
- agent_toolkit/data/skills/delivery/user-story/references/example-advanced-filtering.md +37 -0
- agent_toolkit/data/skills/delivery/work-item/SKILL.md +31 -0
- agent_toolkit/data/skills/delivery/work-item/references/default-template.md +21 -0
- agent_toolkit/data/skills/delivery/work-item/references/example-routing-dashboard.md +23 -0
- agent_toolkit/data/skills/delivery/workflow-client-bootstrap/SKILL.md +148 -0
- agent_toolkit/data/skills/delivery/workflow-client-bootstrap/questions.yaml +165 -0
- agent_toolkit/data/skills/delivery/workflow-generic-project/SKILL.md +79 -0
- agent_toolkit/data/skills/design/design-assessment/SKILL.md +150 -0
- agent_toolkit/data/skills/design/design-assessment/references/design-scorecard-template.md +78 -0
- agent_toolkit/data/skills/design/design-improvement/SKILL.md +167 -0
- agent_toolkit/data/skills/design/design-improvement/references/improvement-plan-template.md +113 -0
- agent_toolkit/data/skills/design/figma/LICENSE.txt +2 -0
- agent_toolkit/data/skills/design/figma/NOTICE.txt +25 -0
- agent_toolkit/data/skills/design/figma/SKILL.md +98 -0
- agent_toolkit/data/skills/design/figma/references/figma-mcp-config.md +82 -0
- agent_toolkit/data/skills/design/figma/references/figma-tools-and-prompts.md +34 -0
- agent_toolkit/data/skills/design/figma-code-connect-components/LICENSE.txt +2 -0
- agent_toolkit/data/skills/design/figma-code-connect-components/NOTICE.txt +18 -0
- agent_toolkit/data/skills/design/figma-code-connect-components/SKILL.md +354 -0
- agent_toolkit/data/skills/design/figma-code-connect-components/references/mapping-checklist.md +7 -0
- agent_toolkit/data/skills/design/figma-code-connect-components/scripts/normalize_node_id.py +25 -0
- agent_toolkit/data/skills/design/figma-create-design-system-rules/LICENSE.txt +2 -0
- agent_toolkit/data/skills/design/figma-create-design-system-rules/NOTICE.txt +19 -0
- agent_toolkit/data/skills/design/figma-create-design-system-rules/SKILL.md +554 -0
- agent_toolkit/data/skills/design/figma-create-design-system-rules/references/rule-template.md +15 -0
- agent_toolkit/data/skills/design/figma-create-design-system-rules/scripts/check_agents_md.sh +9 -0
- agent_toolkit/data/skills/design/figma-create-new-file/LICENSE.txt +2 -0
- agent_toolkit/data/skills/design/figma-create-new-file/NOTICE.txt +17 -0
- agent_toolkit/data/skills/design/figma-create-new-file/SKILL.md +72 -0
- agent_toolkit/data/skills/design/figma-implement-design/LICENSE.txt +2 -0
- agent_toolkit/data/skills/design/figma-implement-design/NOTICE.txt +19 -0
- agent_toolkit/data/skills/design/figma-implement-design/SKILL.md +268 -0
- agent_toolkit/data/skills/design/frontend-design/LICENSE.txt +177 -0
- agent_toolkit/data/skills/design/frontend-design/SKILL.md +82 -0
- agent_toolkit/data/skills/design/frontend-design/UPSTREAM.md +14 -0
- agent_toolkit/data/skills/design/frontend-design-review/LICENSE +21 -0
- agent_toolkit/data/skills/design/frontend-design-review/SKILL.md +194 -0
- agent_toolkit/data/skills/design/frontend-design-review/references/pattern-examples.md +21 -0
- agent_toolkit/data/skills/design/frontend-design-review/references/quick-checklist.md +38 -0
- agent_toolkit/data/skills/design/frontend-design-review/references/review-output-format.md +68 -0
- agent_toolkit/data/skills/design/frontend-design-review/references/review-type-modifiers.md +31 -0
- agent_toolkit/data/skills/design/web-design-guidelines/SKILL.md +78 -0
- agent_toolkit/data/skills/design/web-design-guidelines/references/LICENSE +21 -0
- agent_toolkit/data/skills/design/web-design-guidelines/references/web-interface-guidelines.md +180 -0
- agent_toolkit/data/skills/forge/gh-address-comments/LICENSE.txt +202 -0
- agent_toolkit/data/skills/forge/gh-address-comments/NOTICE.txt +20 -0
- agent_toolkit/data/skills/forge/gh-address-comments/SKILL.md +72 -0
- agent_toolkit/data/skills/forge/gh-address-comments/scripts/fetch_comments.py +239 -0
- agent_toolkit/data/skills/forge/gh-contribution-planner/SKILL.md +160 -0
- agent_toolkit/data/skills/forge/gh-contribution-planner/scripts/inspect_contributions.py +818 -0
- agent_toolkit/data/skills/forge/gh-fix-ci/LICENSE.txt +201 -0
- agent_toolkit/data/skills/forge/gh-fix-ci/NOTICE.txt +20 -0
- agent_toolkit/data/skills/forge/gh-fix-ci/SKILL.md +74 -0
- agent_toolkit/data/skills/forge/gh-fix-ci/scripts/inspect_pr_checks.py +509 -0
- agent_toolkit/data/skills/forge/github-cli-workflow/SKILL.md +49 -0
- agent_toolkit/data/skills/forge/gitlab-cli-workflow/SKILL.md +44 -0
- agent_toolkit/data/skills/forge/workflow-client-bootstrap/SKILL.md +14 -0
- agent_toolkit/data/skills/forge/workflow-generic-project/SKILL.md +14 -0
- agent_toolkit/data/skills/forge/worktree/SKILL.md +113 -0
- agent_toolkit/data/skills/integrations/clickup-cli/SKILL.md +78 -0
- agent_toolkit/data/skills/integrations/clickup-cli/references/docs-management.md +57 -0
- agent_toolkit/data/skills/integrations/clickup-cli/references/task-management.md +131 -0
- agent_toolkit/data/skills/integrations/clickup-cli/references/time-tracking.md +38 -0
- agent_toolkit/data/skills/integrations/linear/LICENSE.txt +202 -0
- agent_toolkit/data/skills/integrations/linear/NOTICE.txt +23 -0
- agent_toolkit/data/skills/integrations/linear/SKILL.md +134 -0
- agent_toolkit/data/skills/integrations/mcp/SKILL.md +88 -0
- agent_toolkit/data/skills/integrations/slack-assistant/SKILL.md +138 -0
- agent_toolkit/data/skills/integrations/slack-cli/SKILL.md +109 -0
- agent_toolkit/data/skills/integrations/slack-cli/references/INSTALLATION.md +42 -0
- agent_toolkit/data/skills/loops/loop-runner/SKILL.md +92 -0
- agent_toolkit/data/skills/ops/docs-generator/SKILL.md +120 -0
- agent_toolkit/data/skills/ops/llm-cost-advisor/SKILL.md +87 -0
- agent_toolkit/data/skills/ops/swarm/SKILL.md +108 -0
- agent_toolkit/data/skills/ops/swarm-handoff/SKILL.md +112 -0
- agent_toolkit/data/skills/ops/swarm-observer/SKILL.md +102 -0
- agent_toolkit/data/skills/ops/triage/SKILL.md +119 -0
- agent_toolkit/data/skills/quality/codeql/SKILL.md +106 -0
- agent_toolkit/data/skills/quality/codeql/references/codeql-queries.md +43 -0
- agent_toolkit/data/skills/quality/megalinter/SKILL.md +162 -0
- agent_toolkit/data/skills/quality/megalinter/references/megalinter-images.md +36 -0
- agent_toolkit/data/skills/quality/megalinter/references/megalinter-license.md +41 -0
- agent_toolkit/data/skills/quality/megalinter/references/megalinter-targets.md +66 -0
- agent_toolkit/data/skills/tooling/chrome-devtools/SKILL.md +146 -0
- agent_toolkit/data/skills/tooling/herdr/SKILL.md +109 -0
- agent_toolkit/data/skills/tooling/inventory/SKILL.md +81 -0
- agent_toolkit/data/skills/tooling/jupyter-notebook/LICENSE.txt +201 -0
- agent_toolkit/data/skills/tooling/jupyter-notebook/NOTICE.txt +27 -0
- agent_toolkit/data/skills/tooling/jupyter-notebook/SKILL.md +145 -0
- agent_toolkit/data/skills/tooling/jupyter-notebook/assets/experiment-template.ipynb +117 -0
- agent_toolkit/data/skills/tooling/jupyter-notebook/assets/tutorial-template.ipynb +115 -0
- agent_toolkit/data/skills/tooling/jupyter-notebook/references/experiment-patterns.md +10 -0
- agent_toolkit/data/skills/tooling/jupyter-notebook/references/notebook-structure.md +17 -0
- agent_toolkit/data/skills/tooling/jupyter-notebook/references/quality-checklist.md +11 -0
- agent_toolkit/data/skills/tooling/jupyter-notebook/references/tutorial-patterns.md +9 -0
- agent_toolkit/data/skills/tooling/jupyter-notebook/scripts/new_notebook.py +132 -0
- agent_toolkit/data/skills/tooling/mermaid/SKILL.md +36 -0
- agent_toolkit/data/skills/tooling/playwright-cli/LICENSE.txt +201 -0
- agent_toolkit/data/skills/tooling/playwright-cli/NOTICE.txt +29 -0
- agent_toolkit/data/skills/tooling/playwright-cli/SKILL.md +154 -0
- agent_toolkit/data/skills/tooling/playwright-cli/references/cli.md +116 -0
- agent_toolkit/data/skills/tooling/playwright-cli/references/workflows.md +98 -0
- agent_toolkit/data/skills/tooling/playwright-cli/scripts/executable_playwright_cli.sh +25 -0
- agent_toolkit/data_cache.py +79 -0
- agent_toolkit/data_sync.py +144 -0
- agent_toolkit/installer/__init__.py +0 -0
- agent_toolkit/installer/merge.py +59 -0
- agent_toolkit/installer/receipt.py +89 -0
- agent_toolkit/installer/sources.py +92 -0
- agent_toolkit/installer/tracking.py +63 -0
- agent_toolkit/launcher.py +69 -0
- agent_toolkit/loop/__init__.py +0 -0
- agent_toolkit/loop/budget.py +107 -0
- agent_toolkit/loop/gh_gate.py +923 -0
- agent_toolkit/loop/loop-gh-gate +923 -0
- agent_toolkit/loop/pack.py +65 -0
- agent_toolkit/loop/runner.py +2722 -0
- agent_toolkit/runner/__init__.py +0 -0
- agent_toolkit/runner/dispatcher.py +163 -0
- agent_toolkit/runner/policy.py +356 -0
- agent_toolkit/runner/providers/__init__.py +21 -0
- agent_toolkit/runner/providers/anthropic_provider.py +109 -0
- agent_toolkit/runner/providers/base.py +53 -0
- agent_toolkit/runner/providers/ollama_provider.py +108 -0
- agent_toolkit/runner/providers/openai_provider.py +103 -0
- agent_toolkit/runner/providers/opencode_provider.py +127 -0
- agent_toolkit/swarm/__init__.py +5 -0
- agent_toolkit/swarm/approvals.py +121 -0
- agent_toolkit/swarm/backends/__init__.py +596 -0
- agent_toolkit/swarm/budget.py +83 -0
- agent_toolkit/swarm/cli.py +2448 -0
- agent_toolkit/swarm/config.py +351 -0
- agent_toolkit/swarm/handoff.py +174 -0
- agent_toolkit/swarm/models.py +230 -0
- agent_toolkit/swarm/prompts.py +177 -0
- agent_toolkit/swarm/recipes.py +304 -0
- agent_toolkit/swarm/runner.py +267 -0
- agent_toolkit/swarm/state.py +93 -0
- agent_toolkit/swarm/store.py +148 -0
- agent_toolkit/swarm/worktree.py +105 -0
- agent_toolkit/templates/workspace/.gitignore +19 -0
- agent_toolkit/templates/workspace/AGENTS.md +82 -0
- agent_toolkit/templates/workspace/knowledge/README.md +22 -0
- agent_toolkit/templates/workspace/knowledge/learnings/general.md +3 -0
- agent_toolkit/templates/workspace/knowledge/todos/pending.md +7 -0
- agent_toolkit/templates/workspace/packs/README.md +24 -0
- agent_toolkit/templates/workspace/personas/architect.md +12 -0
- agent_toolkit/templates/workspace/personas/implementer.md +12 -0
- agent_toolkit/templates/workspace/personas/researcher.md +12 -0
- agent_toolkit/templates/workspace/personas/reviewer.md +12 -0
- agent_toolkit_cli-1.11.0.dist-info/METADATA +363 -0
- agent_toolkit_cli-1.11.0.dist-info/RECORD +438 -0
- agent_toolkit_cli-1.11.0.dist-info/WHEEL +4 -0
- agent_toolkit_cli-1.11.0.dist-info/entry_points.txt +4 -0
- agent_toolkit_cli-1.11.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,2448 @@
|
|
|
1
|
+
"""Swarm CLI — backend-neutral orchestration.
|
|
2
|
+
|
|
3
|
+
Implements all required `agent-toolkit swarm` subcommands.
|
|
4
|
+
Side-effect free `plan`, durable filesystem state, worktrees, handoffs, budgets.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from .approvals import (
|
|
22
|
+
approve_gate,
|
|
23
|
+
default_gates_for_recipe,
|
|
24
|
+
load_approvals,
|
|
25
|
+
reject_gate,
|
|
26
|
+
save_approvals,
|
|
27
|
+
)
|
|
28
|
+
from .backends import get_backend
|
|
29
|
+
from .budget import load_budget, resolve_budget, save_budget
|
|
30
|
+
from .config import find_repo_root, resolve_config
|
|
31
|
+
from .handoff import (
|
|
32
|
+
list_handoffs,
|
|
33
|
+
move_handoff,
|
|
34
|
+
validate_commit_exists,
|
|
35
|
+
validate_handoff,
|
|
36
|
+
write_handoff_outbox,
|
|
37
|
+
)
|
|
38
|
+
from .models import API_VERSION
|
|
39
|
+
from .prompts import compose_role_prompt
|
|
40
|
+
from .recipes import get_recipe, list_recipes
|
|
41
|
+
from .runner import (
|
|
42
|
+
MODEL_PROFILES,
|
|
43
|
+
capability_matrix,
|
|
44
|
+
discover_models,
|
|
45
|
+
generate_opencode_agent,
|
|
46
|
+
resolve_model,
|
|
47
|
+
runner_available,
|
|
48
|
+
)
|
|
49
|
+
from .store import (
|
|
50
|
+
append_trace,
|
|
51
|
+
atomic_write_json,
|
|
52
|
+
atomic_write_text,
|
|
53
|
+
ensure_run_dirs,
|
|
54
|
+
is_path_contained,
|
|
55
|
+
list_runs,
|
|
56
|
+
now_ts,
|
|
57
|
+
read_state,
|
|
58
|
+
run_dir_for,
|
|
59
|
+
validate_artifact_path,
|
|
60
|
+
write_state,
|
|
61
|
+
)
|
|
62
|
+
from .worktree import (
|
|
63
|
+
branch_for_run_role,
|
|
64
|
+
create_worktree,
|
|
65
|
+
is_worktree_dirty,
|
|
66
|
+
remove_worktree,
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# Detect user's login shell — herdr/tmux already run it, so swarm should too
|
|
71
|
+
def _user_shell() -> str:
|
|
72
|
+
"""Return user's login shell, fallback to bash. Respects $SHELL and /etc/passwd."""
|
|
73
|
+
import os as _os
|
|
74
|
+
import pathlib as _pl
|
|
75
|
+
|
|
76
|
+
# 1. $SHELL env (herdr/tmux inherit it)
|
|
77
|
+
for cand in [_os.environ.get("SHELL"), _os.environ.get("SWARM_SHELL")]:
|
|
78
|
+
if cand and _pl.Path(cand).exists():
|
|
79
|
+
return cand
|
|
80
|
+
# 2. passwd entry
|
|
81
|
+
try:
|
|
82
|
+
import pwd as _pwd
|
|
83
|
+
|
|
84
|
+
pw = _pwd.getpwuid(_os.getuid()).pw_shell
|
|
85
|
+
if pw and _pl.Path(pw).exists():
|
|
86
|
+
return pw
|
|
87
|
+
except Exception:
|
|
88
|
+
pass
|
|
89
|
+
# 3. common shells
|
|
90
|
+
for cand in ["/usr/bin/zsh", "/bin/zsh", "/usr/bin/bash", "/bin/bash", "/bin/sh"]:
|
|
91
|
+
if _pl.Path(cand).exists():
|
|
92
|
+
return cand
|
|
93
|
+
return "/bin/bash"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _shell_base() -> str:
|
|
97
|
+
"""Base shell name for exec fallback (zsh/bash/sh)."""
|
|
98
|
+
import pathlib as _pl
|
|
99
|
+
|
|
100
|
+
sh = _user_shell()
|
|
101
|
+
return _pl.Path(sh).name or "bash"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
NO_COLOR = os.environ.get("NO_COLOR") is not None or not sys.stdout.isatty()
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _log(msg: str) -> None:
|
|
108
|
+
print(msg)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _error(msg: str, hint: str | None = None, exit_code: int = 1) -> int:
|
|
112
|
+
print(f"error: {msg}", file=sys.stderr)
|
|
113
|
+
if hint:
|
|
114
|
+
print(hint, file=sys.stderr)
|
|
115
|
+
return exit_code
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _json_out(data: Any) -> int:
|
|
119
|
+
print(json.dumps(data, indent=2))
|
|
120
|
+
return 0
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _need_repo(prompt_text: str | None = None, workspace: str | None = None) -> Path:
|
|
124
|
+
return find_repo_root(prompt_text=prompt_text, workspace=workspace)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def cmd_recipes(args: list[str]) -> int:
|
|
128
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm recipes")
|
|
129
|
+
parser.add_argument("--json", action="store_true")
|
|
130
|
+
ns = parser.parse_args(args)
|
|
131
|
+
items = []
|
|
132
|
+
for name in list_recipes():
|
|
133
|
+
r = get_recipe(name)
|
|
134
|
+
items.append(
|
|
135
|
+
{
|
|
136
|
+
"name": name,
|
|
137
|
+
"description": (r.get("metadata") or {}).get("description", "") if r else "",
|
|
138
|
+
}
|
|
139
|
+
)
|
|
140
|
+
if ns.json:
|
|
141
|
+
return _json_out(items)
|
|
142
|
+
for it in items:
|
|
143
|
+
print(f"{it['name']:8} {it['description']}")
|
|
144
|
+
return 0
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def cmd_recipe_show(args: list[str]) -> int:
|
|
148
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm recipe show")
|
|
149
|
+
parser.add_argument("name")
|
|
150
|
+
parser.add_argument("--json", action="store_true")
|
|
151
|
+
ns = parser.parse_args(args)
|
|
152
|
+
r = get_recipe(ns.name)
|
|
153
|
+
if not r:
|
|
154
|
+
return _error(
|
|
155
|
+
f"Unknown recipe: {ns.name!r}", hint=f"Available: {', '.join(list_recipes())}"
|
|
156
|
+
)
|
|
157
|
+
if ns.json:
|
|
158
|
+
return _json_out(r)
|
|
159
|
+
# Print yaml-like summary
|
|
160
|
+
print(f"name: {ns.name}")
|
|
161
|
+
print(f"description: {(r.get('metadata') or {}).get('description', '')}")
|
|
162
|
+
spec = r.get("spec", {})
|
|
163
|
+
print(f"roles: {', '.join(spec.get('roles', {}).keys())}")
|
|
164
|
+
print(f"execution: {spec.get('execution', {})}")
|
|
165
|
+
print(f"budget: {spec.get('budget', {})}")
|
|
166
|
+
return 0
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def cmd_runners(args: list[str]) -> int:
|
|
170
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm runners")
|
|
171
|
+
parser.add_argument("--json", action="store_true")
|
|
172
|
+
ns = parser.parse_args(args)
|
|
173
|
+
m = capability_matrix()
|
|
174
|
+
if ns.json:
|
|
175
|
+
return _json_out(m)
|
|
176
|
+
for name, caps in m.items():
|
|
177
|
+
avail = "available" if caps.get("available") else "not found"
|
|
178
|
+
print(
|
|
179
|
+
f"{name:10} {avail:12} interactive={caps.get('interactive')} per_role_model={caps.get('per_role_model')} herdr={caps.get('herdr')}"
|
|
180
|
+
)
|
|
181
|
+
return 0
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def cmd_models(args: list[str]) -> int:
|
|
185
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm models")
|
|
186
|
+
parser.add_argument("--runner", default="opencode")
|
|
187
|
+
parser.add_argument("--profile", default=None)
|
|
188
|
+
parser.add_argument("--json", action="store_true")
|
|
189
|
+
ns = parser.parse_args(args)
|
|
190
|
+
if ns.profile:
|
|
191
|
+
mapping = MODEL_PROFILES.get(ns.profile)
|
|
192
|
+
if not mapping:
|
|
193
|
+
return _error(
|
|
194
|
+
f"Unknown profile {ns.profile!r}", hint=f"Choose: {', '.join(MODEL_PROFILES)}"
|
|
195
|
+
)
|
|
196
|
+
if ns.json:
|
|
197
|
+
return _json_out(mapping)
|
|
198
|
+
for k, v in mapping.items():
|
|
199
|
+
print(f"{k:15} {v}")
|
|
200
|
+
return 0
|
|
201
|
+
models = discover_models(ns.runner)
|
|
202
|
+
if ns.json:
|
|
203
|
+
return _json_out(models)
|
|
204
|
+
for m in models:
|
|
205
|
+
print(m)
|
|
206
|
+
return 0
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def cmd_backends(args: list[str]) -> int:
|
|
210
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm backends")
|
|
211
|
+
parser.add_argument("--json", action="store_true")
|
|
212
|
+
ns = parser.parse_args(args)
|
|
213
|
+
backends = ["herdr", "tmux", "auto", "headless"]
|
|
214
|
+
details = {}
|
|
215
|
+
for b in backends:
|
|
216
|
+
be = get_backend(b)
|
|
217
|
+
try:
|
|
218
|
+
details[b] = be.doctor()
|
|
219
|
+
except Exception as e:
|
|
220
|
+
details[b] = {"available": False, "error": str(e)}
|
|
221
|
+
if ns.json:
|
|
222
|
+
return _json_out(details)
|
|
223
|
+
for b, d in details.items():
|
|
224
|
+
avail = d.get("available")
|
|
225
|
+
print(
|
|
226
|
+
f"{b:10} {'available' if avail else 'unavailable':12} {d.get('version', '') or d.get('reason', '')}"
|
|
227
|
+
)
|
|
228
|
+
return 0
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def cmd_doctor(args: list[str]) -> int:
|
|
232
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm doctor")
|
|
233
|
+
parser.add_argument("--json", action="store_true")
|
|
234
|
+
ns = parser.parse_args(args)
|
|
235
|
+
repo = _need_repo()
|
|
236
|
+
data: dict[str, Any] = {"repo": str(repo)}
|
|
237
|
+
# Check git
|
|
238
|
+
try:
|
|
239
|
+
res = subprocess.run(
|
|
240
|
+
["git", "rev-parse", "--is-inside-work-tree"],
|
|
241
|
+
cwd=str(repo),
|
|
242
|
+
capture_output=True,
|
|
243
|
+
text=True,
|
|
244
|
+
timeout=5,
|
|
245
|
+
)
|
|
246
|
+
data["git"] = {"available": res.returncode == 0}
|
|
247
|
+
except Exception as e:
|
|
248
|
+
data["git"] = {"available": False, "error": str(e)}
|
|
249
|
+
# Backends
|
|
250
|
+
for b in ["herdr", "tmux"]:
|
|
251
|
+
be = get_backend(b)
|
|
252
|
+
data[b] = be.doctor()
|
|
253
|
+
# Runners
|
|
254
|
+
data["runners"] = capability_matrix()
|
|
255
|
+
data["recipes"] = list_recipes()
|
|
256
|
+
# Workstation check
|
|
257
|
+
data["toolkit_swarm"] = {"version": "1", "apiVersion": API_VERSION}
|
|
258
|
+
if ns.json:
|
|
259
|
+
return _json_out(data)
|
|
260
|
+
print("Swarm doctor")
|
|
261
|
+
print(f" repo: {repo}")
|
|
262
|
+
print(f" git: {'ok' if data['git'].get('available') else 'missing'}")
|
|
263
|
+
for b in ["herdr", "tmux"]:
|
|
264
|
+
d = data[b]
|
|
265
|
+
status = "pass" if d.get("available") else "warning" if b == "herdr" else "failure"
|
|
266
|
+
print(f" {b}: {status} - {d.get('version') or d.get('reason')}")
|
|
267
|
+
for r, caps in data["runners"].items():
|
|
268
|
+
print(f" runner {r}: {'available' if caps.get('available') else 'not found'}")
|
|
269
|
+
print(f" recipes: {', '.join(data['recipes'])}")
|
|
270
|
+
# Non-zero if git missing
|
|
271
|
+
if not data["git"].get("available"):
|
|
272
|
+
return 1
|
|
273
|
+
return 0
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def cmd_init(args: list[str]) -> int:
|
|
277
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm init")
|
|
278
|
+
parser.add_argument("--workspace", default=".")
|
|
279
|
+
parser.add_argument("--recipe", default=None)
|
|
280
|
+
parser.add_argument("--force", action="store_true")
|
|
281
|
+
ns = parser.parse_args(args)
|
|
282
|
+
ws = Path(ns.workspace).resolve()
|
|
283
|
+
if not ws.is_dir():
|
|
284
|
+
return _error(f"Workspace not found: {ws}")
|
|
285
|
+
cfg_path = ws / ".agent-toolkit" / "swarm.yaml"
|
|
286
|
+
if cfg_path.exists() and not ns.force:
|
|
287
|
+
return _error(f"Config already exists: {cfg_path}", hint="Use --force to overwrite")
|
|
288
|
+
cfg_path.parent.mkdir(parents=True, exist_ok=True)
|
|
289
|
+
recipe = ns.recipe or "pair"
|
|
290
|
+
if recipe not in list_recipes():
|
|
291
|
+
return _error(f"Unknown recipe {recipe!r}")
|
|
292
|
+
content = f"""# Agent Toolkit Swarm workspace config
|
|
293
|
+
# Generated by `agent-toolkit swarm init`
|
|
294
|
+
recipe: {recipe}
|
|
295
|
+
ui: auto
|
|
296
|
+
runner: opencode
|
|
297
|
+
model_profile: balanced
|
|
298
|
+
"""
|
|
299
|
+
cfg_path.write_text(content, encoding="utf-8")
|
|
300
|
+
print(f"Created {cfg_path}")
|
|
301
|
+
return 0
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _resolve_task_text(
|
|
305
|
+
cli_args: argparse.Namespace, remaining: list[str]
|
|
306
|
+
) -> tuple[str | None, str | None]:
|
|
307
|
+
# Returns (task_text, issue_ref)
|
|
308
|
+
if remaining:
|
|
309
|
+
return " ".join(remaining), None
|
|
310
|
+
if getattr(cli_args, "request_file", None):
|
|
311
|
+
p = Path(cli_args.request_file)
|
|
312
|
+
if not p.is_file():
|
|
313
|
+
raise ValueError(f"--request-file not found: {p}")
|
|
314
|
+
return p.read_text(encoding="utf-8"), None
|
|
315
|
+
if getattr(cli_args, "issue", None):
|
|
316
|
+
return f"Implement issue {cli_args.issue}", cli_args.issue
|
|
317
|
+
return None, None
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def cmd_plan(args: list[str]) -> int:
|
|
321
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm plan")
|
|
322
|
+
parser.add_argument("--recipe", default=None)
|
|
323
|
+
parser.add_argument("--ui", default=None, choices=["auto", "herdr", "tmux", "headless"])
|
|
324
|
+
parser.add_argument("--runner", default=None)
|
|
325
|
+
parser.add_argument("--model-profile", default=None, choices=list(MODEL_PROFILES.keys()))
|
|
326
|
+
parser.add_argument("--request-file", default=None)
|
|
327
|
+
parser.add_argument("--issue", default=None)
|
|
328
|
+
parser.add_argument("--json", action="store_true")
|
|
329
|
+
parser.add_argument("--base-ref", default=None)
|
|
330
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO shorthand")
|
|
331
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
332
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
333
|
+
# allow positional task
|
|
334
|
+
ns, rest = parser.parse_known_args(args)
|
|
335
|
+
# rest may contain task words; need to separate --
|
|
336
|
+
if rest and rest[0] == "--":
|
|
337
|
+
rest = rest[1:]
|
|
338
|
+
try:
|
|
339
|
+
task_text, issue = _resolve_task_text(ns, rest)
|
|
340
|
+
except ValueError as e:
|
|
341
|
+
return _error(str(e))
|
|
342
|
+
if not task_text:
|
|
343
|
+
return _error("No task provided", hint="Provide task text, --request-file, or --issue")
|
|
344
|
+
workspace_flag = ns.workspace or ns.repo or ns.workspace_C
|
|
345
|
+
repo = _need_repo(prompt_text=task_text, workspace=workspace_flag)
|
|
346
|
+
# If autodetected via prompt but workspace flag overrides, workspace already handled
|
|
347
|
+
# Validate git repo and give actionable error
|
|
348
|
+
import subprocess as _sp
|
|
349
|
+
|
|
350
|
+
try:
|
|
351
|
+
_r = _sp.run(
|
|
352
|
+
["git", "rev-parse", "--is-inside-work-tree"],
|
|
353
|
+
cwd=str(repo),
|
|
354
|
+
capture_output=True,
|
|
355
|
+
text=True,
|
|
356
|
+
timeout=5,
|
|
357
|
+
)
|
|
358
|
+
if _r.returncode != 0:
|
|
359
|
+
# Try to give hint with autodetected owner/repo
|
|
360
|
+
from .config import _resolve_owner_repo_from_prompt
|
|
361
|
+
|
|
362
|
+
owner_repo = _resolve_owner_repo_from_prompt(task_text)
|
|
363
|
+
hint = f"Resolved repo: {repo} (not a git repo). "
|
|
364
|
+
if owner_repo:
|
|
365
|
+
hint += f"Autodetected {owner_repo} from prompt. Run: agent-toolkit project clone {owner_repo} or specify --workspace <path>"
|
|
366
|
+
else:
|
|
367
|
+
hint += "Run from inside a git repo or use --workspace <path|OWNER/REPO>"
|
|
368
|
+
return _error(f"Not a git repository: {repo}", hint=hint)
|
|
369
|
+
except Exception:
|
|
370
|
+
pass
|
|
371
|
+
cfg = resolve_config(
|
|
372
|
+
repo,
|
|
373
|
+
{"recipe": ns.recipe, "ui": ns.ui, "runner": ns.runner, "model_profile": ns.model_profile},
|
|
374
|
+
)
|
|
375
|
+
recipe_name = cfg.get("recipe", "pair")
|
|
376
|
+
recipe = get_recipe(recipe_name)
|
|
377
|
+
if not recipe:
|
|
378
|
+
return _error(f"Unknown recipe {recipe_name!r}")
|
|
379
|
+
# Validate tools
|
|
380
|
+
backend_name = cfg.get("ui", "auto")
|
|
381
|
+
backend = get_backend(backend_name)
|
|
382
|
+
backend_status = backend.doctor()
|
|
383
|
+
runner_name = cfg.get("runner", "opencode")
|
|
384
|
+
runner_avail = runner_available(runner_name)
|
|
385
|
+
# Resolve models per role
|
|
386
|
+
roles = recipe.get("spec", {}).get("roles", {})
|
|
387
|
+
model_assignments: dict[str, str | None] = {}
|
|
388
|
+
for rname, rdef in roles.items():
|
|
389
|
+
task_class = rdef.get("model_profile", "coding")
|
|
390
|
+
try:
|
|
391
|
+
model_assignments[rname] = resolve_model(
|
|
392
|
+
cfg.get("model_profile", "balanced"),
|
|
393
|
+
task_class,
|
|
394
|
+
model_profiles=cfg.get("model_profiles"),
|
|
395
|
+
)
|
|
396
|
+
except ValueError as e:
|
|
397
|
+
return _error(str(e))
|
|
398
|
+
# Budget
|
|
399
|
+
budget = resolve_budget(recipe.get("spec", {}).get("budget"))
|
|
400
|
+
# Worktrees
|
|
401
|
+
worktrees = []
|
|
402
|
+
for rname, rdef in roles.items():
|
|
403
|
+
wt = rdef.get("worktree")
|
|
404
|
+
if wt:
|
|
405
|
+
branch = branch_for_run_role("plan-preview", rname)
|
|
406
|
+
worktrees.append(
|
|
407
|
+
{
|
|
408
|
+
"role": rname,
|
|
409
|
+
"branch": branch,
|
|
410
|
+
"path": f".agent-toolkit/swarm/runs/<run-id>/worktrees/{rname}",
|
|
411
|
+
}
|
|
412
|
+
)
|
|
413
|
+
# Gates
|
|
414
|
+
gates = default_gates_for_recipe(recipe)
|
|
415
|
+
# Cost estimate (naive)
|
|
416
|
+
budget.get("max_total_tokens")
|
|
417
|
+
# pricing unknown -> report honestly
|
|
418
|
+
pricing_note = "Pricing unavailable for some models; estimate not calculated. Use --model-profile to control cost."
|
|
419
|
+
|
|
420
|
+
plan = {
|
|
421
|
+
"recipe": recipe_name,
|
|
422
|
+
"task": task_text[:2000],
|
|
423
|
+
"ui_backend": {
|
|
424
|
+
"requested": backend_name,
|
|
425
|
+
"resolved": backend_name,
|
|
426
|
+
"available": backend_status.get("available"),
|
|
427
|
+
"details": backend_status,
|
|
428
|
+
},
|
|
429
|
+
"runner": {"requested": runner_name, "available": runner_avail},
|
|
430
|
+
"model_profile": cfg.get("model_profile", "balanced"),
|
|
431
|
+
"model_assignments": model_assignments,
|
|
432
|
+
"roles": list(roles.keys()),
|
|
433
|
+
"role_details": roles,
|
|
434
|
+
"worktrees": worktrees,
|
|
435
|
+
"gates": gates,
|
|
436
|
+
"budget": budget,
|
|
437
|
+
"concurrency": budget.get("max_concurrency"),
|
|
438
|
+
"round_trips": budget.get("max_role_round_trips"),
|
|
439
|
+
"pricing_note": pricing_note,
|
|
440
|
+
"base_ref": ns.base_ref or "HEAD",
|
|
441
|
+
"run_dir_preview": ".agent-toolkit/swarm/runs/<run-id>/",
|
|
442
|
+
}
|
|
443
|
+
if ns.json:
|
|
444
|
+
return _json_out(plan)
|
|
445
|
+
print("Swarm plan (no changes made)")
|
|
446
|
+
print(f" recipe: {recipe_name}")
|
|
447
|
+
print(f" task: {task_text[:120]}")
|
|
448
|
+
print(
|
|
449
|
+
f" ui: {backend_name} -> available={backend_status.get('available')} {backend_status.get('version') or backend_status.get('reason', '')}"
|
|
450
|
+
)
|
|
451
|
+
if backend_name == "herdr" and not backend_status.get("available"):
|
|
452
|
+
hint = "Herdr was explicitly requested but was not found.\n\nInstall:\n https://herdr.dev/docs/install/\n\nOr use:\n agent-toolkit swarm start --ui tmux ..."
|
|
453
|
+
print(hint, file=sys.stderr)
|
|
454
|
+
return 1
|
|
455
|
+
print(f" runner: {runner_name} -> {'available' if runner_avail else 'not found'}")
|
|
456
|
+
if not runner_avail:
|
|
457
|
+
print(f" hint: install {runner_name} or choose another --runner", file=sys.stderr)
|
|
458
|
+
print(f" model_profile: {cfg.get('model_profile')}")
|
|
459
|
+
for r, m in model_assignments.items():
|
|
460
|
+
print(f" {r:12} -> {m}")
|
|
461
|
+
print(f" roles: {', '.join(roles.keys())}")
|
|
462
|
+
print(f" worktrees: {len(worktrees)} (one per writer)")
|
|
463
|
+
for wt in worktrees:
|
|
464
|
+
print(f" {wt['role']}: {wt['branch']} at {wt['path']}")
|
|
465
|
+
print(f" gates: {', '.join(g['id'] for g in gates) or 'none'}")
|
|
466
|
+
print(f" concurrency: {budget.get('max_concurrency')} (default 2)")
|
|
467
|
+
print(f" round_trips: {budget.get('max_role_round_trips')}")
|
|
468
|
+
print(
|
|
469
|
+
f" budget: tokens={budget.get('max_total_tokens')} cost=${budget.get('max_cost_usd')} wall={budget.get('max_wall_seconds')}s"
|
|
470
|
+
)
|
|
471
|
+
print(f" note: {pricing_note}")
|
|
472
|
+
if not runner_avail:
|
|
473
|
+
return 1
|
|
474
|
+
return 0
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _generate_run_id() -> str:
|
|
478
|
+
ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
479
|
+
rand = hashlib.sha256(os.urandom(8)).hexdigest()[:6]
|
|
480
|
+
return f"{ts}-{rand}"
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _load_or_create_run_state(
|
|
484
|
+
repo: Path, run_id: str, recipe_name: str, cfg: dict[str, Any], task_text: str
|
|
485
|
+
) -> Path:
|
|
486
|
+
run_dir = run_dir_for(repo, run_id)
|
|
487
|
+
ensure_run_dirs(run_dir)
|
|
488
|
+
recipe = get_recipe(recipe_name)
|
|
489
|
+
assert recipe is not None
|
|
490
|
+
spec = recipe.get("spec", {})
|
|
491
|
+
budget = resolve_budget(spec.get("budget"))
|
|
492
|
+
gates = default_gates_for_recipe(recipe)
|
|
493
|
+
# Handle initial state
|
|
494
|
+
requires_plan = spec.get("gates", {}).get("require_plan_approval", False)
|
|
495
|
+
from .state import initial_run_state
|
|
496
|
+
|
|
497
|
+
run_state_val = initial_run_state(recipe_name, requires_plan)
|
|
498
|
+
state: dict[str, Any] = {
|
|
499
|
+
"version": 1,
|
|
500
|
+
"run_id": run_id,
|
|
501
|
+
"recipe": recipe_name,
|
|
502
|
+
"run_state": run_state_val,
|
|
503
|
+
"roles": {r: "inactive" for r in spec.get("roles", {}).keys()},
|
|
504
|
+
"created_at": now_ts(),
|
|
505
|
+
"updated_at": now_ts(),
|
|
506
|
+
"ui_backend": cfg.get("ui", "auto"),
|
|
507
|
+
"runner": cfg.get("runner", "opencode"),
|
|
508
|
+
"model_profile": cfg.get("model_profile", "balanced"),
|
|
509
|
+
"model_profiles": cfg.get("model_profiles"),
|
|
510
|
+
"task": task_text[:5000],
|
|
511
|
+
"budget": budget,
|
|
512
|
+
"worktrees": [],
|
|
513
|
+
"trace": [],
|
|
514
|
+
}
|
|
515
|
+
atomic_write_json(run_dir / "state.json", state)
|
|
516
|
+
# run.yaml
|
|
517
|
+
run_yaml = f"run_id: {run_id}\nrecipe: {recipe_name}\ncreated_at: {state['created_at']}\n"
|
|
518
|
+
atomic_write_text(run_dir / "run.yaml", run_yaml)
|
|
519
|
+
# budget.json
|
|
520
|
+
save_budget(run_dir, budget, {"total_tokens": 0, "cost_usd": 0.0, "wall_seconds": 0})
|
|
521
|
+
save_approvals(run_dir, gates)
|
|
522
|
+
append_trace(
|
|
523
|
+
run_dir, {"ts": now_ts(), "kind": "run_created", "run_id": run_id, "recipe": recipe_name}
|
|
524
|
+
)
|
|
525
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "recipe_resolved", "recipe": recipe_name})
|
|
526
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "budget_resolved", "budget": budget})
|
|
527
|
+
# ownership
|
|
528
|
+
atomic_write_json(
|
|
529
|
+
run_dir / "ownership.json",
|
|
530
|
+
{
|
|
531
|
+
"run_id": run_id,
|
|
532
|
+
"created_at": state["created_at"],
|
|
533
|
+
"owned_branches": [],
|
|
534
|
+
"owned_worktrees": [],
|
|
535
|
+
},
|
|
536
|
+
)
|
|
537
|
+
return run_dir
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def cmd_start(args: list[str]) -> int:
|
|
541
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm start")
|
|
542
|
+
parser.add_argument("--recipe", default=None)
|
|
543
|
+
parser.add_argument("--ui", default=None, choices=["auto", "herdr", "tmux", "headless"])
|
|
544
|
+
parser.add_argument("--runner", default=None)
|
|
545
|
+
parser.add_argument("--model-profile", default=None, choices=list(MODEL_PROFILES.keys()))
|
|
546
|
+
parser.add_argument("--request-file", default=None)
|
|
547
|
+
parser.add_argument("--issue", default=None)
|
|
548
|
+
parser.add_argument("--base-ref", default="HEAD")
|
|
549
|
+
parser.add_argument("--json", action="store_true")
|
|
550
|
+
parser.add_argument("--dry-run", action="store_true")
|
|
551
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO shorthand")
|
|
552
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
553
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
554
|
+
parser.add_argument(
|
|
555
|
+
"--attach",
|
|
556
|
+
action="store_true",
|
|
557
|
+
help="Attach to tmux/herdr session after start (blocks, like swarm-forge)",
|
|
558
|
+
)
|
|
559
|
+
parser.add_argument(
|
|
560
|
+
"--no-attach", dest="no_attach", action="store_true", help="Do not attach even if default"
|
|
561
|
+
)
|
|
562
|
+
ns, rest = parser.parse_known_args(args)
|
|
563
|
+
if rest and rest[0] == "--":
|
|
564
|
+
rest = rest[1:]
|
|
565
|
+
try:
|
|
566
|
+
task_text, issue = _resolve_task_text(ns, rest)
|
|
567
|
+
except ValueError as e:
|
|
568
|
+
return _error(str(e))
|
|
569
|
+
if not task_text:
|
|
570
|
+
task_text = ""
|
|
571
|
+
# No task provided — launch agents with system prompt only, ready for interactive input
|
|
572
|
+
# (like swarm-forge ./swarm without initial task)
|
|
573
|
+
_log(
|
|
574
|
+
"No task provided — starting swarm with system prompt only, ready for interactive input"
|
|
575
|
+
)
|
|
576
|
+
workspace_flag = ns.workspace or ns.repo or ns.workspace_C
|
|
577
|
+
repo = _need_repo(prompt_text=task_text, workspace=workspace_flag)
|
|
578
|
+
import subprocess as _sp2
|
|
579
|
+
|
|
580
|
+
try:
|
|
581
|
+
_r = _sp2.run(
|
|
582
|
+
["git", "rev-parse", "--is-inside-work-tree"],
|
|
583
|
+
cwd=str(repo),
|
|
584
|
+
capture_output=True,
|
|
585
|
+
text=True,
|
|
586
|
+
timeout=5,
|
|
587
|
+
)
|
|
588
|
+
if _r.returncode != 0:
|
|
589
|
+
from .config import _resolve_owner_repo_from_prompt
|
|
590
|
+
|
|
591
|
+
owner_repo = _resolve_owner_repo_from_prompt(task_text)
|
|
592
|
+
hint = f"Resolved repo: {repo} (not a git repo). "
|
|
593
|
+
if owner_repo:
|
|
594
|
+
hint += f"Autodetected {owner_repo} from prompt. Run: agent-toolkit project clone {owner_repo} or specify --workspace <path>"
|
|
595
|
+
else:
|
|
596
|
+
hint += "Run from inside a git repo or use --workspace <path|OWNER/REPO>"
|
|
597
|
+
return _error(f"Not a git repository: {repo}", hint=hint)
|
|
598
|
+
except Exception:
|
|
599
|
+
pass
|
|
600
|
+
cfg = resolve_config(
|
|
601
|
+
repo,
|
|
602
|
+
{"recipe": ns.recipe, "ui": ns.ui, "runner": ns.runner, "model_profile": ns.model_profile},
|
|
603
|
+
)
|
|
604
|
+
recipe_name = cfg.get("recipe", "pair")
|
|
605
|
+
recipe = get_recipe(recipe_name)
|
|
606
|
+
if not recipe:
|
|
607
|
+
return _error(f"Unknown recipe {recipe_name!r}")
|
|
608
|
+
# Validate backend explicitly
|
|
609
|
+
backend_name = cfg.get("ui", "auto")
|
|
610
|
+
backend = get_backend(backend_name)
|
|
611
|
+
doctor = backend.doctor()
|
|
612
|
+
if backend_name == "herdr" and not doctor.get("available"):
|
|
613
|
+
print("Herdr was explicitly requested but was not found.", file=sys.stderr)
|
|
614
|
+
print(
|
|
615
|
+
"\nInstall:\n https://herdr.dev/docs/install/\n\nOr use:\n agent-toolkit swarm start --ui tmux ...",
|
|
616
|
+
file=sys.stderr,
|
|
617
|
+
)
|
|
618
|
+
return 1
|
|
619
|
+
if backend_name == "auto" and not doctor.get("available"):
|
|
620
|
+
# fallback to tmux check
|
|
621
|
+
tmux_be = get_backend("tmux")
|
|
622
|
+
tmux_doc = tmux_be.doctor()
|
|
623
|
+
if not tmux_doc.get("available"):
|
|
624
|
+
print("No interactive backend available (herdr and tmux not found).", file=sys.stderr)
|
|
625
|
+
print("Install tmux or herdr, or use --ui headless if supported.", file=sys.stderr)
|
|
626
|
+
return 1
|
|
627
|
+
# auto fallback to tmux
|
|
628
|
+
backend_name = "tmux"
|
|
629
|
+
backend = tmux_be
|
|
630
|
+
cfg["ui"] = "tmux"
|
|
631
|
+
print("[swarm] auto: herdr unavailable, falling back to tmux", file=sys.stderr)
|
|
632
|
+
# Validate runner
|
|
633
|
+
runner_name = cfg.get("runner", "opencode")
|
|
634
|
+
if not runner_available(runner_name) and runner_name != "skeleton":
|
|
635
|
+
# Still allow skeleton for demo
|
|
636
|
+
print(
|
|
637
|
+
f"Runner {runner_name!r} not found. Install it or use --runner skeleton for dry-run.",
|
|
638
|
+
file=sys.stderr,
|
|
639
|
+
)
|
|
640
|
+
# Continue for dry-run?
|
|
641
|
+
if not ns.dry_run:
|
|
642
|
+
# Allow to proceed with warning for tests with fake binaries via PATH override
|
|
643
|
+
pass
|
|
644
|
+
# Create run
|
|
645
|
+
run_id = _generate_run_id()
|
|
646
|
+
run_dir = _load_or_create_run_state(repo, run_id, recipe_name, cfg, task_text)
|
|
647
|
+
# Generate OpenCode agents and prompts
|
|
648
|
+
roles = recipe.get("spec", {}).get("roles", {})
|
|
649
|
+
for rname, rdef in roles.items():
|
|
650
|
+
task_class = rdef.get("model_profile", "coding")
|
|
651
|
+
model = (
|
|
652
|
+
resolve_model(
|
|
653
|
+
cfg.get("model_profile", "balanced"),
|
|
654
|
+
task_class,
|
|
655
|
+
model_profiles=cfg.get("model_profiles"),
|
|
656
|
+
)
|
|
657
|
+
or "unknown/model"
|
|
658
|
+
)
|
|
659
|
+
worktree = rdef.get("worktree")
|
|
660
|
+
try:
|
|
661
|
+
generate_opencode_agent(
|
|
662
|
+
run_dir,
|
|
663
|
+
rname,
|
|
664
|
+
rdef.get("persona", rname),
|
|
665
|
+
rdef.get("policy", "read-only"),
|
|
666
|
+
model,
|
|
667
|
+
recipe_name,
|
|
668
|
+
run_id,
|
|
669
|
+
worktree,
|
|
670
|
+
)
|
|
671
|
+
except Exception:
|
|
672
|
+
pass
|
|
673
|
+
# Prompt composition — inject run_id for handoff instructions
|
|
674
|
+
try:
|
|
675
|
+
rdef_with_run = dict(rdef)
|
|
676
|
+
rdef_with_run["_run_id"] = run_id
|
|
677
|
+
prompt, manifest = compose_role_prompt(
|
|
678
|
+
recipe, rname, rdef_with_run, task_text, None, rdef.get("skills")
|
|
679
|
+
)
|
|
680
|
+
(run_dir / "prompts" / f"{rname}.md").write_text(prompt, encoding="utf-8")
|
|
681
|
+
(run_dir / "prompts" / f"{rname}.manifest.json").write_text(
|
|
682
|
+
json.dumps(manifest, indent=2), encoding="utf-8"
|
|
683
|
+
)
|
|
684
|
+
except Exception:
|
|
685
|
+
pass
|
|
686
|
+
# Worktree creation for writing roles (lazy: only roles whose inputs ready? For now create implementer eagerly)
|
|
687
|
+
spec = recipe.get("spec", {})
|
|
688
|
+
lazy = spec.get("execution", {}).get("lazy_start", True)
|
|
689
|
+
# Determine initially active roles: planner or implementer
|
|
690
|
+
initial_roles = []
|
|
691
|
+
if "planner" in roles:
|
|
692
|
+
initial_roles = ["planner"]
|
|
693
|
+
elif "implementer" in roles:
|
|
694
|
+
initial_roles = ["implementer"]
|
|
695
|
+
else:
|
|
696
|
+
initial_roles = list(roles.keys())[:1]
|
|
697
|
+
created_wts = []
|
|
698
|
+
for rname in roles:
|
|
699
|
+
rdef = roles[rname]
|
|
700
|
+
wt_name = rdef.get("worktree")
|
|
701
|
+
if wt_name:
|
|
702
|
+
# lazy: only create for initially active roles now
|
|
703
|
+
if lazy and rname not in initial_roles:
|
|
704
|
+
continue
|
|
705
|
+
try:
|
|
706
|
+
info = create_worktree(repo, run_dir, rname, run_id, ns.base_ref)
|
|
707
|
+
info["role"] = rname
|
|
708
|
+
created_wts.append(info)
|
|
709
|
+
# Ensure opencode agent is discoverable from worktree (copy to .opencode/agents)
|
|
710
|
+
try:
|
|
711
|
+
_agent_src = run_dir / "runner" / "opencode" / "agents" / f"{rname}.md"
|
|
712
|
+
if _agent_src.exists():
|
|
713
|
+
_wt_agents = Path(info["path"]) / ".opencode" / "agents"
|
|
714
|
+
_wt_agents.mkdir(parents=True, exist_ok=True)
|
|
715
|
+
import shutil as _shutil
|
|
716
|
+
|
|
717
|
+
_shutil.copy2(_agent_src, _wt_agents / f"{rname}.md")
|
|
718
|
+
# Also copy prompt as context if needed
|
|
719
|
+
_prompt_src = run_dir / "prompts" / f"{rname}.md"
|
|
720
|
+
if _prompt_src.exists():
|
|
721
|
+
_shutil.copy2(
|
|
722
|
+
_prompt_src,
|
|
723
|
+
Path(info["path"]) / f".agent-toolkit-prompt-{rname}.md",
|
|
724
|
+
)
|
|
725
|
+
except Exception:
|
|
726
|
+
pass
|
|
727
|
+
append_trace(
|
|
728
|
+
run_dir,
|
|
729
|
+
{
|
|
730
|
+
"ts": now_ts(),
|
|
731
|
+
"kind": "worktree_created",
|
|
732
|
+
"role": rname,
|
|
733
|
+
"path": info["path"],
|
|
734
|
+
"branch": info["branch"],
|
|
735
|
+
},
|
|
736
|
+
)
|
|
737
|
+
except Exception as e:
|
|
738
|
+
# Log but continue
|
|
739
|
+
append_trace(
|
|
740
|
+
run_dir,
|
|
741
|
+
{
|
|
742
|
+
"ts": now_ts(),
|
|
743
|
+
"kind": "worktree_failed",
|
|
744
|
+
"role": rname,
|
|
745
|
+
"error": str(e)[:500],
|
|
746
|
+
},
|
|
747
|
+
)
|
|
748
|
+
# Update state worktrees
|
|
749
|
+
state = read_state(run_dir) or {}
|
|
750
|
+
state["worktrees"] = created_wts
|
|
751
|
+
# Activate initial roles
|
|
752
|
+
for r in initial_roles:
|
|
753
|
+
state["roles"][r] = "ready"
|
|
754
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "role_activated", "role": r})
|
|
755
|
+
append_trace(
|
|
756
|
+
run_dir, {"ts": now_ts(), "kind": "role_state_changed", "role": r, "to": "ready"}
|
|
757
|
+
)
|
|
758
|
+
# If plan approval required, keep awaiting
|
|
759
|
+
if state.get("run_state") == "awaiting_plan_approval":
|
|
760
|
+
_log(f"Run {run_id} created, awaiting plan approval")
|
|
761
|
+
else:
|
|
762
|
+
state["run_state"] = "running"
|
|
763
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "run_state_changed", "to": "running"})
|
|
764
|
+
write_state(run_dir, state)
|
|
765
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "backend_selected", "backend": backend_name})
|
|
766
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "runner_selected", "runner": runner_name})
|
|
767
|
+
# Create backend surfaces (best effort, filesystem correctness not dependent)
|
|
768
|
+
import shlex as _shlex
|
|
769
|
+
|
|
770
|
+
try:
|
|
771
|
+
backend.create_run_surface(run_dir, run_id, recipe_name)
|
|
772
|
+
# Eager windows for ALL roles (UX like swarm-forge), lazy agents only for initial_roles
|
|
773
|
+
# Build eager mapping for waiting message: who feeds whom
|
|
774
|
+
# Determine predecessor for each role based on produces/consumes chain
|
|
775
|
+
_eager_predecessors = {}
|
|
776
|
+
try:
|
|
777
|
+
_spec_roles = recipe.get("spec", {}).get("roles", {}) if recipe else {}
|
|
778
|
+
for _rname, _rdef in _spec_roles.items():
|
|
779
|
+
_consumes = _rdef.get("consumes", [])
|
|
780
|
+
for _other, _odef in _spec_roles.items():
|
|
781
|
+
if _other == _rname:
|
|
782
|
+
continue
|
|
783
|
+
_produces = _odef.get("produces", [])
|
|
784
|
+
if any(pr in _consumes for pr in _produces):
|
|
785
|
+
_eager_predecessors[_rname] = _other
|
|
786
|
+
break
|
|
787
|
+
# Fallback chain for known recipes
|
|
788
|
+
if not _eager_predecessors:
|
|
789
|
+
_fallback = {
|
|
790
|
+
"pair": {"reviewer": "implementer", "integrator": "reviewer"},
|
|
791
|
+
"team": {
|
|
792
|
+
"implementer": "planner",
|
|
793
|
+
"reviewer": "implementer",
|
|
794
|
+
"architect": "reviewer",
|
|
795
|
+
},
|
|
796
|
+
"full": {
|
|
797
|
+
"implementer": "planner",
|
|
798
|
+
"refactorer": "implementer",
|
|
799
|
+
"architect": "refactorer",
|
|
800
|
+
"hardener": "architect",
|
|
801
|
+
"qa": "hardener",
|
|
802
|
+
},
|
|
803
|
+
}.get(recipe_name, {})
|
|
804
|
+
_eager_predecessors.update(_fallback)
|
|
805
|
+
except Exception:
|
|
806
|
+
pass
|
|
807
|
+
for _rname in list(roles.keys()):
|
|
808
|
+
try:
|
|
809
|
+
backend.create_role_surface(run_dir, run_id, _rname)
|
|
810
|
+
if _rname not in initial_roles:
|
|
811
|
+
# Waiting placeholder with clear UX
|
|
812
|
+
_pred = _eager_predecessors.get(_rname, "previous role")
|
|
813
|
+
_msg = f"Waiting for handoff: {_pred} -> {_rname} | role: {_rname} | run: {run_id}"
|
|
814
|
+
_hint = f"Will auto-start {_rname} when {_pred} creates artifact handoff"
|
|
815
|
+
_waiting_cmd = [
|
|
816
|
+
_user_shell(),
|
|
817
|
+
"-lc",
|
|
818
|
+
f'echo "Waiting for handoff: {_pred} -> {_rname} | role: {_rname} | run: {run_id}" && echo "Will auto-start {_rname} when {_pred} creates artifact handoff" && echo "Tip: agent-toolkit swarm handoffs {run_id}" && exec {_shell_base()}',
|
|
819
|
+
]
|
|
820
|
+
try:
|
|
821
|
+
backend.start_agent(run_dir, run_id, _rname, _waiting_cmd)
|
|
822
|
+
append_trace(
|
|
823
|
+
run_dir,
|
|
824
|
+
{
|
|
825
|
+
"ts": now_ts(),
|
|
826
|
+
"kind": "agent_waiting",
|
|
827
|
+
"role": _rname,
|
|
828
|
+
"waiting_for": _pred,
|
|
829
|
+
},
|
|
830
|
+
)
|
|
831
|
+
except Exception:
|
|
832
|
+
pass
|
|
833
|
+
except Exception:
|
|
834
|
+
pass
|
|
835
|
+
# Keep initial role focused for UX (like swarm-forge keeps first window active)
|
|
836
|
+
try:
|
|
837
|
+
if initial_roles and hasattr(backend, "_socket_for"):
|
|
838
|
+
import subprocess as _sp
|
|
839
|
+
|
|
840
|
+
_sock = backend._socket_for(run_id)
|
|
841
|
+
_sp.run(
|
|
842
|
+
[
|
|
843
|
+
"tmux",
|
|
844
|
+
"-L",
|
|
845
|
+
_sock,
|
|
846
|
+
"select-window",
|
|
847
|
+
"-t",
|
|
848
|
+
f"swarm-{run_id}:{initial_roles[0]}",
|
|
849
|
+
],
|
|
850
|
+
capture_output=True,
|
|
851
|
+
timeout=3,
|
|
852
|
+
)
|
|
853
|
+
except Exception:
|
|
854
|
+
pass
|
|
855
|
+
for r in initial_roles:
|
|
856
|
+
# Window already created eagerly above; just start agent
|
|
857
|
+
# Auto-start agent in its tmux/herdr surface
|
|
858
|
+
try:
|
|
859
|
+
worktree_path = next(
|
|
860
|
+
(wt.get("path") for wt in created_wts if wt.get("role") == r),
|
|
861
|
+
str(run_dir),
|
|
862
|
+
)
|
|
863
|
+
# Build runner command — like swarm-forge launch-command: pass prompt as CLI arg
|
|
864
|
+
prompt_file = run_dir / "prompts" / f"{r}.md"
|
|
865
|
+
# swarm-forge style: $(cat prompt) passed as positional prompt
|
|
866
|
+
prompt_cat = (
|
|
867
|
+
f"$(cat {_shlex.quote(str(prompt_file))})" if prompt_file.exists() else ""
|
|
868
|
+
)
|
|
869
|
+
# Export swarm context for handoffs (like SWARMFORGE_ROLE)
|
|
870
|
+
swarm_env = f"export AGENT_TOOLKIT_SWARM_RUN_ID={_shlex.quote(run_id)} && export AGENT_TOOLKIT_SWARM_RUN_DIR={_shlex.quote(str(run_dir))} && export AGENT_TOOLKIT_SWARM_REPO={_shlex.quote(str(repo))} && export SWARMFORGE_ROLE={_shlex.quote(r)} &&"
|
|
871
|
+
if runner_name == "opencode":
|
|
872
|
+
# opencode: --agent + --prompt "$(cat prompt)"
|
|
873
|
+
if prompt_cat:
|
|
874
|
+
cmd = [
|
|
875
|
+
_user_shell(),
|
|
876
|
+
"-lc",
|
|
877
|
+
f'{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec opencode --agent {_shlex.quote(r)} --prompt "{prompt_cat}"',
|
|
878
|
+
]
|
|
879
|
+
else:
|
|
880
|
+
cmd = [
|
|
881
|
+
_user_shell(),
|
|
882
|
+
"-lc",
|
|
883
|
+
f"{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec opencode --agent {_shlex.quote(r)}",
|
|
884
|
+
]
|
|
885
|
+
elif runner_name == "claude":
|
|
886
|
+
if prompt_cat:
|
|
887
|
+
cmd = [
|
|
888
|
+
_user_shell(),
|
|
889
|
+
"-lc",
|
|
890
|
+
f'{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec claude --dangerously-skip-permissions --append-system-prompt-file {_shlex.quote(str(prompt_file))} "{prompt_cat}"',
|
|
891
|
+
]
|
|
892
|
+
else:
|
|
893
|
+
cmd = [
|
|
894
|
+
_user_shell(),
|
|
895
|
+
"-lc",
|
|
896
|
+
f"{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec claude --dangerously-skip-permissions",
|
|
897
|
+
]
|
|
898
|
+
elif runner_name == "codex":
|
|
899
|
+
if prompt_cat:
|
|
900
|
+
cmd = [
|
|
901
|
+
_user_shell(),
|
|
902
|
+
"-lc",
|
|
903
|
+
f'{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec codex -C {_shlex.quote(str(worktree_path))} "{prompt_cat}"',
|
|
904
|
+
]
|
|
905
|
+
else:
|
|
906
|
+
cmd = [
|
|
907
|
+
_user_shell(),
|
|
908
|
+
"-lc",
|
|
909
|
+
f"{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec codex",
|
|
910
|
+
]
|
|
911
|
+
elif runner_name == "cursor":
|
|
912
|
+
if prompt_cat:
|
|
913
|
+
cmd = [
|
|
914
|
+
_user_shell(),
|
|
915
|
+
"-lc",
|
|
916
|
+
f'{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec cursor-agent "{prompt_cat}"',
|
|
917
|
+
]
|
|
918
|
+
else:
|
|
919
|
+
cmd = [
|
|
920
|
+
_user_shell(),
|
|
921
|
+
"-lc",
|
|
922
|
+
f"{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec cursor-agent",
|
|
923
|
+
]
|
|
924
|
+
elif runner_name == "copilot":
|
|
925
|
+
if prompt_cat:
|
|
926
|
+
cmd = [
|
|
927
|
+
_user_shell(),
|
|
928
|
+
"-lc",
|
|
929
|
+
f'{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec copilot --name {_shlex.quote("Swarm " + r)} -i "{prompt_cat}"',
|
|
930
|
+
]
|
|
931
|
+
else:
|
|
932
|
+
cmd = [
|
|
933
|
+
_user_shell(),
|
|
934
|
+
"-lc",
|
|
935
|
+
f"{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec copilot",
|
|
936
|
+
]
|
|
937
|
+
elif runner_name == "muse":
|
|
938
|
+
if prompt_cat:
|
|
939
|
+
cmd = [
|
|
940
|
+
_user_shell(),
|
|
941
|
+
"-lc",
|
|
942
|
+
f'{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec muse chat "{prompt_cat}"',
|
|
943
|
+
]
|
|
944
|
+
else:
|
|
945
|
+
cmd = [
|
|
946
|
+
_user_shell(),
|
|
947
|
+
"-lc",
|
|
948
|
+
f"{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec muse chat",
|
|
949
|
+
]
|
|
950
|
+
elif runner_name == "skeleton":
|
|
951
|
+
cmd = [
|
|
952
|
+
_user_shell(),
|
|
953
|
+
"-lc",
|
|
954
|
+
f"{swarm_env} cd {_shlex.quote(str(worktree_path))} && echo '[skeleton:{r}] ready — no LLM' && exec {_shell_base()}",
|
|
955
|
+
]
|
|
956
|
+
else:
|
|
957
|
+
if prompt_cat:
|
|
958
|
+
cmd = [
|
|
959
|
+
_user_shell(),
|
|
960
|
+
"-lc",
|
|
961
|
+
f'{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec {runner_name} "{prompt_cat}"',
|
|
962
|
+
]
|
|
963
|
+
else:
|
|
964
|
+
cmd = [
|
|
965
|
+
_user_shell(),
|
|
966
|
+
"-lc",
|
|
967
|
+
f"{swarm_env} cd {_shlex.quote(str(worktree_path))} && exec {runner_name}",
|
|
968
|
+
]
|
|
969
|
+
backend.start_agent(run_dir, run_id, r, cmd)
|
|
970
|
+
append_trace(
|
|
971
|
+
run_dir,
|
|
972
|
+
{
|
|
973
|
+
"ts": now_ts(),
|
|
974
|
+
"kind": "agent_started",
|
|
975
|
+
"role": r,
|
|
976
|
+
"runner": runner_name,
|
|
977
|
+
"cmd": cmd,
|
|
978
|
+
},
|
|
979
|
+
)
|
|
980
|
+
except Exception as e:
|
|
981
|
+
append_trace(
|
|
982
|
+
run_dir,
|
|
983
|
+
{
|
|
984
|
+
"ts": now_ts(),
|
|
985
|
+
"kind": "agent_start_failed",
|
|
986
|
+
"role": r,
|
|
987
|
+
"error": str(e)[:500],
|
|
988
|
+
},
|
|
989
|
+
)
|
|
990
|
+
except Exception:
|
|
991
|
+
pass
|
|
992
|
+
# Create artifacts placeholder — interactive mode gets bootstrap note instead of empty contract
|
|
993
|
+
is_interactive_run = not task_text or not task_text.strip()
|
|
994
|
+
if is_interactive_run:
|
|
995
|
+
task_contract_body = (
|
|
996
|
+
"# Task Contract — Interactive mode (no initial task)\n\n"
|
|
997
|
+
"This swarm was started without an initial prompt. The first agent (planner/implementer) "
|
|
998
|
+
"must do a very brief context analysis and stay on standby awaiting the user's first request.\n\n"
|
|
999
|
+
"- If inside a workspace (e.g. `~/.ai-workspace`): run `agent-toolkit workspace context` and briefly review `AGENTS.md` + `knowledge/todos/pending.md`.\n"
|
|
1000
|
+
"- Otherwise, briefly review the current repo (`git status`, `README.md`).\n"
|
|
1001
|
+
'- Do not invent work. Confirm with: "Brief analysis done — awaiting your first request."\n\n'
|
|
1002
|
+
f"Recipe: {recipe_name}\nRun: {run_id}\n"
|
|
1003
|
+
f"Run dir: {run_dir}\n"
|
|
1004
|
+
f"Initial roles: {', '.join(initial_roles)}\n"
|
|
1005
|
+
f"When the user provides the task, apply discovery (`assistant`) + `workflow-generic-project` (plan -> approval -> implement -> draft PR).\n"
|
|
1006
|
+
)
|
|
1007
|
+
else:
|
|
1008
|
+
task_contract_body = (
|
|
1009
|
+
f"# Task Contract\n\n{task_text}\n\nRecipe: {recipe_name}\nRun: {run_id}\n"
|
|
1010
|
+
)
|
|
1011
|
+
(run_dir / "artifacts" / "task-contract.md").write_text(task_contract_body, encoding="utf-8")
|
|
1012
|
+
if ns.json:
|
|
1013
|
+
return _json_out(
|
|
1014
|
+
{
|
|
1015
|
+
"run_id": run_id,
|
|
1016
|
+
"run_dir": str(run_dir),
|
|
1017
|
+
"state": state,
|
|
1018
|
+
"backend": backend_name,
|
|
1019
|
+
"runner": runner_name,
|
|
1020
|
+
}
|
|
1021
|
+
)
|
|
1022
|
+
print(f"Swarm run created: {run_id}")
|
|
1023
|
+
print(f" recipe: {recipe_name}")
|
|
1024
|
+
print(f" run_dir: {run_dir}")
|
|
1025
|
+
print(f" backend: {backend_name}")
|
|
1026
|
+
print(f" runner: {runner_name}")
|
|
1027
|
+
print(f" task: {task_text[:100]}")
|
|
1028
|
+
print(f" initial roles: {', '.join(initial_roles)}")
|
|
1029
|
+
if state.get("run_state") == "awaiting_plan_approval":
|
|
1030
|
+
print(
|
|
1031
|
+
f" status: awaiting_plan_approval — approve with: agent-toolkit swarm approve {run_id} plan"
|
|
1032
|
+
)
|
|
1033
|
+
else:
|
|
1034
|
+
print(" status: running")
|
|
1035
|
+
print(f"Inspect: agent-toolkit swarm status {run_id}")
|
|
1036
|
+
if not ns.json and not ns.dry_run and ns.attach and not ns.no_attach:
|
|
1037
|
+
# Auto-attach to the created session (tmux/herdr)
|
|
1038
|
+
backend_name_eff = cfg.get("ui", "auto")
|
|
1039
|
+
# Resolve actual backend if auto
|
|
1040
|
+
if backend_name_eff == "auto":
|
|
1041
|
+
# prefer tmux if available, else herdr
|
|
1042
|
+
import shutil as _shutil2
|
|
1043
|
+
|
|
1044
|
+
if _shutil2.which("tmux"):
|
|
1045
|
+
backend_name_eff = "tmux"
|
|
1046
|
+
elif _shutil2.which("herdr"):
|
|
1047
|
+
backend_name_eff = "herdr"
|
|
1048
|
+
else:
|
|
1049
|
+
backend_name_eff = "tmux"
|
|
1050
|
+
if backend_name_eff == "tmux":
|
|
1051
|
+
sock = f"agent-toolkit-swarm-{run_id}"
|
|
1052
|
+
session = f"swarm-{run_id}"
|
|
1053
|
+
print(f"Attaching to tmux: tmux -L {sock} attach -t {session}")
|
|
1054
|
+
import os as _os
|
|
1055
|
+
|
|
1056
|
+
try:
|
|
1057
|
+
_os.execvp("tmux", ["tmux", "-L", sock, "attach", "-t", session])
|
|
1058
|
+
except Exception as e:
|
|
1059
|
+
print(f"[attach] tmux attach failed: {e}")
|
|
1060
|
+
elif backend_name_eff == "herdr":
|
|
1061
|
+
print(f"Attaching to herdr: herdr workspace open swarm-{run_id}")
|
|
1062
|
+
import os as _os
|
|
1063
|
+
import shutil as _shutil3
|
|
1064
|
+
|
|
1065
|
+
if _shutil3.which("herdr"):
|
|
1066
|
+
try:
|
|
1067
|
+
_os.execvp("herdr", ["herdr", "workspace", "open", f"swarm-{run_id}"])
|
|
1068
|
+
except Exception as e:
|
|
1069
|
+
print(f"[attach] herdr attach failed: {e}")
|
|
1070
|
+
return 0
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
def cmd_list(args: list[str]) -> int:
|
|
1074
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm list")
|
|
1075
|
+
parser.add_argument("--json", action="store_true")
|
|
1076
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1077
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1078
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1079
|
+
ns = parser.parse_args(args)
|
|
1080
|
+
workspace_flag = ns.workspace or ns.repo or ns.workspace_C
|
|
1081
|
+
# If run from .ai-workspace with no explicit workspace, aggregate across clones
|
|
1082
|
+
if workspace_flag:
|
|
1083
|
+
from .config import find_repo_root
|
|
1084
|
+
|
|
1085
|
+
repo = find_repo_root(workspace=workspace_flag)
|
|
1086
|
+
runs = list_runs(repo)
|
|
1087
|
+
else:
|
|
1088
|
+
from .config import list_all_runs
|
|
1089
|
+
|
|
1090
|
+
runs = list_all_runs()
|
|
1091
|
+
items = []
|
|
1092
|
+
for rd in runs:
|
|
1093
|
+
state = read_state(rd) or {}
|
|
1094
|
+
items.append(
|
|
1095
|
+
{
|
|
1096
|
+
"run_id": rd.name,
|
|
1097
|
+
"recipe": state.get("recipe"),
|
|
1098
|
+
"run_state": state.get("run_state"),
|
|
1099
|
+
"created_at": state.get("created_at"),
|
|
1100
|
+
}
|
|
1101
|
+
)
|
|
1102
|
+
items.sort(key=lambda x: x.get("created_at") or "", reverse=True)
|
|
1103
|
+
if ns.json:
|
|
1104
|
+
return _json_out(items)
|
|
1105
|
+
if not items:
|
|
1106
|
+
print("No swarm runs found.")
|
|
1107
|
+
return 0
|
|
1108
|
+
for it in items:
|
|
1109
|
+
print(
|
|
1110
|
+
f"{it['run_id']:25} {it['recipe'] or '?':8} {it['run_state'] or '?':15} {it['created_at'] or ''}"
|
|
1111
|
+
)
|
|
1112
|
+
return 0
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
def cmd_status(args: list[str]) -> int:
|
|
1116
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm status")
|
|
1117
|
+
parser.add_argument("run_id", nargs="?", default=None)
|
|
1118
|
+
parser.add_argument("--json", action="store_true")
|
|
1119
|
+
parser.add_argument("--watch", action="store_true")
|
|
1120
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1121
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1122
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1123
|
+
ns = parser.parse_args(args)
|
|
1124
|
+
if not ns.run_id:
|
|
1125
|
+
# Show all
|
|
1126
|
+
ws_flag = ns.workspace or ns.repo or ns.workspace_C
|
|
1127
|
+
if ws_flag:
|
|
1128
|
+
return cmd_list(
|
|
1129
|
+
["--json", "--workspace", ws_flag] if ns.json else ["--workspace", ws_flag]
|
|
1130
|
+
)
|
|
1131
|
+
return cmd_list(["--json"] if ns.json else [])
|
|
1132
|
+
workspace_flag = ns.workspace or ns.repo or ns.workspace_C
|
|
1133
|
+
from .config import find_run_dir_by_id
|
|
1134
|
+
|
|
1135
|
+
run_dir = find_run_dir_by_id(ns.run_id, workspace=workspace_flag)
|
|
1136
|
+
if run_dir is None or not run_dir.is_dir():
|
|
1137
|
+
# Fallback to old path for error hint
|
|
1138
|
+
from .config import find_repo_root
|
|
1139
|
+
|
|
1140
|
+
repo = find_repo_root(workspace=workspace_flag)
|
|
1141
|
+
run_dir = run_dir_for(repo, ns.run_id)
|
|
1142
|
+
if not run_dir.is_dir():
|
|
1143
|
+
return _error(f"Run not found: {ns.run_id}", hint="List runs: agent-toolkit swarm list")
|
|
1144
|
+
state = read_state(run_dir) or {}
|
|
1145
|
+
budget_data = load_budget(run_dir)
|
|
1146
|
+
trace_path = run_dir / "trace.jsonl"
|
|
1147
|
+
trace_count = 0
|
|
1148
|
+
if trace_path.is_file():
|
|
1149
|
+
trace_count = len(
|
|
1150
|
+
[line for line in trace_path.read_text(encoding="utf-8").splitlines() if line.strip()]
|
|
1151
|
+
)
|
|
1152
|
+
data = {
|
|
1153
|
+
"run_id": ns.run_id,
|
|
1154
|
+
"state": state,
|
|
1155
|
+
"budget": budget_data,
|
|
1156
|
+
"trace_events": trace_count,
|
|
1157
|
+
"run_dir": str(run_dir),
|
|
1158
|
+
}
|
|
1159
|
+
if ns.json:
|
|
1160
|
+
return _json_out(data)
|
|
1161
|
+
print(f"Run: {ns.run_id}")
|
|
1162
|
+
print(f" recipe: {state.get('recipe')}")
|
|
1163
|
+
print(f" run_state: {state.get('run_state')}")
|
|
1164
|
+
print(f" roles: {state.get('roles')}")
|
|
1165
|
+
print(f" ui_backend: {state.get('ui_backend')}")
|
|
1166
|
+
print(f" runner: {state.get('runner')}")
|
|
1167
|
+
print(f" created_at: {state.get('created_at')}")
|
|
1168
|
+
print(f" trace_events: {trace_count}")
|
|
1169
|
+
if budget_data:
|
|
1170
|
+
print(f" budget: {budget_data}")
|
|
1171
|
+
# Approvals
|
|
1172
|
+
gates = load_approvals(run_dir)
|
|
1173
|
+
if gates:
|
|
1174
|
+
print(" approvals:")
|
|
1175
|
+
for g in gates:
|
|
1176
|
+
print(
|
|
1177
|
+
f" {g['id']}: {'approved' if g.get('approved') else 'pending'} - {g.get('description', '')[:60]}"
|
|
1178
|
+
)
|
|
1179
|
+
if ns.watch:
|
|
1180
|
+
print("Watch mode: tailing trace.jsonl (Ctrl-C to exit)")
|
|
1181
|
+
try:
|
|
1182
|
+
while True:
|
|
1183
|
+
time.sleep(1)
|
|
1184
|
+
# simple poll
|
|
1185
|
+
new_count = (
|
|
1186
|
+
len(
|
|
1187
|
+
[
|
|
1188
|
+
line
|
|
1189
|
+
for line in (run_dir / "trace.jsonl")
|
|
1190
|
+
.read_text(encoding="utf-8")
|
|
1191
|
+
.splitlines()
|
|
1192
|
+
if line.strip()
|
|
1193
|
+
]
|
|
1194
|
+
)
|
|
1195
|
+
if (run_dir / "trace.jsonl").is_file()
|
|
1196
|
+
else 0
|
|
1197
|
+
)
|
|
1198
|
+
if new_count != trace_count:
|
|
1199
|
+
print(f"[trace] {new_count} events")
|
|
1200
|
+
trace_count = new_count
|
|
1201
|
+
except KeyboardInterrupt:
|
|
1202
|
+
pass
|
|
1203
|
+
return 0
|
|
1204
|
+
|
|
1205
|
+
|
|
1206
|
+
def cmd_watch(args: list[str]) -> int:
|
|
1207
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm watch")
|
|
1208
|
+
parser.add_argument("run_id", nargs="?", default=None)
|
|
1209
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1210
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1211
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1212
|
+
parser.add_argument("--current", action="store_true")
|
|
1213
|
+
ns = parser.parse_args(args)
|
|
1214
|
+
if ns.current:
|
|
1215
|
+
repo = _need_repo()
|
|
1216
|
+
runs = list_runs(repo)
|
|
1217
|
+
if not runs:
|
|
1218
|
+
print("No runs")
|
|
1219
|
+
return 1
|
|
1220
|
+
# pick latest
|
|
1221
|
+
latest = sorted(runs, key=lambda p: p.stat().st_mtime, reverse=True)[0]
|
|
1222
|
+
ns.run_id = latest.name
|
|
1223
|
+
if not ns.run_id:
|
|
1224
|
+
return _error("No run_id", hint="Usage: agent-toolkit swarm watch RUN_ID")
|
|
1225
|
+
return cmd_status([ns.run_id, "--watch"])
|
|
1226
|
+
|
|
1227
|
+
|
|
1228
|
+
def cmd_report(args: list[str]) -> int:
|
|
1229
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm report")
|
|
1230
|
+
parser.add_argument("run_id", nargs="?", default=None)
|
|
1231
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1232
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1233
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1234
|
+
parser.add_argument("--json", action="store_true")
|
|
1235
|
+
ns = parser.parse_args(args)
|
|
1236
|
+
if not ns.run_id:
|
|
1237
|
+
return _error("RUN_ID required")
|
|
1238
|
+
repo = _need_repo()
|
|
1239
|
+
run_dir = run_dir_for(repo, ns.run_id)
|
|
1240
|
+
if not run_dir.is_dir():
|
|
1241
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1242
|
+
state = read_state(run_dir) or {}
|
|
1243
|
+
artifacts = list((run_dir / "artifacts").glob("*")) if (run_dir / "artifacts").is_dir() else []
|
|
1244
|
+
handoffs_done = list_handoffs(run_dir, "completed")
|
|
1245
|
+
data = {
|
|
1246
|
+
"run_id": ns.run_id,
|
|
1247
|
+
"recipe": state.get("recipe"),
|
|
1248
|
+
"run_state": state.get("run_state"),
|
|
1249
|
+
"roles": state.get("roles"),
|
|
1250
|
+
"artifacts": [p.name for p in artifacts],
|
|
1251
|
+
"handoffs_completed": len(handoffs_done),
|
|
1252
|
+
"budget": load_budget(run_dir),
|
|
1253
|
+
}
|
|
1254
|
+
if ns.json:
|
|
1255
|
+
return _json_out(data)
|
|
1256
|
+
# Try final-report.md
|
|
1257
|
+
final = run_dir / "artifacts" / "final-report.md"
|
|
1258
|
+
if final.is_file():
|
|
1259
|
+
print(final.read_text(encoding="utf-8"))
|
|
1260
|
+
return 0
|
|
1261
|
+
print(f"Report for {ns.run_id}")
|
|
1262
|
+
print(f" recipe: {data['recipe']}")
|
|
1263
|
+
print(f" state: {data['run_state']}")
|
|
1264
|
+
print(f" artifacts: {', '.join(data['artifacts']) or 'none'}")
|
|
1265
|
+
print(f" handoffs completed: {data['handoffs_completed']}")
|
|
1266
|
+
# Generate placeholder report if not exists
|
|
1267
|
+
if not final.is_file():
|
|
1268
|
+
print("\nNo final-report.md yet. Run is not completed.")
|
|
1269
|
+
return 0
|
|
1270
|
+
|
|
1271
|
+
|
|
1272
|
+
def cmd_artifacts(args: list[str]) -> int:
|
|
1273
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm artifacts")
|
|
1274
|
+
parser.add_argument("run_id")
|
|
1275
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1276
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1277
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1278
|
+
parser.add_argument("--json", action="store_true")
|
|
1279
|
+
ns = parser.parse_args(args)
|
|
1280
|
+
repo = _need_repo()
|
|
1281
|
+
run_dir = run_dir_for(repo, ns.run_id)
|
|
1282
|
+
if not run_dir.is_dir():
|
|
1283
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1284
|
+
art_dir = run_dir / "artifacts"
|
|
1285
|
+
items = []
|
|
1286
|
+
if art_dir.is_dir():
|
|
1287
|
+
for p in sorted(art_dir.iterdir()):
|
|
1288
|
+
if p.is_file():
|
|
1289
|
+
items.append(
|
|
1290
|
+
{"name": p.name, "path": str(p.relative_to(run_dir)), "size": p.stat().st_size}
|
|
1291
|
+
)
|
|
1292
|
+
if ns.json:
|
|
1293
|
+
return _json_out(items)
|
|
1294
|
+
for it in items:
|
|
1295
|
+
print(f"{it['name']:30} {it['size']:6} bytes {it['path']}")
|
|
1296
|
+
if not items:
|
|
1297
|
+
print("No artifacts yet.")
|
|
1298
|
+
return 0
|
|
1299
|
+
|
|
1300
|
+
|
|
1301
|
+
def cmd_handoffs(args: list[str]) -> int:
|
|
1302
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm handoffs")
|
|
1303
|
+
parser.add_argument("run_id")
|
|
1304
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1305
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1306
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1307
|
+
parser.add_argument("--json", action="store_true")
|
|
1308
|
+
ns = parser.parse_args(args)
|
|
1309
|
+
repo = _need_repo()
|
|
1310
|
+
run_dir = run_dir_for(repo, ns.run_id)
|
|
1311
|
+
if not run_dir.is_dir():
|
|
1312
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1313
|
+
all_states = ["outbox", "queued", "active", "completed", "failed"]
|
|
1314
|
+
data: dict[str, list[dict[str, Any]]] = {}
|
|
1315
|
+
for st in all_states:
|
|
1316
|
+
data[st] = list_handoffs(run_dir, st)
|
|
1317
|
+
if ns.json:
|
|
1318
|
+
return _json_out(data)
|
|
1319
|
+
for st, items in data.items():
|
|
1320
|
+
print(f"{st}: {len(items)}")
|
|
1321
|
+
for it in items:
|
|
1322
|
+
print(
|
|
1323
|
+
f" {it.get('handoff_id', '?')} {it.get('type')} {it.get('from')}->{it.get('to')} prio={it.get('priority')}"
|
|
1324
|
+
)
|
|
1325
|
+
return 0
|
|
1326
|
+
|
|
1327
|
+
|
|
1328
|
+
def cmd_logs(args: list[str]) -> int:
|
|
1329
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm logs")
|
|
1330
|
+
parser.add_argument("run_id")
|
|
1331
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1332
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1333
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1334
|
+
parser.add_argument("role", nargs="?", default=None)
|
|
1335
|
+
parser.add_argument("--json", action="store_true")
|
|
1336
|
+
ns = parser.parse_args(args)
|
|
1337
|
+
repo = _need_repo()
|
|
1338
|
+
run_dir = run_dir_for(repo, ns.run_id)
|
|
1339
|
+
if not run_dir.is_dir():
|
|
1340
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1341
|
+
if ns.role:
|
|
1342
|
+
# Try backend log
|
|
1343
|
+
backend_name = (read_state(run_dir) or {}).get("ui_backend", "auto")
|
|
1344
|
+
backend = get_backend(backend_name)
|
|
1345
|
+
try:
|
|
1346
|
+
out = backend.read_agent_output(ns.run_id, ns.role)
|
|
1347
|
+
print(out)
|
|
1348
|
+
return 0
|
|
1349
|
+
except Exception as e:
|
|
1350
|
+
print(f"Logs for {ns.role} not available: {e}")
|
|
1351
|
+
return 0
|
|
1352
|
+
# Show trace
|
|
1353
|
+
trace = run_dir / "trace.jsonl"
|
|
1354
|
+
if trace.is_file():
|
|
1355
|
+
print(trace.read_text(encoding="utf-8"))
|
|
1356
|
+
else:
|
|
1357
|
+
print("No trace.jsonl")
|
|
1358
|
+
return 0
|
|
1359
|
+
|
|
1360
|
+
|
|
1361
|
+
def _change_run_state(repo: Path, run_id: str, new_state: str) -> int:
|
|
1362
|
+
run_dir = run_dir_for(repo, run_id)
|
|
1363
|
+
if not run_dir.is_dir():
|
|
1364
|
+
return _error(f"Run not found: {run_id}")
|
|
1365
|
+
state = read_state(run_dir) or {}
|
|
1366
|
+
old = state.get("run_state")
|
|
1367
|
+
from .state import can_transition_run
|
|
1368
|
+
|
|
1369
|
+
if not can_transition_run(old, new_state):
|
|
1370
|
+
return _error(f"Invalid transition {old!r} -> {new_state!r}")
|
|
1371
|
+
state["run_state"] = new_state
|
|
1372
|
+
write_state(run_dir, state)
|
|
1373
|
+
append_trace(
|
|
1374
|
+
run_dir, {"ts": now_ts(), "kind": "run_state_changed", "from": old, "to": new_state}
|
|
1375
|
+
)
|
|
1376
|
+
print(f"Run {run_id}: {old} -> {new_state}")
|
|
1377
|
+
return 0
|
|
1378
|
+
|
|
1379
|
+
|
|
1380
|
+
def cmd_pause(args: list[str]) -> int:
|
|
1381
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm pause")
|
|
1382
|
+
parser.add_argument("run_id")
|
|
1383
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1384
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1385
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1386
|
+
ns = parser.parse_args(args)
|
|
1387
|
+
return _change_run_state(_need_repo(), ns.run_id, "paused")
|
|
1388
|
+
|
|
1389
|
+
|
|
1390
|
+
def cmd_resume(args: list[str]) -> int:
|
|
1391
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm resume")
|
|
1392
|
+
parser.add_argument("run_id")
|
|
1393
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1394
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1395
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1396
|
+
ns = parser.parse_args(args)
|
|
1397
|
+
# resume from paused or budget_exhausted or failed
|
|
1398
|
+
repo = _need_repo()
|
|
1399
|
+
run_dir = run_dir_for(repo, ns.run_id)
|
|
1400
|
+
if not run_dir.is_dir():
|
|
1401
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1402
|
+
state = read_state(run_dir) or {}
|
|
1403
|
+
old = state.get("run_state")
|
|
1404
|
+
# Allow paused -> running, budget_exhausted -> running, failed -> running
|
|
1405
|
+
if old not in ("paused", "budget_exhausted", "failed"):
|
|
1406
|
+
# try generic paused
|
|
1407
|
+
return _change_run_state(repo, ns.run_id, "running")
|
|
1408
|
+
state["run_state"] = "running"
|
|
1409
|
+
write_state(run_dir, state)
|
|
1410
|
+
append_trace(
|
|
1411
|
+
run_dir, {"ts": now_ts(), "kind": "run_state_changed", "from": old, "to": "running"}
|
|
1412
|
+
)
|
|
1413
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "role_state_changed", "detail": "resume"})
|
|
1414
|
+
print(f"Run {ns.run_id}: {old} -> running")
|
|
1415
|
+
return 0
|
|
1416
|
+
|
|
1417
|
+
|
|
1418
|
+
def cmd_stop(args: list[str]) -> int:
|
|
1419
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm stop")
|
|
1420
|
+
parser.add_argument("run_id")
|
|
1421
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1422
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1423
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1424
|
+
ns = parser.parse_args(args)
|
|
1425
|
+
workspace_flag = ns.workspace or ns.repo or ns.workspace_C
|
|
1426
|
+
from .config import find_run_dir_by_id
|
|
1427
|
+
|
|
1428
|
+
run_dir = find_run_dir_by_id(ns.run_id, workspace=workspace_flag)
|
|
1429
|
+
if run_dir is None:
|
|
1430
|
+
from .config import find_repo_root
|
|
1431
|
+
from .store import run_dir_for as _rdf
|
|
1432
|
+
|
|
1433
|
+
repo = find_repo_root(workspace=workspace_flag)
|
|
1434
|
+
run_dir = _rdf(repo, ns.run_id)
|
|
1435
|
+
if not run_dir.is_dir():
|
|
1436
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1437
|
+
state = read_state(run_dir) or {}
|
|
1438
|
+
state["run_state"] = "paused"
|
|
1439
|
+
write_state(run_dir, state)
|
|
1440
|
+
# stop agents via backend
|
|
1441
|
+
be = get_backend(state.get("ui_backend", "auto"))
|
|
1442
|
+
for role in state.get("roles", {}):
|
|
1443
|
+
try:
|
|
1444
|
+
be.stop_agent(ns.run_id, role)
|
|
1445
|
+
except Exception:
|
|
1446
|
+
pass
|
|
1447
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "role_stopped", "run_id": ns.run_id})
|
|
1448
|
+
print(
|
|
1449
|
+
f"Run {ns.run_id} stopped (state preserved). Resume with: agent-toolkit swarm resume {ns.run_id}"
|
|
1450
|
+
)
|
|
1451
|
+
return 0
|
|
1452
|
+
|
|
1453
|
+
|
|
1454
|
+
def cmd_cancel(args: list[str]) -> int:
|
|
1455
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm cancel")
|
|
1456
|
+
parser.add_argument("run_id")
|
|
1457
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1458
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1459
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1460
|
+
ns = parser.parse_args(args)
|
|
1461
|
+
return _change_run_state(_need_repo(), ns.run_id, "cancelled")
|
|
1462
|
+
|
|
1463
|
+
|
|
1464
|
+
def cmd_cleanup(args: list[str]) -> int:
|
|
1465
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm cleanup")
|
|
1466
|
+
parser.add_argument("run_id")
|
|
1467
|
+
parser.add_argument("--force", action="store_true")
|
|
1468
|
+
parser.add_argument("--dry-run", action="store_true")
|
|
1469
|
+
parser.add_argument("--keep-branches", action="store_true", default=True)
|
|
1470
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1471
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1472
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1473
|
+
ns = parser.parse_args(args)
|
|
1474
|
+
workspace_flag = ns.workspace or ns.repo or ns.workspace_C
|
|
1475
|
+
from .config import find_repo_root, find_run_dir_by_id
|
|
1476
|
+
from .store import run_dir_for as _rdf2
|
|
1477
|
+
|
|
1478
|
+
run_dir = find_run_dir_by_id(ns.run_id, workspace=workspace_flag)
|
|
1479
|
+
if run_dir is None:
|
|
1480
|
+
repo = find_repo_root(workspace=workspace_flag)
|
|
1481
|
+
run_dir = _rdf2(repo, ns.run_id)
|
|
1482
|
+
else:
|
|
1483
|
+
repo = find_repo_root(workspace=workspace_flag) if workspace_flag else find_repo_root()
|
|
1484
|
+
# Try to resolve repo from run_dir's parent
|
|
1485
|
+
try:
|
|
1486
|
+
# run_dir is .../.agent-toolkit/swarm/runs/<id>, so repo is 4 parents up
|
|
1487
|
+
maybe_repo = run_dir.parents[3]
|
|
1488
|
+
if (maybe_repo / ".git").exists():
|
|
1489
|
+
repo = maybe_repo
|
|
1490
|
+
except Exception:
|
|
1491
|
+
pass
|
|
1492
|
+
if not run_dir.is_dir():
|
|
1493
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1494
|
+
state = read_state(run_dir) or {}
|
|
1495
|
+
# Find owned worktrees
|
|
1496
|
+
wts = state.get("worktrees") or []
|
|
1497
|
+
# Also discover on-disk worktrees under run_dir/worktrees
|
|
1498
|
+
disk_wts = []
|
|
1499
|
+
wt_root = run_dir / "worktrees"
|
|
1500
|
+
if wt_root.is_dir():
|
|
1501
|
+
for p in wt_root.iterdir():
|
|
1502
|
+
if p.is_dir():
|
|
1503
|
+
disk_wts.append(p)
|
|
1504
|
+
if not ns.dry_run:
|
|
1505
|
+
print(f"Cleanup for run {ns.run_id}:")
|
|
1506
|
+
print(f" run_dir: {run_dir}")
|
|
1507
|
+
print(f" worktrees: {wts or disk_wts or 'none (no owned)'}")
|
|
1508
|
+
if wts or disk_wts:
|
|
1509
|
+
# Check dirty
|
|
1510
|
+
for wt in disk_wts if disk_wts else [Path(w["path"]) for w in wts if "path" in w]:
|
|
1511
|
+
wt_path = Path(wt) if isinstance(wt, str) else wt
|
|
1512
|
+
if wt_path.exists() and is_worktree_dirty(wt_path) and not ns.force:
|
|
1513
|
+
print(
|
|
1514
|
+
f"Worktree contains uncommitted changes. Toolkit will not remove it.\n\nPath:\n {wt_path}\n\nResolve or preserve the changes, then rerun cleanup with --force.",
|
|
1515
|
+
file=sys.stderr,
|
|
1516
|
+
)
|
|
1517
|
+
return 1
|
|
1518
|
+
if ns.dry_run:
|
|
1519
|
+
print("Dry-run: would remove worktrees but preserving due to --dry-run")
|
|
1520
|
+
return 0
|
|
1521
|
+
# Dry-run path
|
|
1522
|
+
if ns.dry_run:
|
|
1523
|
+
print(
|
|
1524
|
+
f"Would remove {len(disk_wts)} worktrees, keep branches (branches never deleted automatically)"
|
|
1525
|
+
)
|
|
1526
|
+
return 0
|
|
1527
|
+
# Actual removal: only Toolkit-owned under run_dir/worktrees
|
|
1528
|
+
for wt_path in disk_wts:
|
|
1529
|
+
if (
|
|
1530
|
+
not is_path_contained((run_dir / "worktrees").resolve(), wt_path.resolve())
|
|
1531
|
+
and wt_path.resolve() != (run_dir / "worktrees").resolve()
|
|
1532
|
+
):
|
|
1533
|
+
print(f"Skipping non-owned worktree: {wt_path}", file=sys.stderr)
|
|
1534
|
+
continue
|
|
1535
|
+
if wt_path.exists():
|
|
1536
|
+
if is_worktree_dirty(wt_path) and not ns.force:
|
|
1537
|
+
print(f"Worktree contains uncommitted changes.\nPath: {wt_path}", file=sys.stderr)
|
|
1538
|
+
return 1
|
|
1539
|
+
try:
|
|
1540
|
+
remove_worktree(repo, wt_path, force=ns.force)
|
|
1541
|
+
print(f"Removed worktree {wt_path}")
|
|
1542
|
+
except Exception as e:
|
|
1543
|
+
print(f"Failed to remove {wt_path}: {e}", file=sys.stderr)
|
|
1544
|
+
return 1
|
|
1545
|
+
# Do NOT delete branches by default (per spec)
|
|
1546
|
+
# Mark cleanup pending
|
|
1547
|
+
# Optionally remove run_dir if requested? Keep state for audit
|
|
1548
|
+
print(f"Cleanup completed for {ns.run_id} (branches preserved).")
|
|
1549
|
+
# Tear down UI backend surfaces (e.g. tmux sessions / socket files) so runs
|
|
1550
|
+
# do not leak tmux servers. Without this, `swarm start` accumulates
|
|
1551
|
+
# /tmp/tmux-<uid>/agent-toolkit-swarm-* sockets across invocations.
|
|
1552
|
+
backend_name = state.get("ui_backend", "auto")
|
|
1553
|
+
try:
|
|
1554
|
+
be = get_backend(backend_name)
|
|
1555
|
+
be.cleanup(run_dir, ns.run_id)
|
|
1556
|
+
except Exception as e:
|
|
1557
|
+
print(f"Backend cleanup failed (non-fatal): {e}", file=sys.stderr)
|
|
1558
|
+
try:
|
|
1559
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "cleanup_completed", "run_id": ns.run_id})
|
|
1560
|
+
except Exception:
|
|
1561
|
+
pass
|
|
1562
|
+
return 0
|
|
1563
|
+
|
|
1564
|
+
|
|
1565
|
+
def cmd_attach(args: list[str]) -> int:
|
|
1566
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm attach")
|
|
1567
|
+
parser.add_argument("run_id")
|
|
1568
|
+
parser.add_argument("--workspace", default=None, help="Repo path or OWNER/REPO")
|
|
1569
|
+
parser.add_argument("--repo", default=None, help="Alias for --workspace")
|
|
1570
|
+
parser.add_argument("-C", dest="workspace_C", default=None, help="Alias for --workspace")
|
|
1571
|
+
ns = parser.parse_args(args)
|
|
1572
|
+
workspace_flag = (
|
|
1573
|
+
getattr(ns, "workspace", None)
|
|
1574
|
+
or getattr(ns, "repo", None)
|
|
1575
|
+
or getattr(ns, "workspace_C", None)
|
|
1576
|
+
)
|
|
1577
|
+
from .config import find_run_dir_by_id
|
|
1578
|
+
|
|
1579
|
+
run_dir = find_run_dir_by_id(ns.run_id, workspace=workspace_flag)
|
|
1580
|
+
if run_dir is None:
|
|
1581
|
+
from .config import find_repo_root
|
|
1582
|
+
from .store import run_dir_for as _rdf3
|
|
1583
|
+
|
|
1584
|
+
repo = find_repo_root(workspace=workspace_flag)
|
|
1585
|
+
run_dir = _rdf3(repo, ns.run_id)
|
|
1586
|
+
if not run_dir.is_dir():
|
|
1587
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1588
|
+
state = read_state(run_dir) or {}
|
|
1589
|
+
backend_name = state.get("ui_backend", "auto")
|
|
1590
|
+
backend = get_backend(backend_name)
|
|
1591
|
+
backend.attach(ns.run_id)
|
|
1592
|
+
return 0
|
|
1593
|
+
|
|
1594
|
+
|
|
1595
|
+
def cmd_promote(args: list[str]) -> int:
|
|
1596
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm promote")
|
|
1597
|
+
parser.add_argument("run_id")
|
|
1598
|
+
parser.add_argument("--to", dest="to_recipe", required=True, choices=list_recipes())
|
|
1599
|
+
ns = parser.parse_args(args)
|
|
1600
|
+
repo = _need_repo()
|
|
1601
|
+
run_dir = run_dir_for(repo, ns.run_id)
|
|
1602
|
+
if not run_dir.is_dir():
|
|
1603
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1604
|
+
state = read_state(run_dir) or {}
|
|
1605
|
+
old_recipe = state.get("recipe")
|
|
1606
|
+
order = {"pair": 1, "team": 2, "full": 3}
|
|
1607
|
+
if order.get(ns.to_recipe, 0) <= order.get(old_recipe, 0):
|
|
1608
|
+
return _error(
|
|
1609
|
+
f"Cannot promote {old_recipe} -> {ns.to_recipe} (must increase: pair->team->full)"
|
|
1610
|
+
)
|
|
1611
|
+
recipe = get_recipe(ns.to_recipe)
|
|
1612
|
+
if not recipe:
|
|
1613
|
+
return _error(f"Unknown recipe {ns.to_recipe!r}")
|
|
1614
|
+
# Preserve artifacts, branches, budget, audit
|
|
1615
|
+
state["recipe"] = ns.to_recipe
|
|
1616
|
+
# Add missing roles as inactive
|
|
1617
|
+
for r in recipe.get("spec", {}).get("roles", {}):
|
|
1618
|
+
if r not in state.get("roles", {}):
|
|
1619
|
+
state["roles"][r] = "inactive"
|
|
1620
|
+
write_state(run_dir, state)
|
|
1621
|
+
append_trace(
|
|
1622
|
+
run_dir, {"ts": now_ts(), "kind": "recipe_promoted", "from": old_recipe, "to": ns.to_recipe}
|
|
1623
|
+
)
|
|
1624
|
+
# Add gates for new recipe if needed
|
|
1625
|
+
existing_gates = load_approvals(run_dir)
|
|
1626
|
+
new_gates = default_gates_for_recipe(recipe)
|
|
1627
|
+
# Merge without duplicates
|
|
1628
|
+
ids = {g["id"] for g in existing_gates}
|
|
1629
|
+
for g in new_gates:
|
|
1630
|
+
if g["id"] not in ids:
|
|
1631
|
+
existing_gates.append(g)
|
|
1632
|
+
save_approvals(run_dir, existing_gates)
|
|
1633
|
+
# Generate prompts for new roles — inject run_id
|
|
1634
|
+
for rname, rdef in recipe.get("spec", {}).get("roles", {}).items():
|
|
1635
|
+
if (run_dir / "prompts" / f"{rname}.md").exists():
|
|
1636
|
+
continue
|
|
1637
|
+
try:
|
|
1638
|
+
rdef_with_run = dict(rdef)
|
|
1639
|
+
rdef_with_run["_run_id"] = ns.run_id
|
|
1640
|
+
prompt, manifest = compose_role_prompt(
|
|
1641
|
+
recipe, rname, rdef_with_run, state.get("task"), None, rdef.get("skills")
|
|
1642
|
+
)
|
|
1643
|
+
(run_dir / "prompts" / f"{rname}.md").write_text(prompt, encoding="utf-8")
|
|
1644
|
+
(run_dir / "prompts" / f"{rname}.manifest.json").write_text(
|
|
1645
|
+
json.dumps(manifest, indent=2), encoding="utf-8"
|
|
1646
|
+
)
|
|
1647
|
+
generate_opencode_agent(
|
|
1648
|
+
run_dir,
|
|
1649
|
+
rname,
|
|
1650
|
+
rdef.get("persona", rname),
|
|
1651
|
+
rdef.get("policy", "read-only"),
|
|
1652
|
+
(
|
|
1653
|
+
resolve_model(
|
|
1654
|
+
state.get("model_profile", "balanced"),
|
|
1655
|
+
rdef.get("model_profile", "coding"),
|
|
1656
|
+
model_profiles=state.get("model_profiles"),
|
|
1657
|
+
)
|
|
1658
|
+
or "unknown/model"
|
|
1659
|
+
),
|
|
1660
|
+
ns.to_recipe,
|
|
1661
|
+
ns.run_id,
|
|
1662
|
+
rdef.get("worktree"),
|
|
1663
|
+
)
|
|
1664
|
+
except Exception:
|
|
1665
|
+
pass
|
|
1666
|
+
print(
|
|
1667
|
+
f"Promoted {ns.run_id}: {old_recipe} -> {ns.to_recipe} (run ID preserved, artifacts intact)"
|
|
1668
|
+
)
|
|
1669
|
+
return 0
|
|
1670
|
+
|
|
1671
|
+
|
|
1672
|
+
def cmd_activate(args: list[str]) -> int:
|
|
1673
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm activate")
|
|
1674
|
+
parser.add_argument("run_id")
|
|
1675
|
+
parser.add_argument("role")
|
|
1676
|
+
parser.add_argument(
|
|
1677
|
+
"--specialist",
|
|
1678
|
+
default=None,
|
|
1679
|
+
help="For hardener: security-reviewer|database-reviewer|performance-optimizer|typescript-reviewer",
|
|
1680
|
+
)
|
|
1681
|
+
ns = parser.parse_args(args)
|
|
1682
|
+
repo = _need_repo()
|
|
1683
|
+
run_dir = run_dir_for(repo, ns.run_id)
|
|
1684
|
+
if not run_dir.is_dir():
|
|
1685
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1686
|
+
state = read_state(run_dir) or {}
|
|
1687
|
+
if ns.role not in state.get("roles", {}):
|
|
1688
|
+
return _error(f"Role {ns.role!r} not in recipe {state.get('recipe')}")
|
|
1689
|
+
if state["roles"][ns.role] != "inactive":
|
|
1690
|
+
return _error(f"Role {ns.role} already active: {state['roles'][ns.role]}")
|
|
1691
|
+
state["roles"][ns.role] = "ready"
|
|
1692
|
+
# Create worktree if needed
|
|
1693
|
+
recipe = get_recipe(state.get("recipe", "pair"))
|
|
1694
|
+
rdef = (recipe.get("spec", {}).get("roles", {}) if recipe else {}).get(ns.role, {}).copy()
|
|
1695
|
+
if ns.role == "hardener" and ns.specialist:
|
|
1696
|
+
if ns.specialist not in (
|
|
1697
|
+
"security-reviewer",
|
|
1698
|
+
"database-reviewer",
|
|
1699
|
+
"performance-optimizer",
|
|
1700
|
+
"typescript-reviewer",
|
|
1701
|
+
):
|
|
1702
|
+
return _error(
|
|
1703
|
+
f"Invalid specialist {ns.specialist!r}",
|
|
1704
|
+
hint="Choose: security-reviewer, database-reviewer, performance-optimizer, typescript-reviewer",
|
|
1705
|
+
)
|
|
1706
|
+
rdef["persona"] = ns.specialist
|
|
1707
|
+
append_trace(
|
|
1708
|
+
run_dir,
|
|
1709
|
+
{
|
|
1710
|
+
"ts": now_ts(),
|
|
1711
|
+
"kind": "specialist_selected",
|
|
1712
|
+
"role": "hardener",
|
|
1713
|
+
"persona": ns.specialist,
|
|
1714
|
+
},
|
|
1715
|
+
)
|
|
1716
|
+
wt_name = rdef.get("worktree")
|
|
1717
|
+
if wt_name:
|
|
1718
|
+
try:
|
|
1719
|
+
info = create_worktree(repo, run_dir, ns.role, ns.run_id, "HEAD")
|
|
1720
|
+
wts = state.get("worktrees") or []
|
|
1721
|
+
wts.append(info)
|
|
1722
|
+
state["worktrees"] = wts
|
|
1723
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "worktree_created", "role": ns.role})
|
|
1724
|
+
except Exception as e:
|
|
1725
|
+
return _error(str(e))
|
|
1726
|
+
# Regenerate prompt/agent for specialist
|
|
1727
|
+
if ns.role == "hardener" and ns.specialist:
|
|
1728
|
+
try:
|
|
1729
|
+
model = (
|
|
1730
|
+
resolve_model(
|
|
1731
|
+
state.get("model_profile", "balanced"),
|
|
1732
|
+
rdef.get("model_profile", "hardening"),
|
|
1733
|
+
model_profiles=state.get("model_profiles"),
|
|
1734
|
+
)
|
|
1735
|
+
or "unknown/model"
|
|
1736
|
+
)
|
|
1737
|
+
generate_opencode_agent(
|
|
1738
|
+
run_dir,
|
|
1739
|
+
"hardener",
|
|
1740
|
+
ns.specialist,
|
|
1741
|
+
rdef.get("policy", "reviewer-writer"),
|
|
1742
|
+
model,
|
|
1743
|
+
state.get("recipe", "full"),
|
|
1744
|
+
ns.run_id,
|
|
1745
|
+
rdef.get("worktree"),
|
|
1746
|
+
)
|
|
1747
|
+
rdef_with_run2 = dict(rdef)
|
|
1748
|
+
rdef_with_run2["_run_id"] = ns.run_id
|
|
1749
|
+
prompt, manifest = compose_role_prompt(
|
|
1750
|
+
get_recipe(state.get("recipe", "full")) or {},
|
|
1751
|
+
"hardener",
|
|
1752
|
+
rdef_with_run2,
|
|
1753
|
+
state.get("task"),
|
|
1754
|
+
None,
|
|
1755
|
+
rdef.get("skills"),
|
|
1756
|
+
)
|
|
1757
|
+
(run_dir / "prompts" / "hardener.md").write_text(prompt, encoding="utf-8")
|
|
1758
|
+
(run_dir / "prompts" / "hardener.manifest.json").write_text(
|
|
1759
|
+
json.dumps(manifest, indent=2), encoding="utf-8"
|
|
1760
|
+
)
|
|
1761
|
+
except Exception:
|
|
1762
|
+
pass
|
|
1763
|
+
write_state(run_dir, state)
|
|
1764
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "role_activated", "role": ns.role})
|
|
1765
|
+
print(
|
|
1766
|
+
f"Activated {ns.role} in {ns.run_id}"
|
|
1767
|
+
+ (f" specialist={ns.specialist}" if ns.specialist else "")
|
|
1768
|
+
)
|
|
1769
|
+
return 0
|
|
1770
|
+
|
|
1771
|
+
|
|
1772
|
+
def cmd_deactivate(args: list[str]) -> int:
|
|
1773
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm deactivate")
|
|
1774
|
+
parser.add_argument("run_id")
|
|
1775
|
+
parser.add_argument("role")
|
|
1776
|
+
ns = parser.parse_args(args)
|
|
1777
|
+
repo = _need_repo()
|
|
1778
|
+
run_dir = run_dir_for(repo, ns.run_id)
|
|
1779
|
+
if not run_dir.is_dir():
|
|
1780
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1781
|
+
state = read_state(run_dir) or {}
|
|
1782
|
+
if ns.role not in state.get("roles", {}):
|
|
1783
|
+
return _error(f"Role {ns.role!r} not in recipe")
|
|
1784
|
+
state["roles"][ns.role] = "inactive"
|
|
1785
|
+
write_state(run_dir, state)
|
|
1786
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "role_deactivated", "role": ns.role})
|
|
1787
|
+
print(f"Deactivated {ns.role} in {ns.run_id}")
|
|
1788
|
+
return 0
|
|
1789
|
+
|
|
1790
|
+
|
|
1791
|
+
def cmd_approvals(args: list[str]) -> int:
|
|
1792
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm approvals")
|
|
1793
|
+
parser.add_argument("run_id")
|
|
1794
|
+
parser.add_argument("--json", action="store_true")
|
|
1795
|
+
ns = parser.parse_args(args)
|
|
1796
|
+
repo = _need_repo()
|
|
1797
|
+
run_dir = run_dir_for(repo, ns.run_id)
|
|
1798
|
+
if not run_dir.is_dir():
|
|
1799
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1800
|
+
gates = load_approvals(run_dir)
|
|
1801
|
+
if ns.json:
|
|
1802
|
+
return _json_out(gates)
|
|
1803
|
+
if not gates:
|
|
1804
|
+
print("No approval gates.")
|
|
1805
|
+
return 0
|
|
1806
|
+
for g in gates:
|
|
1807
|
+
status = (
|
|
1808
|
+
"approved" if g.get("approved") else ("rejected" if g.get("rejected") else "pending")
|
|
1809
|
+
)
|
|
1810
|
+
print(f"{g['id']:15} {status:10} {g.get('description', '')[:80]}")
|
|
1811
|
+
return 0
|
|
1812
|
+
|
|
1813
|
+
|
|
1814
|
+
def cmd_approve(args: list[str]) -> int:
|
|
1815
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm approve")
|
|
1816
|
+
parser.add_argument("run_id")
|
|
1817
|
+
parser.add_argument("gate_id")
|
|
1818
|
+
ns = parser.parse_args(args)
|
|
1819
|
+
repo = _need_repo()
|
|
1820
|
+
run_dir = run_dir_for(repo, ns.run_id)
|
|
1821
|
+
if not run_dir.is_dir():
|
|
1822
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1823
|
+
g = approve_gate(run_dir, ns.gate_id)
|
|
1824
|
+
if not g:
|
|
1825
|
+
return _error(
|
|
1826
|
+
f"Gate not found: {ns.gate_id}",
|
|
1827
|
+
hint=f"Available: {', '.join(x['id'] for x in load_approvals(run_dir))}",
|
|
1828
|
+
)
|
|
1829
|
+
# If plan gate approved, transition to running
|
|
1830
|
+
if ns.gate_id == "plan":
|
|
1831
|
+
state = read_state(run_dir) or {}
|
|
1832
|
+
if state.get("run_state") == "awaiting_plan_approval":
|
|
1833
|
+
state["run_state"] = "running"
|
|
1834
|
+
write_state(run_dir, state)
|
|
1835
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "approval_granted", "gate": "plan"})
|
|
1836
|
+
print(f"Approved {ns.gate_id} for {ns.run_id}")
|
|
1837
|
+
return 0
|
|
1838
|
+
|
|
1839
|
+
|
|
1840
|
+
def cmd_reject(args: list[str]) -> int:
|
|
1841
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm reject")
|
|
1842
|
+
parser.add_argument("run_id")
|
|
1843
|
+
parser.add_argument("gate_id")
|
|
1844
|
+
parser.add_argument("--reason", required=True)
|
|
1845
|
+
ns = parser.parse_args(args)
|
|
1846
|
+
repo = _need_repo()
|
|
1847
|
+
run_dir = run_dir_for(repo, ns.run_id)
|
|
1848
|
+
if not run_dir.is_dir():
|
|
1849
|
+
return _error(f"Run not found: {ns.run_id}")
|
|
1850
|
+
g = reject_gate(run_dir, ns.gate_id, ns.reason)
|
|
1851
|
+
if not g:
|
|
1852
|
+
return _error(f"Gate not found: {ns.gate_id}")
|
|
1853
|
+
print(f"Rejected {ns.gate_id} for {ns.run_id}: {ns.reason}")
|
|
1854
|
+
return 0
|
|
1855
|
+
|
|
1856
|
+
|
|
1857
|
+
def cmd_handoff_create(args: list[str]) -> int:
|
|
1858
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm handoff create")
|
|
1859
|
+
parser.add_argument(
|
|
1860
|
+
"--type",
|
|
1861
|
+
dest="htype",
|
|
1862
|
+
required=True,
|
|
1863
|
+
choices=["artifact", "commit", "feedback", "decision_request"],
|
|
1864
|
+
)
|
|
1865
|
+
parser.add_argument("--from", dest="from_role", required=True)
|
|
1866
|
+
parser.add_argument("--to", dest="to_role", required=True)
|
|
1867
|
+
parser.add_argument("--priority", type=int, default=10)
|
|
1868
|
+
parser.add_argument("--artifact", default=None)
|
|
1869
|
+
parser.add_argument("--commit", default=None)
|
|
1870
|
+
parser.add_argument("--branch", default=None)
|
|
1871
|
+
parser.add_argument("--blocking", action="store_true")
|
|
1872
|
+
parser.add_argument("--run-id", default=None)
|
|
1873
|
+
ns = parser.parse_args(args)
|
|
1874
|
+
repo = _need_repo()
|
|
1875
|
+
# Resolve run_dir: from --run-id or latest run or env
|
|
1876
|
+
run_id = ns.run_id or os.environ.get("AGENT_TOOLKIT_SWARM_RUN_ID")
|
|
1877
|
+
if not run_id:
|
|
1878
|
+
# Try to extract run_id from worktree path (e.g., .../.agent-toolkit/swarm/runs/<run_id>/worktrees/<role>)
|
|
1879
|
+
try:
|
|
1880
|
+
cwd = Path.cwd().resolve()
|
|
1881
|
+
parts = cwd.parts
|
|
1882
|
+
if ".agent-toolkit" in parts:
|
|
1883
|
+
idx = parts.index(".agent-toolkit")
|
|
1884
|
+
# Expect .../.agent-toolkit/swarm/runs/<run_id>/...
|
|
1885
|
+
if len(parts) > idx + 3 and parts[idx + 1] == "swarm" and parts[idx + 2] == "runs":
|
|
1886
|
+
candidate = parts[idx + 3]
|
|
1887
|
+
# Basic validation: looks like run_id (contains T and Z and -)
|
|
1888
|
+
if "T" in candidate and "Z" in candidate and "-" in candidate:
|
|
1889
|
+
# Verify it exists
|
|
1890
|
+
maybe_dir = (
|
|
1891
|
+
run_dir_for(repo, candidate) if (repo / ".git").exists() else None
|
|
1892
|
+
)
|
|
1893
|
+
# Also try via direct path search
|
|
1894
|
+
if maybe_dir and maybe_dir.is_dir():
|
|
1895
|
+
run_id = candidate
|
|
1896
|
+
else:
|
|
1897
|
+
# Search via config helper
|
|
1898
|
+
from .config import find_run_dir_by_id
|
|
1899
|
+
|
|
1900
|
+
if find_run_dir_by_id(candidate):
|
|
1901
|
+
run_id = candidate
|
|
1902
|
+
except Exception:
|
|
1903
|
+
pass
|
|
1904
|
+
if not run_id:
|
|
1905
|
+
# Pick latest run
|
|
1906
|
+
runs = list_runs(repo)
|
|
1907
|
+
if not runs:
|
|
1908
|
+
# Last fallback: search via find_run_dir_by_id from cwd
|
|
1909
|
+
try:
|
|
1910
|
+
cwd = Path.cwd().resolve()
|
|
1911
|
+
parts = cwd.parts
|
|
1912
|
+
if ".agent-toolkit" in parts:
|
|
1913
|
+
idx = parts.index(".agent-toolkit")
|
|
1914
|
+
if len(parts) > idx + 3:
|
|
1915
|
+
run_id = parts[idx + 3]
|
|
1916
|
+
from .config import find_run_dir_by_id
|
|
1917
|
+
|
|
1918
|
+
rd = find_run_dir_by_id(run_id)
|
|
1919
|
+
if rd and rd.is_dir():
|
|
1920
|
+
repo = rd.parent.parent.parent # .agent-toolkit/swarm/runs -> repo
|
|
1921
|
+
else:
|
|
1922
|
+
run_id = None
|
|
1923
|
+
except Exception:
|
|
1924
|
+
pass
|
|
1925
|
+
if not run_id:
|
|
1926
|
+
runs = list_runs(repo)
|
|
1927
|
+
if not runs:
|
|
1928
|
+
return _error("No run found; specify --run-id")
|
|
1929
|
+
run_id = sorted(runs, key=lambda p: p.stat().st_mtime, reverse=True)[0].name
|
|
1930
|
+
run_dir = run_dir_for(repo, run_id)
|
|
1931
|
+
# Fallback: if run_dir not found, try global search
|
|
1932
|
+
if not run_dir.is_dir():
|
|
1933
|
+
from .config import find_run_dir_by_id
|
|
1934
|
+
|
|
1935
|
+
found = find_run_dir_by_id(run_id)
|
|
1936
|
+
if found and found.is_dir():
|
|
1937
|
+
run_dir = found
|
|
1938
|
+
# Update repo to parent of .agent-toolkit
|
|
1939
|
+
try:
|
|
1940
|
+
repo = found.parent.parent.parent
|
|
1941
|
+
except Exception:
|
|
1942
|
+
pass
|
|
1943
|
+
if not run_dir.is_dir():
|
|
1944
|
+
return _error(f"Run not found: {run_id}")
|
|
1945
|
+
if not run_dir.is_dir():
|
|
1946
|
+
return _error(f"Run not found: {run_id}")
|
|
1947
|
+
state = read_state(run_dir) or {}
|
|
1948
|
+
roles = set(state.get("roles", {}).keys()) | {"human"}
|
|
1949
|
+
data: dict[str, Any] = {
|
|
1950
|
+
"version": 1,
|
|
1951
|
+
"type": ns.htype,
|
|
1952
|
+
"from": ns.from_role,
|
|
1953
|
+
"to": ns.to_role,
|
|
1954
|
+
"priority": ns.priority,
|
|
1955
|
+
}
|
|
1956
|
+
if ns.artifact:
|
|
1957
|
+
# Enforce size limit 1MB
|
|
1958
|
+
art_path = (
|
|
1959
|
+
run_dir / ns.artifact if not Path(ns.artifact).is_absolute() else Path(ns.artifact)
|
|
1960
|
+
)
|
|
1961
|
+
# Validate contained
|
|
1962
|
+
try:
|
|
1963
|
+
validate_artifact_path(run_dir, ns.artifact)
|
|
1964
|
+
except ValueError as e:
|
|
1965
|
+
return _error(str(e))
|
|
1966
|
+
if art_path.is_file() and art_path.stat().st_size > 1_000_000:
|
|
1967
|
+
return _error(f"Artifact too large ({art_path.stat().st_size} bytes), max 1MB")
|
|
1968
|
+
data["artifact"] = ns.artifact
|
|
1969
|
+
if ns.htype == "commit":
|
|
1970
|
+
if not ns.commit or not ns.branch:
|
|
1971
|
+
return _error("commit handoff requires --commit and --branch")
|
|
1972
|
+
# Resolve sha
|
|
1973
|
+
sha = ns.commit.strip().lower()
|
|
1974
|
+
if not re.match(r"^[0-9a-f]{40}$", sha):
|
|
1975
|
+
# Try resolve abbrev
|
|
1976
|
+
from .handoff import resolve_sha
|
|
1977
|
+
|
|
1978
|
+
resolved = resolve_sha(repo, sha)
|
|
1979
|
+
if not resolved:
|
|
1980
|
+
return _error(f"Invalid or ambiguous commit SHA: {ns.commit!r}")
|
|
1981
|
+
sha = resolved
|
|
1982
|
+
if not validate_commit_exists(repo, sha):
|
|
1983
|
+
return _error(f"Commit not found: {sha}")
|
|
1984
|
+
data["commit"] = sha
|
|
1985
|
+
data["branch"] = ns.branch
|
|
1986
|
+
if ns.htype == "feedback":
|
|
1987
|
+
data["blocking"] = bool(ns.blocking)
|
|
1988
|
+
if data["blocking"]:
|
|
1989
|
+
# Enforce max_role_round_trips (default 2)
|
|
1990
|
+
try:
|
|
1991
|
+
budget = (read_state(run_dir) or {}).get("budget", {}) or {}
|
|
1992
|
+
limit = int(budget.get("max_role_round_trips", 2))
|
|
1993
|
+
# Count existing blocking feedback reviewer->implementer
|
|
1994
|
+
all_states = ["queued", "active", "completed"]
|
|
1995
|
+
count = 0
|
|
1996
|
+
for st in all_states:
|
|
1997
|
+
for h in list_handoffs(run_dir, st):
|
|
1998
|
+
if (
|
|
1999
|
+
h.get("type") == "feedback"
|
|
2000
|
+
and h.get("blocking")
|
|
2001
|
+
and h.get("from") == ns.from_role
|
|
2002
|
+
and h.get("to") == ns.to_role
|
|
2003
|
+
):
|
|
2004
|
+
count += 1
|
|
2005
|
+
if count >= limit:
|
|
2006
|
+
return _error(
|
|
2007
|
+
f"The reviewer returned blocking feedback {count} times. The configured round-trip limit ({limit}) has been reached.\n\nInspect:\n agent-toolkit swarm artifacts {run_id}\n\nChoose:\n resume with a higher limit\n escalate to team\n request human intervention",
|
|
2008
|
+
)
|
|
2009
|
+
except Exception:
|
|
2010
|
+
pass
|
|
2011
|
+
# Validate
|
|
2012
|
+
errs = validate_handoff(data, run_dir, roles)
|
|
2013
|
+
if errs:
|
|
2014
|
+
return _error("Handoff validation failed: " + "; ".join(errs))
|
|
2015
|
+
dest = write_handoff_outbox(run_dir, data)
|
|
2016
|
+
append_trace(
|
|
2017
|
+
run_dir,
|
|
2018
|
+
{
|
|
2019
|
+
"ts": now_ts(),
|
|
2020
|
+
"kind": "handoff_created",
|
|
2021
|
+
"type": ns.htype,
|
|
2022
|
+
"from": ns.from_role,
|
|
2023
|
+
"to": ns.to_role,
|
|
2024
|
+
"handoff_id": data.get("handoff_id"),
|
|
2025
|
+
},
|
|
2026
|
+
)
|
|
2027
|
+
# Move to queued (simulate daemon)
|
|
2028
|
+
hid = dest.stem
|
|
2029
|
+
move_handoff(run_dir, hid, "outbox", "queued")
|
|
2030
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "handoff_queued", "handoff_id": hid})
|
|
2031
|
+
# Auto-complete incoming active handoffs for the sender (e.g., reviewer had active implementer->reviewer, now reviewer->integrator should close it)
|
|
2032
|
+
try:
|
|
2033
|
+
active = list_handoffs(run_dir, "active")
|
|
2034
|
+
for h in list(active):
|
|
2035
|
+
if h.get("to") == ns.from_role:
|
|
2036
|
+
hid2 = h.get("handoff_id")
|
|
2037
|
+
if hid2:
|
|
2038
|
+
try:
|
|
2039
|
+
move_handoff(run_dir, hid2, "active", "completed")
|
|
2040
|
+
append_trace(
|
|
2041
|
+
run_dir,
|
|
2042
|
+
{
|
|
2043
|
+
"ts": now_ts(),
|
|
2044
|
+
"kind": "handoff_completed",
|
|
2045
|
+
"handoff_id": hid2,
|
|
2046
|
+
"auto": True,
|
|
2047
|
+
"trigger": f"handoff_create:{hid}",
|
|
2048
|
+
},
|
|
2049
|
+
)
|
|
2050
|
+
except Exception:
|
|
2051
|
+
pass
|
|
2052
|
+
except Exception:
|
|
2053
|
+
pass
|
|
2054
|
+
print(f"Handoff {hid} created: {ns.from_role} -> {ns.to_role} ({ns.htype})")
|
|
2055
|
+
# Auto-provision next role if lazy (create worktree + tmux window + start agent)
|
|
2056
|
+
try:
|
|
2057
|
+
state = read_state(run_dir) or {}
|
|
2058
|
+
roles = state.get("roles", {})
|
|
2059
|
+
worktrees = state.get("worktrees", []) or []
|
|
2060
|
+
has_wt = any(w.get("role") == ns.to_role for w in worktrees)
|
|
2061
|
+
if not has_wt and ns.to_role in roles:
|
|
2062
|
+
# Resolve runner/backend from state
|
|
2063
|
+
runner_name = state.get("runner") or "claude"
|
|
2064
|
+
backend_name = state.get("ui_backend", "tmux")
|
|
2065
|
+
backend = get_backend(backend_name)
|
|
2066
|
+
# Create worktree for target role
|
|
2067
|
+
try:
|
|
2068
|
+
info = create_worktree(
|
|
2069
|
+
repo, run_dir, ns.to_role, run_id, state.get("base_ref", "HEAD")
|
|
2070
|
+
)
|
|
2071
|
+
info["role"] = ns.to_role
|
|
2072
|
+
# Copy opencode agent if present
|
|
2073
|
+
try:
|
|
2074
|
+
_agent_src = run_dir / "runner" / "opencode" / "agents" / f"{ns.to_role}.md"
|
|
2075
|
+
if _agent_src.exists():
|
|
2076
|
+
_wt_agents = Path(info["path"]) / ".opencode" / "agents"
|
|
2077
|
+
_wt_agents.mkdir(parents=True, exist_ok=True)
|
|
2078
|
+
import shutil as _shutil
|
|
2079
|
+
|
|
2080
|
+
_shutil.copy2(_agent_src, _wt_agents / f"{ns.to_role}.md")
|
|
2081
|
+
_prompt_src = run_dir / "prompts" / f"{ns.to_role}.md"
|
|
2082
|
+
if _prompt_src.exists():
|
|
2083
|
+
_shutil.copy2(
|
|
2084
|
+
_prompt_src,
|
|
2085
|
+
Path(info["path"]) / f".agent-toolkit-prompt-{ns.to_role}.md",
|
|
2086
|
+
)
|
|
2087
|
+
except Exception:
|
|
2088
|
+
pass
|
|
2089
|
+
worktrees.append(info)
|
|
2090
|
+
state["worktrees"] = worktrees
|
|
2091
|
+
state["roles"][ns.to_role] = "ready"
|
|
2092
|
+
write_state(run_dir, state)
|
|
2093
|
+
append_trace(
|
|
2094
|
+
run_dir,
|
|
2095
|
+
{
|
|
2096
|
+
"ts": now_ts(),
|
|
2097
|
+
"kind": "worktree_created",
|
|
2098
|
+
"role": ns.to_role,
|
|
2099
|
+
"path": info["path"],
|
|
2100
|
+
"branch": info["branch"],
|
|
2101
|
+
},
|
|
2102
|
+
)
|
|
2103
|
+
append_trace(
|
|
2104
|
+
run_dir, {"ts": now_ts(), "kind": "role_activated", "role": ns.to_role}
|
|
2105
|
+
)
|
|
2106
|
+
# Create tmux/herdr surface and start agent
|
|
2107
|
+
try:
|
|
2108
|
+
backend.create_role_surface(run_dir, run_id, ns.to_role)
|
|
2109
|
+
import shlex as _shlex2
|
|
2110
|
+
|
|
2111
|
+
worktree_path = info["path"]
|
|
2112
|
+
prompt_file = run_dir / "prompts" / f"{ns.to_role}.md"
|
|
2113
|
+
prompt_cat = (
|
|
2114
|
+
f"$(cat {_shlex2.quote(str(prompt_file))})" if prompt_file.exists() else ""
|
|
2115
|
+
)
|
|
2116
|
+
swarm_env = f"export AGENT_TOOLKIT_SWARM_RUN_ID={_shlex2.quote(run_id)} && export AGENT_TOOLKIT_SWARM_RUN_DIR={_shlex2.quote(str(run_dir))} && export AGENT_TOOLKIT_SWARM_REPO={_shlex2.quote(str(repo))} && export SWARMFORGE_ROLE={_shlex2.quote(ns.to_role)} &&"
|
|
2117
|
+
cmd = None
|
|
2118
|
+
if runner_name == "opencode":
|
|
2119
|
+
if prompt_cat:
|
|
2120
|
+
cmd = [
|
|
2121
|
+
_user_shell(),
|
|
2122
|
+
"-lc",
|
|
2123
|
+
f'{swarm_env} cd {_shlex2.quote(str(worktree_path))} && exec opencode --agent {_shlex2.quote(ns.to_role)} --prompt "'
|
|
2124
|
+
+ prompt_cat
|
|
2125
|
+
+ '"',
|
|
2126
|
+
]
|
|
2127
|
+
else:
|
|
2128
|
+
cmd = [
|
|
2129
|
+
_user_shell(),
|
|
2130
|
+
"-lc",
|
|
2131
|
+
f"{swarm_env} cd {_shlex2.quote(str(worktree_path))} && exec opencode --agent {_shlex2.quote(ns.to_role)}",
|
|
2132
|
+
]
|
|
2133
|
+
elif runner_name == "claude":
|
|
2134
|
+
if prompt_cat:
|
|
2135
|
+
cmd = [
|
|
2136
|
+
_user_shell(),
|
|
2137
|
+
"-lc",
|
|
2138
|
+
f'{swarm_env} cd {_shlex2.quote(str(worktree_path))} && exec claude --dangerously-skip-permissions --append-system-prompt-file {_shlex2.quote(str(prompt_file))} "'
|
|
2139
|
+
+ prompt_cat
|
|
2140
|
+
+ '"',
|
|
2141
|
+
]
|
|
2142
|
+
else:
|
|
2143
|
+
cmd = [
|
|
2144
|
+
_user_shell(),
|
|
2145
|
+
"-lc",
|
|
2146
|
+
f"{swarm_env} cd {_shlex2.quote(str(worktree_path))} && exec claude --dangerously-skip-permissions",
|
|
2147
|
+
]
|
|
2148
|
+
elif runner_name == "codex":
|
|
2149
|
+
if prompt_cat:
|
|
2150
|
+
cmd = [
|
|
2151
|
+
_user_shell(),
|
|
2152
|
+
"-lc",
|
|
2153
|
+
f'{swarm_env} cd {_shlex2.quote(str(worktree_path))} && exec codex -C {_shlex2.quote(str(worktree_path))} "'
|
|
2154
|
+
+ prompt_cat
|
|
2155
|
+
+ '"',
|
|
2156
|
+
]
|
|
2157
|
+
else:
|
|
2158
|
+
cmd = [
|
|
2159
|
+
_user_shell(),
|
|
2160
|
+
"-lc",
|
|
2161
|
+
f"{swarm_env} cd {_shlex2.quote(str(worktree_path))} && exec codex",
|
|
2162
|
+
]
|
|
2163
|
+
elif runner_name == "cursor":
|
|
2164
|
+
if prompt_cat:
|
|
2165
|
+
cmd = [
|
|
2166
|
+
_user_shell(),
|
|
2167
|
+
"-lc",
|
|
2168
|
+
f'{swarm_env} cd {_shlex2.quote(str(worktree_path))} && exec cursor-agent "'
|
|
2169
|
+
+ prompt_cat
|
|
2170
|
+
+ '"',
|
|
2171
|
+
]
|
|
2172
|
+
else:
|
|
2173
|
+
cmd = [
|
|
2174
|
+
_user_shell(),
|
|
2175
|
+
"-lc",
|
|
2176
|
+
f"{swarm_env} cd {_shlex2.quote(str(worktree_path))} && exec cursor-agent",
|
|
2177
|
+
]
|
|
2178
|
+
if cmd:
|
|
2179
|
+
backend.start_agent(run_dir, run_id, ns.to_role, cmd)
|
|
2180
|
+
append_trace(
|
|
2181
|
+
run_dir,
|
|
2182
|
+
{
|
|
2183
|
+
"ts": now_ts(),
|
|
2184
|
+
"kind": "agent_started",
|
|
2185
|
+
"role": ns.to_role,
|
|
2186
|
+
"runner": runner_name,
|
|
2187
|
+
"cmd": cmd,
|
|
2188
|
+
"trigger": "handoff_auto_provision",
|
|
2189
|
+
},
|
|
2190
|
+
)
|
|
2191
|
+
except Exception as e:
|
|
2192
|
+
append_trace(
|
|
2193
|
+
run_dir,
|
|
2194
|
+
{
|
|
2195
|
+
"ts": now_ts(),
|
|
2196
|
+
"kind": "agent_start_failed",
|
|
2197
|
+
"role": ns.to_role,
|
|
2198
|
+
"error": str(e)[:500],
|
|
2199
|
+
},
|
|
2200
|
+
)
|
|
2201
|
+
except Exception as e:
|
|
2202
|
+
append_trace(
|
|
2203
|
+
run_dir,
|
|
2204
|
+
{
|
|
2205
|
+
"ts": now_ts(),
|
|
2206
|
+
"kind": "worktree_failed",
|
|
2207
|
+
"role": ns.to_role,
|
|
2208
|
+
"error": str(e)[:500],
|
|
2209
|
+
},
|
|
2210
|
+
)
|
|
2211
|
+
except Exception:
|
|
2212
|
+
pass
|
|
2213
|
+
return 0
|
|
2214
|
+
|
|
2215
|
+
|
|
2216
|
+
def cmd_task(args: list[str]) -> int:
|
|
2217
|
+
if not args:
|
|
2218
|
+
print("Usage: agent-toolkit swarm task <next|complete> [options]", file=sys.stderr)
|
|
2219
|
+
return 2
|
|
2220
|
+
sub = args[0]
|
|
2221
|
+
rest = args[1:]
|
|
2222
|
+
if sub == "next":
|
|
2223
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm task next")
|
|
2224
|
+
parser.add_argument("--role", required=True)
|
|
2225
|
+
parser.add_argument("--run-id", default=None)
|
|
2226
|
+
parser.add_argument("--json", action="store_true")
|
|
2227
|
+
ns = parser.parse_args(rest)
|
|
2228
|
+
repo = _need_repo()
|
|
2229
|
+
run_id = ns.run_id or os.environ.get("AGENT_TOOLKIT_SWARM_RUN_ID")
|
|
2230
|
+
if not run_id:
|
|
2231
|
+
runs = list_runs(repo)
|
|
2232
|
+
if not runs:
|
|
2233
|
+
return _error("No run found")
|
|
2234
|
+
run_id = sorted(runs, key=lambda p: p.stat().st_mtime, reverse=True)[0].name
|
|
2235
|
+
run_dir = run_dir_for(repo, run_id)
|
|
2236
|
+
# Find tasks for role in queued
|
|
2237
|
+
items = list_handoffs(run_dir, "queued")
|
|
2238
|
+
# Filter to_role == role
|
|
2239
|
+
candidates = [x for x in items if x.get("to") == ns.role]
|
|
2240
|
+
# Sort by priority (lower first? spec says 00 is high)
|
|
2241
|
+
candidates.sort(key=lambda x: x.get("priority", 10))
|
|
2242
|
+
# Enforce at most one active per task-mode
|
|
2243
|
+
active = list_handoffs(run_dir, "active")
|
|
2244
|
+
task_mode_active = [x for x in active if x.get("to") == ns.role]
|
|
2245
|
+
if task_mode_active:
|
|
2246
|
+
# Check receive_mode
|
|
2247
|
+
recipe_name = (read_state(run_dir) or {}).get("recipe", "pair")
|
|
2248
|
+
recipe = get_recipe(recipe_name) or {}
|
|
2249
|
+
rdef = recipe.get("spec", {}).get("roles", {}).get(ns.role, {})
|
|
2250
|
+
if rdef.get("receive_mode") != "batch":
|
|
2251
|
+
return _error(
|
|
2252
|
+
f"Role {ns.role} already has active task (at most one active task per task-mode role)"
|
|
2253
|
+
)
|
|
2254
|
+
if not candidates:
|
|
2255
|
+
if ns.json:
|
|
2256
|
+
return _json_out({"task": None, "message": "No queued tasks"})
|
|
2257
|
+
print("No queued tasks")
|
|
2258
|
+
return 0
|
|
2259
|
+
task = candidates[0]
|
|
2260
|
+
hid = task.get("handoff_id")
|
|
2261
|
+
if hid:
|
|
2262
|
+
move_handoff(run_dir, hid, "queued", "active")
|
|
2263
|
+
append_trace(
|
|
2264
|
+
run_dir,
|
|
2265
|
+
{"ts": now_ts(), "kind": "handoff_accepted", "handoff_id": hid, "role": ns.role},
|
|
2266
|
+
)
|
|
2267
|
+
if ns.json:
|
|
2268
|
+
return _json_out(task)
|
|
2269
|
+
print(json.dumps(task, indent=2))
|
|
2270
|
+
return 0
|
|
2271
|
+
elif sub == "complete":
|
|
2272
|
+
parser = argparse.ArgumentParser(prog="agent-toolkit swarm task complete")
|
|
2273
|
+
parser.add_argument("--handoff", required=True)
|
|
2274
|
+
parser.add_argument("--run-id", default=None)
|
|
2275
|
+
ns = parser.parse_args(rest)
|
|
2276
|
+
repo = _need_repo()
|
|
2277
|
+
run_id = ns.run_id or os.environ.get("AGENT_TOOLKIT_SWARM_RUN_ID")
|
|
2278
|
+
if not run_id:
|
|
2279
|
+
runs = list_runs(repo)
|
|
2280
|
+
if not runs:
|
|
2281
|
+
return _error("No run found")
|
|
2282
|
+
run_id = sorted(runs, key=lambda p: p.stat().st_mtime, reverse=True)[0].name
|
|
2283
|
+
run_dir = run_dir_for(repo, run_id)
|
|
2284
|
+
hid = ns.handoff
|
|
2285
|
+
# Move active -> completed
|
|
2286
|
+
src = run_dir / "handoffs" / "active" / f"{hid}.json"
|
|
2287
|
+
if not src.is_file():
|
|
2288
|
+
# Also check queued
|
|
2289
|
+
src2 = run_dir / "handoffs" / "queued" / f"{hid}.json"
|
|
2290
|
+
if src2.is_file():
|
|
2291
|
+
move_handoff(run_dir, hid, "queued", "completed")
|
|
2292
|
+
else:
|
|
2293
|
+
return _error(f"Handoff not active: {hid}")
|
|
2294
|
+
else:
|
|
2295
|
+
move_handoff(run_dir, hid, "active", "completed")
|
|
2296
|
+
append_trace(run_dir, {"ts": now_ts(), "kind": "handoff_completed", "handoff_id": hid})
|
|
2297
|
+
print(f"Completed handoff {hid}")
|
|
2298
|
+
return 0
|
|
2299
|
+
else:
|
|
2300
|
+
return _error(f"Unknown task subcommand: {sub}")
|
|
2301
|
+
|
|
2302
|
+
|
|
2303
|
+
def main(argv: list[str] | None = None) -> int:
|
|
2304
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
2305
|
+
# Top-level swarm help
|
|
2306
|
+
if not argv or argv[0] in ("-h", "--help", "help"):
|
|
2307
|
+
print(_SWARM_HELP)
|
|
2308
|
+
return 0
|
|
2309
|
+
cmd = argv[0]
|
|
2310
|
+
rest = argv[1:]
|
|
2311
|
+
# Support recipes subcommand alias: `swarm recipes` and `swarm recipe show`
|
|
2312
|
+
if cmd == "recipes":
|
|
2313
|
+
return cmd_recipes(rest)
|
|
2314
|
+
if cmd == "recipe":
|
|
2315
|
+
if not rest or rest[0] not in ("show", "list"):
|
|
2316
|
+
# if `swarm recipe pair` treat as show
|
|
2317
|
+
if rest and rest[0] in list_recipes():
|
|
2318
|
+
return cmd_recipe_show(rest)
|
|
2319
|
+
print("Usage: agent-toolkit swarm recipe show <name>", file=sys.stderr)
|
|
2320
|
+
return 2
|
|
2321
|
+
if rest[0] == "show":
|
|
2322
|
+
return cmd_recipe_show(rest[1:])
|
|
2323
|
+
if rest[0] == "list":
|
|
2324
|
+
return cmd_recipes(rest[1:])
|
|
2325
|
+
if cmd == "runners":
|
|
2326
|
+
return cmd_runners(rest)
|
|
2327
|
+
if cmd == "models":
|
|
2328
|
+
return cmd_models(rest)
|
|
2329
|
+
if cmd == "backends":
|
|
2330
|
+
return cmd_backends(rest)
|
|
2331
|
+
if cmd == "doctor":
|
|
2332
|
+
return cmd_doctor(rest)
|
|
2333
|
+
if cmd == "init":
|
|
2334
|
+
return cmd_init(rest)
|
|
2335
|
+
if cmd == "plan":
|
|
2336
|
+
return cmd_plan(rest)
|
|
2337
|
+
if cmd == "start":
|
|
2338
|
+
return cmd_start(rest)
|
|
2339
|
+
if cmd in ("list", "ls"):
|
|
2340
|
+
return cmd_list(rest)
|
|
2341
|
+
if cmd == "status":
|
|
2342
|
+
return cmd_status(rest)
|
|
2343
|
+
if cmd == "watch":
|
|
2344
|
+
return cmd_watch(rest)
|
|
2345
|
+
if cmd == "report":
|
|
2346
|
+
return cmd_report(rest)
|
|
2347
|
+
if cmd == "artifacts":
|
|
2348
|
+
return cmd_artifacts(rest)
|
|
2349
|
+
if cmd == "handoffs":
|
|
2350
|
+
return cmd_handoffs(rest)
|
|
2351
|
+
if cmd == "logs":
|
|
2352
|
+
return cmd_logs(rest)
|
|
2353
|
+
if cmd == "pause":
|
|
2354
|
+
return cmd_pause(rest)
|
|
2355
|
+
if cmd == "resume":
|
|
2356
|
+
return cmd_resume(rest)
|
|
2357
|
+
if cmd == "stop":
|
|
2358
|
+
return cmd_stop(rest)
|
|
2359
|
+
if cmd == "cancel":
|
|
2360
|
+
return cmd_cancel(rest)
|
|
2361
|
+
if cmd == "cleanup":
|
|
2362
|
+
return cmd_cleanup(rest)
|
|
2363
|
+
if cmd == "attach":
|
|
2364
|
+
return cmd_attach(rest)
|
|
2365
|
+
if cmd == "promote":
|
|
2366
|
+
return cmd_promote(rest)
|
|
2367
|
+
if cmd == "activate":
|
|
2368
|
+
return cmd_activate(rest)
|
|
2369
|
+
if cmd == "deactivate":
|
|
2370
|
+
return cmd_deactivate(rest)
|
|
2371
|
+
if cmd == "approvals":
|
|
2372
|
+
return cmd_approvals(rest)
|
|
2373
|
+
if cmd == "approve":
|
|
2374
|
+
return cmd_approve(rest)
|
|
2375
|
+
if cmd == "reject":
|
|
2376
|
+
return cmd_reject(rest)
|
|
2377
|
+
if cmd == "handoff":
|
|
2378
|
+
# expect subcommand create
|
|
2379
|
+
if rest and rest[0] == "create":
|
|
2380
|
+
return cmd_handoff_create(rest[1:])
|
|
2381
|
+
return _error(
|
|
2382
|
+
f"Unknown handoff subcommand: {rest[0] if rest else ''}",
|
|
2383
|
+
hint="Usage: agent-toolkit swarm handoff create ...",
|
|
2384
|
+
)
|
|
2385
|
+
if cmd == "task":
|
|
2386
|
+
return cmd_task(rest)
|
|
2387
|
+
print(f"Unknown swarm command: {cmd}", file=sys.stderr)
|
|
2388
|
+
print("Run 'agent-toolkit swarm --help' for usage.", file=sys.stderr)
|
|
2389
|
+
return 1
|
|
2390
|
+
|
|
2391
|
+
|
|
2392
|
+
_SWARM_HELP = """agent-toolkit swarm — Backend-neutral local multi-agent swarm orchestration
|
|
2393
|
+
|
|
2394
|
+
Usage:
|
|
2395
|
+
agent-toolkit swarm <command> [args...]
|
|
2396
|
+
|
|
2397
|
+
Discovery:
|
|
2398
|
+
recipes List available recipes (pair, team, full)
|
|
2399
|
+
recipe show <name> Show recipe details
|
|
2400
|
+
runners List runner capability matrix
|
|
2401
|
+
models [--runner NAME] List models / profiles
|
|
2402
|
+
backends List UI backends and availability
|
|
2403
|
+
doctor [--json] Check swarm prerequisites
|
|
2404
|
+
|
|
2405
|
+
Init & Plan:
|
|
2406
|
+
init [--workspace PATH] [--recipe NAME] [--force]
|
|
2407
|
+
plan [--recipe NAME] [--ui auto|herdr|tmux] [--runner NAME] [--model-profile balanced|economy|quality|private] [--request-file PATH] [--issue OWNER/REPO#NUM] [--json] "task..."
|
|
2408
|
+
|
|
2409
|
+
Run:
|
|
2410
|
+
start [same options as plan] [--base-ref REF] [--json] "task..."
|
|
2411
|
+
list [--json] List all runs
|
|
2412
|
+
status [RUN_ID] [--json] Show run status
|
|
2413
|
+
watch [RUN_ID] Tail run trace
|
|
2414
|
+
report RUN_ID [--json] Show final report
|
|
2415
|
+
artifacts RUN_ID [--json]
|
|
2416
|
+
handoffs RUN_ID [--json]
|
|
2417
|
+
logs RUN_ID [ROLE] [--json]
|
|
2418
|
+
|
|
2419
|
+
Lifecycle:
|
|
2420
|
+
pause RUN_ID
|
|
2421
|
+
resume RUN_ID
|
|
2422
|
+
stop RUN_ID
|
|
2423
|
+
cancel RUN_ID
|
|
2424
|
+
cleanup RUN_ID [--force] [--dry-run]
|
|
2425
|
+
attach RUN_ID
|
|
2426
|
+
|
|
2427
|
+
Elastic:
|
|
2428
|
+
promote RUN_ID --to team|full
|
|
2429
|
+
activate RUN_ID ROLE
|
|
2430
|
+
deactivate RUN_ID ROLE
|
|
2431
|
+
|
|
2432
|
+
Human decisions:
|
|
2433
|
+
approvals RUN_ID [--json]
|
|
2434
|
+
approve RUN_ID GATE_ID
|
|
2435
|
+
reject RUN_ID GATE_ID --reason "..."
|
|
2436
|
+
|
|
2437
|
+
Handoffs:
|
|
2438
|
+
handoff create --type artifact|commit|feedback|decision_request --from ROLE --to ROLE [--priority N] [--artifact PATH] [--commit SHA --branch BRANCH] [--blocking]
|
|
2439
|
+
task next --role ROLE [--run-id ID] [--json]
|
|
2440
|
+
task complete --handoff ID [--run-id ID]
|
|
2441
|
+
|
|
2442
|
+
Examples:
|
|
2443
|
+
agent-toolkit swarm plan --recipe pair --ui auto --runner opencode --model-profile balanced "Implement issue #123"
|
|
2444
|
+
agent-toolkit swarm start --recipe pair --ui herdr --runner opencode --model-profile balanced "Implement issue #123"
|
|
2445
|
+
agent-toolkit swarm start --recipe pair --ui tmux --runner opencode "Fix bug in auth cache"
|
|
2446
|
+
|
|
2447
|
+
Docs: docs/SWARMS.md, docs/SWARM_ARCHITECTURE.md
|
|
2448
|
+
"""
|