claude-flow-novice 2.15.5 → 2.15.6
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.
- package/.claude/cfn-extras/.gs-api-quota.json +16 -0
- package/.claude/cfn-extras/.gs-progress-state.json +22 -0
- package/.claude/cfn-extras/GOOGLE_SHEETS_IMPLEMENTATION_SUMMARY.md +414 -0
- package/.claude/cfn-extras/agents/google-sheets/README.md +114 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-advanced-analytics-specialist.md +288 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-api-integrator.md +127 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-automation-scripting-specialist.md +195 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-business-validator.md +179 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-collaboration-security-specialist.md +240 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-coordinator.md +214 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-data-transformer.md +127 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-data-validation-quality-specialist.md +177 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-data-validator.md +119 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-data-visualization-specialist.md +135 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-design-layout-specialist.md +109 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-formula-engineer.md +127 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-formula-engineering-specialist.md +138 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-formula-validator.md +128 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-generalist.md +645 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-integration-api-specialist.md +258 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-performance-analyst.md +125 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-performance-optimization-specialist.md +211 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-schema-designer.md +130 -0
- package/.claude/cfn-extras/agents/google-sheets/google-sheets-template-architecture-specialist.md +259 -0
- package/.claude/cfn-extras/docs/GOOGLE_SHEETS_CFN_LOOP.md +617 -0
- package/.claude/cfn-extras/skills/GOOGLE_SHEETS_SKILLS_README.md +453 -0
- package/.claude/cfn-extras/skills/google-sheets-api-coordinator/SKILL.md +272 -0
- package/.claude/cfn-extras/skills/google-sheets-api-coordinator/api-call.sh +254 -0
- package/.claude/cfn-extras/skills/google-sheets-api-coordinator/test.sh +174 -0
- package/.claude/cfn-extras/skills/google-sheets-api-coordinator/validate.sh +98 -0
- package/.claude/cfn-extras/skills/google-sheets-decomposition/SKILL.md +269 -0
- package/.claude/cfn-extras/skills/google-sheets-decomposition/decompose.sh +313 -0
- package/.claude/cfn-extras/skills/google-sheets-formula-builder/SKILL.md +237 -0
- package/.claude/cfn-extras/skills/google-sheets-formula-builder/build-formula.sh +220 -0
- package/.claude/cfn-extras/skills/google-sheets-formula-builder/test.sh +172 -0
- package/.claude/cfn-extras/skills/google-sheets-formula-builder/validate.sh +98 -0
- package/.claude/cfn-extras/skills/google-sheets-progress/SKILL.md +287 -0
- package/.claude/cfn-extras/skills/google-sheets-progress/test.sh +385 -0
- package/.claude/cfn-extras/skills/google-sheets-progress/track-progress.sh +516 -0
- package/.claude/cfn-extras/skills/google-sheets-progress/validate.sh +119 -0
- package/.claude/cfn-extras/skills/google-sheets-sprint-order/SKILL.md +277 -0
- package/.claude/cfn-extras/skills/google-sheets-sprint-order/order-sprints.sh +233 -0
- package/.claude/cfn-extras/skills/google-sheets-validation/SKILL.md +352 -0
- package/.claude/cfn-extras/skills/google-sheets-validation/test.sh +355 -0
- package/.claude/cfn-extras/skills/google-sheets-validation/validate-state.sh +374 -0
- package/.claude/cfn-extras/skills/google-sheets-validation/validate.sh +128 -0
- package/.claude/commands/cfn-context.md +10 -0
- package/.claude/commands/cfn-loop-cli.md +36 -15
- package/.claude/commands/google-sheets/google-sheets-loop.md +289 -0
- package/.claude/skills/cfn-agent-selector/SKILL.md +143 -0
- package/.claude/skills/cfn-agent-selector/select-agents.sh +94 -0
- package/.claude/skills/cfn-agent-spawning/get-agent-provider-env.sh +22 -2
- package/.claude/skills/cfn-docker-agent-spawning/spawn-agent.sh +21 -2
- package/.claude/skills/cfn-docker-loop-orchestration/orchestrate.sh +11 -5
- package/.claude/skills/cfn-docker-redis-coordination/MIGRATION_SUMMARY.md +348 -0
- package/.claude/skills/cfn-docker-redis-coordination/README.md +294 -0
- package/.claude/skills/cfn-docker-redis-coordination/jest.config.js +37 -0
- package/.claude/skills/cfn-docker-redis-coordination/package-lock.json +5259 -0
- package/.claude/skills/cfn-docker-redis-coordination/package.json +40 -0
- package/.claude/skills/cfn-docker-redis-coordination/src/coordinator.ts +801 -0
- package/.claude/skills/cfn-docker-redis-coordination/src/index.ts +42 -0
- package/.claude/skills/cfn-docker-redis-coordination/src/types.ts +351 -0
- package/.claude/skills/cfn-docker-redis-coordination/tests/coordinator.test.ts +1464 -0
- package/.claude/skills/cfn-docker-redis-coordination/tsconfig.json +30 -0
- package/.claude/skills/cfn-loop-orchestration/.eslintrc.js +56 -0
- package/.claude/skills/cfn-loop-orchestration/.prettierrc.json +18 -0
- package/.claude/skills/cfn-loop-orchestration/README.md +149 -41
- package/.claude/skills/cfn-loop-orchestration/jest.config.js +67 -0
- package/.claude/skills/cfn-loop-orchestration/orchestrate-wrapper.sh +268 -0
- package/.claude/skills/cfn-loop-orchestration/orchestrate.sh +91 -8
- package/.claude/skills/cfn-loop-orchestration/package-lock.json +5470 -0
- package/.claude/skills/cfn-loop-orchestration/package.json +49 -0
- package/.claude/skills/cfn-loop-orchestration/src/agent-spawner/agent-spawner.ts +34 -0
- package/.claude/skills/cfn-loop-orchestration/src/gate-checker/gate-checker.ts +36 -0
- package/.claude/skills/cfn-loop-orchestration/src/index.ts +14 -0
- package/.claude/skills/cfn-loop-orchestration/src/orchestrator/orchestrator.ts +31 -0
- package/.claude/skills/cfn-loop-orchestration/src/redis/redis-coordinator.ts +72 -0
- package/.claude/skills/cfn-loop-orchestration/src/types.ts +188 -0
- package/.claude/skills/cfn-loop-orchestration/src/utils/logger.ts +32 -0
- package/.claude/skills/cfn-loop-orchestration/tests/setup.ts +22 -0
- package/.claude/skills/cfn-loop-orchestration/tests/types.test.ts +132 -0
- package/.claude/skills/cfn-loop-orchestration/tsconfig.json +54 -0
- package/.claude/skills/cfn-redis-coordination/bash-wrappers/store-context.sh +23 -0
- package/.claude/skills/cfn-redis-coordination/dist/agent-logger.d.ts +92 -0
- package/.claude/skills/cfn-redis-coordination/dist/agent-logger.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/agent-logger.js +329 -0
- package/.claude/skills/cfn-redis-coordination/dist/agent-logger.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/agent-recovery.d.ts +75 -0
- package/.claude/skills/cfn-redis-coordination/dist/agent-recovery.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/agent-recovery.js +302 -0
- package/.claude/skills/cfn-redis-coordination/dist/agent-recovery.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/completion-reporter.d.ts +58 -0
- package/.claude/skills/cfn-redis-coordination/dist/completion-reporter.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/completion-reporter.js +237 -0
- package/.claude/skills/cfn-redis-coordination/dist/completion-reporter.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/context-manager.d.ts +63 -0
- package/.claude/skills/cfn-redis-coordination/dist/context-manager.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/context-manager.js +230 -0
- package/.claude/skills/cfn-redis-coordination/dist/context-manager.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/index.d.ts +45 -0
- package/.claude/skills/cfn-redis-coordination/dist/index.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/index.js +114 -0
- package/.claude/skills/cfn-redis-coordination/dist/index.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/mode-detector.d.ts +31 -0
- package/.claude/skills/cfn-redis-coordination/dist/mode-detector.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/mode-detector.js +185 -0
- package/.claude/skills/cfn-redis-coordination/dist/mode-detector.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/redis-client.d.ts +191 -0
- package/.claude/skills/cfn-redis-coordination/dist/redis-client.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/redis-client.js +509 -0
- package/.claude/skills/cfn-redis-coordination/dist/redis-client.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/result-collector.d.ts +75 -0
- package/.claude/skills/cfn-redis-coordination/dist/result-collector.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/result-collector.js +281 -0
- package/.claude/skills/cfn-redis-coordination/dist/result-collector.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/swarm-manager.d.ts +75 -0
- package/.claude/skills/cfn-redis-coordination/dist/swarm-manager.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/swarm-manager.js +354 -0
- package/.claude/skills/cfn-redis-coordination/dist/swarm-manager.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/task-analyzer.d.ts +62 -0
- package/.claude/skills/cfn-redis-coordination/dist/task-analyzer.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/task-analyzer.js +305 -0
- package/.claude/skills/cfn-redis-coordination/dist/task-analyzer.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/task-executor.d.ts +97 -0
- package/.claude/skills/cfn-redis-coordination/dist/task-executor.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/task-executor.js +283 -0
- package/.claude/skills/cfn-redis-coordination/dist/task-executor.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/types.d.ts +176 -0
- package/.claude/skills/cfn-redis-coordination/dist/types.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/types.js +81 -0
- package/.claude/skills/cfn-redis-coordination/dist/types.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/waiting-coordinator.d.ts +86 -0
- package/.claude/skills/cfn-redis-coordination/dist/waiting-coordinator.d.ts.map +1 -0
- package/.claude/skills/cfn-redis-coordination/dist/waiting-coordinator.js +419 -0
- package/.claude/skills/cfn-redis-coordination/dist/waiting-coordinator.js.map +1 -0
- package/.claude/skills/cfn-redis-coordination/docs/migration/PHASE_3_REDIS_COORDINATION_COMPLETION_REPORT.md +553 -0
- package/.claude/skills/cfn-redis-coordination/jest.config.js +23 -0
- package/.claude/skills/cfn-redis-coordination/package-lock.json +5272 -0
- package/.claude/skills/cfn-redis-coordination/package.json +45 -0
- package/.claude/skills/cfn-redis-coordination/redis-cli-wrapper.sh +21 -8
- package/.claude/skills/cfn-redis-coordination/src/agent-logger.ts +446 -0
- package/.claude/skills/cfn-redis-coordination/src/agent-recovery.ts +454 -0
- package/.claude/skills/cfn-redis-coordination/src/completion-reporter.ts +396 -0
- package/.claude/skills/cfn-redis-coordination/src/context-manager.ts +327 -0
- package/.claude/skills/cfn-redis-coordination/src/index.ts +82 -0
- package/.claude/skills/cfn-redis-coordination/src/mode-detector.ts +155 -0
- package/.claude/skills/cfn-redis-coordination/src/redis/redis-client.ts +305 -0
- package/.claude/skills/cfn-redis-coordination/src/redis/redis-functions.ts +283 -0
- package/.claude/skills/cfn-redis-coordination/src/redis-client.ts +654 -0
- package/.claude/skills/cfn-redis-coordination/src/result-collector.ts +437 -0
- package/.claude/skills/cfn-redis-coordination/src/swarm-manager.ts +494 -0
- package/.claude/skills/cfn-redis-coordination/src/task-analyzer.ts +404 -0
- package/.claude/skills/cfn-redis-coordination/src/task-executor.ts +423 -0
- package/.claude/skills/cfn-redis-coordination/src/types.ts +235 -0
- package/.claude/skills/cfn-redis-coordination/src/waiting-coordinator.ts +587 -0
- package/.claude/skills/cfn-redis-coordination/test-connection-attempts.js +70 -0
- package/.claude/skills/cfn-redis-coordination/test-mode-simple.js +121 -0
- package/.claude/skills/cfn-redis-coordination/test-redis-check.js +84 -0
- package/.claude/skills/cfn-redis-coordination/test-task-mode-redis.cjs +391 -0
- package/.claude/skills/cfn-redis-coordination/tests/coordination.test.ts +779 -0
- package/.claude/skills/cfn-redis-coordination/tsconfig.json +31 -0
- package/claude-assets/agents/cfn-dev-team/coordinators/cfn-v3-coordinator.md +172 -2
- package/claude-assets/agents/cfn-dev-team/testers/api-testing-specialist.md +1 -1
- package/claude-assets/agents/custom/cfn-redis-operations.md +530 -0
- package/claude-assets/agents/custom/cfn-system-expert.md +77 -0
- package/claude-assets/cfn-extras/.gs-api-quota.json +16 -0
- package/claude-assets/cfn-extras/.gs-progress-state.json +22 -0
- package/claude-assets/cfn-extras/GOOGLE_SHEETS_IMPLEMENTATION_SUMMARY.md +414 -0
- package/claude-assets/cfn-extras/agents/google-sheets/README.md +114 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-advanced-analytics-specialist.md +288 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-api-integrator.md +127 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-automation-scripting-specialist.md +195 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-business-validator.md +179 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-collaboration-security-specialist.md +240 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-coordinator.md +214 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-data-transformer.md +127 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-data-validation-quality-specialist.md +177 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-data-validator.md +119 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-data-visualization-specialist.md +135 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-design-layout-specialist.md +109 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-formula-engineer.md +127 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-formula-engineering-specialist.md +138 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-formula-validator.md +128 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-generalist.md +645 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-integration-api-specialist.md +258 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-performance-analyst.md +125 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-performance-optimization-specialist.md +211 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-schema-designer.md +130 -0
- package/claude-assets/cfn-extras/agents/google-sheets/google-sheets-template-architecture-specialist.md +259 -0
- package/claude-assets/cfn-extras/docs/GOOGLE_SHEETS_CFN_LOOP.md +617 -0
- package/claude-assets/cfn-extras/skills/GOOGLE_SHEETS_SKILLS_README.md +453 -0
- package/claude-assets/cfn-extras/skills/google-sheets-api-coordinator/SKILL.md +272 -0
- package/claude-assets/cfn-extras/skills/google-sheets-api-coordinator/api-call.sh +254 -0
- package/claude-assets/cfn-extras/skills/google-sheets-api-coordinator/test.sh +174 -0
- package/claude-assets/cfn-extras/skills/google-sheets-api-coordinator/validate.sh +98 -0
- package/claude-assets/cfn-extras/skills/google-sheets-decomposition/SKILL.md +269 -0
- package/claude-assets/cfn-extras/skills/google-sheets-decomposition/decompose.sh +313 -0
- package/claude-assets/cfn-extras/skills/google-sheets-formula-builder/SKILL.md +237 -0
- package/claude-assets/cfn-extras/skills/google-sheets-formula-builder/build-formula.sh +220 -0
- package/claude-assets/cfn-extras/skills/google-sheets-formula-builder/test.sh +172 -0
- package/claude-assets/cfn-extras/skills/google-sheets-formula-builder/validate.sh +98 -0
- package/claude-assets/cfn-extras/skills/google-sheets-progress/SKILL.md +287 -0
- package/claude-assets/cfn-extras/skills/google-sheets-progress/test.sh +385 -0
- package/claude-assets/cfn-extras/skills/google-sheets-progress/track-progress.sh +516 -0
- package/claude-assets/cfn-extras/skills/google-sheets-progress/validate.sh +119 -0
- package/claude-assets/cfn-extras/skills/google-sheets-sprint-order/SKILL.md +277 -0
- package/claude-assets/cfn-extras/skills/google-sheets-sprint-order/order-sprints.sh +233 -0
- package/claude-assets/cfn-extras/skills/google-sheets-validation/SKILL.md +352 -0
- package/claude-assets/cfn-extras/skills/google-sheets-validation/test.sh +355 -0
- package/claude-assets/cfn-extras/skills/google-sheets-validation/validate-state.sh +374 -0
- package/claude-assets/cfn-extras/skills/google-sheets-validation/validate.sh +128 -0
- package/claude-assets/commands/cfn-context.md +10 -0
- package/claude-assets/commands/cfn-loop-cli.md +36 -15
- package/claude-assets/commands/google-sheets/google-sheets-loop.md +289 -0
- package/claude-assets/hooks/cfn-pre-execution/SESSION_START_README.md +87 -0
- package/claude-assets/hooks/cfn-pre-execution/TEST_SESSION_START.md +128 -0
- package/claude-assets/hooks/cfn-pre-execution/session-start-context.sh +111 -0
- package/claude-assets/skills/cfn-agent-selection-with-fallback/INTEGRATION_EXAMPLE.md +209 -0
- package/claude-assets/skills/cfn-agent-selection-with-fallback/README.md +130 -0
- package/claude-assets/skills/cfn-agent-selection-with-fallback/SKILL.md +243 -0
- package/claude-assets/skills/cfn-agent-selection-with-fallback/agent-mappings.json +142 -0
- package/claude-assets/skills/cfn-agent-selection-with-fallback/select-agents.sh +173 -0
- package/claude-assets/skills/cfn-agent-selection-with-fallback/task-classifier.sh +71 -0
- package/claude-assets/skills/cfn-agent-selection-with-fallback/test-agent-selection.sh +282 -0
- package/claude-assets/skills/cfn-agent-selector/SKILL.md +143 -0
- package/claude-assets/skills/cfn-agent-selector/select-agents.sh +94 -0
- package/claude-assets/skills/cfn-agent-spawning/get-agent-provider-env.sh +22 -2
- package/claude-assets/skills/cfn-docker-agent-spawning/spawn-agent.sh +21 -2
- package/claude-assets/skills/cfn-docker-coordination/.eslintrc.json +33 -0
- package/claude-assets/skills/cfn-docker-coordination/README.md +349 -0
- package/claude-assets/skills/cfn-docker-coordination/docker-helpers.sh +433 -0
- package/claude-assets/skills/cfn-docker-coordination/jest.config.js +25 -0
- package/claude-assets/skills/cfn-docker-coordination/package-lock.json +6827 -0
- package/claude-assets/skills/cfn-docker-coordination/package.json +38 -0
- package/claude-assets/skills/cfn-docker-coordination/src/agent-container.ts +471 -0
- package/claude-assets/skills/cfn-docker-coordination/src/docker-client.ts +483 -0
- package/claude-assets/skills/cfn-docker-coordination/src/health-checker.ts +418 -0
- package/claude-assets/skills/cfn-docker-coordination/src/index.ts +45 -0
- package/claude-assets/skills/cfn-docker-coordination/src/network-manager.ts +377 -0
- package/claude-assets/skills/cfn-docker-coordination/src/types.ts +412 -0
- package/claude-assets/skills/cfn-docker-coordination/src/volume-manager.ts +389 -0
- package/claude-assets/skills/cfn-docker-coordination/tests/agent-container.test.ts +379 -0
- package/claude-assets/skills/cfn-docker-coordination/tests/docker-client.test.ts +345 -0
- package/claude-assets/skills/cfn-docker-coordination/tests/health-checker.test.ts +535 -0
- package/claude-assets/skills/cfn-docker-coordination/tests/integration.test.ts +193 -0
- package/claude-assets/skills/cfn-docker-coordination/tests/network-manager.test.ts +352 -0
- package/claude-assets/skills/cfn-docker-coordination/tests/setup.ts +36 -0
- package/claude-assets/skills/cfn-docker-coordination/tsconfig.json +29 -0
- package/claude-assets/skills/cfn-docker-logging/INTEGRATION.md +268 -0
- package/claude-assets/skills/cfn-docker-logging/SAMPLE_OUTPUTS.md +237 -0
- package/claude-assets/skills/cfn-docker-logging/SKILL.md +442 -0
- package/claude-assets/skills/cfn-docker-logging/capture-container-logs.sh +120 -0
- package/claude-assets/skills/cfn-docker-logging/enable-logging.sh +430 -0
- package/claude-assets/skills/cfn-docker-logging/init-hybrid-logging.sh +210 -0
- package/claude-assets/skills/cfn-docker-logging/queries/analytics-summary.sh +87 -0
- package/claude-assets/skills/cfn-docker-logging/queries/query-agent-timeline.sh +51 -0
- package/claude-assets/skills/cfn-docker-logging/queries/query-consensus-history.sh +56 -0
- package/claude-assets/skills/cfn-docker-logging/queries/query-coordination-timeline.sh +39 -0
- package/claude-assets/skills/cfn-docker-logging/queries/query-failed-containers.sh +40 -0
- package/claude-assets/skills/cfn-docker-logging/queries/query-gate-checks.sh +39 -0
- package/claude-assets/skills/cfn-docker-logging/schema.sql +111 -0
- package/claude-assets/skills/cfn-docker-logging/sqlite-helpers.sh +240 -0
- package/claude-assets/skills/cfn-docker-logging/test-hybrid-logging.sh +331 -0
- package/claude-assets/skills/cfn-docker-loop-orchestration/orchestrate.sh +11 -5
- package/claude-assets/skills/cfn-docker-redis-coordination/MIGRATION_SUMMARY.md +348 -0
- package/claude-assets/skills/cfn-docker-redis-coordination/README.md +294 -0
- package/claude-assets/skills/cfn-docker-redis-coordination/jest.config.js +37 -0
- package/claude-assets/skills/cfn-docker-redis-coordination/package-lock.json +5259 -0
- package/claude-assets/skills/cfn-docker-redis-coordination/package.json +40 -0
- package/claude-assets/skills/cfn-docker-redis-coordination/src/coordinator.ts +801 -0
- package/claude-assets/skills/cfn-docker-redis-coordination/src/index.ts +42 -0
- package/claude-assets/skills/cfn-docker-redis-coordination/src/types.ts +351 -0
- package/claude-assets/skills/cfn-docker-redis-coordination/tests/coordinator.test.ts +1464 -0
- package/claude-assets/skills/cfn-docker-redis-coordination/tsconfig.json +30 -0
- package/claude-assets/skills/cfn-error-logging/.eslintrc.json +57 -0
- package/claude-assets/skills/cfn-error-logging/.prettierrc.json +10 -0
- package/claude-assets/skills/cfn-error-logging/MIGRATION_SUMMARY.md +485 -0
- package/claude-assets/skills/cfn-error-logging/package.json +47 -0
- package/claude-assets/skills/cfn-error-logging/src/error-logger.ts +1042 -0
- package/claude-assets/skills/cfn-error-logging/src/index.ts +12 -0
- package/claude-assets/skills/cfn-error-logging/src/types.ts +456 -0
- package/claude-assets/skills/cfn-error-logging/tests/error-logger.test.ts +1302 -0
- package/claude-assets/skills/cfn-error-logging/tsconfig.json +38 -0
- package/claude-assets/skills/cfn-loop-orchestration/.eslintrc.js +56 -0
- package/claude-assets/skills/cfn-loop-orchestration/.prettierrc.json +18 -0
- package/claude-assets/skills/cfn-loop-orchestration/README.md +149 -41
- package/claude-assets/skills/cfn-loop-orchestration/jest.config.js +67 -0
- package/claude-assets/skills/cfn-loop-orchestration/orchestrate-wrapper.sh +268 -0
- package/claude-assets/skills/cfn-loop-orchestration/orchestrate.sh +91 -8
- package/claude-assets/skills/cfn-loop-orchestration/package-lock.json +5470 -0
- package/claude-assets/skills/cfn-loop-orchestration/package.json +49 -0
- package/claude-assets/skills/cfn-loop-orchestration/src/agent-spawner/agent-spawner.ts +34 -0
- package/claude-assets/skills/cfn-loop-orchestration/src/gate-checker/gate-checker.ts +36 -0
- package/claude-assets/skills/cfn-loop-orchestration/src/index.ts +14 -0
- package/claude-assets/skills/cfn-loop-orchestration/src/orchestrator/orchestrator.ts +31 -0
- package/claude-assets/skills/cfn-loop-orchestration/src/redis/redis-coordinator.ts +72 -0
- package/claude-assets/skills/cfn-loop-orchestration/src/types.ts +188 -0
- package/claude-assets/skills/cfn-loop-orchestration/src/utils/logger.ts +32 -0
- package/claude-assets/skills/cfn-loop-orchestration/tests/setup.ts +22 -0
- package/claude-assets/skills/cfn-loop-orchestration/tests/types.test.ts +132 -0
- package/claude-assets/skills/cfn-loop-orchestration/tsconfig.json +54 -0
- package/claude-assets/skills/cfn-redis-coordination/bash-wrappers/store-context.sh +23 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/agent-logger.d.ts +92 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/agent-logger.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/agent-logger.js +329 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/agent-logger.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/agent-recovery.d.ts +75 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/agent-recovery.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/agent-recovery.js +302 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/agent-recovery.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/completion-reporter.d.ts +58 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/completion-reporter.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/completion-reporter.js +237 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/completion-reporter.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/context-manager.d.ts +63 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/context-manager.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/context-manager.js +230 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/context-manager.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/index.d.ts +45 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/index.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/index.js +114 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/index.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/mode-detector.d.ts +31 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/mode-detector.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/mode-detector.js +185 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/mode-detector.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/redis-client.d.ts +191 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/redis-client.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/redis-client.js +509 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/redis-client.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/result-collector.d.ts +75 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/result-collector.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/result-collector.js +281 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/result-collector.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/swarm-manager.d.ts +75 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/swarm-manager.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/swarm-manager.js +354 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/swarm-manager.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/task-analyzer.d.ts +62 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/task-analyzer.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/task-analyzer.js +305 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/task-analyzer.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/task-executor.d.ts +97 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/task-executor.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/task-executor.js +283 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/task-executor.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/types.d.ts +176 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/types.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/types.js +81 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/types.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/waiting-coordinator.d.ts +86 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/waiting-coordinator.d.ts.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/waiting-coordinator.js +419 -0
- package/claude-assets/skills/cfn-redis-coordination/dist/waiting-coordinator.js.map +1 -0
- package/claude-assets/skills/cfn-redis-coordination/docs/migration/PHASE_3_REDIS_COORDINATION_COMPLETION_REPORT.md +553 -0
- package/claude-assets/skills/cfn-redis-coordination/jest.config.js +23 -0
- package/claude-assets/skills/cfn-redis-coordination/package-lock.json +5272 -0
- package/claude-assets/skills/cfn-redis-coordination/package.json +45 -0
- package/claude-assets/skills/cfn-redis-coordination/redis-cli-wrapper.sh +21 -8
- package/claude-assets/skills/cfn-redis-coordination/src/agent-logger.ts +446 -0
- package/claude-assets/skills/cfn-redis-coordination/src/agent-recovery.ts +454 -0
- package/claude-assets/skills/cfn-redis-coordination/src/completion-reporter.ts +396 -0
- package/claude-assets/skills/cfn-redis-coordination/src/context-manager.ts +327 -0
- package/claude-assets/skills/cfn-redis-coordination/src/index.ts +82 -0
- package/claude-assets/skills/cfn-redis-coordination/src/mode-detector.ts +155 -0
- package/claude-assets/skills/cfn-redis-coordination/src/redis/redis-client.ts +305 -0
- package/claude-assets/skills/cfn-redis-coordination/src/redis/redis-functions.ts +283 -0
- package/claude-assets/skills/cfn-redis-coordination/src/redis-client.ts +654 -0
- package/claude-assets/skills/cfn-redis-coordination/src/result-collector.ts +437 -0
- package/claude-assets/skills/cfn-redis-coordination/src/swarm-manager.ts +494 -0
- package/claude-assets/skills/cfn-redis-coordination/src/task-analyzer.ts +404 -0
- package/claude-assets/skills/cfn-redis-coordination/src/task-executor.ts +423 -0
- package/claude-assets/skills/cfn-redis-coordination/src/types.ts +235 -0
- package/claude-assets/skills/cfn-redis-coordination/src/waiting-coordinator.ts +587 -0
- package/claude-assets/skills/cfn-redis-coordination/test-connection-attempts.js +70 -0
- package/claude-assets/skills/cfn-redis-coordination/test-mode-simple.js +121 -0
- package/claude-assets/skills/cfn-redis-coordination/test-redis-check.js +84 -0
- package/claude-assets/skills/cfn-redis-coordination/test-task-mode-redis.cjs +391 -0
- package/claude-assets/skills/cfn-redis-coordination/tests/coordination.test.ts +779 -0
- package/claude-assets/skills/cfn-redis-coordination/tsconfig.json +31 -0
- package/claude-assets/skills/cfn-skill-propagation/README.md +233 -0
- package/claude-assets/skills/cfn-skill-propagation/package-lock.json +5174 -0
- package/claude-assets/skills/cfn-skill-propagation/package.json +52 -0
- package/claude-assets/skills/cfn-skill-propagation/propagate-skill-update.sh +32 -0
- package/claude-assets/skills/cfn-skill-propagation/src/cli.ts +75 -0
- package/claude-assets/skills/cfn-skill-propagation/src/database-adapter.ts +239 -0
- package/claude-assets/skills/cfn-skill-propagation/src/file-system-adapter.ts +113 -0
- package/claude-assets/skills/cfn-skill-propagation/src/index.ts +72 -0
- package/claude-assets/skills/cfn-skill-propagation/src/logger.ts +43 -0
- package/claude-assets/skills/cfn-skill-propagation/src/metadata-parser.ts +154 -0
- package/claude-assets/skills/cfn-skill-propagation/src/skill-propagator.ts +274 -0
- package/claude-assets/skills/cfn-skill-propagation/src/skill-validator.ts +179 -0
- package/claude-assets/skills/cfn-skill-propagation/src/types.ts +143 -0
- package/claude-assets/skills/cfn-skill-propagation/src/version-manager.ts +118 -0
- package/claude-assets/skills/cfn-skill-propagation/tests/file-system-adapter.test.ts +91 -0
- package/claude-assets/skills/cfn-skill-propagation/tests/metadata-parser.test.ts +176 -0
- package/claude-assets/skills/cfn-skill-propagation/tests/skill-propagator.test.ts +209 -0
- package/claude-assets/skills/cfn-skill-propagation/tests/skill-validator.test.ts +203 -0
- package/claude-assets/skills/cfn-skill-propagation/tests/version-manager.test.ts +115 -0
- package/claude-assets/skills/cfn-skill-propagation/tsconfig.json +34 -0
- package/claude-assets/skills/task-classifier/SKILL.md +81 -0
- package/claude-assets/skills/task-classifier/classify-task.sh +62 -0
- package/claude-assets/skills/workflow-codification/package-lock.json +5170 -0
- package/claude-assets/skills/workflow-codification/package.json +30 -0
- package/claude-assets/skills/workflow-codification/src/index.ts +24 -0
- package/claude-assets/skills/workflow-codification/src/pattern-analyzer.ts +537 -0
- package/claude-assets/skills/workflow-codification/src/types.ts +180 -0
- package/claude-assets/skills/workflow-codification/tests/pattern-analyzer.test.ts +960 -0
- package/claude-assets/skills/workflow-codification/tsconfig.json +34 -0
- package/claude-assets/skills/workflow-codification/workflow-codification.db +0 -0
- package/dist/agent-spawner/agent-spawner.js +448 -0
- package/dist/agent-spawner/agent-spawner.js.map +1 -0
- package/dist/agent-spawner/index.js +10 -0
- package/dist/agent-spawner/index.js.map +1 -0
- package/dist/agent-spawner/types.js +14 -0
- package/dist/agent-spawner/types.js.map +1 -0
- package/dist/agents/agent-loader.js +146 -165
- package/dist/agents/agent-loader.js.map +1 -1
- package/dist/cli/agent-executor.js +47 -1
- package/dist/cli/agent-executor.js.map +1 -1
- package/dist/cli/agent-spawn.js +4 -1
- package/dist/cli/agent-spawn.js.map +1 -1
- package/dist/cli/tool-executor.js +3 -1
- package/dist/cli/tool-executor.js.map +1 -1
- package/dist/gate-checker/gate-checker.js +292 -0
- package/dist/gate-checker/gate-checker.js.map +1 -0
- package/dist/gate-checker/types.js +94 -0
- package/dist/gate-checker/types.js.map +1 -0
- package/dist/lib/database-service/connection-pool-manager.js +2 -1
- package/dist/lib/database-service/connection-pool-manager.js.map +1 -1
- package/dist/orchestrator/index.js +10 -0
- package/dist/orchestrator/index.js.map +1 -0
- package/dist/orchestrator/orchestrate.js +496 -0
- package/dist/orchestrator/orchestrate.js.map +1 -0
- package/dist/orchestrator/types.js +58 -0
- package/dist/orchestrator/types.js.map +1 -0
- package/package.json +1 -1
- package/scripts/switch-api.sh +142 -4
- package/scripts/verify-no-secrets.sh +6 -13
- package/tests/README.md +175 -58
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/agent-executor.ts"],"sourcesContent":["/**\r\n * Agent Executor\r\n *\r\n * Executes CLI-spawned agents by:\r\n * 1. Checking custom routing configuration (z.ai vs Anthropic)\r\n * 2. Invoking the appropriate API\r\n * 3. Managing agent lifecycle and output\r\n */\r\n\r\nimport { spawn } from 'child_process';\r\nimport { exec } from 'child_process';\r\nimport { promisify } from 'util';\r\nimport { AgentDefinition } from './agent-definition-parser.js';\r\nimport { TaskContext, getAgentId } from './agent-prompt-builder.js';\r\nimport { buildCLIAgentSystemPrompt, loadContextFromEnv } from './cli-agent-context.js';\r\nimport {\r\n loadMessages,\r\n storeMessage,\r\n getCurrentFork,\r\n formatMessagesForAPI,\r\n type Message\r\n} from './conversation-fork.js';\r\nimport { convertToolNames } from './tool-definitions.js';\r\nimport fs from 'fs/promises';\r\nimport path from 'path';\r\nimport os from 'os';\r\n\r\nconst execAsync = promisify(exec);\r\n\r\n// Bug #6 Fix: Read Redis connection parameters from process.env\r\n// ENV-001: Standardized environment variable naming (REDIS_PASSWORD for all deployments)\r\nconst redisHost = process.env.CFN_REDIS_HOST || 'cfn-redis';\r\nconst redisPort = process.env.CFN_REDIS_PORT || '6379';\r\nconst redisPassword = process.env.CFN_REDIS_PASSWORD || process.env.REDIS_PASSWORD || '';\r\n\r\nexport interface AgentExecutionResult {\r\n success: boolean;\r\n agentId: string;\r\n output?: string;\r\n error?: string;\r\n exitCode: number;\r\n}\r\n\r\n/**\r\n * Extract confidence score from agent output\r\n * Looks for patterns like:\r\n * - \"confidence: 0.85\"\r\n * - \"Confidence: 0.90\"\r\n * - \"confidence score: 0.95\"\r\n * - \"self-confidence: 0.88\"\r\n */\r\nfunction extractConfidence(output: string | undefined): number {\r\n if (!output) return 0.85;\r\n\r\n // Try multiple patterns\r\n const patterns = [\r\n /confidence:\\s*([0-9.]+)/i,\r\n /confidence\\s+score:\\s*([0-9.]+)/i,\r\n /self-confidence:\\s*([0-9.]+)/i,\r\n /my\\s+confidence:\\s*([0-9.]+)/i,\r\n ];\r\n\r\n for (const pattern of patterns) {\r\n const match = output.match(pattern);\r\n if (match && match[1]) {\r\n const score = parseFloat(match[1]);\r\n if (score >= 0 && score <= 1) {\r\n return score;\r\n }\r\n }\r\n }\r\n\r\n // Default to 0.85 if not found\r\n return 0.85;\r\n}\r\n\r\n/**\r\n * Execute CFN Loop protocol after agent completes work\r\n *\r\n * Steps:\r\n * 1. Signal completion to orchestrator\r\n * 2. Report confidence score\r\n * 3. Enter waiting mode (if iterations enabled)\r\n */\r\nasync function executeCFNProtocol(\r\n taskId: string,\r\n agentId: string,\r\n output: string | undefined,\r\n iteration: number,\r\n enableIterations: boolean = false,\r\n maxIterations: number = 10\r\n): Promise<void> {\r\n console.log(`\\n[CFN Protocol] Starting for agent ${agentId}`);\r\n console.log(`[CFN Protocol] Task ID: ${taskId}, Iteration: ${iteration}`);\r\n\r\n try {\r\n // Step 1: Signal completion\r\n console.log('[CFN Protocol] Step 1: Signaling completion...');\r\n const authFlag = redisPassword ? `-a \"${redisPassword}\"` : '';\r\n await execAsync(`redis-cli -h \"${redisHost}\" -p \"${redisPort}\" ${authFlag} lpush \"swarm:${taskId}:${agentId}:done\" \"complete\"`);\r\n console.log('[CFN Protocol] ✓ Completion signaled');\r\n\r\n // Step 2: Extract and report confidence\r\n const confidence = extractConfidence(output);\r\n console.log(`[CFN Protocol] Step 2: Reporting confidence (${confidence})...`);\r\n\r\n const reportCmd = `./.claude/skills/cfn-redis-coordination/report-completion.sh \\\r\n --task-id \"${taskId}\" \\\r\n --agent-id \"${agentId}\" \\\r\n --confidence ${confidence} \\\r\n --iteration ${iteration}`;\r\n\r\n await execAsync(reportCmd);\r\n console.log('[CFN Protocol] ✓ Confidence reported');\r\n\r\n // Step 3: Exit cleanly (BUG #18 FIX - removed waiting mode)\r\n // Orchestrator will spawn appropriate specialist agent for next iteration\r\n // This enables adaptive agent specialization based on feedback type\r\n console.log('[CFN Protocol] Step 3: Exiting cleanly (iteration complete)');\r\n console.log('[CFN Protocol] Protocol complete\\n');\r\n } catch (error) {\r\n console.error('[CFN Protocol] Error:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Check if custom routing (z.ai) is enabled\r\n */\r\nasync function isCustomRoutingEnabled(): Promise<boolean> {\r\n // Check environment variable\r\n if (process.env.CLAUDE_API_PROVIDER === 'zai') {\r\n return true;\r\n }\r\n\r\n // Check config file (.claude/config/api-provider.json)\r\n try {\r\n const configPath = path.join('.claude', 'config', 'api-provider.json');\r\n const config = JSON.parse(await fs.readFile(configPath, 'utf-8'));\r\n return config.provider === 'zai' || config.provider === 'z.ai';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Get API provider configuration\r\n */\r\nasync function getAPIProvider(): Promise<'anthropic' | 'zai'> {\r\n const customEnabled = await isCustomRoutingEnabled();\r\n return customEnabled ? 'zai' : 'anthropic';\r\n}\r\n\r\n/**\r\n * Execute agent using direct API calls\r\n */\r\nasync function executeViaAPI(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext\r\n): Promise<AgentExecutionResult> {\r\n const agentId = getAgentId(definition, context);\r\n\r\n console.log(`[agent-executor] Executing agent via API: ${definition.name}`);\r\n console.log(`[agent-executor] Agent ID: ${agentId}`);\r\n console.log(`[agent-executor] Model: ${definition.model}`);\r\n console.log('');\r\n\r\n try {\r\n // Check for conversation fork (Sprint 4 enhancement)\r\n const forkId = process.env.FORK_ID || await getCurrentFork(context.taskId || '', agentId);\r\n const iteration = context.iteration || 1;\r\n\r\n let systemPrompt: string;\r\n let messages: Array<{role: string, content: string}> = [];\r\n\r\n if (forkId && iteration > 1) {\r\n // Continue from fork (iterations 2+)\r\n console.log(`[agent-executor] Continuing from fork: ${forkId}`);\r\n\r\n // Load fork messages\r\n const forkMessages = await loadMessages(context.taskId || '', agentId, forkId);\r\n console.log(`[agent-executor] Loaded ${forkMessages.length} messages from fork`);\r\n\r\n // Extract system prompt from first message (it's always the system message)\r\n // The fork messages are assistant/user pairs, we need to add system separately\r\n systemPrompt = forkMessages[0]?.content || '';\r\n\r\n // Format remaining messages for API\r\n messages = formatMessagesForAPI(forkMessages.slice(1));\r\n\r\n // Add new user message with feedback\r\n messages.push({\r\n role: 'user',\r\n content: prompt\r\n });\r\n\r\n console.log(`[agent-executor] Fork continuation: ${messages.length} messages`);\r\n } else {\r\n // New conversation (iteration 1)\r\n console.log('[agent-executor] Starting new conversation');\r\n console.log('[agent-executor] Building system prompt with context...');\r\n\r\n const contextOptions = loadContextFromEnv();\r\n contextOptions.agentType = definition.name;\r\n if (context.taskId) contextOptions.taskId = context.taskId;\r\n if (context.iteration) contextOptions.iteration = context.iteration;\r\n\r\n systemPrompt = await buildCLIAgentSystemPrompt(contextOptions);\r\n console.log('[agent-executor] System prompt built successfully');\r\n\r\n // Initial user message\r\n messages = [{\r\n role: 'user',\r\n content: prompt\r\n }];\r\n }\r\n\r\n console.log('');\r\n\r\n // Dynamic import to avoid bundling issues\r\n const { executeAgentAPI } = await import('./anthropic-client.js');\r\n\r\n // Convert agent tool names to Anthropic API format\r\n const tools = definition.tools && definition.tools.length > 0\r\n ? convertToolNames(definition.tools)\r\n : undefined;\r\n\r\n const result = await executeAgentAPI(\r\n definition.name,\r\n agentId,\r\n definition.model,\r\n prompt,\r\n systemPrompt,\r\n messages.length > 1 ? messages : undefined,\r\n undefined, // maxTokens (use default)\r\n tools // Pass converted tools\r\n );\r\n\r\n // Store messages in conversation history (for future forking)\r\n if (context.taskId) {\r\n // Store user message\r\n const userMessage: Message = {\r\n role: 'user',\r\n content: prompt,\r\n iteration,\r\n timestamp: new Date().toISOString()\r\n };\r\n await storeMessage(context.taskId, agentId, userMessage);\r\n\r\n // Store assistant response\r\n if (result.output) {\r\n const assistantMessage: Message = {\r\n role: 'assistant',\r\n content: result.output,\r\n iteration,\r\n timestamp: new Date().toISOString()\r\n };\r\n await storeMessage(context.taskId, agentId, assistantMessage);\r\n }\r\n\r\n console.log(`[agent-executor] Stored messages for iteration ${iteration}`);\r\n\r\n // Execute CFN Loop protocol (signal completion, report confidence, enter waiting mode)\r\n // Iterations are enabled for CFN Loop tasks (indicated by presence of taskId)\r\n try {\r\n const maxIterations = 10; // Default max iterations\r\n const enableIterations = true; // Enable iterations for all CFN Loop tasks\r\n\r\n await executeCFNProtocol(\r\n context.taskId,\r\n agentId,\r\n result.output,\r\n iteration,\r\n enableIterations,\r\n maxIterations\r\n );\r\n } catch (error) {\r\n console.error('[agent-executor] CFN Protocol execution failed:', error);\r\n // Don't fail the entire agent execution if CFN protocol fails\r\n // This allows agents to complete even if Redis coordination has issues\r\n }\r\n }\r\n\r\n return {\r\n success: result.success,\r\n agentId,\r\n output: result.output,\r\n error: result.error,\r\n exitCode: result.success ? 0 : 1,\r\n };\r\n } catch (error) {\r\n console.error('[agent-executor] API execution failed:', error);\r\n return {\r\n success: false,\r\n agentId,\r\n error: error instanceof Error ? error.message : String(error),\r\n exitCode: 1,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Execute agent using shell script (fallback/simulation)\r\n */\r\nasync function executeViaScript(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext\r\n): Promise<AgentExecutionResult> {\r\n const agentId = getAgentId(definition, context);\r\n\r\n // Write prompt to temporary file\r\n const tmpDir = os.tmpdir();\r\n const promptFile = path.join(tmpDir, `agent-${agentId}-${Date.now()}.md`);\r\n await fs.writeFile(promptFile, prompt, 'utf-8');\r\n\r\n console.log(`[agent-executor] Executing agent via script: ${definition.name}`);\r\n console.log(`[agent-executor] Agent ID: ${agentId}`);\r\n console.log(`[agent-executor] Model: ${definition.model}`);\r\n console.log(`[agent-executor] Prompt file: ${promptFile}`);\r\n\r\n return new Promise((resolve) => {\r\n const scriptPath = path.join('.claude', 'skills', 'agent-execution', 'execute-agent.sh');\r\n\r\n // Build environment variables - WHITELIST ONLY APPROACH\r\n // SECURITY FIX: Do not use ...process.env spread which exposes ALL variables including secrets\r\n // Instead, explicitly whitelist safe variables to pass to spawned process\r\n const safeEnvVars = [\r\n 'CFN_REDIS_HOST',\r\n 'CFN_REDIS_PORT',\r\n 'CFN_REDIS_URL',\r\n 'CFN_MEMORY_BUDGET',\r\n 'CFN_API_HOST',\r\n 'CFN_API_PORT',\r\n 'CFN_LOG_LEVEL',\r\n 'CFN_LOG_FORMAT',\r\n 'CFN_CONTAINER_MODE',\r\n 'CFN_DOCKER_SOCKET',\r\n 'CFN_NETWORK_NAME',\r\n 'CFN_CUSTOM_ROUTING',\r\n 'CFN_DEFAULT_PROVIDER',\r\n 'NODE_ENV',\r\n 'PATH',\r\n 'HOME'\r\n ];\r\n\r\n const env: Record<string, string> = {};\r\n\r\n // Add whitelisted variables\r\n for (const key of safeEnvVars) {\r\n const value = process.env[key];\r\n if (value !== undefined) {\r\n env[key] = value;\r\n }\r\n }\r\n\r\n // Add API key only when explicitly needed (with strict validation)\r\n if (process.env.ANTHROPIC_API_KEY) {\r\n if (process.env.ANTHROPIC_API_KEY.match(/^sk-[a-zA-Z0-9-]+$/)) {\r\n env.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;\r\n }\r\n }\r\n\r\n // Add agent execution context (safe values)\r\n env.AGENT_TYPE = definition.name;\r\n env.AGENT_ID = agentId;\r\n env.AGENT_MODEL = definition.model;\r\n env.AGENT_TOOLS = definition.tools.join(',');\r\n env.TASK_ID = context.taskId || '';\r\n env.ITERATION = String(context.iteration || 1);\r\n env.MODE = context.mode || 'cli';\r\n env.PROMPT_FILE = promptFile;\r\n\r\n // Check if execute script exists\r\n fs.access(scriptPath)\r\n .then(() => {\r\n // Use execution script\r\n const proc = spawn('bash', [scriptPath], { env, stdio: 'inherit' });\r\n\r\n proc.on('exit', (code) => {\r\n resolve({\r\n success: code === 0,\r\n agentId,\r\n exitCode: code || 0,\r\n });\r\n });\r\n\r\n proc.on('error', (err) => {\r\n resolve({\r\n success: false,\r\n agentId,\r\n error: err.message,\r\n exitCode: 1,\r\n });\r\n });\r\n })\r\n .catch(() => {\r\n // Fallback: Print prompt\r\n console.log('\\n=== Agent Prompt ===');\r\n console.log(prompt.substring(0, 500) + '...');\r\n console.log('\\n[agent-executor] Execution script not found');\r\n console.log('[agent-executor] Using simulation mode\\n');\r\n\r\n resolve({\r\n success: true,\r\n agentId,\r\n output: prompt,\r\n exitCode: 0,\r\n });\r\n });\r\n });\r\n}\r\n\r\n/**\r\n * Main agent execution function\r\n */\r\nexport async function executeAgent(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext,\r\n options: {\r\n method?: 'auto' | 'api' | 'script';\r\n } = {}\r\n): Promise<AgentExecutionResult> {\r\n const method = options.method || 'auto';\r\n\r\n // Auto-select execution method\r\n if (method === 'auto') {\r\n // Try API execution first, fallback to script if API key not available\r\n try {\r\n return await executeViaAPI(definition, prompt, context);\r\n } catch (error) {\r\n if (error instanceof Error && error.message.includes('API key not found')) {\r\n console.log('[agent-executor] API key not found, using script fallback');\r\n return executeViaScript(definition, prompt, context);\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n if (method === 'api') {\r\n return executeViaAPI(definition, prompt, context);\r\n }\r\n\r\n return executeViaScript(definition, prompt, context);\r\n}\r\n\r\n/**\r\n * Write agent output to file for debugging\r\n */\r\nexport async function saveAgentOutput(\r\n agentId: string,\r\n output: string,\r\n outputDir: string = '.claude/tmp/agent-output'\r\n): Promise<string> {\r\n await fs.mkdir(outputDir, { recursive: true });\r\n\r\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\r\n const filename = `${agentId}-${timestamp}.txt`;\r\n const filepath = path.join(outputDir, filename);\r\n\r\n await fs.writeFile(filepath, output, 'utf-8');\r\n\r\n return filepath;\r\n}\r\n"],"names":["spawn","exec","promisify","getAgentId","buildCLIAgentSystemPrompt","loadContextFromEnv","loadMessages","storeMessage","getCurrentFork","formatMessagesForAPI","convertToolNames","fs","path","os","execAsync","redisHost","process","env","CFN_REDIS_HOST","redisPort","CFN_REDIS_PORT","redisPassword","CFN_REDIS_PASSWORD","REDIS_PASSWORD","extractConfidence","output","patterns","pattern","match","score","parseFloat","executeCFNProtocol","taskId","agentId","iteration","enableIterations","maxIterations","console","log","authFlag","confidence","reportCmd","error","isCustomRoutingEnabled","CLAUDE_API_PROVIDER","configPath","join","config","JSON","parse","readFile","provider","getAPIProvider","customEnabled","executeViaAPI","definition","prompt","context","name","model","forkId","FORK_ID","systemPrompt","messages","forkMessages","length","content","slice","push","role","contextOptions","agentType","executeAgentAPI","tools","undefined","result","userMessage","timestamp","Date","toISOString","assistantMessage","success","exitCode","Error","message","String","executeViaScript","tmpDir","tmpdir","promptFile","now","writeFile","Promise","resolve","scriptPath","safeEnvVars","key","value","ANTHROPIC_API_KEY","AGENT_TYPE","AGENT_ID","AGENT_MODEL","AGENT_TOOLS","TASK_ID","ITERATION","MODE","mode","PROMPT_FILE","access","then","proc","stdio","on","code","err","catch","substring","executeAgent","options","method","includes","saveAgentOutput","outputDir","mkdir","recursive","replace","filename","filepath"],"mappings":"AAAA;;;;;;;CAOC,GAED,SAASA,KAAK,QAAQ,gBAAgB;AACtC,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AAEjC,SAAsBC,UAAU,QAAQ,4BAA4B;AACpE,SAASC,yBAAyB,EAAEC,kBAAkB,QAAQ,yBAAyB;AACvF,SACEC,YAAY,EACZC,YAAY,EACZC,cAAc,EACdC,oBAAoB,QAEf,yBAAyB;AAChC,SAASC,gBAAgB,QAAQ,wBAAwB;AACzD,OAAOC,QAAQ,cAAc;AAC7B,OAAOC,UAAU,OAAO;AACxB,OAAOC,QAAQ,KAAK;AAEpB,MAAMC,YAAYZ,UAAUD;AAE5B,gEAAgE;AAChE,yFAAyF;AACzF,MAAMc,YAAYC,QAAQC,GAAG,CAACC,cAAc,IAAI;AAChD,MAAMC,YAAYH,QAAQC,GAAG,CAACG,cAAc,IAAI;AAChD,MAAMC,gBAAgBL,QAAQC,GAAG,CAACK,kBAAkB,IAAIN,QAAQC,GAAG,CAACM,cAAc,IAAI;AAUtF;;;;;;;CAOC,GACD,SAASC,kBAAkBC,MAA0B;IACnD,IAAI,CAACA,QAAQ,OAAO;IAEpB,wBAAwB;IACxB,MAAMC,WAAW;QACf;QACA;QACA;QACA;KACD;IAED,KAAK,MAAMC,WAAWD,SAAU;QAC9B,MAAME,QAAQH,OAAOG,KAAK,CAACD;QAC3B,IAAIC,SAASA,KAAK,CAAC,EAAE,EAAE;YACrB,MAAMC,QAAQC,WAAWF,KAAK,CAAC,EAAE;YACjC,IAAIC,SAAS,KAAKA,SAAS,GAAG;gBAC5B,OAAOA;YACT;QACF;IACF;IAEA,+BAA+B;IAC/B,OAAO;AACT;AAEA;;;;;;;CAOC,GACD,eAAeE,mBACbC,MAAc,EACdC,OAAe,EACfR,MAA0B,EAC1BS,SAAiB,E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,EACfR,MAAc,EACdiG,YAAoB,0BAA0B;IAE9C,MAAM/G,GAAGgH,KAAK,CAACD,WAAW;QAAEE,WAAW;IAAK;IAE5C,MAAM/C,YAAY,IAAIC,OAAOC,WAAW,GAAG8C,OAAO,CAAC,SAAS;IAC5D,MAAMC,WAAW,GAAG7F,QAAQ,CAAC,EAAE4C,UAAU,IAAI,CAAC;IAC9C,MAAMkD,WAAWnH,KAAKkC,IAAI,CAAC4E,WAAWI;IAEtC,MAAMnH,GAAGgF,SAAS,CAACoC,UAAUtG,QAAQ;IAErC,OAAOsG;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/agent-executor.ts"],"sourcesContent":["/**\r\n * Agent Executor\r\n *\r\n * Executes CLI-spawned agents by:\r\n * 1. Checking custom routing configuration (z.ai vs Anthropic)\r\n * 2. Invoking the appropriate API\r\n * 3. Managing agent lifecycle and output\r\n */\r\n\r\nimport { spawn } from 'child_process';\r\nimport { exec } from 'child_process';\r\nimport { promisify } from 'util';\r\nimport { AgentDefinition } from './agent-definition-parser.js';\r\nimport { TaskContext, getAgentId } from './agent-prompt-builder.js';\r\nimport { buildCLIAgentSystemPrompt, loadContextFromEnv } from './cli-agent-context.js';\r\nimport {\r\n loadMessages,\r\n storeMessage,\r\n getCurrentFork,\r\n formatMessagesForAPI,\r\n type Message\r\n} from './conversation-fork.js';\r\nimport { convertToolNames } from './tool-definitions.js';\r\nimport fs from 'fs/promises';\r\nimport path from 'path';\r\nimport os from 'os';\r\n\r\nconst execAsync = promisify(exec);\r\n\r\n// Bug #6 Fix: Read Redis connection parameters from process.env\r\n// ENV-001: Standardized environment variable naming (REDIS_PASSWORD for all deployments)\r\nconst redisHost = process.env.CFN_REDIS_HOST || 'cfn-redis';\r\nconst redisPort = process.env.CFN_REDIS_PORT || '6379';\r\nconst redisPassword = process.env.CFN_REDIS_PASSWORD || process.env.REDIS_PASSWORD || '';\r\n\r\nexport interface AgentExecutionResult {\r\n success: boolean;\r\n agentId: string;\r\n output?: string;\r\n error?: string;\r\n exitCode: number;\r\n}\r\n\r\n/**\r\n * Parse context string into environment variables\r\n *\r\n * Parses context string like \"TASK_ID='xyz' MODE='mvp' MAX_ITERATIONS=5\"\r\n * and sets the values as environment variables.\r\n *\r\n * Supports:\r\n * - Single quoted: KEY='value with spaces'\r\n * - Double quoted: KEY=\"value with spaces\"\r\n * - Unquoted: KEY=value (no spaces in value)\r\n *\r\n * @param contextString - Context string from --context parameter\r\n * @returns Object with parsed key-value pairs\r\n */\r\nfunction parseContextToEnv(contextString: string | undefined): Record<string, string> {\r\n if (!contextString) return {};\r\n\r\n const envVars: Record<string, string> = {};\r\n\r\n // Match KEY='value' or KEY=\"value\" or KEY=value patterns\r\n // For quoted values: capture everything between quotes\r\n // For unquoted values: capture until next space or end of string\r\n const regex = /(\\w+)=(?:(['\"])([^\\2]*?)\\2|([^\\s]+))/g;\r\n let match;\r\n\r\n while ((match = regex.exec(contextString)) !== null) {\r\n const [, key, , quotedValue, unquotedValue] = match;\r\n const value = quotedValue !== undefined ? quotedValue : unquotedValue;\r\n envVars[key] = value;\r\n // Also set in process.env for current process\r\n process.env[key] = value;\r\n }\r\n\r\n return envVars;\r\n}\r\n\r\n/**\r\n * Extract confidence score from agent output\r\n * Looks for patterns like:\r\n * - \"confidence: 0.85\"\r\n * - \"Confidence: 0.90\"\r\n * - \"confidence score: 0.95\"\r\n * - \"self-confidence: 0.88\"\r\n */\r\nfunction extractConfidence(output: string | undefined): number {\r\n if (!output) return 0.85;\r\n\r\n // Try multiple patterns\r\n const patterns = [\r\n /confidence:\\s*([0-9.]+)/i,\r\n /confidence\\s+score:\\s*([0-9.]+)/i,\r\n /self-confidence:\\s*([0-9.]+)/i,\r\n /my\\s+confidence:\\s*([0-9.]+)/i,\r\n ];\r\n\r\n for (const pattern of patterns) {\r\n const match = output.match(pattern);\r\n if (match && match[1]) {\r\n const score = parseFloat(match[1]);\r\n if (score >= 0 && score <= 1) {\r\n return score;\r\n }\r\n }\r\n }\r\n\r\n // Default to 0.85 if not found\r\n return 0.85;\r\n}\r\n\r\n/**\r\n * Execute CFN Loop protocol after agent completes work\r\n *\r\n * Steps:\r\n * 1. Signal completion to orchestrator\r\n * 2. Report confidence score\r\n * 3. Enter waiting mode (if iterations enabled)\r\n */\r\nasync function executeCFNProtocol(\r\n taskId: string,\r\n agentId: string,\r\n output: string | undefined,\r\n iteration: number,\r\n enableIterations: boolean = false,\r\n maxIterations: number = 10\r\n): Promise<void> {\r\n console.log(`\\n[CFN Protocol] Starting for agent ${agentId}`);\r\n console.log(`[CFN Protocol] Task ID: ${taskId}, Iteration: ${iteration}`);\r\n\r\n try {\r\n // Step 1: Signal completion\r\n console.log('[CFN Protocol] Step 1: Signaling completion...');\r\n const authFlag = redisPassword ? `-a \"${redisPassword}\"` : '';\r\n await execAsync(`redis-cli -h \"${redisHost}\" -p \"${redisPort}\" ${authFlag} lpush \"swarm:${taskId}:${agentId}:done\" \"complete\"`);\r\n console.log('[CFN Protocol] ✓ Completion signaled');\r\n\r\n // Step 2: Extract and report confidence\r\n const confidence = extractConfidence(output);\r\n console.log(`[CFN Protocol] Step 2: Reporting confidence (${confidence})...`);\r\n\r\n const reportCmd = `./.claude/skills/cfn-redis-coordination/report-completion.sh \\\r\n --task-id \"${taskId}\" \\\r\n --agent-id \"${agentId}\" \\\r\n --confidence ${confidence} \\\r\n --iteration ${iteration}`;\r\n\r\n await execAsync(reportCmd);\r\n console.log('[CFN Protocol] ✓ Confidence reported');\r\n\r\n // Step 3: Exit cleanly (BUG #18 FIX - removed waiting mode)\r\n // Orchestrator will spawn appropriate specialist agent for next iteration\r\n // This enables adaptive agent specialization based on feedback type\r\n console.log('[CFN Protocol] Step 3: Exiting cleanly (iteration complete)');\r\n console.log('[CFN Protocol] Protocol complete\\n');\r\n } catch (error) {\r\n console.error('[CFN Protocol] Error:', error);\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Check if custom routing (z.ai) is enabled\r\n */\r\nasync function isCustomRoutingEnabled(): Promise<boolean> {\r\n // Check environment variable\r\n if (process.env.CLAUDE_API_PROVIDER === 'zai') {\r\n return true;\r\n }\r\n\r\n // Check config file (.claude/config/api-provider.json)\r\n try {\r\n const configPath = path.join('.claude', 'config', 'api-provider.json');\r\n const config = JSON.parse(await fs.readFile(configPath, 'utf-8'));\r\n return config.provider === 'zai' || config.provider === 'z.ai';\r\n } catch {\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Get API provider configuration\r\n */\r\nasync function getAPIProvider(): Promise<'anthropic' | 'zai'> {\r\n const customEnabled = await isCustomRoutingEnabled();\r\n return customEnabled ? 'zai' : 'anthropic';\r\n}\r\n\r\n/**\r\n * Execute agent using direct API calls\r\n */\r\nasync function executeViaAPI(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext\r\n): Promise<AgentExecutionResult> {\r\n const agentId = getAgentId(definition, context);\r\n\r\n console.log(`[agent-executor] Executing agent via API: ${definition.name}`);\r\n console.log(`[agent-executor] Agent ID: ${agentId}`);\r\n console.log(`[agent-executor] Model: ${definition.model}`);\r\n console.log('');\r\n\r\n // BUG #24 FIX: Parse and inject context environment variables\r\n // This enables CLI-spawned agents to access TASK_ID, MODE, etc. in Bash tool\r\n if (context.context) {\r\n console.log(`[agent-executor] Parsing context: ${context.context}`);\r\n const contextEnv = parseContextToEnv(context.context);\r\n console.log(`[agent-executor] Injected env vars: ${Object.keys(contextEnv).join(', ')}`);\r\n }\r\n\r\n try {\r\n // Check for conversation fork (Sprint 4 enhancement)\r\n const forkId = process.env.FORK_ID || await getCurrentFork(context.taskId || '', agentId);\r\n const iteration = context.iteration || 1;\r\n\r\n let systemPrompt: string;\r\n let messages: Array<{role: string, content: string}> = [];\r\n\r\n if (forkId && iteration > 1) {\r\n // Continue from fork (iterations 2+)\r\n console.log(`[agent-executor] Continuing from fork: ${forkId}`);\r\n\r\n // Load fork messages\r\n const forkMessages = await loadMessages(context.taskId || '', agentId, forkId);\r\n console.log(`[agent-executor] Loaded ${forkMessages.length} messages from fork`);\r\n\r\n // Extract system prompt from first message (it's always the system message)\r\n // The fork messages are assistant/user pairs, we need to add system separately\r\n systemPrompt = forkMessages[0]?.content || '';\r\n\r\n // Format remaining messages for API\r\n messages = formatMessagesForAPI(forkMessages.slice(1));\r\n\r\n // Add new user message with feedback\r\n messages.push({\r\n role: 'user',\r\n content: prompt\r\n });\r\n\r\n console.log(`[agent-executor] Fork continuation: ${messages.length} messages`);\r\n } else {\r\n // New conversation (iteration 1)\r\n console.log('[agent-executor] Starting new conversation');\r\n console.log('[agent-executor] Building system prompt with context...');\r\n\r\n const contextOptions = loadContextFromEnv();\r\n contextOptions.agentType = definition.name;\r\n if (context.taskId) contextOptions.taskId = context.taskId;\r\n if (context.iteration) contextOptions.iteration = context.iteration;\r\n\r\n systemPrompt = await buildCLIAgentSystemPrompt(contextOptions);\r\n console.log('[agent-executor] System prompt built successfully');\r\n\r\n // Initial user message\r\n messages = [{\r\n role: 'user',\r\n content: prompt\r\n }];\r\n }\r\n\r\n console.log('');\r\n\r\n // Dynamic import to avoid bundling issues\r\n const { executeAgentAPI } = await import('./anthropic-client.js');\r\n\r\n // Convert agent tool names to Anthropic API format\r\n const tools = definition.tools && definition.tools.length > 0\r\n ? convertToolNames(definition.tools)\r\n : undefined;\r\n\r\n const result = await executeAgentAPI(\r\n definition.name,\r\n agentId,\r\n definition.model,\r\n prompt,\r\n systemPrompt,\r\n messages.length > 1 ? messages : undefined,\r\n undefined, // maxTokens (use default)\r\n tools // Pass converted tools\r\n );\r\n\r\n // Store messages in conversation history (for future forking)\r\n if (context.taskId) {\r\n // Store user message\r\n const userMessage: Message = {\r\n role: 'user',\r\n content: prompt,\r\n iteration,\r\n timestamp: new Date().toISOString()\r\n };\r\n await storeMessage(context.taskId, agentId, userMessage);\r\n\r\n // Store assistant response\r\n if (result.output) {\r\n const assistantMessage: Message = {\r\n role: 'assistant',\r\n content: result.output,\r\n iteration,\r\n timestamp: new Date().toISOString()\r\n };\r\n await storeMessage(context.taskId, agentId, assistantMessage);\r\n }\r\n\r\n console.log(`[agent-executor] Stored messages for iteration ${iteration}`);\r\n\r\n // Execute CFN Loop protocol (signal completion, report confidence, enter waiting mode)\r\n // Iterations are enabled for CFN Loop tasks (indicated by presence of taskId)\r\n try {\r\n const maxIterations = 10; // Default max iterations\r\n const enableIterations = true; // Enable iterations for all CFN Loop tasks\r\n\r\n await executeCFNProtocol(\r\n context.taskId,\r\n agentId,\r\n result.output,\r\n iteration,\r\n enableIterations,\r\n maxIterations\r\n );\r\n } catch (error) {\r\n console.error('[agent-executor] CFN Protocol execution failed:', error);\r\n // Don't fail the entire agent execution if CFN protocol fails\r\n // This allows agents to complete even if Redis coordination has issues\r\n }\r\n }\r\n\r\n return {\r\n success: result.success,\r\n agentId,\r\n output: result.output,\r\n error: result.error,\r\n exitCode: result.success ? 0 : 1,\r\n };\r\n } catch (error) {\r\n console.error('[agent-executor] API execution failed:', error);\r\n return {\r\n success: false,\r\n agentId,\r\n error: error instanceof Error ? error.message : String(error),\r\n exitCode: 1,\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Execute agent using shell script (fallback/simulation)\r\n */\r\nasync function executeViaScript(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext\r\n): Promise<AgentExecutionResult> {\r\n const agentId = getAgentId(definition, context);\r\n\r\n // BUG #24 FIX: Parse and inject context environment variables\r\n if (context.context) {\r\n console.log(`[agent-executor] Parsing context: ${context.context}`);\r\n const contextEnv = parseContextToEnv(context.context);\r\n console.log(`[agent-executor] Injected env vars: ${Object.keys(contextEnv).join(', ')}`);\r\n }\r\n\r\n // Write prompt to temporary file\r\n const tmpDir = os.tmpdir();\r\n const promptFile = path.join(tmpDir, `agent-${agentId}-${Date.now()}.md`);\r\n await fs.writeFile(promptFile, prompt, 'utf-8');\r\n\r\n console.log(`[agent-executor] Executing agent via script: ${definition.name}`);\r\n console.log(`[agent-executor] Agent ID: ${agentId}`);\r\n console.log(`[agent-executor] Model: ${definition.model}`);\r\n console.log(`[agent-executor] Prompt file: ${promptFile}`);\r\n\r\n return new Promise((resolve) => {\r\n const scriptPath = path.join('.claude', 'skills', 'agent-execution', 'execute-agent.sh');\r\n\r\n // Build environment variables - WHITELIST ONLY APPROACH\r\n // SECURITY FIX: Do not use ...process.env spread which exposes ALL variables including secrets\r\n // Instead, explicitly whitelist safe variables to pass to spawned process\r\n const safeEnvVars = [\r\n 'CFN_REDIS_HOST',\r\n 'CFN_REDIS_PORT',\r\n 'CFN_REDIS_PASSWORD', // CRITICAL: Required for Redis authentication\r\n 'CFN_REDIS_URL',\r\n 'REDIS_PASSWORD', // Fallback for Redis password\r\n 'CFN_MEMORY_BUDGET',\r\n 'CFN_API_HOST',\r\n 'CFN_API_PORT',\r\n 'CFN_LOG_LEVEL',\r\n 'CFN_LOG_FORMAT',\r\n 'CFN_CONTAINER_MODE',\r\n 'CFN_DOCKER_SOCKET',\r\n 'CFN_NETWORK_NAME',\r\n 'CFN_CUSTOM_ROUTING',\r\n 'CFN_DEFAULT_PROVIDER',\r\n 'NODE_ENV',\r\n 'PATH',\r\n 'HOME',\r\n 'PWD' // Required for working directory context\r\n ];\r\n\r\n const env: Record<string, string> = {};\r\n\r\n // Add whitelisted variables\r\n for (const key of safeEnvVars) {\r\n const value = process.env[key];\r\n if (value !== undefined) {\r\n env[key] = value;\r\n }\r\n }\r\n\r\n // Add API key only when explicitly needed (with strict validation)\r\n if (process.env.ANTHROPIC_API_KEY) {\r\n if (process.env.ANTHROPIC_API_KEY.match(/^sk-[a-zA-Z0-9-]+$/)) {\r\n env.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;\r\n }\r\n }\r\n\r\n // Add agent execution context (safe values)\r\n env.AGENT_TYPE = definition.name;\r\n env.AGENT_ID = agentId;\r\n env.AGENT_MODEL = definition.model;\r\n env.AGENT_TOOLS = definition.tools.join(',');\r\n env.TASK_ID = context.taskId || '';\r\n env.ITERATION = String(context.iteration || 1);\r\n env.MODE = context.mode || 'cli';\r\n env.PROMPT_FILE = promptFile;\r\n\r\n // Check if execute script exists\r\n fs.access(scriptPath)\r\n .then(() => {\r\n // Use execution script\r\n const proc = spawn('bash', [scriptPath], { env, stdio: 'inherit' });\r\n\r\n proc.on('exit', (code) => {\r\n resolve({\r\n success: code === 0,\r\n agentId,\r\n exitCode: code || 0,\r\n });\r\n });\r\n\r\n proc.on('error', (err) => {\r\n resolve({\r\n success: false,\r\n agentId,\r\n error: err.message,\r\n exitCode: 1,\r\n });\r\n });\r\n })\r\n .catch(() => {\r\n // Fallback: Print prompt\r\n console.log('\\n=== Agent Prompt ===');\r\n console.log(prompt.substring(0, 500) + '...');\r\n console.log('\\n[agent-executor] Execution script not found');\r\n console.log('[agent-executor] Using simulation mode\\n');\r\n\r\n resolve({\r\n success: true,\r\n agentId,\r\n output: prompt,\r\n exitCode: 0,\r\n });\r\n });\r\n });\r\n}\r\n\r\n/**\r\n * Main agent execution function\r\n */\r\nexport async function executeAgent(\r\n definition: AgentDefinition,\r\n prompt: string,\r\n context: TaskContext,\r\n options: {\r\n method?: 'auto' | 'api' | 'script';\r\n } = {}\r\n): Promise<AgentExecutionResult> {\r\n const method = options.method || 'auto';\r\n\r\n // Auto-select execution method\r\n if (method === 'auto') {\r\n // Try API execution first, fallback to script if API key not available\r\n try {\r\n return await executeViaAPI(definition, prompt, context);\r\n } catch (error) {\r\n if (error instanceof Error && error.message.includes('API key not found')) {\r\n console.log('[agent-executor] API key not found, using script fallback');\r\n return executeViaScript(definition, prompt, context);\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n if (method === 'api') {\r\n return executeViaAPI(definition, prompt, context);\r\n }\r\n\r\n return executeViaScript(definition, prompt, context);\r\n}\r\n\r\n/**\r\n * Write agent output to file for debugging\r\n */\r\nexport async function saveAgentOutput(\r\n agentId: string,\r\n output: string,\r\n outputDir: string = '.claude/tmp/agent-output'\r\n): Promise<string> {\r\n await fs.mkdir(outputDir, { recursive: true });\r\n\r\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\r\n const filename = `${agentId}-${timestamp}.txt`;\r\n const filepath = path.join(outputDir, filename);\r\n\r\n await fs.writeFile(filepath, output, 'utf-8');\r\n\r\n return filepath;\r\n}\r\n"],"names":["spawn","exec","promisify","getAgentId","buildCLIAgentSystemPrompt","loadContextFromEnv","loadMessages","storeMessage","getCurrentFork","formatMessagesForAPI","convertToolNames","fs","path","os","execAsync","redisHost","process","env","CFN_REDIS_HOST","redisPort","CFN_REDIS_PORT","redisPassword","CFN_REDIS_PASSWORD","REDIS_PASSWORD","parseContextToEnv","contextString","envVars","regex","match","key","quotedValue","unquotedValue","value","undefined","extractConfidence","output","patterns","pattern","score","parseFloat","executeCFNProtocol","taskId","agentId","iteration","enableIterations","maxIterations","console","log","authFlag","confidence","reportCmd","error","isCustomRoutingEnabled","CLAUDE_API_PROVIDER","configPath","join","config","JSON","parse","readFile","provider","getAPIProvider","customEnabled","executeViaAPI","definition","prompt","context","name","model","contextEnv","Object","keys","forkId","FORK_ID","systemPrompt","messages","forkMessages","length","content","slice","push","role","contextOptions","agentType","executeAgentAPI","tools","result","userMessage","timestamp","Date","toISOString","assistantMessage","success","exitCode","Error","message","String","executeViaScript","tmpDir","tmpdir","promptFile","now","writeFile","Promise","resolve","scriptPath","safeEnvVars","ANTHROPIC_API_KEY","AGENT_TYPE","AGENT_ID","AGENT_MODEL","AGENT_TOOLS","TASK_ID","ITERATION","MODE","mode","PROMPT_FILE","access","then","proc","stdio","on","code","err","catch","substring","executeAgent","options","method","includes","saveAgentOutput","outputDir","mkdir","recursive","replace","filename","filepath"],"mappings":"AAAA;;;;;;;CAOC,GAED,SAASA,KAAK,QAAQ,gBAAgB;AACtC,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AAEjC,SAAsBC,UAAU,QAAQ,4BAA4B;AACpE,SAASC,yBAAyB,EAAEC,kBAAkB,QAAQ,yBAAyB;AACvF,SACEC,YAAY,EACZC,YAAY,EACZ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',
|
|
251
|
+
'CFN_REDIS_PASSWORD',
|
|
251
252
|
'CFN_REDIS_URL',
|
|
253
|
+
'REDIS_PASSWORD',
|
|
252
254
|
'CFN_MEMORY_BUDGET',
|
|
253
255
|
'CFN_API_HOST',
|
|
254
256
|
'CFN_API_PORT',
|
|
@@ -261,7 +263,8 @@
|
|
|
261
263
|
'CFN_DEFAULT_PROVIDER',
|
|
262
264
|
'NODE_ENV',
|
|
263
265
|
'PATH',
|
|
264
|
-
'HOME'
|
|
266
|
+
'HOME',
|
|
267
|
+
'PWD' // Required for working directory context
|
|
265
268
|
];
|
|
266
269
|
// Build whitelist-only env object
|
|
267
270
|
const env = {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/agent-spawn.ts"],"sourcesContent":["#!/usr/bin/env node\r\n/**\r\n * Agent Spawning CLI - Direct agent process spawning\r\n *\r\n * Usage:\r\n * npx cfn-spawn agent <type> [options]\r\n * npx cfn-spawn <type> [options] (agent is implied)\r\n *\r\n * Examples:\r\n * npx cfn-spawn agent researcher --task-id task-123 --iteration 1\r\n * npx cfn-spawn researcher --task-id task-123 --iteration 1\r\n */\r\n\r\nimport { spawn, execFileSync } from 'child_process';\r\nimport { resolve } from 'path';\r\n\r\ninterface AgentSpawnOptions {\r\n agentType: string;\r\n agentId?: string;\r\n taskId?: string;\r\n iteration?: number;\r\n context?: string;\r\n mode?: string;\r\n priority?: number;\r\n parentTaskId?: string;\r\n}\r\n\r\n/**\r\n * SECURITY: Parameter validation to prevent command injection (CVSS 8.9)\r\n * Validates all parameters that will be passed to execFileSync()\r\n */\r\n\r\n/**\r\n * Validates taskId format to prevent command injection attacks\r\n * Pattern: alphanumeric, underscore, hyphen only, 1-64 chars\r\n */\r\nfunction validateTaskId(taskId: string): { valid: boolean; error?: string } {\r\n if (typeof taskId !== 'string' || taskId.length === 0) {\r\n return { valid: false, error: 'Task ID must be a non-empty string' };\r\n }\r\n\r\n const taskIdPattern = /^[a-zA-Z0-9_-]{1,64}$/;\r\n if (!taskIdPattern.test(taskId)) {\r\n return {\r\n valid: false,\r\n error: 'Invalid task ID format - must contain only alphanumeric characters, underscores, and hyphens (max 64 chars)'\r\n };\r\n }\r\n return { valid: true };\r\n}\r\n\r\n/**\r\n * Validates Redis host to prevent command injection\r\n * Allows: hostnames, domain names, localhost, IPv4, IPv6 (::1)\r\n */\r\nfunction validateRedisHost(host: string): { valid: boolean; error?: string } {\r\n if (typeof host !== 'string' || host.length === 0) {\r\n return { valid: false, error: 'Redis host must be a non-empty string' };\r\n }\r\n\r\n // Pattern: alphanumeric, hyphens, dots (for domains), plus special IPv6 loopback\r\n const hostPattern = /^[a-zA-Z0-9.-]+$|^::1$/;\r\n if (!hostPattern.test(host)) {\r\n return { valid: false, error: 'Invalid Redis host format' };\r\n }\r\n return { valid: true };\r\n}\r\n\r\n/**\r\n * Validates Redis port to prevent command injection\r\n * Range: 1-65535\r\n */\r\nfunction validateRedisPort(port: string): { valid: boolean; error?: string } {\r\n if (typeof port !== 'string' || port.length === 0) {\r\n return { valid: false, error: 'Redis port must be a non-empty string' };\r\n }\r\n\r\n const portNum = parseInt(port, 10);\r\n if (isNaN(portNum) || portNum < 1 || portNum > 65535) {\r\n return { valid: false, error: 'Invalid Redis port - must be between 1 and 65535' };\r\n }\r\n return { valid: true };\r\n}\r\n\r\n/**\r\n * Safely retrieves context from Redis using execFileSync()\r\n * Prevents command injection by using array-based arguments instead of template literals\r\n */\r\nfunction getRedisContextSafely(\r\n taskId: string,\r\n redisHost: string,\r\n redisPort: string,\r\n contextKey: string\r\n): string {\r\n try {\r\n // Validate all parameters BEFORE executing\r\n const taskIdValidation = validateTaskId(taskId);\r\n if (!taskIdValidation.valid) {\r\n console.warn(`[cfn-spawn] Invalid task ID: ${taskIdValidation.error}`);\r\n return '';\r\n }\r\n\r\n const hostValidation = validateRedisHost(redisHost);\r\n if (!hostValidation.valid) {\r\n console.warn(`[cfn-spawn] Invalid Redis host: ${hostValidation.error}`);\r\n return '';\r\n }\r\n\r\n const portValidation = validateRedisPort(redisPort);\r\n if (!portValidation.valid) {\r\n console.warn(`[cfn-spawn] Invalid Redis port: ${portValidation.error}`);\r\n return '';\r\n }\r\n\r\n // All parameters validated - now execute safely with execFileSync()\r\n // Using array arguments prevents shell interpolation of metacharacters\r\n const redisKey = `swarm:${taskId}:${contextKey}`;\r\n const result = execFileSync('redis-cli', [\r\n '-h', redisHost,\r\n '-p', redisPort,\r\n 'get',\r\n redisKey\r\n ], { encoding: 'utf8' });\r\n\r\n const trimmed = result.trim();\r\n return trimmed === '(nil)' ? '' : trimmed;\r\n } catch (e) {\r\n // Redis not available or key doesn't exist - fail silently\r\n return '';\r\n }\r\n}\r\n\r\n/**\r\n * Parse command line arguments for agent spawning\r\n */\r\nexport function parseAgentArgs(args: string[]): AgentSpawnOptions | null {\r\n // Handle both \"agent <type>\" and \"<type>\" patterns\r\n let agentType: string;\r\n let optionArgs: string[];\r\n\r\n if (args[0] === 'agent') {\r\n agentType = args[1];\r\n optionArgs = args.slice(2);\r\n } else {\r\n agentType = args[0];\r\n optionArgs = args.slice(1);\r\n }\r\n\r\n // Validate agent type exists and is not a flag\r\n if (!agentType || agentType.startsWith('--')) {\r\n console.error('Error: Agent type is required');\r\n console.error('Usage: cfn-spawn agent <type> [options]');\r\n return null;\r\n }\r\n\r\n const options: AgentSpawnOptions = { agentType };\r\n\r\n // Parse optional parameters\r\n for (let i = 0; i < optionArgs.length; i += 2) {\r\n const key = optionArgs[i];\r\n const value = optionArgs[i + 1];\r\n\r\n switch (key) {\r\n case '--agent-id':\r\n options.agentId = value;\r\n break;\r\n case '--task-id':\r\n options.taskId = value;\r\n break;\r\n case '--iteration':\r\n options.iteration = parseInt(value, 10);\r\n break;\r\n case '--context':\r\n options.context = value;\r\n break;\r\n case '--mode':\r\n options.mode = value;\r\n break;\r\n case '--priority':\r\n options.priority = parseInt(value, 10);\r\n break;\r\n case '--parent-task':\r\n case '--parent-task-id':\r\n options.parentTaskId = value;\r\n break;\r\n default:\r\n console.warn(`Unknown option: ${key}`);\r\n }\r\n }\r\n\r\n return options;\r\n}\r\n\r\n/**\r\n * Spawn an agent process using npx claude-flow-novice agent\r\n *\r\n * This is a wrapper/alias for the existing claude-flow-novice agent spawning mechanism\r\n * Provides the cfn-spawn naming pattern while delegating to the working implementation\r\n */\r\nexport async function spawnAgent(options: AgentSpawnOptions): Promise<void> {\r\n const { agentType, agentId, taskId, iteration, context, mode, priority, parentTaskId } = options;\r\n\r\n console.log(`[cfn-spawn] Spawning agent: ${agentType}`);\r\n if (agentId) console.log(`[cfn-spawn] Agent ID: ${agentId}`);\r\n if (taskId) console.log(`[cfn-spawn] Task ID: ${taskId}`);\r\n if (iteration) console.log(`[cfn-spawn] Iteration: ${iteration}`);\r\n if (context) console.log(`[cfn-spawn] Context: ${context}`);\r\n if (mode) console.log(`[cfn-spawn] Mode: ${mode}`);\r\n\r\n // Build command arguments for npx claude-flow-novice agent\r\n const claudeArgs = ['claude-flow-novice', 'agent', agentType];\r\n\r\n // Add optional parameters\r\n if (agentId) {\r\n claudeArgs.push('--agent-id', agentId);\r\n }\r\n if (taskId) {\r\n claudeArgs.push('--task-id', taskId);\r\n }\r\n if (iteration) {\r\n claudeArgs.push('--iteration', iteration.toString());\r\n }\r\n if (context) {\r\n claudeArgs.push('--context', context);\r\n }\r\n if (mode) {\r\n claudeArgs.push('--mode', mode);\r\n }\r\n if (priority) {\r\n claudeArgs.push('--priority', priority.toString());\r\n }\r\n if (parentTaskId) {\r\n claudeArgs.push('--parent-task-id', parentTaskId);\r\n }\r\n\r\n // Fetch epic context from Redis if available\r\n let epicContext = '';\r\n let phaseContext = '';\r\n let successCriteria = '';\r\n\r\n if (taskId) {\r\n // SECURITY FIX (CVSS 8.9): Use safe parameter validation and execFileSync()\r\n // Prevent command injection by validating all parameters BEFORE execution\r\n const redisHost = process.env.CFN_REDIS_HOST || 'cfn-redis';\r\n const redisPort = process.env.CFN_REDIS_PORT || '6379';\r\n\r\n // Validate Redis connection parameters\r\n const hostValidation = validateRedisHost(redisHost);\r\n const portValidation = validateRedisPort(redisPort);\r\n\r\n if (hostValidation.valid && portValidation.valid) {\r\n // Try to read epic-level context from Redis\r\n epicContext = getRedisContextSafely(taskId, redisHost, redisPort, 'epic-context');\r\n\r\n // Try to read phase-specific context\r\n phaseContext = getRedisContextSafely(taskId, redisHost, redisPort, 'phase-context');\r\n\r\n // Try to read success criteria\r\n successCriteria = getRedisContextSafely(taskId, redisHost, redisPort, 'success-criteria');\r\n\r\n if (epicContext) {\r\n console.log(`[cfn-spawn] Epic context loaded from Redis`);\r\n }\r\n } else {\r\n console.warn(`[cfn-spawn] Invalid Redis configuration - skipping context load`);\r\n if (!hostValidation.valid) console.warn(`[cfn-spawn] ${hostValidation.error}`);\r\n if (!portValidation.valid) console.warn(`[cfn-spawn] ${portValidation.error}`);\r\n }\r\n }\r\n\r\n // Add environment variables for agent context - WHITELIST ONLY APPROACH\r\n // SECURITY FIX: Do not use ...process.env spread which exposes ALL variables including secrets\r\n // Instead, explicitly whitelist safe variables to pass to spawned process\r\n const safeEnvVars = [\r\n 'CFN_REDIS_HOST',\r\n 'CFN_REDIS_PORT',\r\n 'CFN_REDIS_URL',\r\n 'CFN_MEMORY_BUDGET',\r\n 'CFN_API_HOST',\r\n 'CFN_API_PORT',\r\n 'CFN_LOG_LEVEL',\r\n 'CFN_LOG_FORMAT',\r\n 'CFN_CONTAINER_MODE',\r\n 'CFN_DOCKER_SOCKET',\r\n 'CFN_NETWORK_NAME',\r\n 'CFN_CUSTOM_ROUTING',\r\n 'CFN_DEFAULT_PROVIDER',\r\n 'NODE_ENV',\r\n 'PATH',\r\n 'HOME'\r\n ];\r\n\r\n // Build whitelist-only env object\r\n const env: Record<string, string> = {};\r\n\r\n // Add whitelisted CFN variables\r\n for (const key of safeEnvVars) {\r\n const value = process.env[key];\r\n if (value !== undefined) {\r\n env[key] = value;\r\n }\r\n }\r\n\r\n // Add API key only when explicitly needed (with strict validation)\r\n if (process.env.ANTHROPIC_API_KEY) {\r\n // Validate format: should start with \"sk-\" or \"sk-ant-\"\r\n if (process.env.ANTHROPIC_API_KEY.match(/^sk-[a-zA-Z0-9-]+$/)) {\r\n env.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;\r\n } else {\r\n console.warn('[cfn-spawn] Warning: ANTHROPIC_API_KEY format invalid, not passing to agent');\r\n }\r\n }\r\n\r\n // Add task and execution context variables\r\n env.AGENT_TYPE = agentType;\r\n env.TASK_ID = taskId || '';\r\n env.ITERATION = iteration?.toString() || '1';\r\n env.CONTEXT = context || '';\r\n env.MODE = mode || 'cli';\r\n env.PRIORITY = priority?.toString() || '5';\r\n env.PARENT_TASK_ID = parentTaskId || '';\r\n\r\n // Epic-level context from Redis (sanitized)\r\n env.EPIC_CONTEXT = epicContext;\r\n env.PHASE_CONTEXT = phaseContext;\r\n env.SUCCESS_CRITERIA = successCriteria;\r\n\r\n console.log(`[cfn-spawn] Executing: npx ${claudeArgs.join(' ')}`);\r\n\r\n // Spawn the claude-flow-novice agent process\r\n const agentProcess = spawn('npx', claudeArgs, {\r\n stdio: 'inherit',\r\n env,\r\n cwd: process.cwd()\r\n });\r\n\r\n // Handle process exit\r\n agentProcess.on('exit', (code, signal) => {\r\n if (code === 0) {\r\n console.log(`[cfn-spawn] Agent ${agentType} completed successfully`);\r\n } else {\r\n console.error(`[cfn-spawn] Agent ${agentType} exited with code ${code}, signal ${signal}`);\r\n }\r\n process.exit(code || 0);\r\n });\r\n\r\n // Handle process errors\r\n agentProcess.on('error', (err) => {\r\n console.error(`[cfn-spawn] Failed to spawn agent ${agentType}:`, err.message);\r\n process.exit(1);\r\n });\r\n\r\n // Cleanup on parent exit\r\n process.on('SIGINT', () => {\r\n console.log('\\n[cfn-spawn] Received SIGINT, terminating agent...');\r\n agentProcess.kill('SIGINT');\r\n });\r\n\r\n process.on('SIGTERM', () => {\r\n console.log('\\n[cfn-spawn] Received SIGTERM, terminating agent...');\r\n agentProcess.kill('SIGTERM');\r\n });\r\n}\r\n\r\n/**\r\n * Build task description for the agent\r\n */\r\nexport function buildTaskDescription(\r\n agentType: string,\r\n taskId?: string,\r\n iteration?: number,\r\n context?: string\r\n): string {\r\n let desc = `Execute task as ${agentType} agent`;\r\n\r\n if (taskId) desc += ` for task ${taskId}`;\r\n if (iteration !== undefined) desc += ` (iteration ${iteration})`;\r\n if (context) desc += `: ${context}`;\r\n\r\n return desc;\r\n}\r\n\r\n/**\r\n * Main CLI entry point\r\n */\r\nexport async function main(args: string[] = process.argv.slice(2)): Promise<void> {\r\n // Show help if requested\r\n if (args.includes('--help') || args.includes('-h')) {\r\n console.log(`\r\ncfn-spawn - Claude Flow Novice Agent Spawner\r\n\r\nUsage:\r\n cfn-spawn agent <type> [options]\r\n cfn-spawn <type> [options] (agent is implied)\r\n\r\nOptions:\r\n --agent-id <id> Explicit agent identifier (overrides auto-generation)\r\n --task-id <id> Task identifier\r\n --iteration <n> Iteration number\r\n --context <text> Context description\r\n --mode <mode> Execution mode (cli, api, hybrid)\r\n --priority <1-10> Task priority\r\n --parent-task-id <id> Parent task identifier\r\n\r\nExamples:\r\n cfn-spawn agent researcher --task-id task-123 --iteration 1\r\n cfn-spawn coder --task-id auth-impl --context \"Implement JWT auth\"\r\n cfn-spawn reviewer --task-id auth-impl --iteration 2 --mode cli\r\n cfn-spawn tester --agent-id tester-1-1 --task-id test-phase --iteration 1\r\n `);\r\n return;\r\n }\r\n\r\n // Parse arguments\r\n const options = parseAgentArgs(args);\r\n if (!options) {\r\n process.exit(1);\r\n }\r\n\r\n // Spawn the agent\r\n await spawnAgent(options);\r\n}\r\n\r\n// Run if called directly\r\n// ES module check - compare import.meta.url with the executed file\r\nconst isMainModule = import.meta.url.endsWith(process.argv[1]?.replace(/\\\\/g, '/') || '');\r\nif (isMainModule) {\r\n main().catch((err) => {\r\n console.error('[cfn-spawn] Fatal error:', err);\r\n process.exit(1);\r\n });\r\n}\r\n"],"names":["spawn","execFileSync","validateTaskId","taskId","length","valid","error","taskIdPattern","test","validateRedisHost","host","hostPattern","validateRedisPort","port","portNum","parseInt","isNaN","getRedisContextSafely","redisHost","redisPort","contextKey","taskIdValidation","console","warn","hostValidation","portValidation","redisKey","result","encoding","trimmed","trim","e","parseAgentArgs","args","agentType","optionArgs","slice","startsWith","options","i","key","value","agentId","iteration","context","mode","priority","parentTaskId","spawnAgent","log","claudeArgs","push","toString","epicContext","phaseContext","successCriteria","process","env","CFN_REDIS_HOST","CFN_REDIS_PORT","safeEnvVars","undefined","ANTHROPIC_API_KEY","match","AGENT_TYPE","TASK_ID","ITERATION","CONTEXT","MODE","PRIORITY","PARENT_TASK_ID","EPIC_CONTEXT","PHASE_CONTEXT","SUCCESS_CRITERIA","join","agentProcess","stdio","cwd","on","code","signal","exit","err","message","kill","buildTaskDescription","desc","main","argv","includes","isMainModule","url","endsWith","replace","catch"],"mappings":";AACA;;;;;;;;;;CAUC,GAED,SAASA,KAAK,EAAEC,YAAY,QAAQ,gBAAgB;AAcpD;;;CAGC,GAED;;;CAGC,GACD,SAASC,eAAeC,MAAc;IACpC,IAAI,OAAOA,WAAW,YAAYA,OAAOC,MAAM,KAAK,GAAG;QACrD,OAAO;YAAEC,OAAO;YAAOC,OAAO;QAAqC;IACrE;IAEA,MAAMC,gBAAgB;IACtB,IAAI,CAACA,cAAcC,IAAI,CAACL,SAAS;QAC/B,OAAO;YACLE,OAAO;YACPC,OAAO;QACT;IACF;IACA,OAAO;QAAED,OAAO;IAAK;AACvB;AAEA;;;CAGC,GACD,SAASI,kBAAkBC,IAAY;IACrC,IAAI,OAAOA,SAAS,YAAYA,KAAKN,MAAM,KAAK,GAAG;QACjD,OAAO;YAAEC,OAAO;YAAOC,OAAO;QAAwC;IACxE;IAEA,iFAAiF;IACjF,MAAMK,cAAc;IACpB,IAAI,CAACA,YAAYH,IAAI,CAACE,OAAO;QAC3B,OAAO;YAAEL,OAAO;YAAOC,OAAO;QAA4B;IAC5D;IACA,OAAO;QAAED,OAAO;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/env node\r\n/**\r\n * Agent Spawning CLI - Direct agent process spawning\r\n *\r\n * Usage:\r\n * npx cfn-spawn agent <type> [options]\r\n * npx cfn-spawn <type> [options] (agent is implied)\r\n *\r\n * Examples:\r\n * npx cfn-spawn agent researcher --task-id task-123 --iteration 1\r\n * npx cfn-spawn researcher --task-id task-123 --iteration 1\r\n */\r\n\r\nimport { spawn, execFileSync } from 'child_process';\r\nimport { resolve } from 'path';\r\n\r\ninterface AgentSpawnOptions {\r\n agentType: string;\r\n agentId?: string;\r\n taskId?: string;\r\n iteration?: number;\r\n context?: string;\r\n mode?: string;\r\n priority?: number;\r\n parentTaskId?: string;\r\n}\r\n\r\n/**\r\n * SECURITY: Parameter validation to prevent command injection (CVSS 8.9)\r\n * Validates all parameters that will be passed to execFileSync()\r\n */\r\n\r\n/**\r\n * Validates taskId format to prevent command injection attacks\r\n * Pattern: alphanumeric, underscore, hyphen only, 1-64 chars\r\n */\r\nfunction validateTaskId(taskId: string): { valid: boolean; error?: string } {\r\n if (typeof taskId !== 'string' || taskId.length === 0) {\r\n return { valid: false, error: 'Task ID must be a non-empty string' };\r\n }\r\n\r\n const taskIdPattern = /^[a-zA-Z0-9_-]{1,64}$/;\r\n if (!taskIdPattern.test(taskId)) {\r\n return {\r\n valid: false,\r\n error: 'Invalid task ID format - must contain only alphanumeric characters, underscores, and hyphens (max 64 chars)'\r\n };\r\n }\r\n return { valid: true };\r\n}\r\n\r\n/**\r\n * Validates Redis host to prevent command injection\r\n * Allows: hostnames, domain names, localhost, IPv4, IPv6 (::1)\r\n */\r\nfunction validateRedisHost(host: string): { valid: boolean; error?: string } {\r\n if (typeof host !== 'string' || host.length === 0) {\r\n return { valid: false, error: 'Redis host must be a non-empty string' };\r\n }\r\n\r\n // Pattern: alphanumeric, hyphens, dots (for domains), plus special IPv6 loopback\r\n const hostPattern = /^[a-zA-Z0-9.-]+$|^::1$/;\r\n if (!hostPattern.test(host)) {\r\n return { valid: false, error: 'Invalid Redis host format' };\r\n }\r\n return { valid: true };\r\n}\r\n\r\n/**\r\n * Validates Redis port to prevent command injection\r\n * Range: 1-65535\r\n */\r\nfunction validateRedisPort(port: string): { valid: boolean; error?: string } {\r\n if (typeof port !== 'string' || port.length === 0) {\r\n return { valid: false, error: 'Redis port must be a non-empty string' };\r\n }\r\n\r\n const portNum = parseInt(port, 10);\r\n if (isNaN(portNum) || portNum < 1 || portNum > 65535) {\r\n return { valid: false, error: 'Invalid Redis port - must be between 1 and 65535' };\r\n }\r\n return { valid: true };\r\n}\r\n\r\n/**\r\n * Safely retrieves context from Redis using execFileSync()\r\n * Prevents command injection by using array-based arguments instead of template literals\r\n */\r\nfunction getRedisContextSafely(\r\n taskId: string,\r\n redisHost: string,\r\n redisPort: string,\r\n contextKey: string\r\n): string {\r\n try {\r\n // Validate all parameters BEFORE executing\r\n const taskIdValidation = validateTaskId(taskId);\r\n if (!taskIdValidation.valid) {\r\n console.warn(`[cfn-spawn] Invalid task ID: ${taskIdValidation.error}`);\r\n return '';\r\n }\r\n\r\n const hostValidation = validateRedisHost(redisHost);\r\n if (!hostValidation.valid) {\r\n console.warn(`[cfn-spawn] Invalid Redis host: ${hostValidation.error}`);\r\n return '';\r\n }\r\n\r\n const portValidation = validateRedisPort(redisPort);\r\n if (!portValidation.valid) {\r\n console.warn(`[cfn-spawn] Invalid Redis port: ${portValidation.error}`);\r\n return '';\r\n }\r\n\r\n // All parameters validated - now execute safely with execFileSync()\r\n // Using array arguments prevents shell interpolation of metacharacters\r\n const redisKey = `swarm:${taskId}:${contextKey}`;\r\n const result = execFileSync('redis-cli', [\r\n '-h', redisHost,\r\n '-p', redisPort,\r\n 'get',\r\n redisKey\r\n ], { encoding: 'utf8' });\r\n\r\n const trimmed = result.trim();\r\n return trimmed === '(nil)' ? '' : trimmed;\r\n } catch (e) {\r\n // Redis not available or key doesn't exist - fail silently\r\n return '';\r\n }\r\n}\r\n\r\n/**\r\n * Parse command line arguments for agent spawning\r\n */\r\nexport function parseAgentArgs(args: string[]): AgentSpawnOptions | null {\r\n // Handle both \"agent <type>\" and \"<type>\" patterns\r\n let agentType: string;\r\n let optionArgs: string[];\r\n\r\n if (args[0] === 'agent') {\r\n agentType = args[1];\r\n optionArgs = args.slice(2);\r\n } else {\r\n agentType = args[0];\r\n optionArgs = args.slice(1);\r\n }\r\n\r\n // Validate agent type exists and is not a flag\r\n if (!agentType || agentType.startsWith('--')) {\r\n console.error('Error: Agent type is required');\r\n console.error('Usage: cfn-spawn agent <type> [options]');\r\n return null;\r\n }\r\n\r\n const options: AgentSpawnOptions = { agentType };\r\n\r\n // Parse optional parameters\r\n for (let i = 0; i < optionArgs.length; i += 2) {\r\n const key = optionArgs[i];\r\n const value = optionArgs[i + 1];\r\n\r\n switch (key) {\r\n case '--agent-id':\r\n options.agentId = value;\r\n break;\r\n case '--task-id':\r\n options.taskId = value;\r\n break;\r\n case '--iteration':\r\n options.iteration = parseInt(value, 10);\r\n break;\r\n case '--context':\r\n options.context = value;\r\n break;\r\n case '--mode':\r\n options.mode = value;\r\n break;\r\n case '--priority':\r\n options.priority = parseInt(value, 10);\r\n break;\r\n case '--parent-task':\r\n case '--parent-task-id':\r\n options.parentTaskId = value;\r\n break;\r\n default:\r\n console.warn(`Unknown option: ${key}`);\r\n }\r\n }\r\n\r\n return options;\r\n}\r\n\r\n/**\r\n * Spawn an agent process using npx claude-flow-novice agent\r\n *\r\n * This is a wrapper/alias for the existing claude-flow-novice agent spawning mechanism\r\n * Provides the cfn-spawn naming pattern while delegating to the working implementation\r\n */\r\nexport async function spawnAgent(options: AgentSpawnOptions): Promise<void> {\r\n const { agentType, agentId, taskId, iteration, context, mode, priority, parentTaskId } = options;\r\n\r\n console.log(`[cfn-spawn] Spawning agent: ${agentType}`);\r\n if (agentId) console.log(`[cfn-spawn] Agent ID: ${agentId}`);\r\n if (taskId) console.log(`[cfn-spawn] Task ID: ${taskId}`);\r\n if (iteration) console.log(`[cfn-spawn] Iteration: ${iteration}`);\r\n if (context) console.log(`[cfn-spawn] Context: ${context}`);\r\n if (mode) console.log(`[cfn-spawn] Mode: ${mode}`);\r\n\r\n // Build command arguments for npx claude-flow-novice agent\r\n const claudeArgs = ['claude-flow-novice', 'agent', agentType];\r\n\r\n // Add optional parameters\r\n if (agentId) {\r\n claudeArgs.push('--agent-id', agentId);\r\n }\r\n if (taskId) {\r\n claudeArgs.push('--task-id', taskId);\r\n }\r\n if (iteration) {\r\n claudeArgs.push('--iteration', iteration.toString());\r\n }\r\n if (context) {\r\n claudeArgs.push('--context', context);\r\n }\r\n if (mode) {\r\n claudeArgs.push('--mode', mode);\r\n }\r\n if (priority) {\r\n claudeArgs.push('--priority', priority.toString());\r\n }\r\n if (parentTaskId) {\r\n claudeArgs.push('--parent-task-id', parentTaskId);\r\n }\r\n\r\n // Fetch epic context from Redis if available\r\n let epicContext = '';\r\n let phaseContext = '';\r\n let successCriteria = '';\r\n\r\n if (taskId) {\r\n // SECURITY FIX (CVSS 8.9): Use safe parameter validation and execFileSync()\r\n // Prevent command injection by validating all parameters BEFORE execution\r\n const redisHost = process.env.CFN_REDIS_HOST || 'cfn-redis';\r\n const redisPort = process.env.CFN_REDIS_PORT || '6379';\r\n\r\n // Validate Redis connection parameters\r\n const hostValidation = validateRedisHost(redisHost);\r\n const portValidation = validateRedisPort(redisPort);\r\n\r\n if (hostValidation.valid && portValidation.valid) {\r\n // Try to read epic-level context from Redis\r\n epicContext = getRedisContextSafely(taskId, redisHost, redisPort, 'epic-context');\r\n\r\n // Try to read phase-specific context\r\n phaseContext = getRedisContextSafely(taskId, redisHost, redisPort, 'phase-context');\r\n\r\n // Try to read success criteria\r\n successCriteria = getRedisContextSafely(taskId, redisHost, redisPort, 'success-criteria');\r\n\r\n if (epicContext) {\r\n console.log(`[cfn-spawn] Epic context loaded from Redis`);\r\n }\r\n } else {\r\n console.warn(`[cfn-spawn] Invalid Redis configuration - skipping context load`);\r\n if (!hostValidation.valid) console.warn(`[cfn-spawn] ${hostValidation.error}`);\r\n if (!portValidation.valid) console.warn(`[cfn-spawn] ${portValidation.error}`);\r\n }\r\n }\r\n\r\n // Add environment variables for agent context - WHITELIST ONLY APPROACH\r\n // SECURITY FIX: Do not use ...process.env spread which exposes ALL variables including secrets\r\n // Instead, explicitly whitelist safe variables to pass to spawned process\r\n const safeEnvVars = [\r\n 'CFN_REDIS_HOST',\r\n 'CFN_REDIS_PORT',\r\n 'CFN_REDIS_PASSWORD', // CRITICAL: Required for Redis authentication\r\n 'CFN_REDIS_URL',\r\n 'REDIS_PASSWORD', // Fallback for Redis password\r\n 'CFN_MEMORY_BUDGET',\r\n 'CFN_API_HOST',\r\n 'CFN_API_PORT',\r\n 'CFN_LOG_LEVEL',\r\n 'CFN_LOG_FORMAT',\r\n 'CFN_CONTAINER_MODE',\r\n 'CFN_DOCKER_SOCKET',\r\n 'CFN_NETWORK_NAME',\r\n 'CFN_CUSTOM_ROUTING',\r\n 'CFN_DEFAULT_PROVIDER',\r\n 'NODE_ENV',\r\n 'PATH',\r\n 'HOME',\r\n 'PWD' // Required for working directory context\r\n ];\r\n\r\n // Build whitelist-only env object\r\n const env: Record<string, string> = {};\r\n\r\n // Add whitelisted CFN variables\r\n for (const key of safeEnvVars) {\r\n const value = process.env[key];\r\n if (value !== undefined) {\r\n env[key] = value;\r\n }\r\n }\r\n\r\n // Add API key only when explicitly needed (with strict validation)\r\n if (process.env.ANTHROPIC_API_KEY) {\r\n // Validate format: should start with \"sk-\" or \"sk-ant-\"\r\n if (process.env.ANTHROPIC_API_KEY.match(/^sk-[a-zA-Z0-9-]+$/)) {\r\n env.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;\r\n } else {\r\n console.warn('[cfn-spawn] Warning: ANTHROPIC_API_KEY format invalid, not passing to agent');\r\n }\r\n }\r\n\r\n // Add task and execution context variables\r\n env.AGENT_TYPE = agentType;\r\n env.TASK_ID = taskId || '';\r\n env.ITERATION = iteration?.toString() || '1';\r\n env.CONTEXT = context || '';\r\n env.MODE = mode || 'cli';\r\n env.PRIORITY = priority?.toString() || '5';\r\n env.PARENT_TASK_ID = parentTaskId || '';\r\n\r\n // Epic-level context from Redis (sanitized)\r\n env.EPIC_CONTEXT = epicContext;\r\n env.PHASE_CONTEXT = phaseContext;\r\n env.SUCCESS_CRITERIA = successCriteria;\r\n\r\n console.log(`[cfn-spawn] Executing: npx ${claudeArgs.join(' ')}`);\r\n\r\n // Spawn the claude-flow-novice agent process\r\n const agentProcess = spawn('npx', claudeArgs, {\r\n stdio: 'inherit',\r\n env,\r\n cwd: process.cwd()\r\n });\r\n\r\n // Handle process exit\r\n agentProcess.on('exit', (code, signal) => {\r\n if (code === 0) {\r\n console.log(`[cfn-spawn] Agent ${agentType} completed successfully`);\r\n } else {\r\n console.error(`[cfn-spawn] Agent ${agentType} exited with code ${code}, signal ${signal}`);\r\n }\r\n process.exit(code || 0);\r\n });\r\n\r\n // Handle process errors\r\n agentProcess.on('error', (err) => {\r\n console.error(`[cfn-spawn] Failed to spawn agent ${agentType}:`, err.message);\r\n process.exit(1);\r\n });\r\n\r\n // Cleanup on parent exit\r\n process.on('SIGINT', () => {\r\n console.log('\\n[cfn-spawn] Received SIGINT, terminating agent...');\r\n agentProcess.kill('SIGINT');\r\n });\r\n\r\n process.on('SIGTERM', () => {\r\n console.log('\\n[cfn-spawn] Received SIGTERM, terminating agent...');\r\n agentProcess.kill('SIGTERM');\r\n });\r\n}\r\n\r\n/**\r\n * Build task description for the agent\r\n */\r\nexport function buildTaskDescription(\r\n agentType: string,\r\n taskId?: string,\r\n iteration?: number,\r\n context?: string\r\n): string {\r\n let desc = `Execute task as ${agentType} agent`;\r\n\r\n if (taskId) desc += ` for task ${taskId}`;\r\n if (iteration !== undefined) desc += ` (iteration ${iteration})`;\r\n if (context) desc += `: ${context}`;\r\n\r\n return desc;\r\n}\r\n\r\n/**\r\n * Main CLI entry point\r\n */\r\nexport async function main(args: string[] = process.argv.slice(2)): Promise<void> {\r\n // Show help if requested\r\n if (args.includes('--help') || args.includes('-h')) {\r\n console.log(`\r\ncfn-spawn - Claude Flow Novice Agent Spawner\r\n\r\nUsage:\r\n cfn-spawn agent <type> [options]\r\n cfn-spawn <type> [options] (agent is implied)\r\n\r\nOptions:\r\n --agent-id <id> Explicit agent identifier (overrides auto-generation)\r\n --task-id <id> Task identifier\r\n --iteration <n> Iteration number\r\n --context <text> Context description\r\n --mode <mode> Execution mode (cli, api, hybrid)\r\n --priority <1-10> Task priority\r\n --parent-task-id <id> Parent task identifier\r\n\r\nExamples:\r\n cfn-spawn agent researcher --task-id task-123 --iteration 1\r\n cfn-spawn coder --task-id auth-impl --context \"Implement JWT auth\"\r\n cfn-spawn reviewer --task-id auth-impl --iteration 2 --mode cli\r\n cfn-spawn tester --agent-id tester-1-1 --task-id test-phase --iteration 1\r\n `);\r\n return;\r\n }\r\n\r\n // Parse arguments\r\n const options = parseAgentArgs(args);\r\n if (!options) {\r\n process.exit(1);\r\n }\r\n\r\n // Spawn the agent\r\n await spawnAgent(options);\r\n}\r\n\r\n// Run if called directly\r\n// ES module check - compare import.meta.url with the executed file\r\nconst isMainModule = import.meta.url.endsWith(process.argv[1]?.replace(/\\\\/g, '/') || '');\r\nif (isMainModule) {\r\n main().catch((err) => {\r\n console.error('[cfn-spawn] Fatal error:', err);\r\n process.exit(1);\r\n });\r\n}\r\n"],"names":["spawn","execFileSync","validateTaskId","taskId","length","valid","error","taskIdPattern","test","validateRedisHost","host","hostPattern","validateRedisPort","port","portNum","parseInt","isNaN","getRedisContextSafely","redisHost","redisPort","contextKey","taskIdValidation","console","warn","hostValidation","portValidation","redisKey","result","encoding","trimmed","trim","e","parseAgentArgs","args","agentType","optionArgs","slice","startsWith","options","i","key","value","agentId","iteration","context","mode","priority","parentTaskId","spawnAgent","log","claudeArgs","push","toString","epicContext","phaseContext","successCriteria","process","env","CFN_REDIS_HOST","CFN_REDIS_PORT","safeEnvVars","undefined","ANTHROPIC_API_KEY","match","AGENT_TYPE","TASK_ID","ITERATION","CONTEXT","MODE","PRIORITY","PARENT_TASK_ID","EPIC_CONTEXT","PHASE_CONTEXT","SUCCESS_CRITERIA","join","agentProcess","stdio","cwd","on","code","signal","exit","err","message","kill","buildTaskDescription","desc","main","argv","includes","isMainModule","url","endsWith","replace","catch"],"mappings":";AACA;;;;;;;;;;CAUC,GAED,SAASA,KAAK,EAAEC,YAAY,QAAQ,gBAAgB;AAcpD;;;CAGC,GAED;;;CAGC,GACD,SAASC,eAAeC,MAAc;IACpC,IAAI,OAAOA,WAAW,YAAYA,OAAOC,MAAM,KAAK,GAAG;QACrD,OAAO;YAAEC,OAAO;YAAOC,OAAO;QAAqC;IACrE;IAEA,MAAMC,gBAAgB;IACtB,IAAI,CAACA,cAAcC,IAAI,CAACL,SAAS;QAC/B,OAAO;YACLE,OAAO;YACPC,OAAO;QACT;IACF;IACA,OAAO;QAAED,OAAO;IAAK;AACvB;AAEA;;;CAGC,GACD,SAASI,kBAAkBC,IAAY;IACrC,IAAI,OAAOA,SAAS,YAAYA,KAAKN,MAAM,KAAK,GAAG;QACjD,OAAO;YAAEC,OAAO;YAAOC,OAAO;QAAwC;IACxE;IAEA,iFAAiF;IACjF,MAAMK,cAAc;IACpB,IAAI,CAACA,YAAYH,IAAI,CAACE,OAAO;QAC3B,OAAO;YAAEL,OAAO;YAAOC,OAAO;QAA4B;IAC5D;IACA,OAAO;QAAED,OAAO;IAAK;AACvB;AAEA;;;CAGC,GACD,SAASO,kBAAkBC,IAAY;IACrC,IAAI,OAAOA,SAAS,YAAYA,KAAKT,MAAM,KAAK,GAAG;QACjD,OAAO;YAAEC,OAAO;YAAOC,OAAO;QAAwC;IACxE;IAEA,MAAMQ,UAAUC,SAASF,MAAM;IAC/B,IAAIG,MAAMF,YAAYA,UAAU,KAAKA,UAAU,OAAO;QACpD,OAAO;YAAET,OAAO;YAAOC,OAAO;QAAmD;IACnF;IACA,OAAO;QAAED,OAAO;IAAK;AACvB;AAEA;;;CAGC,GACD,SAASY,sBACPd,MAAc,EACde,SAAiB,EACjBC,SAAiB,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,QAAQ,CAAC,YAAY,EAAE3C,UAAU,CAAC,CAAC;IAChE,IAAIC,SAAS0C,QAAQ,CAAC,EAAE,EAAE1C,SAAS;IAEnC,OAAO0C;AACT;AAEA;;CAEC,GACD,OAAO,eAAeC,KAAKtD,OAAiBuB,QAAQgC,IAAI,CAACpD,KAAK,CAAC,EAAE;IAC/D,yBAAyB;IACzB,IAAIH,KAAKwD,QAAQ,CAAC,aAAaxD,KAAKwD,QAAQ,CAAC,OAAO;QAClDnE,QAAQ2B,GAAG,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;IAqBb,CAAC;QACD;IACF;IAEA,kBAAkB;IAClB,MAAMX,UAAUN,eAAeC;IAC/B,IAAI,CAACK,SAAS;QACZkB,QAAQyB,IAAI,CAAC;IACf;IAEA,kBAAkB;IAClB,MAAMjC,WAAWV;AACnB;AAEA,yBAAyB;AACzB,mEAAmE;AACnE,MAAMoD,eAAe,YAAYC,GAAG,CAACC,QAAQ,CAACpC,QAAQgC,IAAI,CAAC,EAAE,EAAEK,QAAQ,OAAO,QAAQ;AACtF,IAAIH,cAAc;IAChBH,OAAOO,KAAK,CAAC,CAACZ;QACZ5D,QAAQhB,KAAK,CAAC,4BAA4B4E;QAC1C1B,QAAQyB,IAAI,CAAC;IACf;AACF"}
|
|
@@ -139,9 +139,11 @@ const execAsync = promisify(exec);
|
|
|
139
139
|
return `Command started in background: ${command}`;
|
|
140
140
|
}
|
|
141
141
|
// Execute synchronously with timeout
|
|
142
|
+
// CRITICAL: Use /bin/bash instead of /bin/sh for [[ ]] support
|
|
142
143
|
const { stdout, stderr } = await execAsync(command, {
|
|
143
144
|
timeout: timeoutMs,
|
|
144
|
-
maxBuffer: 10 * 1024 * 1024
|
|
145
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
146
|
+
shell: '/bin/bash' // REQUIRED: Coordinator uses [[ ]] conditionals
|
|
145
147
|
});
|
|
146
148
|
return stdout + stderr;
|
|
147
149
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cli/tool-executor.ts"],"sourcesContent":["/**\r\n * Tool Executor for CLI-Spawned Agents\r\n *\r\n * Executes tools requested by agents via Anthropic API tool_use blocks.\r\n * Implements Read, Write, Edit, Bash, TodoWrite, Glob, Grep.\r\n */\r\n\r\nimport fs from 'fs/promises';\r\nimport { exec } from 'child_process';\r\nimport { promisify } from 'util';\r\nimport { glob } from 'glob';\r\n\r\nconst execAsync = promisify(exec);\r\n\r\nexport interface ToolUse {\r\n type: 'tool_use';\r\n id: string;\r\n name: string;\r\n input: Record<string, any>;\r\n}\r\n\r\nexport interface ToolResult {\r\n type: 'tool_result';\r\n tool_use_id: string;\r\n content: string;\r\n is_error?: boolean;\r\n}\r\n\r\n/**\r\n * Execute a single tool and return result\r\n */\r\nexport async function executeTool(toolUse: ToolUse): Promise<ToolResult> {\r\n console.log(`[tool-executor] Executing tool: ${toolUse.name}`);\r\n console.log(`[tool-executor] Tool use ID: ${toolUse.id}`);\r\n\r\n try {\r\n let result: string;\r\n\r\n switch (toolUse.name) {\r\n case 'Read':\r\n result = await executeRead(toolUse.input);\r\n break;\r\n\r\n case 'Write':\r\n result = await executeWrite(toolUse.input);\r\n break;\r\n\r\n case 'Edit':\r\n result = await executeEdit(toolUse.input);\r\n break;\r\n\r\n case 'Bash':\r\n result = await executeBash(toolUse.input);\r\n break;\r\n\r\n case 'TodoWrite':\r\n result = await executeTodoWrite(toolUse.input);\r\n break;\r\n\r\n case 'Glob':\r\n result = await executeGlob(toolUse.input);\r\n break;\r\n\r\n case 'Grep':\r\n result = await executeGrep(toolUse.input);\r\n break;\r\n\r\n default:\r\n throw new Error(`Unknown tool: ${toolUse.name}`);\r\n }\r\n\r\n console.log(`[tool-executor] ✓ Tool executed successfully`);\r\n\r\n return {\r\n type: 'tool_result',\r\n tool_use_id: toolUse.id,\r\n content: result\r\n };\r\n } catch (error) {\r\n console.error(`[tool-executor] ✗ Tool execution failed:`, error);\r\n\r\n return {\r\n type: 'tool_result',\r\n tool_use_id: toolUse.id,\r\n content: error instanceof Error ? error.message : String(error),\r\n is_error: true\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Execute Read tool\r\n */\r\nasync function executeRead(input: Record<string, any>): Promise<string> {\r\n const { file_path, offset, limit } = input;\r\n\r\n if (!file_path) {\r\n throw new Error('file_path parameter is required');\r\n }\r\n\r\n const content = await fs.readFile(file_path, 'utf-8');\r\n const lines = content.split('\\n');\r\n\r\n // Apply offset and limit if provided\r\n const startLine = offset ? Number(offset) - 1 : 0;\r\n const endLine = limit ? startLine + Number(limit) : lines.length;\r\n const selectedLines = lines.slice(startLine, endLine);\r\n\r\n // Format with line numbers (cat -n style)\r\n const formatted = selectedLines\r\n .map((line, idx) => `${String(startLine + idx + 1).padStart(6)}→${line}`)\r\n .join('\\n');\r\n\r\n return formatted;\r\n}\r\n\r\n/**\r\n * Execute Write tool\r\n */\r\nasync function executeWrite(input: Record<string, any>): Promise<string> {\r\n const { file_path, content } = input;\r\n\r\n if (!file_path) {\r\n throw new Error('file_path parameter is required');\r\n }\r\n\r\n if (content === undefined) {\r\n throw new Error('content parameter is required');\r\n }\r\n\r\n await fs.writeFile(file_path, content, 'utf-8');\r\n\r\n return `File written successfully: ${file_path}`;\r\n}\r\n\r\n/**\r\n * Execute Edit tool\r\n */\r\nasync function executeEdit(input: Record<string, any>): Promise<string> {\r\n const { file_path, old_string, new_string, replace_all } = input;\r\n\r\n if (!file_path) {\r\n throw new Error('file_path parameter is required');\r\n }\r\n\r\n if (!old_string) {\r\n throw new Error('old_string parameter is required');\r\n }\r\n\r\n if (new_string === undefined) {\r\n throw new Error('new_string parameter is required');\r\n }\r\n\r\n // Read file\r\n const content = await fs.readFile(file_path, 'utf-8');\r\n\r\n // Perform replacement\r\n let newContent: string;\r\n if (replace_all) {\r\n // Replace all occurrences\r\n newContent = content.split(old_string).join(new_string);\r\n } else {\r\n // Replace first occurrence only (must be unique)\r\n const occurrences = content.split(old_string).length - 1;\r\n if (occurrences === 0) {\r\n throw new Error('old_string not found in file');\r\n }\r\n if (occurrences > 1) {\r\n throw new Error(`old_string appears ${occurrences} times. Must be unique or use replace_all: true`);\r\n }\r\n newContent = content.replace(old_string, new_string);\r\n }\r\n\r\n // Write back\r\n await fs.writeFile(file_path, newContent, 'utf-8');\r\n\r\n return `File edited successfully: ${file_path}`;\r\n}\r\n\r\n/**\r\n * Execute Bash tool\r\n */\r\nasync function executeBash(input: Record<string, any>): Promise<string> {\r\n const { command, timeout, run_in_background } = input;\r\n\r\n if (!command) {\r\n throw new Error('command parameter is required');\r\n }\r\n\r\n // DEBUG: Log bash command execution details\r\n console.log(`[tool-executor] Bash command: ${command}`);\r\n console.log(`[tool-executor] Timeout: ${timeout || 120000}ms`);\r\n console.log(`[tool-executor] Background: ${run_in_background || false}`);\r\n\r\n const timeoutMs = timeout ? Number(timeout) : 120000; // 2 minutes default\r\n\r\n if (run_in_background) {\r\n // Start background process and return immediately\r\n exec(command);\r\n return `Command started in background: ${command}`;\r\n }\r\n\r\n // Execute synchronously with timeout\r\n const { stdout, stderr } = await execAsync(command, {\r\n timeout: timeoutMs,\r\n maxBuffer: 10 * 1024 * 1024 // 10MB buffer\r\n });\r\n\r\n return stdout + stderr;\r\n}\r\n\r\n/**\r\n * Execute TodoWrite tool\r\n */\r\nasync function executeTodoWrite(input: Record<string, any>): Promise<string> {\r\n const { todos } = input;\r\n\r\n if (!Array.isArray(todos)) {\r\n throw new Error('todos parameter must be an array');\r\n }\r\n\r\n // Validate todo structure\r\n for (const todo of todos) {\r\n if (!todo.content || !todo.status || !todo.activeForm) {\r\n throw new Error('Each todo must have content, status, and activeForm');\r\n }\r\n if (!['pending', 'in_progress', 'completed'].includes(todo.status)) {\r\n throw new Error('Invalid status. Must be pending, in_progress, or completed');\r\n }\r\n }\r\n\r\n // Format todos for display\r\n const formatted = todos\r\n .map((todo, idx) => {\r\n const status = todo.status === 'completed' ? '✓' : todo.status === 'in_progress' ? '⚡' : '○';\r\n return `${idx + 1}. [${status}] ${todo.content}`;\r\n })\r\n .join('\\n');\r\n\r\n return `Todo list updated:\\n${formatted}`;\r\n}\r\n\r\n/**\r\n * Execute Glob tool\r\n */\r\nasync function executeGlob(input: Record<string, any>): Promise<string> {\r\n const { pattern, path } = input;\r\n\r\n if (!pattern) {\r\n throw new Error('pattern parameter is required');\r\n }\r\n\r\n const cwd = path || process.cwd();\r\n const files = await glob(pattern, { cwd, nodir: true });\r\n\r\n if (files.length === 0) {\r\n return 'No files found';\r\n }\r\n\r\n return files.join('\\n');\r\n}\r\n\r\n/**\r\n * Execute Grep tool\r\n */\r\nasync function executeGrep(input: Record<string, any>): Promise<string> {\r\n const { pattern, path, output_mode, glob: globPattern, type } = input;\r\n\r\n if (!pattern) {\r\n throw new Error('pattern parameter is required');\r\n }\r\n\r\n // Build ripgrep command\r\n const args: string[] = ['rg'];\r\n\r\n // Output mode\r\n if (output_mode === 'files_with_matches' || !output_mode) {\r\n args.push('-l'); // List files with matches\r\n } else if (output_mode === 'count') {\r\n args.push('-c'); // Count matches per file\r\n }\r\n // Default is content (no flag)\r\n\r\n // Optional flags\r\n if (input['-i']) args.push('-i'); // Case insensitive\r\n if (input['-n']) args.push('-n'); // Line numbers\r\n if (input['-A']) args.push(`-A${input['-A']}`); // After context\r\n if (input['-B']) args.push(`-B${input['-B']}`); // Before context\r\n if (input['-C']) args.push(`-C${input['-C']}`); // Context\r\n\r\n // File filtering\r\n if (globPattern) args.push('--glob', globPattern);\r\n if (type) args.push('--type', type);\r\n\r\n // Pattern and path\r\n args.push(pattern);\r\n if (path) args.push(path);\r\n\r\n const command = args.join(' ');\r\n\r\n try {\r\n const { stdout } = await execAsync(command, {\r\n maxBuffer: 10 * 1024 * 1024 // 10MB buffer\r\n });\r\n return stdout || 'No matches found';\r\n } catch (error: any) {\r\n // ripgrep exits with code 1 if no matches found\r\n if (error.code === 1) {\r\n return 'No matches found';\r\n }\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Execute multiple tools in sequence\r\n */\r\nexport async function executeTools(toolUses: ToolUse[]): Promise<ToolResult[]> {\r\n const results: ToolResult[] = [];\r\n\r\n for (const toolUse of toolUses) {\r\n const result = await executeTool(toolUse);\r\n results.push(result);\r\n }\r\n\r\n return results;\r\n}\r\n"],"names":["fs","exec","promisify","glob","execAsync","executeTool","toolUse","console","log","name","id","result","executeRead","input","executeWrite","executeEdit","executeBash","executeTodoWrite","executeGlob","executeGrep","Error","type","tool_use_id","content","error","message","String","is_error","file_path","offset","limit","readFile","lines","split","startLine","Number","endLine","length","selectedLines","slice","formatted","map","line","idx","padStart","join","undefined","writeFile","old_string","new_string","replace_all","newContent","occurrences","replace","command","timeout","run_in_background","timeoutMs","stdout","stderr","maxBuffer","todos","Array","isArray","todo","status","activeForm","includes","pattern","path","cwd","process","files","nodir","output_mode","globPattern","args","push","code","executeTools","toolUses","results"],"mappings":"AAAA;;;;;CAKC,GAED,OAAOA,QAAQ,cAAc;AAC7B,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,IAAI,QAAQ,OAAO;AAE5B,MAAMC,YAAYF,UAAUD;AAgB5B;;CAEC,GACD,OAAO,eAAeI,YAAYC,OAAgB;IAChDC,QAAQC,GAAG,CAAC,CAAC,gCAAgC,EAAEF,QAAQG,IAAI,EAAE;IAC7DF,QAAQC,GAAG,CAAC,CAAC,6BAA6B,EAAEF,QAAQI,EAAE,EAAE;IAExD,IAAI;QACF,IAAIC;QAEJ,OAAQL,QAAQG,IAAI;YAClB,KAAK;gBACHE,SAAS,MAAMC,YAAYN,QAAQO,KAAK;gBACxC;YAEF,KAAK;gBACHF,SAAS,MAAMG,aAAaR,QAAQO,KAAK;gBACzC;YAEF,KAAK;gBACHF,SAAS,MAAMI,YAAYT,QAAQO,KAAK;gBACxC;YAEF,KAAK;gBACHF,SAAS,MAAMK,YAAYV,QAAQO,KAAK;gBACxC;YAEF,KAAK;gBACHF,SAAS,MAAMM,iBAAiBX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;IAChE,IAAIA,KAAK,CAAC,KAAK,EAAE+D,KAAKC,IAAI,CAAC,CAAC,EAAE,EAAEhE,KAAK,CAAC,KAAK,EAAE,GAAG,iBAAiB;IACjE,IAAIA,KAAK,CAAC,KAAK,EAAE+D,KAAKC,IAAI,CAAC,CAAC,EAAE,EAAEhE,KAAK,CAAC,KAAK,EAAE,GAAG,UAAU;IAE1D,iBAAiB;IACjB,IAAI8D,aAAaC,KAAKC,IAAI,CAAC,UAAUF;IACrC,IAAItD,MAAMuD,KAAKC,IAAI,CAAC,UAAUxD;IAE9B,mBAAmB;IACnBuD,KAAKC,IAAI,CAACT;IACV,IAAIC,MAAMO,KAAKC,IAAI,CAACR;IAEpB,MAAMf,UAAUsB,KAAK/B,IAAI,CAAC;IAE1B,IAAI;QACF,MAAM,EAAEa,MAAM,EAAE,GAAG,MAAMtD,UAAUkD,SAAS;YAC1CM,WAAW,KAAK,OAAO,KAAK,cAAc;QAC5C;QACA,OAAOF,UAAU;IACnB,EAAE,OAAOlC,OAAY;QACnB,gDAAgD;QAChD,IAAIA,MAAMsD,IAAI,KAAK,GAAG;YACpB,OAAO;QACT;QACA,MAAMtD;IACR;AACF;AAEA;;CAEC,GACD,OAAO,eAAeuD,aAAaC,QAAmB;IACpD,MAAMC,UAAwB,EAAE;IAEhC,KAAK,MAAM3E,WAAW0E,SAAU;QAC9B,MAAMrE,SAAS,MAAMN,YAAYC;QACjC2E,QAAQJ,IAAI,CAAClE;IACf;IAEA,OAAOsE;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../src/cli/tool-executor.ts"],"sourcesContent":["/**\r\n * Tool Executor for CLI-Spawned Agents\r\n *\r\n * Executes tools requested by agents via Anthropic API tool_use blocks.\r\n * Implements Read, Write, Edit, Bash, TodoWrite, Glob, Grep.\r\n */\r\n\r\nimport fs from 'fs/promises';\r\nimport { exec } from 'child_process';\r\nimport { promisify } from 'util';\r\nimport { glob } from 'glob';\r\n\r\nconst execAsync = promisify(exec);\r\n\r\nexport interface ToolUse {\r\n type: 'tool_use';\r\n id: string;\r\n name: string;\r\n input: Record<string, any>;\r\n}\r\n\r\nexport interface ToolResult {\r\n type: 'tool_result';\r\n tool_use_id: string;\r\n content: string;\r\n is_error?: boolean;\r\n}\r\n\r\n/**\r\n * Execute a single tool and return result\r\n */\r\nexport async function executeTool(toolUse: ToolUse): Promise<ToolResult> {\r\n console.log(`[tool-executor] Executing tool: ${toolUse.name}`);\r\n console.log(`[tool-executor] Tool use ID: ${toolUse.id}`);\r\n\r\n try {\r\n let result: string;\r\n\r\n switch (toolUse.name) {\r\n case 'Read':\r\n result = await executeRead(toolUse.input);\r\n break;\r\n\r\n case 'Write':\r\n result = await executeWrite(toolUse.input);\r\n break;\r\n\r\n case 'Edit':\r\n result = await executeEdit(toolUse.input);\r\n break;\r\n\r\n case 'Bash':\r\n result = await executeBash(toolUse.input);\r\n break;\r\n\r\n case 'TodoWrite':\r\n result = await executeTodoWrite(toolUse.input);\r\n break;\r\n\r\n case 'Glob':\r\n result = await executeGlob(toolUse.input);\r\n break;\r\n\r\n case 'Grep':\r\n result = await executeGrep(toolUse.input);\r\n break;\r\n\r\n default:\r\n throw new Error(`Unknown tool: ${toolUse.name}`);\r\n }\r\n\r\n console.log(`[tool-executor] ✓ Tool executed successfully`);\r\n\r\n return {\r\n type: 'tool_result',\r\n tool_use_id: toolUse.id,\r\n content: result\r\n };\r\n } catch (error) {\r\n console.error(`[tool-executor] ✗ Tool execution failed:`, error);\r\n\r\n return {\r\n type: 'tool_result',\r\n tool_use_id: toolUse.id,\r\n content: error instanceof Error ? error.message : String(error),\r\n is_error: true\r\n };\r\n }\r\n}\r\n\r\n/**\r\n * Execute Read tool\r\n */\r\nasync function executeRead(input: Record<string, any>): Promise<string> {\r\n const { file_path, offset, limit } = input;\r\n\r\n if (!file_path) {\r\n throw new Error('file_path parameter is required');\r\n }\r\n\r\n const content = await fs.readFile(file_path, 'utf-8');\r\n const lines = content.split('\\n');\r\n\r\n // Apply offset and limit if provided\r\n const startLine = offset ? Number(offset) - 1 : 0;\r\n const endLine = limit ? startLine + Number(limit) : lines.length;\r\n const selectedLines = lines.slice(startLine, endLine);\r\n\r\n // Format with line numbers (cat -n style)\r\n const formatted = selectedLines\r\n .map((line, idx) => `${String(startLine + idx + 1).padStart(6)}→${line}`)\r\n .join('\\n');\r\n\r\n return formatted;\r\n}\r\n\r\n/**\r\n * Execute Write tool\r\n */\r\nasync function executeWrite(input: Record<string, any>): Promise<string> {\r\n const { file_path, content } = input;\r\n\r\n if (!file_path) {\r\n throw new Error('file_path parameter is required');\r\n }\r\n\r\n if (content === undefined) {\r\n throw new Error('content parameter is required');\r\n }\r\n\r\n await fs.writeFile(file_path, content, 'utf-8');\r\n\r\n return `File written successfully: ${file_path}`;\r\n}\r\n\r\n/**\r\n * Execute Edit tool\r\n */\r\nasync function executeEdit(input: Record<string, any>): Promise<string> {\r\n const { file_path, old_string, new_string, replace_all } = input;\r\n\r\n if (!file_path) {\r\n throw new Error('file_path parameter is required');\r\n }\r\n\r\n if (!old_string) {\r\n throw new Error('old_string parameter is required');\r\n }\r\n\r\n if (new_string === undefined) {\r\n throw new Error('new_string parameter is required');\r\n }\r\n\r\n // Read file\r\n const content = await fs.readFile(file_path, 'utf-8');\r\n\r\n // Perform replacement\r\n let newContent: string;\r\n if (replace_all) {\r\n // Replace all occurrences\r\n newContent = content.split(old_string).join(new_string);\r\n } else {\r\n // Replace first occurrence only (must be unique)\r\n const occurrences = content.split(old_string).length - 1;\r\n if (occurrences === 0) {\r\n throw new Error('old_string not found in file');\r\n }\r\n if (occurrences > 1) {\r\n throw new Error(`old_string appears ${occurrences} times. Must be unique or use replace_all: true`);\r\n }\r\n newContent = content.replace(old_string, new_string);\r\n }\r\n\r\n // Write back\r\n await fs.writeFile(file_path, newContent, 'utf-8');\r\n\r\n return `File edited successfully: ${file_path}`;\r\n}\r\n\r\n/**\r\n * Execute Bash tool\r\n */\r\nasync function executeBash(input: Record<string, any>): Promise<string> {\r\n const { command, timeout, run_in_background } = input;\r\n\r\n if (!command) {\r\n throw new Error('command parameter is required');\r\n }\r\n\r\n // DEBUG: Log bash command execution details\r\n console.log(`[tool-executor] Bash command: ${command}`);\r\n console.log(`[tool-executor] Timeout: ${timeout || 120000}ms`);\r\n console.log(`[tool-executor] Background: ${run_in_background || false}`);\r\n\r\n const timeoutMs = timeout ? Number(timeout) : 120000; // 2 minutes default\r\n\r\n if (run_in_background) {\r\n // Start background process and return immediately\r\n exec(command);\r\n return `Command started in background: ${command}`;\r\n }\r\n\r\n // Execute synchronously with timeout\r\n // CRITICAL: Use /bin/bash instead of /bin/sh for [[ ]] support\r\n const { stdout, stderr } = await execAsync(command, {\r\n timeout: timeoutMs,\r\n maxBuffer: 10 * 1024 * 1024, // 10MB buffer\r\n shell: '/bin/bash' // REQUIRED: Coordinator uses [[ ]] conditionals\r\n });\r\n\r\n return stdout + stderr;\r\n}\r\n\r\n/**\r\n * Execute TodoWrite tool\r\n */\r\nasync function executeTodoWrite(input: Record<string, any>): Promise<string> {\r\n const { todos } = input;\r\n\r\n if (!Array.isArray(todos)) {\r\n throw new Error('todos parameter must be an array');\r\n }\r\n\r\n // Validate todo structure\r\n for (const todo of todos) {\r\n if (!todo.content || !todo.status || !todo.activeForm) {\r\n throw new Error('Each todo must have content, status, and activeForm');\r\n }\r\n if (!['pending', 'in_progress', 'completed'].includes(todo.status)) {\r\n throw new Error('Invalid status. Must be pending, in_progress, or completed');\r\n }\r\n }\r\n\r\n // Format todos for display\r\n const formatted = todos\r\n .map((todo, idx) => {\r\n const status = todo.status === 'completed' ? '✓' : todo.status === 'in_progress' ? '⚡' : '○';\r\n return `${idx + 1}. [${status}] ${todo.content}`;\r\n })\r\n .join('\\n');\r\n\r\n return `Todo list updated:\\n${formatted}`;\r\n}\r\n\r\n/**\r\n * Execute Glob tool\r\n */\r\nasync function executeGlob(input: Record<string, any>): Promise<string> {\r\n const { pattern, path } = input;\r\n\r\n if (!pattern) {\r\n throw new Error('pattern parameter is required');\r\n }\r\n\r\n const cwd = path || process.cwd();\r\n const files = await glob(pattern, { cwd, nodir: true });\r\n\r\n if (files.length === 0) {\r\n return 'No files found';\r\n }\r\n\r\n return files.join('\\n');\r\n}\r\n\r\n/**\r\n * Execute Grep tool\r\n */\r\nasync function executeGrep(input: Record<string, any>): Promise<string> {\r\n const { pattern, path, output_mode, glob: globPattern, type } = input;\r\n\r\n if (!pattern) {\r\n throw new Error('pattern parameter is required');\r\n }\r\n\r\n // Build ripgrep command\r\n const args: string[] = ['rg'];\r\n\r\n // Output mode\r\n if (output_mode === 'files_with_matches' || !output_mode) {\r\n args.push('-l'); // List files with matches\r\n } else if (output_mode === 'count') {\r\n args.push('-c'); // Count matches per file\r\n }\r\n // Default is content (no flag)\r\n\r\n // Optional flags\r\n if (input['-i']) args.push('-i'); // Case insensitive\r\n if (input['-n']) args.push('-n'); // Line numbers\r\n if (input['-A']) args.push(`-A${input['-A']}`); // After context\r\n if (input['-B']) args.push(`-B${input['-B']}`); // Before context\r\n if (input['-C']) args.push(`-C${input['-C']}`); // Context\r\n\r\n // File filtering\r\n if (globPattern) args.push('--glob', globPattern);\r\n if (type) args.push('--type', type);\r\n\r\n // Pattern and path\r\n args.push(pattern);\r\n if (path) args.push(path);\r\n\r\n const command = args.join(' ');\r\n\r\n try {\r\n const { stdout } = await execAsync(command, {\r\n maxBuffer: 10 * 1024 * 1024 // 10MB buffer\r\n });\r\n return stdout || 'No matches found';\r\n } catch (error: any) {\r\n // ripgrep exits with code 1 if no matches found\r\n if (error.code === 1) {\r\n return 'No matches found';\r\n }\r\n throw error;\r\n }\r\n}\r\n\r\n/**\r\n * Execute multiple tools in sequence\r\n */\r\nexport async function executeTools(toolUses: ToolUse[]): Promise<ToolResult[]> {\r\n const results: ToolResult[] = [];\r\n\r\n for (const toolUse of toolUses) {\r\n const result = await executeTool(toolUse);\r\n results.push(result);\r\n }\r\n\r\n return results;\r\n}\r\n"],"names":["fs","exec","promisify","glob","execAsync","executeTool","toolUse","console","log","name","id","result","executeRead","input","executeWrite","executeEdit","executeBash","executeTodoWrite","executeGlob","executeGrep","Error","type","tool_use_id","content","error","message","String","is_error","file_path","offset","limit","readFile","lines","split","startLine","Number","endLine","length","selectedLines","slice","formatted","map","line","idx","padStart","join","undefined","writeFile","old_string","new_string","replace_all","newContent","occurrences","replace","command","timeout","run_in_background","timeoutMs","stdout","stderr","maxBuffer","shell","todos","Array","isArray","todo","status","activeForm","includes","pattern","path","cwd","process","files","nodir","output_mode","globPattern","args","push","code","executeTools","toolUses","results"],"mappings":"AAAA;;;;;CAKC,GAED,OAAOA,QAAQ,cAAc;AAC7B,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AACjC,SAASC,IAAI,QAAQ,OAAO;AAE5B,MAAMC,YAAYF,UAAUD;AAgB5B;;CAEC,GACD,OAAO,eAAeI,YAAYC,OAAgB;IAChDC,QAAQC,GAAG,CAAC,CAAC,gCAAgC,EAAEF,QAAQG,IAAI,EAAE;IAC7DF,QAAQC,GAAG,CAAC,CAAC,6BAA6B,EAAEF,QAAQI,EAAE,EAAE;IAExD,IAAI;QACF,IAAIC;QAEJ,OAAQL,QAAQG,IAAI;YAClB,KAAK;gBACHE,SAAS,MAAMC,YAAYN,QAAQO,KAAK;gBACxC;YAEF,KAAK;gBACHF,SAAS,MAAMG,aAAaR,QAAQO,KAAK;gBACzC;YAEF,KAAK;gBACHF,SAAS,MAAMI,YAAYT,QAAQO,KAAK;gBACxC;YAEF,KAAK;gBACHF,SAAS,MAAMK,YAAYV,QAAQO,KAAK;gBACxC;YAEF,KAAK;gBACHF,SAAS,MAAMM,iBAAiBX,QAAQO,KAAK;gBAC7C;YAEF,KAAK;gBACHF,SAAS,MAAMO,YAAYZ,QAAQO,KAAK;gBACxC;YAEF,KAAK;gBACHF,SAAS,MAAMQ,YAAYb,QAAQO,KAAK;gBACxC;YAEF;gBACE,MAAM,IAAIO,MAAM,CAAC,cAAc,EAAEd,QAAQG,I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