@apralabs/apra-fleet 0.3.5 → 0.4.0
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/README.md +245 -257
- package/dist/agents/backlog-groomer.md +287 -0
- package/dist/agents/deployer.md +52 -11
- package/dist/agents/doer.md +32 -7
- package/dist/agents/integ-test-runner.md +151 -61
- package/dist/agents/plan-reviewer.md +74 -17
- package/dist/agents/planner.md +94 -14
- package/dist/agents/regression-test-runner.md +216 -0
- package/dist/agents/reviewer.md +21 -6
- package/dist/agents/schemas/backlog-groomer-input.json +35 -0
- package/dist/agents/schemas/backlog-groomer-output.json +164 -0
- package/dist/agents/schemas/integ-test-runner-output.json +34 -0
- package/dist/agents/schemas/regression-test-runner-input.json +15 -0
- package/dist/agents/schemas/regression-test-runner-output.json +50 -0
- package/dist/agents/schemas/reviewer-output.json +4 -0
- package/dist/cli/agent-transform.d.ts +1 -0
- package/dist/cli/agent-transform.d.ts.map +1 -1
- package/dist/cli/agent-transform.js +77 -0
- package/dist/cli/agent-transform.js.map +1 -1
- package/dist/cli/auth.d.ts +3 -0
- package/dist/cli/auth.d.ts.map +1 -1
- package/dist/cli/auth.js +181 -5
- package/dist/cli/auth.js.map +1 -1
- package/dist/cli/config.d.ts +5 -1
- package/dist/cli/config.d.ts.map +1 -1
- package/dist/cli/config.js +7 -1
- package/dist/cli/config.js.map +1 -1
- package/dist/cli/dolt-install.d.ts +91 -0
- package/dist/cli/dolt-install.d.ts.map +1 -0
- package/dist/cli/dolt-install.js +334 -0
- package/dist/cli/dolt-install.js.map +1 -0
- package/dist/cli/install-guard.d.ts +29 -0
- package/dist/cli/install-guard.d.ts.map +1 -0
- package/dist/cli/install-guard.js +153 -0
- package/dist/cli/install-guard.js.map +1 -0
- package/dist/cli/install.d.ts +44 -3
- package/dist/cli/install.d.ts.map +1 -1
- package/dist/cli/install.js +604 -108
- package/dist/cli/install.js.map +1 -1
- package/dist/cli/join.d.ts +12 -0
- package/dist/cli/join.d.ts.map +1 -0
- package/dist/cli/join.js +87 -0
- package/dist/cli/join.js.map +1 -0
- package/dist/cli/register-member.d.ts +2 -0
- package/dist/cli/register-member.d.ts.map +1 -0
- package/dist/cli/register-member.js +193 -0
- package/dist/cli/register-member.js.map +1 -0
- package/dist/cli/restart.d.ts +2 -0
- package/dist/cli/restart.d.ts.map +1 -0
- package/dist/cli/restart.js +7 -0
- package/dist/cli/restart.js.map +1 -0
- package/dist/cli/secret.js +8 -2
- package/dist/cli/secret.js.map +1 -1
- package/dist/cli/spoke.d.ts +35 -0
- package/dist/cli/spoke.d.ts.map +1 -0
- package/dist/cli/spoke.js +212 -0
- package/dist/cli/spoke.js.map +1 -0
- package/dist/cli/start.d.ts +2 -0
- package/dist/cli/start.d.ts.map +1 -0
- package/dist/cli/start.js +92 -0
- package/dist/cli/start.js.map +1 -0
- package/dist/cli/status.d.ts +2 -0
- package/dist/cli/status.d.ts.map +1 -0
- package/dist/cli/status.js +83 -0
- package/dist/cli/status.js.map +1 -0
- package/dist/cli/stop.d.ts +2 -0
- package/dist/cli/stop.d.ts.map +1 -0
- package/dist/cli/stop.js +51 -0
- package/dist/cli/stop.js.map +1 -0
- package/dist/cli/uninstall.d.ts.map +1 -1
- package/dist/cli/uninstall.js +109 -9
- package/dist/cli/uninstall.js.map +1 -1
- package/dist/cli/update.d.ts.map +1 -1
- package/dist/cli/update.js +10 -1
- package/dist/cli/update.js.map +1 -1
- package/dist/cli/workflow-assets.d.ts +37 -0
- package/dist/cli/workflow-assets.d.ts.map +1 -0
- package/dist/cli/workflow-assets.js +144 -0
- package/dist/cli/workflow-assets.js.map +1 -0
- package/dist/cli/workflow.d.ts +75 -0
- package/dist/cli/workflow.d.ts.map +1 -0
- package/dist/cli/workflow.js +397 -0
- package/dist/cli/workflow.js.map +1 -0
- package/dist/hub-service/activity.d.ts +30 -0
- package/dist/hub-service/activity.d.ts.map +1 -0
- package/dist/hub-service/activity.js +20 -0
- package/dist/hub-service/activity.js.map +1 -0
- package/dist/hub-service/audit-log.d.ts +19 -0
- package/dist/hub-service/audit-log.d.ts.map +1 -0
- package/dist/hub-service/audit-log.js +13 -0
- package/dist/hub-service/audit-log.js.map +1 -0
- package/dist/hub-service/db/pool.d.ts +19 -0
- package/dist/hub-service/db/pool.d.ts.map +1 -0
- package/dist/hub-service/db/pool.js +53 -0
- package/dist/hub-service/db/pool.js.map +1 -0
- package/dist/hub-service/enrollment.d.ts +29 -0
- package/dist/hub-service/enrollment.d.ts.map +1 -0
- package/dist/hub-service/enrollment.js +48 -0
- package/dist/hub-service/enrollment.js.map +1 -0
- package/dist/hub-service/envelope-routes.d.ts +46 -0
- package/dist/hub-service/envelope-routes.d.ts.map +1 -0
- package/dist/hub-service/envelope-routes.js +94 -0
- package/dist/hub-service/envelope-routes.js.map +1 -0
- package/dist/hub-service/handlers/installers.d.ts +14 -0
- package/dist/hub-service/handlers/installers.d.ts.map +1 -0
- package/dist/hub-service/handlers/installers.js +8 -0
- package/dist/hub-service/handlers/installers.js.map +1 -0
- package/dist/hub-service/http-server.d.ts +31 -0
- package/dist/hub-service/http-server.d.ts.map +1 -0
- package/dist/hub-service/http-server.js +711 -0
- package/dist/hub-service/http-server.js.map +1 -0
- package/dist/hub-service/hub-jwt.d.ts +30 -0
- package/dist/hub-service/hub-jwt.d.ts.map +1 -0
- package/dist/hub-service/hub-jwt.js +105 -0
- package/dist/hub-service/hub-jwt.js.map +1 -0
- package/dist/hub-service/jwt-revocation.d.ts +20 -0
- package/dist/hub-service/jwt-revocation.d.ts.map +1 -0
- package/dist/hub-service/jwt-revocation.js +18 -0
- package/dist/hub-service/jwt-revocation.js.map +1 -0
- package/dist/hub-service/machines.d.ts +16 -0
- package/dist/hub-service/machines.d.ts.map +1 -0
- package/dist/hub-service/machines.js +14 -0
- package/dist/hub-service/machines.js.map +1 -0
- package/dist/hub-service/main.d.ts +3 -0
- package/dist/hub-service/main.d.ts.map +1 -0
- package/dist/hub-service/main.js +64 -0
- package/dist/hub-service/main.js.map +1 -0
- package/dist/hub-service/member-tokens.d.ts +11 -0
- package/dist/hub-service/member-tokens.d.ts.map +1 -0
- package/dist/hub-service/member-tokens.js +49 -0
- package/dist/hub-service/member-tokens.js.map +1 -0
- package/dist/hub-service/member-view.d.ts +20 -0
- package/dist/hub-service/member-view.d.ts.map +1 -0
- package/dist/hub-service/member-view.js +76 -0
- package/dist/hub-service/member-view.js.map +1 -0
- package/dist/hub-service/members.d.ts +44 -0
- package/dist/hub-service/members.d.ts.map +1 -0
- package/dist/hub-service/members.js +25 -0
- package/dist/hub-service/members.js.map +1 -0
- package/dist/hub-service/presence.d.ts +40 -0
- package/dist/hub-service/presence.d.ts.map +1 -0
- package/dist/hub-service/presence.js +44 -0
- package/dist/hub-service/presence.js.map +1 -0
- package/dist/hub-service/project-view.d.ts +12 -0
- package/dist/hub-service/project-view.d.ts.map +1 -0
- package/dist/hub-service/project-view.js +34 -0
- package/dist/hub-service/project-view.js.map +1 -0
- package/dist/hub-service/projects.d.ts +48 -0
- package/dist/hub-service/projects.d.ts.map +1 -0
- package/dist/hub-service/projects.js +80 -0
- package/dist/hub-service/projects.js.map +1 -0
- package/dist/hub-service/relay-queue.d.ts +115 -0
- package/dist/hub-service/relay-queue.d.ts.map +1 -0
- package/dist/hub-service/relay-queue.js +148 -0
- package/dist/hub-service/relay-queue.js.map +1 -0
- package/dist/hub-service/session-jwt.d.ts +10 -0
- package/dist/hub-service/session-jwt.d.ts.map +1 -0
- package/dist/hub-service/session-jwt.js +69 -0
- package/dist/hub-service/session-jwt.js.map +1 -0
- package/dist/hub-service/usage.d.ts +40 -0
- package/dist/hub-service/usage.d.ts.map +1 -0
- package/dist/hub-service/usage.js +25 -0
- package/dist/hub-service/usage.js.map +1 -0
- package/dist/hub-service/users.d.ts +56 -0
- package/dist/hub-service/users.d.ts.map +1 -0
- package/dist/hub-service/users.js +72 -0
- package/dist/hub-service/users.js.map +1 -0
- package/dist/hub-service/workspaces.d.ts +20 -0
- package/dist/hub-service/workspaces.d.ts.map +1 -0
- package/dist/hub-service/workspaces.js +10 -0
- package/dist/hub-service/workspaces.js.map +1 -0
- package/dist/index.js +179 -132
- package/dist/index.js.map +1 -1
- package/dist/os/linux.d.ts +13 -0
- package/dist/os/linux.d.ts.map +1 -1
- package/dist/os/linux.js +62 -3
- package/dist/os/linux.js.map +1 -1
- package/dist/os/os-commands.d.ts +10 -0
- package/dist/os/os-commands.d.ts.map +1 -1
- package/dist/os/windows.d.ts +1 -0
- package/dist/os/windows.d.ts.map +1 -1
- package/dist/os/windows.js +21 -1
- package/dist/os/windows.js.map +1 -1
- package/dist/paths.d.ts +23 -0
- package/dist/paths.d.ts.map +1 -1
- package/dist/paths.js +29 -0
- package/dist/paths.js.map +1 -1
- package/dist/providers/agy.d.ts +9 -2
- package/dist/providers/agy.d.ts.map +1 -1
- package/dist/providers/agy.js +127 -14
- package/dist/providers/agy.js.map +1 -1
- package/dist/providers/claude.d.ts +6 -2
- package/dist/providers/claude.d.ts.map +1 -1
- package/dist/providers/claude.js +248 -9
- package/dist/providers/claude.js.map +1 -1
- package/dist/providers/codex.d.ts +3 -2
- package/dist/providers/codex.d.ts.map +1 -1
- package/dist/providers/codex.js +7 -0
- package/dist/providers/codex.js.map +1 -1
- package/dist/providers/copilot.d.ts +3 -2
- package/dist/providers/copilot.d.ts.map +1 -1
- package/dist/providers/copilot.js +8 -1
- package/dist/providers/copilot.js.map +1 -1
- package/dist/providers/gemini.d.ts +3 -2
- package/dist/providers/gemini.d.ts.map +1 -1
- package/dist/providers/gemini.js +11 -1
- package/dist/providers/gemini.js.map +1 -1
- package/dist/providers/index.d.ts +1 -0
- package/dist/providers/index.d.ts.map +1 -1
- package/dist/providers/index.js +3 -0
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/none.d.ts +51 -0
- package/dist/providers/none.d.ts.map +1 -0
- package/dist/providers/none.js +103 -0
- package/dist/providers/none.js.map +1 -0
- package/dist/providers/opencode.d.ts +4 -2
- package/dist/providers/opencode.d.ts.map +1 -1
- package/dist/providers/opencode.js +49 -0
- package/dist/providers/opencode.js.map +1 -1
- package/dist/providers/provider.d.ts +79 -1
- package/dist/providers/provider.d.ts.map +1 -1
- package/dist/providers/provider.js +10 -0
- package/dist/providers/provider.js.map +1 -1
- package/dist/services/agent-provisioner.d.ts +3 -3
- package/dist/services/agent-provisioner.d.ts.map +1 -1
- package/dist/services/agent-provisioner.js +12 -5
- package/dist/services/agent-provisioner.js.map +1 -1
- package/dist/services/auth-socket.d.ts.map +1 -1
- package/dist/services/auth-socket.js +2 -0
- package/dist/services/auth-socket.js.map +1 -1
- package/dist/services/budget-awareness.d.ts +130 -0
- package/dist/services/budget-awareness.d.ts.map +1 -0
- package/dist/services/budget-awareness.js +129 -0
- package/dist/services/budget-awareness.js.map +1 -0
- package/dist/services/cloud-sync.d.ts +35 -0
- package/dist/services/cloud-sync.d.ts.map +1 -0
- package/dist/services/cloud-sync.js +90 -0
- package/dist/services/cloud-sync.js.map +1 -0
- package/dist/services/context-admission.d.ts +82 -0
- package/dist/services/context-admission.d.ts.map +1 -0
- package/dist/services/context-admission.js +136 -0
- package/dist/services/context-admission.js.map +1 -0
- package/dist/services/event-bus.d.ts +27 -0
- package/dist/services/event-bus.d.ts.map +1 -0
- package/dist/services/event-bus.js +20 -0
- package/dist/services/event-bus.js.map +1 -0
- package/dist/services/file-chunker.d.ts +38 -0
- package/dist/services/file-chunker.d.ts.map +1 -0
- package/dist/services/file-chunker.js +63 -0
- package/dist/services/file-chunker.js.map +1 -0
- package/dist/services/file-transfer-relay.d.ts +55 -0
- package/dist/services/file-transfer-relay.d.ts.map +1 -0
- package/dist/services/file-transfer-relay.js +115 -0
- package/dist/services/file-transfer-relay.js.map +1 -0
- package/dist/services/github-app.d.ts.map +1 -1
- package/dist/services/github-app.js +1 -0
- package/dist/services/github-app.js.map +1 -1
- package/dist/services/http-transport.d.ts +25 -0
- package/dist/services/http-transport.d.ts.map +1 -0
- package/dist/services/http-transport.js +371 -0
- package/dist/services/http-transport.js.map +1 -0
- package/dist/services/hub-client.d.ts +69 -0
- package/dist/services/hub-client.d.ts.map +1 -0
- package/dist/services/hub-client.js +217 -0
- package/dist/services/hub-client.js.map +1 -0
- package/dist/services/jwt.d.ts +17 -0
- package/dist/services/jwt.d.ts.map +1 -0
- package/dist/services/jwt.js +70 -0
- package/dist/services/jwt.js.map +1 -0
- package/dist/services/known-sessions.d.ts +8 -0
- package/dist/services/known-sessions.d.ts.map +1 -0
- package/dist/services/known-sessions.js +40 -0
- package/dist/services/known-sessions.js.map +1 -0
- package/dist/services/model-pricing.d.ts +36 -0
- package/dist/services/model-pricing.d.ts.map +1 -0
- package/dist/services/model-pricing.js +108 -0
- package/dist/services/model-pricing.js.map +1 -0
- package/dist/services/orphan-recovery.d.ts +56 -0
- package/dist/services/orphan-recovery.d.ts.map +1 -0
- package/dist/services/orphan-recovery.js +111 -0
- package/dist/services/orphan-recovery.js.map +1 -0
- package/dist/services/pending-responses.d.ts +23 -0
- package/dist/services/pending-responses.d.ts.map +1 -0
- package/dist/services/pending-responses.js +52 -0
- package/dist/services/pending-responses.js.map +1 -0
- package/dist/services/registry.d.ts +4 -1
- package/dist/services/registry.d.ts.map +1 -1
- package/dist/services/registry.js +3 -0
- package/dist/services/registry.js.map +1 -1
- package/dist/services/relay-context.d.ts +23 -0
- package/dist/services/relay-context.d.ts.map +1 -0
- package/dist/services/relay-context.js +8 -0
- package/dist/services/relay-context.js.map +1 -0
- package/dist/services/relay-executor.d.ts +68 -0
- package/dist/services/relay-executor.d.ts.map +1 -0
- package/dist/services/relay-executor.js +70 -0
- package/dist/services/relay-executor.js.map +1 -0
- package/dist/services/relay-request.d.ts +65 -0
- package/dist/services/relay-request.d.ts.map +1 -0
- package/dist/services/relay-request.js +129 -0
- package/dist/services/relay-request.js.map +1 -0
- package/dist/services/relay-strategy.d.ts +19 -0
- package/dist/services/relay-strategy.d.ts.map +1 -0
- package/dist/services/relay-strategy.js +111 -0
- package/dist/services/relay-strategy.js.map +1 -0
- package/dist/services/service-manager/index.d.ts +5 -0
- package/dist/services/service-manager/index.d.ts.map +1 -0
- package/dist/services/service-manager/index.js +66 -0
- package/dist/services/service-manager/index.js.map +1 -0
- package/dist/services/service-manager/linux.d.ts +10 -0
- package/dist/services/service-manager/linux.d.ts.map +1 -0
- package/dist/services/service-manager/linux.js +97 -0
- package/dist/services/service-manager/linux.js.map +1 -0
- package/dist/services/service-manager/macos.d.ts +10 -0
- package/dist/services/service-manager/macos.d.ts.map +1 -0
- package/dist/services/service-manager/macos.js +94 -0
- package/dist/services/service-manager/macos.js.map +1 -0
- package/dist/services/service-manager/types.d.ts +18 -0
- package/dist/services/service-manager/types.d.ts.map +1 -0
- package/dist/services/service-manager/types.js +5 -0
- package/dist/services/service-manager/types.js.map +1 -0
- package/dist/services/service-manager/windows.d.ts +10 -0
- package/dist/services/service-manager/windows.d.ts.map +1 -0
- package/dist/services/service-manager/windows.js +73 -0
- package/dist/services/service-manager/windows.js.map +1 -0
- package/dist/services/session-registry.d.ts +70 -0
- package/dist/services/session-registry.d.ts.map +1 -0
- package/dist/services/session-registry.js +91 -0
- package/dist/services/session-registry.js.map +1 -0
- package/dist/services/singleton.d.ts +15 -0
- package/dist/services/singleton.d.ts.map +1 -0
- package/dist/services/singleton.js +98 -0
- package/dist/services/singleton.js.map +1 -0
- package/dist/services/sprint-coordination.d.ts +168 -0
- package/dist/services/sprint-coordination.d.ts.map +1 -0
- package/dist/services/sprint-coordination.js +564 -0
- package/dist/services/sprint-coordination.js.map +1 -0
- package/dist/services/ssh.d.ts.map +1 -1
- package/dist/services/ssh.js +70 -3
- package/dist/services/ssh.js.map +1 -1
- package/dist/services/stall/log-path-resolver.d.ts.map +1 -1
- package/dist/services/stall/log-path-resolver.js +8 -1
- package/dist/services/stall/log-path-resolver.js.map +1 -1
- package/dist/services/stall/stall-detector.d.ts.map +1 -1
- package/dist/services/stall/stall-detector.js +39 -7
- package/dist/services/stall/stall-detector.js.map +1 -1
- package/dist/services/stall/stall-poller.d.ts +16 -0
- package/dist/services/stall/stall-poller.d.ts.map +1 -1
- package/dist/services/stall/stall-poller.js +136 -18
- package/dist/services/stall/stall-poller.js.map +1 -1
- package/dist/services/strategy.d.ts.map +1 -1
- package/dist/services/strategy.js +55 -5
- package/dist/services/strategy.js.map +1 -1
- package/dist/services/substitution-engine.d.ts +20 -0
- package/dist/services/substitution-engine.d.ts.map +1 -0
- package/dist/services/substitution-engine.js +92 -0
- package/dist/services/substitution-engine.js.map +1 -0
- package/dist/services/task-cleanup.d.ts.map +1 -1
- package/dist/services/task-cleanup.js +1 -9
- package/dist/services/task-cleanup.js.map +1 -1
- package/dist/services/token-issuer.d.ts +47 -0
- package/dist/services/token-issuer.d.ts.map +1 -0
- package/dist/services/token-issuer.js +63 -0
- package/dist/services/token-issuer.js.map +1 -0
- package/dist/services/tool-registry.d.ts +3 -0
- package/dist/services/tool-registry.d.ts.map +1 -0
- package/dist/services/tool-registry.js +139 -0
- package/dist/services/tool-registry.js.map +1 -0
- package/dist/services/user-config.d.ts +14 -0
- package/dist/services/user-config.d.ts.map +1 -1
- package/dist/services/user-config.js +55 -0
- package/dist/services/user-config.js.map +1 -1
- package/dist/services/vcs/types.d.ts +44 -0
- package/dist/services/vcs/types.d.ts.map +1 -1
- package/dist/skills/fleet-sprint-cli/SKILL.md +103 -0
- package/dist/skills/pm/cost.md +3 -0
- package/dist/skills/pm/doer-reviewer-loop.md +3 -0
- package/dist/tools/check-status.d.ts.map +1 -1
- package/dist/tools/check-status.js +8 -2
- package/dist/tools/check-status.js.map +1 -1
- package/dist/tools/child-id-allocator.d.ts +45 -0
- package/dist/tools/child-id-allocator.d.ts.map +1 -0
- package/dist/tools/child-id-allocator.js +62 -0
- package/dist/tools/child-id-allocator.js.map +1 -0
- package/dist/tools/cloud-control.d.ts +2 -2
- package/dist/tools/compose-permissions.d.ts +12 -4
- package/dist/tools/compose-permissions.d.ts.map +1 -1
- package/dist/tools/compose-permissions.js +55 -4
- package/dist/tools/compose-permissions.js.map +1 -1
- package/dist/tools/dolt-push-mutex.d.ts +44 -0
- package/dist/tools/dolt-push-mutex.d.ts.map +1 -0
- package/dist/tools/dolt-push-mutex.js +83 -0
- package/dist/tools/dolt-push-mutex.js.map +1 -0
- package/dist/tools/execute-command.d.ts +11 -1
- package/dist/tools/execute-command.d.ts.map +1 -1
- package/dist/tools/execute-command.js +22 -5
- package/dist/tools/execute-command.js.map +1 -1
- package/dist/tools/execute-prompt.d.ts +72 -12
- package/dist/tools/execute-prompt.d.ts.map +1 -1
- package/dist/tools/execute-prompt.js +962 -71
- package/dist/tools/execute-prompt.js.map +1 -1
- package/dist/tools/get-member-model-pricing.d.ts +21 -0
- package/dist/tools/get-member-model-pricing.d.ts.map +1 -0
- package/dist/tools/get-member-model-pricing.js +29 -0
- package/dist/tools/get-member-model-pricing.js.map +1 -0
- package/dist/tools/list-members.d.ts.map +1 -1
- package/dist/tools/list-members.js +39 -7
- package/dist/tools/list-members.js.map +1 -1
- package/dist/tools/member-detail.d.ts +1 -1
- package/dist/tools/member-detail.d.ts.map +1 -1
- package/dist/tools/member-detail.js +8 -2
- package/dist/tools/member-detail.js.map +1 -1
- package/dist/tools/member-reservation.d.ts +29 -0
- package/dist/tools/member-reservation.d.ts.map +1 -0
- package/dist/tools/member-reservation.js +71 -0
- package/dist/tools/member-reservation.js.map +1 -0
- package/dist/tools/provision-vcs-auth.d.ts +7 -7
- package/dist/tools/provision-vcs-auth.js +1 -1
- package/dist/tools/provision-vcs-auth.js.map +1 -1
- package/dist/tools/register-member.d.ts +17 -5
- package/dist/tools/register-member.d.ts.map +1 -1
- package/dist/tools/register-member.js +144 -5
- package/dist/tools/register-member.js.map +1 -1
- package/dist/tools/remove-member.d.ts +1 -1
- package/dist/tools/report-status.d.ts +33 -0
- package/dist/tools/report-status.d.ts.map +1 -0
- package/dist/tools/report-status.js +44 -0
- package/dist/tools/report-status.js.map +1 -0
- package/dist/tools/respond-to-message.d.ts +21 -0
- package/dist/tools/respond-to-message.d.ts.map +1 -0
- package/dist/tools/respond-to-message.js +23 -0
- package/dist/tools/respond-to-message.js.map +1 -0
- package/dist/tools/send-files.d.ts +3 -0
- package/dist/tools/send-files.d.ts.map +1 -1
- package/dist/tools/send-files.js +88 -8
- package/dist/tools/send-files.js.map +1 -1
- package/dist/tools/send-message.d.ts +27 -0
- package/dist/tools/send-message.d.ts.map +1 -0
- package/dist/tools/send-message.js +46 -0
- package/dist/tools/send-message.js.map +1 -0
- package/dist/tools/shutdown-server.d.ts +2 -0
- package/dist/tools/shutdown-server.d.ts.map +1 -1
- package/dist/tools/shutdown-server.js +19 -0
- package/dist/tools/shutdown-server.js.map +1 -1
- package/dist/tools/update-member.d.ts +8 -8
- package/dist/tools/update-member.d.ts.map +1 -1
- package/dist/tools/update-member.js +11 -1
- package/dist/tools/update-member.js.map +1 -1
- package/dist/types.d.ts +15 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/agent-helpers.d.ts +2 -1
- package/dist/utils/agent-helpers.d.ts.map +1 -1
- package/dist/utils/agent-helpers.js +7 -2
- package/dist/utils/agent-helpers.js.map +1 -1
- package/dist/utils/pid-helpers.d.ts +15 -0
- package/dist/utils/pid-helpers.d.ts.map +1 -1
- package/dist/utils/pid-helpers.js +23 -0
- package/dist/utils/pid-helpers.js.map +1 -1
- package/dist/utils/process-utils.d.ts +3 -0
- package/dist/utils/process-utils.d.ts.map +1 -0
- package/dist/utils/process-utils.js +42 -0
- package/dist/utils/process-utils.js.map +1 -0
- package/dist/utils/prompt-errors.d.ts +2 -1
- package/dist/utils/prompt-errors.d.ts.map +1 -1
- package/dist/utils/prompt-errors.js +13 -3
- package/dist/utils/prompt-errors.js.map +1 -1
- package/dist/utils/workspace-trust.d.ts +24 -0
- package/dist/utils/workspace-trust.d.ts.map +1 -0
- package/dist/utils/workspace-trust.js +35 -0
- package/dist/utils/workspace-trust.js.map +1 -0
- package/dist/workflows/auto-sprint.js +450 -87
- package/package.json +35 -7
- package/packages/apra-fleet-client/package.json +26 -0
- package/packages/apra-fleet-client/src/client/api.mjs +396 -0
- package/packages/apra-fleet-client/src/client/client.mjs +146 -0
- package/packages/apra-fleet-client/src/client/errors.mjs +71 -0
- package/packages/apra-fleet-client/src/client/factory.mjs +65 -0
- package/packages/apra-fleet-client/src/client/server-resolution.mjs +265 -0
- package/packages/apra-fleet-client/src/client/transport.mjs +327 -0
- package/packages/apra-fleet-se/apra-pm/agents/backlog-groomer.md +287 -0
- package/packages/apra-fleet-se/apra-pm/agents/ci-watcher.md +89 -0
- package/packages/apra-fleet-se/apra-pm/agents/deployer.md +139 -0
- package/packages/apra-fleet-se/apra-pm/agents/doer.md +225 -0
- package/packages/apra-fleet-se/apra-pm/agents/harvester.md +169 -0
- package/packages/apra-fleet-se/apra-pm/agents/integ-test-runner.md +316 -0
- package/packages/apra-fleet-se/apra-pm/agents/plan-reviewer.md +188 -0
- package/packages/apra-fleet-se/apra-pm/agents/planner.md +239 -0
- package/packages/apra-fleet-se/apra-pm/agents/regression-test-runner.md +216 -0
- package/packages/apra-fleet-se/apra-pm/agents/reviewer.md +174 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/backlog-groomer-input.json +35 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/backlog-groomer-output.json +164 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/ci-watcher-input.json +26 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/ci-watcher-output.json +18 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/deployer-input.json +19 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/deployer-output.json +17 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-input.json +25 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/doer-output.json +22 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-input.json +31 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/harvester-output.json +18 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/integ-test-runner-input.json +20 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/integ-test-runner-output.json +61 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/plan-reviewer-input.json +15 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/plan-reviewer-output.json +30 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-input.json +15 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/regression-test-runner-output.json +50 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-input.json +25 -0
- package/packages/apra-fleet-se/apra-pm/agents/schemas/reviewer-output.json +38 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/SKILL.md +402 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/beads.md +142 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/cost.md +157 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/doer-reviewer-loop.md +300 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/fleet-addendum.md +121 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/simple-sprint.md +65 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/sprint.md +327 -0
- package/packages/apra-fleet-se/apra-pm/skills/pm/worktrees.md +92 -0
- package/packages/apra-fleet-se/apra-pm/version.json +3 -0
- package/packages/apra-fleet-se/bin/cli.mjs +857 -0
- package/packages/apra-fleet-se/bin/serve.mjs +383 -0
- package/packages/apra-fleet-se/fleet-sprint/conflict-ladder.mjs +178 -0
- package/packages/apra-fleet-se/fleet-sprint/contracts.mjs +914 -0
- package/packages/apra-fleet-se/fleet-sprint/dispatch-safety-guard.mjs +177 -0
- package/packages/apra-fleet-se/fleet-sprint/docs/README.md +191 -0
- package/packages/apra-fleet-se/fleet-sprint/docs/coach-role-design.md +151 -0
- package/packages/apra-fleet-se/fleet-sprint/docs/dolt-tier2-runbook.md +127 -0
- package/packages/apra-fleet-se/fleet-sprint/docs/fleet-sprint-diagram.md +94 -0
- package/packages/apra-fleet-se/fleet-sprint/docs/stabilization-log.md +1125 -0
- package/packages/apra-fleet-se/fleet-sprint/dolt-literal-guard.mjs +72 -0
- package/packages/apra-fleet-se/fleet-sprint/dolt-recovery-path-b.mjs +339 -0
- package/packages/apra-fleet-se/fleet-sprint/dolt-recovery-tier2.mjs +360 -0
- package/packages/apra-fleet-se/fleet-sprint/dolt-recovery.mjs +363 -0
- package/packages/apra-fleet-se/fleet-sprint/dolt-sync.mjs +1244 -0
- package/packages/apra-fleet-se/fleet-sprint/errors.mjs +572 -0
- package/packages/apra-fleet-se/fleet-sprint/full-db-fetch-guard.mjs +118 -0
- package/packages/apra-fleet-se/fleet-sprint/runner.js +9447 -0
- package/packages/apra-fleet-se/fleet-sprint/skills/fleet-sprint-cli/SKILL.md +103 -0
- package/packages/apra-fleet-se/fleet-sprint/sprint-lock.mjs +140 -0
- package/packages/apra-fleet-se/fleet-sprint/vcs-module.mjs +435 -0
- package/packages/apra-fleet-se/fleet-sprint/vcs-providers/azure-devops.mjs +68 -0
- package/packages/apra-fleet-se/fleet-sprint/vcs-providers/bitbucket.mjs +53 -0
- package/packages/apra-fleet-se/fleet-sprint/vcs-providers/dolt.mjs +146 -0
- package/packages/apra-fleet-se/fleet-sprint/vcs-providers/generic-git.mjs +176 -0
- package/packages/apra-fleet-se/fleet-sprint/vcs-providers/github.mjs +222 -0
- package/packages/apra-fleet-se/fleet-sprint/vcs-providers/index.mjs +218 -0
- package/packages/apra-fleet-se/fleet-sprint/viewer-extensions.mjs +882 -0
- package/packages/apra-fleet-se/package.json +28 -0
- package/packages/apra-fleet-se/workflow.json +1 -0
- package/packages/apra-fleet-workflow/package.json +30 -0
- package/packages/apra-fleet-workflow/src/viewer/command-output-cap.mjs +112 -0
- package/packages/apra-fleet-workflow/src/viewer/debounced-writer.mjs +153 -0
- package/packages/apra-fleet-workflow/src/viewer/html-utils.mjs +31 -0
- package/packages/apra-fleet-workflow/src/viewer/index.mjs +1325 -0
- package/packages/apra-fleet-workflow/src/viewer/lean-state.mjs +237 -0
- package/packages/apra-fleet-workflow/src/viewer/run-state-paths.mjs +130 -0
- package/packages/apra-fleet-workflow/src/viewer/sprint-state-paths.mjs +29 -0
- package/packages/apra-fleet-workflow/src/workflow/engine.mjs +200 -0
- package/packages/apra-fleet-workflow/src/workflow/errors.mjs +146 -0
- package/packages/apra-fleet-workflow/src/workflow/index.mjs +1723 -0
- package/packages/apra-fleet-workflow/src/workflow/journal.mjs +291 -0
- package/packages/apra-fleet-workflow/src/workflow/pricing.mjs +99 -0
- package/packages/apra-fleet-workflow/src/workflow/vetting.mjs +111 -0
- package/scripts/agy-transcript-reader.js +1 -0
- package/scripts/fleet-statusline.sh +17 -13
- package/skills/fleet/SKILL.md +37 -2
- package/skills/fleet/beads.md +14 -7
- package/skills/fleet/permissions.md +50 -0
- package/skills/fleet/profiles/base-dev.json +1 -0
- package/skills/fleet/profiles/base-reviewer.json +1 -0
- package/skills/fleet/profiles/node.json +2 -2
- package/version.json +1 -1
- package/scripts/agy-settings-merge.js +0 -27
- /package/{dist → packages/apra-fleet-se/apra-pm}/agents/_shared/GRAPH-SEMANTICS.md +0 -0
|
@@ -0,0 +1,1723 @@
|
|
|
1
|
+
import Ajv from 'ajv';
|
|
2
|
+
import { EventEmitter } from 'events';
|
|
3
|
+
import { randomUUID } from 'crypto';
|
|
4
|
+
import { AsyncLocalStorage } from 'async_hooks';
|
|
5
|
+
import { calculateCost } from './pricing.mjs';
|
|
6
|
+
import { WorkflowError, MemberNotFoundError, AgentOutputError, AgentDispatchError, CommandError, FleetTransportError, BudgetExceededError, CancelledError } from './errors.mjs';
|
|
7
|
+
import { hashText, computeActivityKey } from './journal.mjs';
|
|
8
|
+
|
|
9
|
+
export { WorkflowError, MemberNotFoundError, AgentOutputError, AgentDispatchError, CommandError, FleetTransportError, BudgetExceededError, CancelledError } from './errors.mjs';
|
|
10
|
+
|
|
11
|
+
const ajv = new Ajv({ strict: false });
|
|
12
|
+
|
|
13
|
+
// --- Per-run execution context (apra-fleet-unw.9, F11) --------------------
|
|
14
|
+
//
|
|
15
|
+
// Before this change, `FleetWorkflow` kept its "current run" state --
|
|
16
|
+
// `args`, `currentPhase`, `currentGroup`, `budget` -- as plain mutable
|
|
17
|
+
// instance fields. `WorkflowEngine.executeFile()` mutated `this.wf.args` on
|
|
18
|
+
// every call, and `phase()`/`group()` mutated a single shared
|
|
19
|
+
// `currentPhase`/`currentGroup`. That's fine for exactly one execution at a
|
|
20
|
+
// time, but breaks as soon as:
|
|
21
|
+
// (a) two concurrent `executeFile()` calls run on the same `FleetWorkflow`
|
|
22
|
+
// instance -- their `args` and phase attribution stomp on each other, or
|
|
23
|
+
// (b) a single run's `parallel()` branches each call `phase()` with a
|
|
24
|
+
// different value -- every branch (and every activity emitted from any
|
|
25
|
+
// branch, including ones dispatched before the racing `phase()` call
|
|
26
|
+
// resolves) ends up labeled with whichever branch's `phase()` call
|
|
27
|
+
// happened to run last, not its own.
|
|
28
|
+
//
|
|
29
|
+
// `runStorage` (an AsyncLocalStorage) holds a small per-run store --
|
|
30
|
+
// `{ runId, args, phase, group, budget }` -- that is threaded automatically
|
|
31
|
+
// through the async call graph of a single `executeFile()` invocation:
|
|
32
|
+
// - `WorkflowEngine.executeFile()` creates a fresh store via
|
|
33
|
+
// `FleetWorkflow.runWithContext(args, entryFn)` and runs the whole script
|
|
34
|
+
// inside `runStorage.run(store, ...)`. Every `agent()`/`command()`/
|
|
35
|
+
// `phase()`/etc. call made anywhere inside that script -- including
|
|
36
|
+
// across `await` boundaries -- automatically sees that run's store via
|
|
37
|
+
// `runStorage.getStore()`, with no explicit threading required in the
|
|
38
|
+
// workflow script itself.
|
|
39
|
+
// - `parallel()` forks a *shallow copy* of the current store for each
|
|
40
|
+
// branch before invoking its processor. `phase`/`group` are copied by
|
|
41
|
+
// value, so a `phase()` call inside one branch only mutates that
|
|
42
|
+
// branch's own copy and can never leak into a sibling branch or the
|
|
43
|
+
// parent. `args`/`budget` are copied by reference, so budget spend is
|
|
44
|
+
// still aggregated for the whole run and `args` stays consistent.
|
|
45
|
+
// - Every activity/log/state event still carries the store's `runId`, so
|
|
46
|
+
// even though the shared `EventEmitter` on `FleetWorkflow` fans events
|
|
47
|
+
// out to a single global listener (the dashboard viewer subscribes
|
|
48
|
+
// once), events from concurrent runs remain distinguishable.
|
|
49
|
+
//
|
|
50
|
+
// Direct, non-`executeFile()` usage (e.g. calling `wf.agent()`/`wf.phase()`
|
|
51
|
+
// straight off a `FleetWorkflow` instance, as several unit tests do) is
|
|
52
|
+
// preserved unchanged: when there is no active `runStorage` store (i.e.
|
|
53
|
+
// `runStorage.getStore()` returns `undefined`), every primitive falls back
|
|
54
|
+
// to the legacy instance-level fields (`this.args`, `this.currentPhase`,
|
|
55
|
+
// `this.currentGroup`, `this.budget`), exactly as before this change.
|
|
56
|
+
const runStorage = new AsyncLocalStorage();
|
|
57
|
+
|
|
58
|
+
// --- Structured-output extraction (apra-fleet-unw.8) ---------------------
|
|
59
|
+
//
|
|
60
|
+
// The old extraction path used a single greedy regex,
|
|
61
|
+
// /\{[\s\S]*\}|\[[\s\S]*\]/, which grabs from the FIRST `{`/`[` to the LAST
|
|
62
|
+
// `}`/`]` in the whole reply. That fails as soon as a reply contains more
|
|
63
|
+
// than one JSON block, or trailing prose that happens to contain a brace --
|
|
64
|
+
// the regex swallows everything in between as one "candidate" and JSON.parse
|
|
65
|
+
// then throws on it. The functions below replace that with real bracket
|
|
66
|
+
// matching plus schema-directed candidate selection: prefer fenced ```json
|
|
67
|
+
// blocks; otherwise scan the raw text for every balanced top-level
|
|
68
|
+
// {...}/[...] span (tracking string state so braces inside string literals
|
|
69
|
+
// don't confuse the matcher); validate each candidate against the schema in
|
|
70
|
+
// the order found and return the first one that both parses and validates.
|
|
71
|
+
//
|
|
72
|
+
// NOTE (descoped, see agent() below for the full note): this is a
|
|
73
|
+
// client-side mitigation. The more robust fix -- enforcing the schema at the
|
|
74
|
+
// member/harness tool-call layer -- requires fleet-server changes.
|
|
75
|
+
|
|
76
|
+
const FENCED_JSON_RE = /```(?:json)?\s*\n([\s\S]*?)```/gi;
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Extracts the contents of every fenced ```json (or bare ```) code block in
|
|
80
|
+
* `text`, in the order they appear.
|
|
81
|
+
* @param {string} text
|
|
82
|
+
* @returns {string[]}
|
|
83
|
+
*/
|
|
84
|
+
function extractFencedJsonBlocks(text) {
|
|
85
|
+
const blocks = [];
|
|
86
|
+
let match;
|
|
87
|
+
FENCED_JSON_RE.lastIndex = 0;
|
|
88
|
+
while ((match = FENCED_JSON_RE.exec(text)) !== null) {
|
|
89
|
+
blocks.push(match[1].trim());
|
|
90
|
+
}
|
|
91
|
+
return blocks;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Given `text[start]` is `{` or `[`, scans forward tracking bracket nesting
|
|
96
|
+
* and JSON string state (so braces/brackets inside string literals are
|
|
97
|
+
* ignored) to find the index of the matching closing bracket. Returns -1 if
|
|
98
|
+
* the span never closes or the brackets are mismatched.
|
|
99
|
+
* @param {string} text
|
|
100
|
+
* @param {number} start
|
|
101
|
+
* @returns {number}
|
|
102
|
+
*/
|
|
103
|
+
function findBalancedEnd(text, start) {
|
|
104
|
+
const closerFor = { '{': '}', '[': ']' };
|
|
105
|
+
const stack = [closerFor[text[start]]];
|
|
106
|
+
let inString = false;
|
|
107
|
+
let escaped = false;
|
|
108
|
+
|
|
109
|
+
for (let i = start + 1; i < text.length; i++) {
|
|
110
|
+
const ch = text[i];
|
|
111
|
+
if (inString) {
|
|
112
|
+
if (escaped) {
|
|
113
|
+
escaped = false;
|
|
114
|
+
} else if (ch === '\\') {
|
|
115
|
+
escaped = true;
|
|
116
|
+
} else if (ch === '"') {
|
|
117
|
+
inString = false;
|
|
118
|
+
}
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (ch === '"') {
|
|
122
|
+
inString = true;
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (ch === '{' || ch === '[') {
|
|
126
|
+
stack.push(closerFor[ch]);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (ch === '}' || ch === ']') {
|
|
130
|
+
if (stack.length === 0) return -1;
|
|
131
|
+
const expected = stack.pop();
|
|
132
|
+
if (expected !== ch) return -1;
|
|
133
|
+
if (stack.length === 0) return i;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return -1;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Scans `text` for every balanced top-level JSON object/array span, using
|
|
141
|
+
* real bracket matching (not a greedy regex), in the order they appear.
|
|
142
|
+
* @param {string} text
|
|
143
|
+
* @returns {string[]}
|
|
144
|
+
*/
|
|
145
|
+
function extractBalancedJsonCandidates(text) {
|
|
146
|
+
const candidates = [];
|
|
147
|
+
let i = 0;
|
|
148
|
+
while (i < text.length) {
|
|
149
|
+
const ch = text[i];
|
|
150
|
+
if (ch === '{' || ch === '[') {
|
|
151
|
+
const end = findBalancedEnd(text, i);
|
|
152
|
+
if (end !== -1) {
|
|
153
|
+
candidates.push(text.slice(i, end + 1));
|
|
154
|
+
i = end + 1;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
i++;
|
|
159
|
+
}
|
|
160
|
+
return candidates;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Attempts to find a schema-valid JSON candidate in `text`. Prefers fenced
|
|
165
|
+
* ```json blocks; falls back to a balanced top-level bracket scan of the raw
|
|
166
|
+
* text. Every candidate found is parsed and validated in order; the first
|
|
167
|
+
* one that both parses and validates against `compiledSchema` wins. Returns
|
|
168
|
+
* `{ ok: true, parsed, raw }` on success, or `{ ok: false, attempts }` where
|
|
169
|
+
* `attempts` records why every candidate was rejected (parse error or ajv
|
|
170
|
+
* validation errors) for repair-prompt / error-reporting purposes.
|
|
171
|
+
* @param {string} text
|
|
172
|
+
* @param {import('ajv').ValidateFunction} compiledSchema
|
|
173
|
+
*/
|
|
174
|
+
function extractStructuredOutput(text, compiledSchema) {
|
|
175
|
+
const fenced = extractFencedJsonBlocks(text);
|
|
176
|
+
|
|
177
|
+
const attempts = [];
|
|
178
|
+
const tryCandidate = (raw) => {
|
|
179
|
+
let parsed;
|
|
180
|
+
try {
|
|
181
|
+
parsed = JSON.parse(raw);
|
|
182
|
+
} catch (parseError) {
|
|
183
|
+
attempts.push({ raw, parseError });
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
if (compiledSchema(parsed)) {
|
|
187
|
+
return { ok: true, parsed, raw };
|
|
188
|
+
}
|
|
189
|
+
attempts.push({ raw, parsed, validationErrors: compiledSchema.errors ? [...compiledSchema.errors] : [] });
|
|
190
|
+
return null;
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
// Prefer fenced ```json blocks: try every fenced candidate first so the
|
|
194
|
+
// common case (a well-behaved reply whose only JSON lives in a fenced
|
|
195
|
+
// block) keeps picking the fenced block exactly as before.
|
|
196
|
+
for (const raw of fenced) {
|
|
197
|
+
const result = tryCandidate(raw);
|
|
198
|
+
if (result) return result;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Fall through to a balanced-bracket scan when no fenced candidate
|
|
202
|
+
// parsed and validated -- either because there were no fenced blocks at
|
|
203
|
+
// all, or because every fenced block was something else entirely (e.g.
|
|
204
|
+
// a shell command the reply quotes for illustration) and the real
|
|
205
|
+
// schema-satisfying JSON lives outside the fences. Scan the text with
|
|
206
|
+
// the fenced spans blanked out so we don't re-try content already
|
|
207
|
+
// rejected above, and so a stray brace inside a non-JSON fenced block
|
|
208
|
+
// can't be mistaken for a balanced candidate.
|
|
209
|
+
const unfencedText = text.replace(FENCED_JSON_RE, (match) => ' '.repeat(match.length));
|
|
210
|
+
const balanced = extractBalancedJsonCandidates(unfencedText);
|
|
211
|
+
for (const raw of balanced) {
|
|
212
|
+
const result = tryCandidate(raw);
|
|
213
|
+
if (result) return result;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Last-resort fallback: no bracketed candidate was found at all (e.g. a
|
|
217
|
+
// reply that is itself plain JSON with stray leading/trailing
|
|
218
|
+
// whitespace but somehow no `{`/`[` was detected as an opener -- should
|
|
219
|
+
// be rare given the scan above, but keeps behavior at least as good as
|
|
220
|
+
// the old single-shot JSON.parse(text) path).
|
|
221
|
+
if (fenced.length === 0 && balanced.length === 0) {
|
|
222
|
+
const result = tryCandidate(text.trim());
|
|
223
|
+
if (result) return result;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
return { ok: false, attempts };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Summarizes why every extraction attempt failed, for both the repair-prompt
|
|
231
|
+
* re-ask and the final AgentOutputError message.
|
|
232
|
+
* @param {Array<{raw: string, parseError?: Error, validationErrors?: object[]}>} attempts
|
|
233
|
+
*/
|
|
234
|
+
function summarizeExtractionAttempts(attempts) {
|
|
235
|
+
if (attempts.length === 0) {
|
|
236
|
+
return 'No JSON object or array was found in the response.';
|
|
237
|
+
}
|
|
238
|
+
return attempts
|
|
239
|
+
.map((a, idx) => {
|
|
240
|
+
if (a.parseError) {
|
|
241
|
+
return `Candidate ${idx + 1}: JSON parse error: ${a.parseError.message}`;
|
|
242
|
+
}
|
|
243
|
+
return `Candidate ${idx + 1}: schema validation failed: ${ajv.errorsText(a.validationErrors)}`;
|
|
244
|
+
})
|
|
245
|
+
.join('\n');
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Builds the lean repair re-ask prompt sent to the SAME member after an
|
|
250
|
+
* invalid structured-output attempt. apra-fleet-02s.3: repair re-asks now
|
|
251
|
+
* force `resume: true` (see the payload construction below), so the member's
|
|
252
|
+
* session already has the original prompt/schema and its own invalid
|
|
253
|
+
* output in context -- re-embedding all of that here would just re-spend
|
|
254
|
+
* tokens re-sending what the resumed session already has. Only the
|
|
255
|
+
* validation errors plus a short corrected-JSON instruction are needed.
|
|
256
|
+
* @param {string} errorsText
|
|
257
|
+
*/
|
|
258
|
+
function buildRepairPrompt(errorsText) {
|
|
259
|
+
return `Your previous response could not be used.\n\n` +
|
|
260
|
+
`Validation errors:\n${errorsText}\n\n` +
|
|
261
|
+
`Please respond again with corrected JSON only, strictly conforming to the schema from your previous instructions. ` +
|
|
262
|
+
`Do not include any commentary, explanation, or text outside the JSON.`;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* @typedef {Object} AgentOptions
|
|
267
|
+
* @property {string} [label] - UI label for this run
|
|
268
|
+
* @property {string} [phase] - Workflow phase grouping
|
|
269
|
+
* @property {object} [schema] - JSON Schema for structured output. The dispatch-time
|
|
270
|
+
* `schema` passed here is the one actually ajv-validated against the member's
|
|
271
|
+
* response (see the compile/append/validate logic in agent() below) -- it is
|
|
272
|
+
* therefore authoritative at the member, per each persona's precedence clause
|
|
273
|
+
* ("if your dispatch prompt includes a JSON schema instruction, that schema is
|
|
274
|
+
* authoritative"). When `agentType` names a role that publishes its own output
|
|
275
|
+
* contract (apra-pm's role-owned schema design), callers MUST source this value
|
|
276
|
+
* from that role's published schema via their application-layer adapter (e.g.
|
|
277
|
+
* `contracts.mjs`'s `SCHEMAS.<name>` for auto-sprint) rather than authoring an
|
|
278
|
+
* independent, parallel definition here. Two independently-authored schemas for
|
|
279
|
+
* the same role is the double-specification hazard this single-source rule
|
|
280
|
+
* exists to prevent; the workflow layer itself stays generic and does not (and
|
|
281
|
+
* cannot) resolve or detect such drift -- see
|
|
282
|
+
* `docs/agent-schema-layering-proposal.md` (section 4, recommendation item 4;
|
|
283
|
+
* section 5.3) for the full rationale, and `docs/structured-errors-proposal.md`
|
|
284
|
+
* for the sibling design-doc pattern this cross-reference follows.
|
|
285
|
+
* @property {string} [model] - Overrides model for this call
|
|
286
|
+
* @property {string} [member_name] - Apra-fleet member to dispatch to
|
|
287
|
+
* @property {string} [member_id] - Specific member UUID
|
|
288
|
+
* @property {Record<string, string>} [substitutions] - Template substitutions for prompt
|
|
289
|
+
* @property {number} [timeout_s] - Execution timeout (server-side INACTIVITY timeout:
|
|
290
|
+
* resets on every output chunk from the member CLI)
|
|
291
|
+
* @property {number} [max_total_s] - Server-side HARD wall-clock ceiling for the dispatch,
|
|
292
|
+
* independent of activity. Also drives the derived client-side request timeout:
|
|
293
|
+
* deriveTimeoutMs (packages/apra-fleet-client/src/client/api.mjs) prefers max_total_s
|
|
294
|
+
* over timeout_s, so omitting it here caps the whole dispatch at timeout_s+grace
|
|
295
|
+
* client-side even when the caller intended a much larger total budget. Observed live
|
|
296
|
+
* (stabilization log Issue 10): this option was silently DROPPED from the payload, so a
|
|
297
|
+
* legitimate 15+ minute reviewer dispatch was client-timed-out at 930s while the remote
|
|
298
|
+
* session kept running.
|
|
299
|
+
* @property {number} [max_turns] - Max turns for conversational tools
|
|
300
|
+
* @property {'low'|'medium'|'high'|'xhigh'|'max'} [effort] - Effort parameter for fleet routing
|
|
301
|
+
* @property {string} [agentType] - Agent persona to activate on the member
|
|
302
|
+
* @property {boolean|string} [resume] - Resume the previous session on the member if one exists.
|
|
303
|
+
* A boolean `true` resumes the member's stored last session; a non-empty STRING resumes
|
|
304
|
+
* EXACTLY that session id (apra-fleet-eft.78.1 widened execute_prompt's resume input to
|
|
305
|
+
* boolean|session-id and made an explicit-id resume that cannot be resumed a TERMINAL
|
|
306
|
+
* error). The value is passed straight through to executePrompt's payload.resume.
|
|
307
|
+
* NOTE: the underlying ApraFleet client (packages/apra-fleet-client/src/client/api.mjs)
|
|
308
|
+
* defaults `resume` to `true` when omitted. The WORKFLOW layer overrides that: agent()
|
|
309
|
+
* explicitly sends `resume: false` unless the caller sets this option, so that
|
|
310
|
+
* workflow-authored prompts are self-contained by default and don't silently inherit
|
|
311
|
+
* state from a prior session. (F10 / apra-fleet-unw.3)
|
|
312
|
+
* @property {(sessionId: string, meta: { member?: string, agent?: string, usage?: object }) => void} [onSessionId]
|
|
313
|
+
* Optional best-effort callback invoked with the resumable session id that execute_prompt
|
|
314
|
+
* promoted into structuredContent.sessionId (apra-fleet-eft.78.1), on a non-error dispatch
|
|
315
|
+
* that actually produced one. Lets a caller (the auto-sprint engine's per-role round-resume
|
|
316
|
+
* registry, apra-fleet-eft.78.3) record each dispatch's session id per (role, cycle) so it
|
|
317
|
+
* can resume the same role's session across rounds via `resume: <id>`. Never fires when the
|
|
318
|
+
* provider returns no session id (a capability signal, not a provider-name check); a throwing
|
|
319
|
+
* callback is caught and never breaks the dispatch. (apra-fleet-eft.78.3)
|
|
320
|
+
* @property {number} [timeoutMs] - Client-side McpClient.request() timeout override (ms),
|
|
321
|
+
* passed through to ApraFleet.executePrompt. Not sent to the server. When omitted, a
|
|
322
|
+
* default is derived from timeout_s/max_total_s (see deriveTimeoutMs in
|
|
323
|
+
* packages/apra-fleet-client/src/client/api.mjs). (apra-fleet-unw.5)
|
|
324
|
+
* @property {AbortSignal} [signal] - Optional AbortSignal, passed through to
|
|
325
|
+
* ApraFleet.executePrompt / McpClient.request. Aborting rejects the pending client-side
|
|
326
|
+
* wait for a response; it cannot cancel a job already accepted by the remote fleet-server.
|
|
327
|
+
* Groundwork for the cooperative-stop work in apra-fleet-unw.10 -- no /stop UI wiring here.
|
|
328
|
+
* (apra-fleet-unw.5)
|
|
329
|
+
* @property {number} [schemaRetries] - Only meaningful when `schema` is set. Bounded number
|
|
330
|
+
* of repair re-asks to the SAME member after a parse/validation failure, before giving up
|
|
331
|
+
* and throwing AgentOutputError. Defaults to 2 (so up to 3 total dispatches: 1 original +
|
|
332
|
+
* 2 repairs). Each repair re-ask FORCES `resume: true` (apra-fleet-02s.3) so the member's
|
|
333
|
+
* session already has the original prompt/schema and its own invalid output in context --
|
|
334
|
+
* the re-ask itself is a lean reminder containing only the ajv validation/parse errors
|
|
335
|
+
* plus a corrected-JSON instruction, not a re-embedding of the full original prompt/output.
|
|
336
|
+
* Each attempt emits its own activity:start/activity:end pair and is cost-accounted
|
|
337
|
+
* individually. (apra-fleet-unw.8)
|
|
338
|
+
* @property {number} [busyWaitMs] - How long (ms) to keep waiting-and-retrying when the
|
|
339
|
+
* fleet server reports the member is busy ("execute_prompt is already running") before
|
|
340
|
+
* surfacing the busy AgentDispatchError. Defaults to 10 minutes. A busy member is
|
|
341
|
+
* almost always TRANSIENT-but-slow: observed live, a client-side transport drop
|
|
342
|
+
* orphans the in-flight remote session, which keeps running (and holding the member's
|
|
343
|
+
* one-dispatch-at-a-time lock) for however long its work takes -- minutes, not
|
|
344
|
+
* seconds -- then completes and releases the lock. A blind fixed backoff loses that
|
|
345
|
+
* race; polling until the lock actually frees wins it. Set 0 to disable (immediate
|
|
346
|
+
* throw, the pre-existing behavior). Each poll is a cheap re-dispatch attempt (the
|
|
347
|
+
* server rejects busy calls in milliseconds with no side effects).
|
|
348
|
+
* @property {number} [busyPollMs] - Poll interval (ms) for the busy-wait above. Default 15s.
|
|
349
|
+
* @property {string} [sprint_id] - Opaque sprint identity to pass straight through to
|
|
350
|
+
* execute_prompt's server-side reservation check (apra-fleet-eft.29.1). Callers that
|
|
351
|
+
* also reserve members via member_reservation (e.g. auto-sprint's
|
|
352
|
+
* createMemberReservationClient) should pass the SAME token here so a dispatch from
|
|
353
|
+
* the owning sprint is recognized as such even when the fleet server this call
|
|
354
|
+
* dispatches through is a pre-existing shared singleton with no per-sprint
|
|
355
|
+
* APRA_FLEET_SPRINT_ID of its own. Omit to preserve prior (env-var-only) behavior.
|
|
356
|
+
*/
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* @typedef {Object} CommandOptions
|
|
360
|
+
* @property {string} [label] - UI label for this run
|
|
361
|
+
* @property {string} [phase] - Workflow phase grouping
|
|
362
|
+
* @property {string} [member_name] - Apra-fleet member to dispatch to
|
|
363
|
+
* @property {string} [member_id] - Specific member UUID
|
|
364
|
+
* @property {Record<string, string>} [substitutions] - Template substitutions for command
|
|
365
|
+
* @property {number} [timeout_s] - Execution timeout
|
|
366
|
+
* @property {boolean} [long_running] - Run as background task
|
|
367
|
+
* @property {number} [timeoutMs] - Client-side McpClient.request() timeout override (ms),
|
|
368
|
+
* passed through to ApraFleet.executeCommand. Not sent to the server. See AgentOptions
|
|
369
|
+
* .timeoutMs above for details. (apra-fleet-unw.5)
|
|
370
|
+
* @property {AbortSignal} [signal] - Optional AbortSignal, passed through to
|
|
371
|
+
* ApraFleet.executeCommand / McpClient.request. See AgentOptions.signal above for details.
|
|
372
|
+
* (apra-fleet-unw.5)
|
|
373
|
+
* @property {boolean} [failSoft] - When true, command() never throws for a
|
|
374
|
+
* command-level failure (CommandError / MemberNotFoundError /
|
|
375
|
+
* FleetTransportError); it instead resolves to
|
|
376
|
+
* `{ ok: boolean, output: string, error: string|null }`. A success also
|
|
377
|
+
* resolves to that shape (`{ ok: true, output: <text>, error: null }`)
|
|
378
|
+
* instead of the bare string, so callers don't have to branch on the
|
|
379
|
+
* return type. `CancelledError` (cooperative `requestStop()`) is never
|
|
380
|
+
* soft-caught -- it always throws, regardless of this option.
|
|
381
|
+
* (apra-fleet-unw.17)
|
|
382
|
+
*/
|
|
383
|
+
|
|
384
|
+
export class FleetWorkflow extends EventEmitter {
|
|
385
|
+
/**
|
|
386
|
+
* @param {import('../fleet-client/api.mjs').ApraFleet} fleetApi
|
|
387
|
+
* @param {any} args
|
|
388
|
+
*/
|
|
389
|
+
constructor(fleetApi, args = {}) {
|
|
390
|
+
super();
|
|
391
|
+
this.fleetApi = fleetApi;
|
|
392
|
+
this.args = args;
|
|
393
|
+
this.currentPhase = null;
|
|
394
|
+
this.budget = {
|
|
395
|
+
total: null,
|
|
396
|
+
_spent: 0,
|
|
397
|
+
// apra-fleet-dv5.6: counts of dispatches priced via real
|
|
398
|
+
// per-member rates (get_member_model_pricing) vs. the
|
|
399
|
+
// tier-band/concrete-model fallback (pricing.mjs) -- see
|
|
400
|
+
// pricingSummary() and buildCostAnalysis() in runner.js.
|
|
401
|
+
_pricedReal: 0,
|
|
402
|
+
_pricedFallback: 0,
|
|
403
|
+
spent: () => this.budget._spent,
|
|
404
|
+
remaining: () => this.budget.total === null ? Infinity : (this.budget.total - this.budget._spent),
|
|
405
|
+
pricingSummary: () => ({ real: this.budget._pricedReal, fallback: this.budget._pricedFallback })
|
|
406
|
+
};
|
|
407
|
+
// apra-fleet-dv5.6: member_id/member_name -> MemberModelPricing (or
|
|
408
|
+
// `null` when real pricing is unavailable for that member), cached
|
|
409
|
+
// for the lifetime of a run (fresh per runWithContext() call, see
|
|
410
|
+
// `store.memberPricingCache` below) -- tier->model resolution is
|
|
411
|
+
// static for a run's duration, so this is a plain cache, not a TTL.
|
|
412
|
+
this._memberPricingCache = new Map();
|
|
413
|
+
// member_id/member_name we've already logged a "pricing unavailable"
|
|
414
|
+
// warning for (apra-fleet-dv5.6 acceptance criteria: log ONCE per
|
|
415
|
+
// member, not once per dispatch).
|
|
416
|
+
this._warnedPricingMembers = new Set();
|
|
417
|
+
// (apra-fleet-unw.10) runId -> AbortController for every currently
|
|
418
|
+
// active runWithContext() run. requestStop() aborts every entry in
|
|
419
|
+
// this map; agent()/command() default to the current run's
|
|
420
|
+
// controller.signal (via _currentSignal()) when the caller doesn't
|
|
421
|
+
// pass its own opts.signal. See runWithContext()/requestStop() below.
|
|
422
|
+
this._activeControllers = new Map();
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// Returns the active per-run store (see runStorage above), or
|
|
426
|
+
// `undefined` when called outside of `WorkflowEngine.executeFile()` /
|
|
427
|
+
// `runWithContext()` -- e.g. direct `wf.method()` calls in unit tests.
|
|
428
|
+
_store() {
|
|
429
|
+
return runStorage.getStore();
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
// Effective phase: the current run's store.phase if one is active,
|
|
433
|
+
// otherwise the legacy instance-level `this.currentPhase`.
|
|
434
|
+
_currentPhase() {
|
|
435
|
+
const store = this._store();
|
|
436
|
+
return store ? store.phase : this.currentPhase;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
_currentGroup() {
|
|
440
|
+
const store = this._store();
|
|
441
|
+
return store ? store.group : this.currentGroup;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
_currentArgs() {
|
|
445
|
+
const store = this._store();
|
|
446
|
+
return store ? store.args : this.args;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
_currentBudget() {
|
|
450
|
+
const store = this._store();
|
|
451
|
+
return store ? store.budget : this.budget;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// apra-fleet-dv5.6: same store-or-legacy-field pattern as the other
|
|
455
|
+
// _current*() accessors -- a fresh Map per run (see runWithContext()),
|
|
456
|
+
// or the legacy instance-level field for direct non-executeFile() usage.
|
|
457
|
+
_currentMemberPricingCache() {
|
|
458
|
+
const store = this._store();
|
|
459
|
+
return store ? store.memberPricingCache : this._memberPricingCache;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
_currentRunId() {
|
|
463
|
+
const store = this._store();
|
|
464
|
+
return store ? store.runId : null;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// The active run's cooperative-cancellation AbortSignal (apra-fleet-
|
|
468
|
+
// unw.10), or `undefined` outside of a runWithContext() run / when the
|
|
469
|
+
// run's controller has no signal for some reason. agent()/command()
|
|
470
|
+
// fall back to this when the caller doesn't pass its own opts.signal.
|
|
471
|
+
_currentSignal() {
|
|
472
|
+
const store = this._store();
|
|
473
|
+
return store ? store.signal : undefined;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Cooperatively requests cancellation of every currently active run
|
|
478
|
+
* (every `runWithContext()` invocation -- i.e. every in-flight
|
|
479
|
+
* `WorkflowEngine.executeFile()` call -- on this `FleetWorkflow`
|
|
480
|
+
* instance). Aborts each run's `AbortController`, which rejects any
|
|
481
|
+
* in-flight `agent()`/`command()` dispatch that is using that run's
|
|
482
|
+
* signal (either implicitly, via `_currentSignal()`, or because the
|
|
483
|
+
* script never overrode `opts.signal`) with a client-side `AbortError`;
|
|
484
|
+
* `agent()`/`command()` re-wrap that as a typed `CancelledError` (see
|
|
485
|
+
* errors.mjs) so the run unwinds as a cancellation failure rather than a
|
|
486
|
+
* generic transport error.
|
|
487
|
+
*
|
|
488
|
+
* This is the mechanism the dashboard viewer's `/stop` endpoint uses
|
|
489
|
+
* (packages/apra-fleet-workflow/src/viewer/index.mjs) instead of the old
|
|
490
|
+
* `process.exit(1)` -- no state flush, mid-dispatch agents orphaned.
|
|
491
|
+
*
|
|
492
|
+
* NOTE: local/client-side cancellation only. A remote fleet member that
|
|
493
|
+
* already accepted a job may keep running to completion even after this
|
|
494
|
+
* run unwinds -- true server-side cancellation would require changes to
|
|
495
|
+
* the external apra-fleet MCP server and is out of scope here.
|
|
496
|
+
*
|
|
497
|
+
* @param {string} [reason]
|
|
498
|
+
*/
|
|
499
|
+
requestStop(reason = 'Workflow run cancelled via requestStop()') {
|
|
500
|
+
for (const controller of this._activeControllers.values()) {
|
|
501
|
+
controller.abort(new CancelledError(`[Workflow Error] ${reason}`));
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
log(msg) {
|
|
506
|
+
console.log(`[Workflow Log] ${msg}`);
|
|
507
|
+
this.emit('log', { phase: this._currentPhase(), msg, runId: this._currentRunId() });
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
group(title) {
|
|
511
|
+
const store = this._store();
|
|
512
|
+
if (store) {
|
|
513
|
+
store.group = title;
|
|
514
|
+
} else {
|
|
515
|
+
this.currentGroup = title;
|
|
516
|
+
}
|
|
517
|
+
console.log(`\n=== Group: ${title} ===`);
|
|
518
|
+
this.emit('group:start', { title, runId: this._currentRunId() });
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
endGroup() {
|
|
522
|
+
this.emit('group:end', { title: this._currentGroup(), runId: this._currentRunId() });
|
|
523
|
+
const store = this._store();
|
|
524
|
+
if (store) {
|
|
525
|
+
store.group = null;
|
|
526
|
+
} else {
|
|
527
|
+
this.currentGroup = null;
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// NOTE: `title` set inside a `parallel()` branch only mutates that
|
|
532
|
+
// branch's own forked store copy (see `parallel()` below and the
|
|
533
|
+
// runStorage comment above this class) -- it never leaks to sibling
|
|
534
|
+
// branches or the parent run.
|
|
535
|
+
phase(title) {
|
|
536
|
+
const store = this._store();
|
|
537
|
+
if (store) {
|
|
538
|
+
store.phase = title;
|
|
539
|
+
} else {
|
|
540
|
+
this.currentPhase = title;
|
|
541
|
+
}
|
|
542
|
+
console.log(`--- Phase: ${title} ---`);
|
|
543
|
+
// Event payload deliberately kept as the bare `title` string (not an
|
|
544
|
+
// object) -- the dashboard viewer subscribes to this event and
|
|
545
|
+
// single-run rendering must stay byte-identical (apra-fleet-unw.9
|
|
546
|
+
// acceptance criteria #3). Concurrent-run disambiguation is carried
|
|
547
|
+
// on activity/log/state events instead, which already have an
|
|
548
|
+
// object payload.
|
|
549
|
+
this.emit('phase', title);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
publishState(namespace, data) {
|
|
554
|
+
this.emit('state', { namespace, data, phase: this._currentPhase(), runId: this._currentRunId() });
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// apra-fleet-dv5.6: fetches (and caches for the run) a member's real
|
|
558
|
+
// per-tier pricing via the get_member_model_pricing MCP tool. Never
|
|
559
|
+
// throws -- any failure (older fleet server without the tool,
|
|
560
|
+
// network/hub-relay error, member not found) degrades to `null`
|
|
561
|
+
// (meaning "use the tier-band/concrete-model fallback for this
|
|
562
|
+
// member"), logged ONCE per member rather than once per dispatch.
|
|
563
|
+
async _getMemberPricing(memberKey, opts) {
|
|
564
|
+
const cache = this._currentMemberPricingCache();
|
|
565
|
+
if (cache.has(memberKey)) return cache.get(memberKey);
|
|
566
|
+
|
|
567
|
+
const warnUnavailable = (reason) => {
|
|
568
|
+
if (!this._warnedPricingMembers.has(memberKey)) {
|
|
569
|
+
this._warnedPricingMembers.add(memberKey);
|
|
570
|
+
console.warn(`[Workflow] Real per-member pricing unavailable for member "${memberKey}" (${reason}) -- falling back to tier-band cost estimates for this member's dispatches.`);
|
|
571
|
+
}
|
|
572
|
+
};
|
|
573
|
+
|
|
574
|
+
try {
|
|
575
|
+
const res = await this.fleetApi.getMemberModelPricing({ member_id: opts.member_id, member_name: opts.member_name });
|
|
576
|
+
const text = res && res.content && res.content[0] ? res.content[0].text : null;
|
|
577
|
+
const parsed = text ? JSON.parse(text) : null;
|
|
578
|
+
if (!parsed || parsed.error || !parsed.pricing) {
|
|
579
|
+
warnUnavailable(parsed && parsed.error ? parsed.error : 'no pricing data returned');
|
|
580
|
+
cache.set(memberKey, null);
|
|
581
|
+
return null;
|
|
582
|
+
}
|
|
583
|
+
cache.set(memberKey, parsed.pricing);
|
|
584
|
+
return parsed.pricing;
|
|
585
|
+
} catch (err) {
|
|
586
|
+
warnUnavailable(err && err.message ? err.message : String(err));
|
|
587
|
+
cache.set(memberKey, null);
|
|
588
|
+
return null;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// apra-fleet-dv5.6: resolves the cost of one dispatch, preferring real
|
|
593
|
+
// per-member pricing over the pricing.mjs tier-band/concrete-model
|
|
594
|
+
// fallback whenever `opts.model` is a tier keyword AND real pricing is
|
|
595
|
+
// available for that member and tier. Falls back to calculateCost()
|
|
596
|
+
// (unchanged behavior) for: a literal (non-tier-keyword) model id, a
|
|
597
|
+
// dispatch with no member_id/member_name (shouldn't happen -- agent()
|
|
598
|
+
// requires one), or when real pricing is unavailable/doesn't cover this
|
|
599
|
+
// tier. Increments budget._pricedReal/_pricedFallback so
|
|
600
|
+
// buildCostAnalysis() (runner.js) can honestly report which source
|
|
601
|
+
// priced a run's total.
|
|
602
|
+
async _resolveCost(opts, usage, budget) {
|
|
603
|
+
const tier = opts.model;
|
|
604
|
+
if (tier === 'cheap' || tier === 'standard' || tier === 'premium') {
|
|
605
|
+
const memberKey = opts.member_id || opts.member_name;
|
|
606
|
+
if (memberKey) {
|
|
607
|
+
const realPricing = await this._getMemberPricing(memberKey, opts);
|
|
608
|
+
const entry = realPricing && realPricing[tier];
|
|
609
|
+
if (entry && typeof entry.promptPrice === 'number' && typeof entry.completionPrice === 'number') {
|
|
610
|
+
const pTokens = usage.input_tokens || 0;
|
|
611
|
+
const cTokens = usage.output_tokens || 0;
|
|
612
|
+
const cost = (pTokens / 1_000_000) * entry.promptPrice + (cTokens / 1_000_000) * entry.completionPrice;
|
|
613
|
+
budget._pricedReal++;
|
|
614
|
+
return cost;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
const cost = calculateCost(opts.model, usage);
|
|
619
|
+
if (cost !== null) budget._pricedFallback++;
|
|
620
|
+
return cost;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* @param {string} prompt
|
|
625
|
+
* @param {AgentOptions} [opts]
|
|
626
|
+
*/
|
|
627
|
+
async agent(prompt, opts = {}) {
|
|
628
|
+
if (!opts.member_name && !opts.member_id) {
|
|
629
|
+
throw new Error(`[Workflow Error] agent() requires either member_name or member_id`);
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
const effectivePhase = opts.phase || this._currentPhase();
|
|
633
|
+
const runId = this._currentRunId();
|
|
634
|
+
if (effectivePhase) {
|
|
635
|
+
console.log(`[Dispatch] phase: ${effectivePhase} | member: ${opts.member_name || opts.member_id} | label: ${opts.label || 'none'}`);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
let compiledSchema = null;
|
|
639
|
+
if (opts.schema) {
|
|
640
|
+
try {
|
|
641
|
+
compiledSchema = ajv.compile(opts.schema);
|
|
642
|
+
} catch (err) {
|
|
643
|
+
throw new Error(`[Workflow Error] Invalid JSON Schema provided to agent(): ${err.message}`);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
const initialPrompt = opts.schema
|
|
648
|
+
? `${prompt}\n\nOnly provide your response strictly as per this JSON schema:\n${JSON.stringify(opts.schema, null, 2)}`
|
|
649
|
+
: prompt;
|
|
650
|
+
|
|
651
|
+
// Bounded schema-repair loop (apra-fleet-unw.8, F5). Non-schema
|
|
652
|
+
// calls always run exactly one iteration (maxRepairs = 0). For
|
|
653
|
+
// schema calls, a parse/validation failure re-dispatches to the SAME
|
|
654
|
+
// member with a self-contained repair prompt (see buildRepairPrompt
|
|
655
|
+
// above) instead of hard-throwing on the first bad reply -- one
|
|
656
|
+
// malformed JSON reply used to kill a whole multi-cycle sprint.
|
|
657
|
+
//
|
|
658
|
+
// DESCOPED: the more robust fix is enforcing the schema at the
|
|
659
|
+
// member/harness tool-call layer (e.g. a Claude-CLI-style structured
|
|
660
|
+
// tool call) so the member literally cannot emit non-conforming
|
|
661
|
+
// output. That requires fleet-server changes and is out of scope
|
|
662
|
+
// here; this client-side repair loop is the best available
|
|
663
|
+
// mitigation until that lands.
|
|
664
|
+
const maxRepairs = opts.schema ? (opts.schemaRetries ?? 2) : 0;
|
|
665
|
+
|
|
666
|
+
let currentPrompt = initialPrompt;
|
|
667
|
+
let lastActivityMeta = null;
|
|
668
|
+
const budget = this._currentBudget();
|
|
669
|
+
|
|
670
|
+
// (apra-fleet-unw.11, F6) Journal replay. `replayKey` is computed
|
|
671
|
+
// ONCE per logical agent() call (not per schema-repair attempt) from
|
|
672
|
+
// this run's monotonic activity sequence counter + call type +
|
|
673
|
+
// member + a hash of the fully-resolved initial prompt (including
|
|
674
|
+
// any appended schema instructions), so it's stable across repair
|
|
675
|
+
// attempts and deterministic across an uninterrupted-vs-resumed run
|
|
676
|
+
// of the SAME script with the SAME args. `store.activitySeq` is only
|
|
677
|
+
// non-null when the caller opted into journaling at all (see
|
|
678
|
+
// runWithContext()); a normal call with no journal/resumeJournal
|
|
679
|
+
// option never enters this block and never attaches
|
|
680
|
+
// sequence/replayKey to its activity events, so behavior/output are
|
|
681
|
+
// unchanged from before this feature existed.
|
|
682
|
+
const store = this._store();
|
|
683
|
+
let sequence = null;
|
|
684
|
+
let replayKey = null;
|
|
685
|
+
if (store && store.activitySeq) {
|
|
686
|
+
// (apra-fleet-unw2.14, N6) `sequence` is numeric at the top level
|
|
687
|
+
// and a hierarchical, scheduler-independent string inside a
|
|
688
|
+
// parallel() branch -- see _nextSequence()/parallel().
|
|
689
|
+
sequence = this._nextSequence(store);
|
|
690
|
+
replayKey = computeActivityKey({
|
|
691
|
+
sequence,
|
|
692
|
+
type: 'agent',
|
|
693
|
+
member: opts.member_name || opts.member_id,
|
|
694
|
+
textHash: hashText(initialPrompt)
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
const replay = store && store.replay;
|
|
699
|
+
if (replay && !replay.diverged && replayKey) {
|
|
700
|
+
const cached = replay.completedByKey.get(replayKey);
|
|
701
|
+
if (cached && cached.success) {
|
|
702
|
+
// Cache hit: return the journaled result WITHOUT dispatching
|
|
703
|
+
// to the fleet at all. Still emit activity:start/activity:end
|
|
704
|
+
// (marked `replayed: true`) so a listening dashboard/journal
|
|
705
|
+
// writer sees this step as part of the run.
|
|
706
|
+
const cachedActivityMeta = {
|
|
707
|
+
id: randomUUID(),
|
|
708
|
+
type: 'agent',
|
|
709
|
+
phase: effectivePhase,
|
|
710
|
+
runId,
|
|
711
|
+
label: (opts.label || prompt.split('\n')[0].substring(0, 50) + (prompt.length > 50 ? '...' : '')),
|
|
712
|
+
member: opts.member_name || opts.member_id,
|
|
713
|
+
model: opts.model || 'default',
|
|
714
|
+
repairAttempt: 0,
|
|
715
|
+
startTime: Date.now(),
|
|
716
|
+
sequence,
|
|
717
|
+
replayKey,
|
|
718
|
+
replayed: true
|
|
719
|
+
};
|
|
720
|
+
this.emit('activity:start', cachedActivityMeta);
|
|
721
|
+
// (apra-fleet-unw2.14, N18) INTENTIONAL: a replayed agent
|
|
722
|
+
// activity re-debits the run's budget using the journaled
|
|
723
|
+
// (cached) cost of the ORIGINAL dispatch. This is
|
|
724
|
+
// "total-spend-view" semantics: `budget.spent()` on a resumed
|
|
725
|
+
// run reflects the cumulative real cost of the whole logical
|
|
726
|
+
// run (original + resumed portions), NOT just what the resumed
|
|
727
|
+
// process dispatched live. That is deliberate -- a resume is a
|
|
728
|
+
// continuation of one run, and its budget ceiling must still
|
|
729
|
+
// account for money already spent before the crash, otherwise
|
|
730
|
+
// a run that crashed near its budget limit could resume and
|
|
731
|
+
// massively overspend. It is NOT the "fresh run starts at $0"
|
|
732
|
+
// model some callers might naively assume; that expectation is
|
|
733
|
+
// explicitly wrong here. (See the resumed-budget test in
|
|
734
|
+
// apra-fleet-workflow-journal.test.mjs.)
|
|
735
|
+
if (typeof cached.cost === 'number') {
|
|
736
|
+
budget._spent += cached.cost;
|
|
737
|
+
}
|
|
738
|
+
const cachedOutput = opts.schema ? JSON.parse(cached.output) : cached.output;
|
|
739
|
+
this.emit('activity:end', {
|
|
740
|
+
...cachedActivityMeta,
|
|
741
|
+
duration: 0,
|
|
742
|
+
success: true,
|
|
743
|
+
usage: cached.usage ?? null,
|
|
744
|
+
cost: cached.cost ?? null,
|
|
745
|
+
output: cached.output,
|
|
746
|
+
replayed: true
|
|
747
|
+
});
|
|
748
|
+
return cachedOutput;
|
|
749
|
+
}
|
|
750
|
+
// First mismatch or first missing entry for this run: stop
|
|
751
|
+
// replay and switch to live execution from here onward (partial
|
|
752
|
+
// replay, not all-or-nothing).
|
|
753
|
+
replay.diverged = true;
|
|
754
|
+
const inParallel = !!(store && store.seqPrefix);
|
|
755
|
+
console.warn(this._divergenceWarning({ sequence, type: 'agent', member: opts.member_name || opts.member_id, inParallel }));
|
|
756
|
+
this.emit('journal:diverged', { runId, sequence, type: 'agent', replayKey, inParallel });
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
for (let attempt = 0; attempt <= maxRepairs; attempt++) {
|
|
760
|
+
if (budget.total !== null && budget.remaining() <= 0) {
|
|
761
|
+
throw new BudgetExceededError(
|
|
762
|
+
`[Workflow Error] Budget exceeded: spent $${budget._spent.toFixed(4)} of $${budget.total.toFixed(4)} total. Aborting agent() dispatch.`,
|
|
763
|
+
{ details: { spent: budget._spent, total: budget.total, member: opts.member_name || opts.member_id } }
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
const isRepair = attempt > 0;
|
|
768
|
+
const activityMeta = {
|
|
769
|
+
id: randomUUID(),
|
|
770
|
+
type: 'agent',
|
|
771
|
+
phase: effectivePhase,
|
|
772
|
+
runId,
|
|
773
|
+
label: (opts.label || prompt.split('\n')[0].substring(0, 50) + (prompt.length > 50 ? '...' : ''))
|
|
774
|
+
+ (isRepair ? ` [schema repair ${attempt}/${maxRepairs}]` : ''),
|
|
775
|
+
member: opts.member_name || opts.member_id,
|
|
776
|
+
model: opts.model || 'default',
|
|
777
|
+
repairAttempt: attempt,
|
|
778
|
+
startTime: Date.now(),
|
|
779
|
+
...(replayKey !== null ? { sequence, replayKey } : {})
|
|
780
|
+
};
|
|
781
|
+
lastActivityMeta = activityMeta;
|
|
782
|
+
this.emit('activity:start', activityMeta);
|
|
783
|
+
|
|
784
|
+
const payload = {
|
|
785
|
+
prompt: currentPrompt,
|
|
786
|
+
model: opts.model,
|
|
787
|
+
member_name: opts.member_name,
|
|
788
|
+
member_id: opts.member_id,
|
|
789
|
+
substitutions: opts.substitutions,
|
|
790
|
+
timeout_s: opts.timeout_s,
|
|
791
|
+
max_total_s: opts.max_total_s,
|
|
792
|
+
max_turns: opts.max_turns,
|
|
793
|
+
effort: opts.effort,
|
|
794
|
+
agent: opts.agentType,
|
|
795
|
+
// apra-fleet-eft.29.1: pass-through opt-in, see AgentOptions.sprint_id above.
|
|
796
|
+
sprint_id: opts.sprint_id,
|
|
797
|
+
// F10: default to a self-contained (non-resumed) session for
|
|
798
|
+
// the INITIAL dispatch of a workflow-authored prompt. See
|
|
799
|
+
// AgentOptions.resume above and apra-fleet-unw.3.
|
|
800
|
+
// apra-fleet-02s.3: a schema-repair re-ask (isRepair===true)
|
|
801
|
+
// is a different case -- it now FORCES resume:true,
|
|
802
|
+
// regardless of opts.resume, so the member's session already
|
|
803
|
+
// has the original prompt/schema and its own invalid output
|
|
804
|
+
// in context; buildRepairPrompt() was shrunk accordingly to a
|
|
805
|
+
// lean reminder (validation errors only), since re-sending
|
|
806
|
+
// that context fresh every repair round would waste tokens.
|
|
807
|
+
resume: isRepair ? true : (opts.resume ?? false),
|
|
808
|
+
// apra-fleet-unw.5: opts pass-through only, no control-flow change here.
|
|
809
|
+
timeoutMs: opts.timeoutMs,
|
|
810
|
+
// apra-fleet-unw.10: defaults to the active run's cooperative
|
|
811
|
+
// -cancellation signal (set up by runWithContext()/
|
|
812
|
+
// requestStop()) when the caller doesn't supply its own.
|
|
813
|
+
signal: opts.signal ?? this._currentSignal()
|
|
814
|
+
};
|
|
815
|
+
|
|
816
|
+
try {
|
|
817
|
+
let result = await this.fleetApi.executePrompt(payload);
|
|
818
|
+
|
|
819
|
+
// Busy-wait (see AgentOptions.busyWaitMs): a busy member is
|
|
820
|
+
// transient-but-slow -- an orphaned prior session can hold
|
|
821
|
+
// the per-member dispatch lock for minutes before finishing.
|
|
822
|
+
// Poll (cheap, side-effect-free re-dispatch) until the lock
|
|
823
|
+
// frees or the budget runs out, instead of failing the whole
|
|
824
|
+
// step on the first busy rejection.
|
|
825
|
+
const busyWaitMs = opts.busyWaitMs ?? 600000;
|
|
826
|
+
const busyPollMs = opts.busyPollMs ?? 15000;
|
|
827
|
+
if (busyWaitMs > 0) {
|
|
828
|
+
const busyDeadline = Date.now() + busyWaitMs;
|
|
829
|
+
while (
|
|
830
|
+
result && result.structuredContent && result.structuredContent.isError
|
|
831
|
+
&& result.structuredContent.reason === 'busy'
|
|
832
|
+
&& Date.now() < busyDeadline
|
|
833
|
+
&& !(payload.signal && payload.signal.aborted)
|
|
834
|
+
) {
|
|
835
|
+
console.error(`[Agent Busy-Wait] member '${opts.member_name || opts.member_id}' is busy (a prior dispatch still holds its lock); retrying in ${Math.round(busyPollMs / 1000)}s (up to ${Math.round((busyDeadline - Date.now()) / 1000)}s left)...`);
|
|
836
|
+
await new Promise((resolve) => setTimeout(resolve, busyPollMs));
|
|
837
|
+
result = await this.fleetApi.executePrompt(payload);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
// execute_prompt's dispatch-level structuredContent (added
|
|
842
|
+
// alongside the display text -- see src/tools/execute-prompt.ts)
|
|
843
|
+
// reports real per-call token usage AND classifies dispatch
|
|
844
|
+
// failures (busy member, non-zero CLI exit, transport
|
|
845
|
+
// exception) distinctly from a genuine LLM response. Prefer it;
|
|
846
|
+
// fall back to result.usage directly for older servers that
|
|
847
|
+
// predate this field.
|
|
848
|
+
const structured = result && result.structuredContent;
|
|
849
|
+
const reportedUsage = (structured && structured.usage) || result.usage;
|
|
850
|
+
|
|
851
|
+
// apra-fleet-unw.4: never fabricate usage. If the fleet result
|
|
852
|
+
// didn't report real token usage, both usage and cost are
|
|
853
|
+
// explicitly null -- the viewer renders "n/a" and excludes the
|
|
854
|
+
// activity from cost totals rather than showing fiction. This
|
|
855
|
+
// applies per-attempt: every repair dispatch is accounted
|
|
856
|
+
// individually, exactly like the original attempt.
|
|
857
|
+
const hasRealUsage = !!(reportedUsage && typeof reportedUsage.total_tokens === 'number');
|
|
858
|
+
result.usage = hasRealUsage ? reportedUsage : null;
|
|
859
|
+
|
|
860
|
+
const cost = hasRealUsage ? await this._resolveCost(opts, result.usage, budget) : null;
|
|
861
|
+
if (cost !== null) {
|
|
862
|
+
budget._spent += cost;
|
|
863
|
+
}
|
|
864
|
+
const duration = Date.now() - activityMeta.startTime;
|
|
865
|
+
|
|
866
|
+
// Dispatch-level failure (busy member, non-zero exit, transport
|
|
867
|
+
// exception): the text is never the LLM's actual answer, so
|
|
868
|
+
// feeding it to the schema/JSON extractor below would always
|
|
869
|
+
// fail and misreport as "LLM failed to return parseable JSON".
|
|
870
|
+
// Surface it as a typed, distinctly-classified error instead,
|
|
871
|
+
// and never retry it through the bounded schema-repair loop --
|
|
872
|
+
// repair re-asks the SAME prompt with "here's why your JSON was
|
|
873
|
+
// invalid" framing, which cannot fix a dispatch failure and
|
|
874
|
+
// both wastes attempts and produces a misleading error message.
|
|
875
|
+
// The caller's own top-level retry (e.g. the streak-dispatch
|
|
876
|
+
// "retrying once" wrapper in apra-fleet-se's runner.js) still
|
|
877
|
+
// applies on top of this.
|
|
878
|
+
if (structured && structured.isError) {
|
|
879
|
+
const text = result && result.content && result.content.length > 0 ? result.content[0].text : '';
|
|
880
|
+
console.error(`[Agent API Error]`, text);
|
|
881
|
+
// apra-fleet-202.3: a dispatch that FAILED (isError) but still
|
|
882
|
+
// reported real input/output tokens really did consume that
|
|
883
|
+
// spend -- carry its usage/cost onto the activity record (as
|
|
884
|
+
// the empty-response failure path below already does) so the
|
|
885
|
+
// dashboard's per-activity totalTokens/totalCost tally
|
|
886
|
+
// includes it instead of silently dropping it. budget._spent
|
|
887
|
+
// was already bumped above (drives the harvester cost-
|
|
888
|
+
// analysis via spent()), and this failed activity was never
|
|
889
|
+
// previously recorded with a cost, so neither total is
|
|
890
|
+
// double-counted. When the provider reported no usage at all,
|
|
891
|
+
// result.usage is null and cost is null -- the viewer then
|
|
892
|
+
// tallies it as an unknown-cost activity rather than fiction.
|
|
893
|
+
this.emit('activity:end', { ...activityMeta, error: text, duration, usage: result.usage, cost, success: false });
|
|
894
|
+
throw new AgentDispatchError(`[Workflow Error] Agent dispatch failed (${structured.reason || 'unknown'}): ${text}`, { details: { text, reason: structured.reason, member: opts.member_name || opts.member_id } });
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
// apra-fleet-eft.78.3: surface the resumable session id
|
|
898
|
+
// (promoted into structuredContent.sessionId by execute_prompt
|
|
899
|
+
// in apra-fleet-eft.78.1) to the caller via an optional callback,
|
|
900
|
+
// WITHOUT changing agent()'s string/parsed return contract. The
|
|
901
|
+
// auto-sprint engine uses this to record each dispatch's session
|
|
902
|
+
// per (role, cycle) so it can resume the same role's session
|
|
903
|
+
// across rounds within a cycle (runner.js's round-session
|
|
904
|
+
// registry). Fired only on a non-error dispatch that actually
|
|
905
|
+
// produced a session id; a provider that does not support resume
|
|
906
|
+
// returns no sessionId, so the callback never fires and the
|
|
907
|
+
// engine falls back to a fresh session (a capability signal, not
|
|
908
|
+
// a provider-name check). Best-effort: a throwing callback must
|
|
909
|
+
// never break the dispatch.
|
|
910
|
+
if (
|
|
911
|
+
structured
|
|
912
|
+
&& typeof structured.sessionId === 'string'
|
|
913
|
+
&& structured.sessionId
|
|
914
|
+
&& typeof opts.onSessionId === 'function'
|
|
915
|
+
) {
|
|
916
|
+
try {
|
|
917
|
+
opts.onSessionId(structured.sessionId, { member: opts.member_name || opts.member_id, agent: opts.agentType, usage: result.usage });
|
|
918
|
+
} catch (cbErr) {
|
|
919
|
+
console.error(`[Agent onSessionId] callback threw (non-fatal): ${cbErr && cbErr.message ? cbErr.message : cbErr}`);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
if (result && result.content && result.content.length > 0) {
|
|
924
|
+
const text = result.content[0].text;
|
|
925
|
+
|
|
926
|
+
// STOPGAP: the apra-fleet MCP server currently reports a
|
|
927
|
+
// missing member as a normal-looking success payload whose
|
|
928
|
+
// text happens to match this pattern, instead of a
|
|
929
|
+
// structured error (see docs/structured-errors-proposal.md).
|
|
930
|
+
// Until the server ships Option 1 (JSON-RPC error) or
|
|
931
|
+
// Option 2 (isError payload), this string-sniff is the only
|
|
932
|
+
// classifier available; keep it, but always surface it as a
|
|
933
|
+
// typed error rather than a silent `null` return. A missing
|
|
934
|
+
// member is not a schema problem, so it is never retried
|
|
935
|
+
// through the repair loop.
|
|
936
|
+
if (text.startsWith('Member "') && text.includes('" not found.')) {
|
|
937
|
+
console.error(`[Agent API Error]`, text);
|
|
938
|
+
this.emit('activity:end', { ...activityMeta, error: text, duration, success: false });
|
|
939
|
+
throw new MemberNotFoundError(`[Workflow Error] ${text}`, { details: { text, member: opts.member_name || opts.member_id } });
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
// Empty-response detection (observed live, apra-fleet-eft.14):
|
|
943
|
+
// the fleet server can return success (exit 0, isError
|
|
944
|
+
// absent) whose text is ONLY the display wrapper -- e.g.
|
|
945
|
+
// exactly "\u{1F4CB} Response from <member>:\n\n" with an empty
|
|
946
|
+
// parsed result (the member CLI produced no parseable
|
|
947
|
+
// output; the server-side log line for such a dispatch
|
|
948
|
+
// also lacks its usual in=/out= token counts). Feeding
|
|
949
|
+
// that to schema extraction misclassifies it as "LLM
|
|
950
|
+
// returned invalid JSON" (and its repair re-ask wastes a
|
|
951
|
+
// dispatch); for no-schema calls it silently becomes a
|
|
952
|
+
// garbage "successful" result. It is a DISPATCH-level
|
|
953
|
+
// failure: surface it typed so callers' existing
|
|
954
|
+
// AgentDispatchError handling (retry / degrade the
|
|
955
|
+
// round) applies.
|
|
956
|
+
//
|
|
957
|
+
// structuredContent.response (added alongside this text --
|
|
958
|
+
// see src/tools/execute-prompt.ts) carries the exact reply
|
|
959
|
+
// the server parsed, with no display wrapper to strip --
|
|
960
|
+
// prefer it when present (upgraded server) as a direct,
|
|
961
|
+
// reliable emptiness check and as the clean value to hand
|
|
962
|
+
// back to callers, instead of text-scraping the wrapper.
|
|
963
|
+
// Fall back to the wrapper-stripping regex for an
|
|
964
|
+
// older/not-yet-rebuilt server that predates this field.
|
|
965
|
+
const hasStructuredResponse = !!structured && typeof structured.response === 'string';
|
|
966
|
+
const cleanText = hasStructuredResponse
|
|
967
|
+
? structured.response
|
|
968
|
+
: text
|
|
969
|
+
.replace(/^\u{1F4CB} Response from [^\n:]+:\s*/u, '')
|
|
970
|
+
.replace(/^Tokens: input=\d+ output=\d+\s*$/mu, '')
|
|
971
|
+
.replace(/^---\s*$/mu, '')
|
|
972
|
+
.replace(/^session: \S+\s*$/mu, '');
|
|
973
|
+
if (cleanText.trim() === '') {
|
|
974
|
+
const emptyMsg = `execute_prompt returned an empty response (display wrapper only, no LLM output) from member '${opts.member_name || opts.member_id}'.`;
|
|
975
|
+
console.error(`[Agent API Error]`, emptyMsg);
|
|
976
|
+
this.emit('activity:end', { ...activityMeta, error: emptyMsg, output: text, duration, usage: result.usage, cost, success: false });
|
|
977
|
+
throw new AgentDispatchError(`[Workflow Error] Agent dispatch failed (empty_response): ${emptyMsg}`, { details: { text, reason: 'empty_response', member: opts.member_name || opts.member_id } });
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
if (!opts.schema) {
|
|
981
|
+
this.emit('activity:end', { ...activityMeta, duration, success: true, usage: result.usage, cost, output: text });
|
|
982
|
+
return hasStructuredResponse ? structured.response : text;
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
const extraction = extractStructuredOutput(hasStructuredResponse ? structured.response : text, compiledSchema);
|
|
986
|
+
if (extraction.ok) {
|
|
987
|
+
this.emit('activity:end', { ...activityMeta, duration, success: true, usage: result.usage, cost, output: JSON.stringify(extraction.parsed, null, 2) });
|
|
988
|
+
return extraction.parsed;
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
const errorsText = summarizeExtractionAttempts(extraction.attempts);
|
|
992
|
+
|
|
993
|
+
if (attempt < maxRepairs) {
|
|
994
|
+
// Bounded repair: re-dispatch to the SAME member with
|
|
995
|
+
// a fresh, self-contained prompt (original prompt +
|
|
996
|
+
// invalid output + ajv errors). This attempt is still
|
|
997
|
+
// recorded as its own activity:end (success: false)
|
|
998
|
+
// so the journal/dashboard show it as a distinct step
|
|
999
|
+
// before the repair attempt that follows.
|
|
1000
|
+
const repairMsg = `Schema-invalid output, retrying (repair ${attempt + 1}/${maxRepairs}): ${errorsText}`;
|
|
1001
|
+
// apra-fleet-wei: this branch used to ONLY emit
|
|
1002
|
+
// activity:end (visible via /state, i.e. the
|
|
1003
|
+
// dashboard) with no console/text-log line at all --
|
|
1004
|
+
// only the terminal failure paths (member-not-found,
|
|
1005
|
+
// repairs-exhausted, dispatch errors) call
|
|
1006
|
+
// console.error. A caller watching just the workflow
|
|
1007
|
+
// log stream had no way to see an intermediate repair
|
|
1008
|
+
// attempt fail, even when it eventually recovers on a
|
|
1009
|
+
// later repair (as most of these do) -- the failure
|
|
1010
|
+
// was only ever visible by separately querying the
|
|
1011
|
+
// dashboard's structured activity data.
|
|
1012
|
+
console.error(`[Agent API Error]`, repairMsg);
|
|
1013
|
+
this.emit('activity:end', { ...activityMeta, error: repairMsg, output: text, duration, usage: result.usage, cost, success: false });
|
|
1014
|
+
currentPrompt = buildRepairPrompt(errorsText);
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// Repairs exhausted -- surface a typed AgentOutputError.
|
|
1019
|
+
// Classify the message the same way the old single-shot
|
|
1020
|
+
// code did (parseable-JSON vs schema-compliance failure)
|
|
1021
|
+
// based on the final attempt, so existing callers keyed
|
|
1022
|
+
// off either phrase keep working.
|
|
1023
|
+
const allUnparseable = extraction.attempts.length === 0 || extraction.attempts.every((a) => a.parseError);
|
|
1024
|
+
const attemptCount = attempt + 1;
|
|
1025
|
+
const message = allUnparseable
|
|
1026
|
+
? `[Workflow Error] LLM failed to return parseable JSON for structured output after ${attemptCount} attempt(s) (${maxRepairs} repair(s) exhausted).`
|
|
1027
|
+
: `[Workflow Error] LLM returned non-compliant JSON. Validation failed after ${attemptCount} attempt(s) (${maxRepairs} repair(s) exhausted): ${errorsText}`;
|
|
1028
|
+
const validationErrors = extraction.attempts
|
|
1029
|
+
.filter((a) => a.validationErrors)
|
|
1030
|
+
.flatMap((a) => a.validationErrors);
|
|
1031
|
+
// Preserve the underlying JSON.parse error on `.cause`
|
|
1032
|
+
// when the final attempt was unparseable, matching the
|
|
1033
|
+
// original single-shot contract that callers can inspect
|
|
1034
|
+
// `.cause` for the raw parse failure.
|
|
1035
|
+
const lastParseError = [...extraction.attempts].reverse().find((a) => a.parseError)?.parseError;
|
|
1036
|
+
|
|
1037
|
+
const err = new AgentOutputError(message, {
|
|
1038
|
+
details: {
|
|
1039
|
+
text,
|
|
1040
|
+
attempts: attemptCount,
|
|
1041
|
+
repairs: maxRepairs,
|
|
1042
|
+
errorsText,
|
|
1043
|
+
validationErrors: validationErrors.length > 0 ? validationErrors : undefined
|
|
1044
|
+
},
|
|
1045
|
+
cause: lastParseError
|
|
1046
|
+
});
|
|
1047
|
+
this.emit('activity:end', { ...activityMeta, error: err.message, output: text, duration, usage: result.usage, cost, success: false });
|
|
1048
|
+
throw err;
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
this.emit('activity:end', { ...activityMeta, duration, success: false });
|
|
1052
|
+
throw new AgentOutputError(`[Workflow Error] agent() received an empty content response from the fleet API.`, { details: { result } });
|
|
1053
|
+
} catch (error) {
|
|
1054
|
+
console.error(`[Agent API Error]`, error.message || error);
|
|
1055
|
+
if (error instanceof WorkflowError) {
|
|
1056
|
+
// activity:end for typed errors was already emitted at
|
|
1057
|
+
// the throw site above (with the richer, attempt-scoped
|
|
1058
|
+
// metadata); don't double-emit here.
|
|
1059
|
+
throw error;
|
|
1060
|
+
}
|
|
1061
|
+
const duration = Date.now() - activityMeta.startTime;
|
|
1062
|
+
// apra-fleet-unw.10: a client-side AbortError (.code ===
|
|
1063
|
+
// 'ABORTED', from McpClient.request() reacting to the
|
|
1064
|
+
// signal above) means this dispatch was cooperatively
|
|
1065
|
+
// cancelled via requestStop() -- surface it as a typed
|
|
1066
|
+
// CancelledError, not a generic transport failure.
|
|
1067
|
+
if (error && error.code === 'ABORTED') {
|
|
1068
|
+
const cancelErr = new CancelledError(`[Workflow Error] agent() dispatch cancelled: ${error.message || error}`, { details: { payload }, cause: error });
|
|
1069
|
+
this.emit('activity:end', { ...activityMeta, error: cancelErr.message, duration, success: false, cancelled: true });
|
|
1070
|
+
throw cancelErr;
|
|
1071
|
+
}
|
|
1072
|
+
this.emit('activity:end', { ...activityMeta, error: error.message || error, duration, success: false });
|
|
1073
|
+
throw new FleetTransportError(`[Workflow Error] Transport failure while executing agent prompt: ${error.message || error}`, { details: { payload }, cause: error });
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
// Unreachable: the loop above always returns or throws. Kept as a
|
|
1078
|
+
// defensive guard in case maxRepairs computation is ever negative.
|
|
1079
|
+
throw new AgentOutputError(`[Workflow Error] agent() exhausted its dispatch loop without a result.`, { details: { activity: lastActivityMeta } });
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
/**
|
|
1083
|
+
* @param {string} cmd
|
|
1084
|
+
* @param {CommandOptions} [opts]
|
|
1085
|
+
*/
|
|
1086
|
+
async command(cmd, opts = {}) {
|
|
1087
|
+
// (apra-fleet-unw.17, A4) `opts.failSoft`: when set, a command
|
|
1088
|
+
// failure that would otherwise throw (a well-formed `isError`
|
|
1089
|
+
// result -> CommandError, a "Member not found" text sniff ->
|
|
1090
|
+
// MemberNotFoundError, or a transport-level rejection ->
|
|
1091
|
+
// FleetTransportError) is instead returned to the caller as
|
|
1092
|
+
// `{ ok: false, output: '', error: <message> }` -- and a success is
|
|
1093
|
+
// returned as `{ ok: true, output: <text>, error: null }` instead of
|
|
1094
|
+
// the bare string. This exists for callers like runner.js's
|
|
1095
|
+
// deploy.md/integ-test-playbook.md file-existence probes, which must
|
|
1096
|
+
// never let a transient/portability probe failure (e.g. a
|
|
1097
|
+
// node-not-on-PATH quirk on some member) kill the whole sprint --
|
|
1098
|
+
// the probe is best-effort; a failure just means "treat as not
|
|
1099
|
+
// found" (skip the dependent phase), not "abort everything".
|
|
1100
|
+
// Deliberately does NOT catch CancelledError (cooperative
|
|
1101
|
+
// requestStop() cancellation must still unwind the run even for a
|
|
1102
|
+
// failSoft caller -- swallowing that would defeat requestStop()).
|
|
1103
|
+
const failSoft = !!opts.failSoft;
|
|
1104
|
+
const softFail = (err) => {
|
|
1105
|
+
if (err instanceof CancelledError) throw err;
|
|
1106
|
+
if (!failSoft) throw err;
|
|
1107
|
+
return { ok: false, output: '', error: err.message };
|
|
1108
|
+
};
|
|
1109
|
+
if (!opts.member_name && !opts.member_id) {
|
|
1110
|
+
throw new Error(`[Workflow Error] command() requires either member_name or member_id`);
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
const effectivePhase = opts.phase || this._currentPhase();
|
|
1114
|
+
const runId = this._currentRunId();
|
|
1115
|
+
if (!opts.silent) {
|
|
1116
|
+
console.log(`[Command] phase: ${effectivePhase} | member: ${opts.member_name || opts.member_id} | label: ${opts.label || 'none'}`);
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
let finalCmd = cmd;
|
|
1120
|
+
if (opts.substitutions) {
|
|
1121
|
+
for (const [key, value] of Object.entries(opts.substitutions)) {
|
|
1122
|
+
finalCmd = finalCmd.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), value);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
// (apra-fleet-unw.11, F6) Journal replay -- see the matching, more
|
|
1127
|
+
// detailed comment in agent() above. `command()`'s activity events
|
|
1128
|
+
// already carry the raw, substituted command text (the `command`
|
|
1129
|
+
// field above), so the replay key hashes that same text rather than
|
|
1130
|
+
// requiring a second copy.
|
|
1131
|
+
const store = this._store();
|
|
1132
|
+
let sequence = null;
|
|
1133
|
+
let replayKey = null;
|
|
1134
|
+
if (store && store.activitySeq) {
|
|
1135
|
+
// (apra-fleet-unw2.14, N6) See agent()/_nextSequence(): numeric at
|
|
1136
|
+
// the top level, hierarchical/order-independent inside parallel().
|
|
1137
|
+
sequence = this._nextSequence(store);
|
|
1138
|
+
replayKey = computeActivityKey({
|
|
1139
|
+
sequence,
|
|
1140
|
+
type: 'command',
|
|
1141
|
+
member: opts.member_name || opts.member_id,
|
|
1142
|
+
textHash: hashText(finalCmd)
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
const replay = store && store.replay;
|
|
1147
|
+
if (replay && !replay.diverged && replayKey) {
|
|
1148
|
+
const cached = replay.completedByKey.get(replayKey);
|
|
1149
|
+
if (cached && cached.success) {
|
|
1150
|
+
// apra-fleet-unw2.13 (N5): reconstruct the shape the CURRENT
|
|
1151
|
+
// call would have gotten live -- a failSoft caller expects
|
|
1152
|
+
// `{ ok, output, error }`, a plain caller expects the raw
|
|
1153
|
+
// string. `cached.failSoft` is read from the journaled
|
|
1154
|
+
// `activity:end` record (see the `failSoft` field added to
|
|
1155
|
+
// `activityMeta` below), which reflects how the ORIGINAL run
|
|
1156
|
+
// shaped this same call. Since a resumed run replays the
|
|
1157
|
+
// same script in the same order with the same opts, this
|
|
1158
|
+
// should always agree with the current call's `failSoft`.
|
|
1159
|
+
//
|
|
1160
|
+
// OLD-FORMAT journals (written before this fix) have no
|
|
1161
|
+
// `failSoft` field at all -- `cached.failSoft` is then
|
|
1162
|
+
// `undefined`, and we cannot know how the original call was
|
|
1163
|
+
// shaped. We fall back to the pre-fix behavior of returning
|
|
1164
|
+
// the raw string (best-effort; a failSoft caller resuming
|
|
1165
|
+
// from an old journal will see `res.ok === undefined` exactly
|
|
1166
|
+
// as it did before this fix, until the journal is
|
|
1167
|
+
// regenerated by a fresh, non-resumed run).
|
|
1168
|
+
const cachedFailSoft = !!cached.failSoft;
|
|
1169
|
+
const cachedActivityMeta = {
|
|
1170
|
+
id: randomUUID(),
|
|
1171
|
+
type: 'command',
|
|
1172
|
+
phase: effectivePhase,
|
|
1173
|
+
runId,
|
|
1174
|
+
label: opts.label || finalCmd.substring(0, 60),
|
|
1175
|
+
member: opts.member_name || opts.member_id,
|
|
1176
|
+
command: finalCmd,
|
|
1177
|
+
startTime: Date.now(),
|
|
1178
|
+
sequence,
|
|
1179
|
+
replayKey,
|
|
1180
|
+
replayed: true,
|
|
1181
|
+
failSoft: cachedFailSoft
|
|
1182
|
+
};
|
|
1183
|
+
this.emit('activity:start', cachedActivityMeta);
|
|
1184
|
+
this.emit('activity:end', {
|
|
1185
|
+
...cachedActivityMeta,
|
|
1186
|
+
duration: 0,
|
|
1187
|
+
success: true,
|
|
1188
|
+
output: cached.output,
|
|
1189
|
+
replayed: true
|
|
1190
|
+
});
|
|
1191
|
+
return cachedFailSoft ? { ok: true, output: cached.output, error: null } : cached.output;
|
|
1192
|
+
}
|
|
1193
|
+
replay.diverged = true;
|
|
1194
|
+
const inParallel = !!(store && store.seqPrefix);
|
|
1195
|
+
console.warn(this._divergenceWarning({ sequence, type: 'command', member: opts.member_name || opts.member_id, inParallel }));
|
|
1196
|
+
this.emit('journal:diverged', { runId, sequence, type: 'command', replayKey, inParallel });
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
const activityMeta = {
|
|
1200
|
+
id: randomUUID(),
|
|
1201
|
+
type: 'command',
|
|
1202
|
+
phase: effectivePhase,
|
|
1203
|
+
runId,
|
|
1204
|
+
label: opts.label || finalCmd.substring(0, 60),
|
|
1205
|
+
member: opts.member_name || opts.member_id,
|
|
1206
|
+
command: finalCmd,
|
|
1207
|
+
startTime: Date.now(),
|
|
1208
|
+
// apra-fleet-unw2.13 (N5): journal the failSoft flag as part of
|
|
1209
|
+
// every activity:start/activity:end record for this call, so a
|
|
1210
|
+
// FUTURE resume of this journal can reconstruct the right return
|
|
1211
|
+
// shape from `cached.failSoft` above, instead of unconditionally
|
|
1212
|
+
// returning the raw string regardless of how the original call
|
|
1213
|
+
// was made.
|
|
1214
|
+
failSoft,
|
|
1215
|
+
...(replayKey !== null ? { sequence, replayKey } : {})
|
|
1216
|
+
};
|
|
1217
|
+
this.emit('activity:start', activityMeta);
|
|
1218
|
+
|
|
1219
|
+
const payload = {
|
|
1220
|
+
command: finalCmd,
|
|
1221
|
+
member_name: opts.member_name,
|
|
1222
|
+
member_id: opts.member_id,
|
|
1223
|
+
timeout_s: opts.timeout_s,
|
|
1224
|
+
long_running: opts.long_running,
|
|
1225
|
+
// apra-fleet-unw.5: opts pass-through only, no control-flow change here.
|
|
1226
|
+
timeoutMs: opts.timeoutMs,
|
|
1227
|
+
// apra-fleet-unw.10: see the matching comment in agent() above.
|
|
1228
|
+
signal: opts.signal ?? this._currentSignal()
|
|
1229
|
+
};
|
|
1230
|
+
|
|
1231
|
+
try {
|
|
1232
|
+
const result = await this.fleetApi.executeCommand(payload);
|
|
1233
|
+
const outText = result.content && result.content.length > 0 ? result.content[0].text : '';
|
|
1234
|
+
// Servers new enough to send structuredContent give clean stdout
|
|
1235
|
+
// directly -- no "Exit code: N\n" prefix to strip, no risk of a
|
|
1236
|
+
// caller (e.g. parseBdJson() in fleet-sprint/runner.js) choking on
|
|
1237
|
+
// display formatting mixed into what should be raw command
|
|
1238
|
+
// output. Older servers (no structuredContent) fall back to the
|
|
1239
|
+
// legacy text field as-is, preserving prior behavior exactly.
|
|
1240
|
+
const cleanOutput = (result.structuredContent && typeof result.structuredContent.stdout === 'string')
|
|
1241
|
+
? result.structuredContent.stdout
|
|
1242
|
+
: outText;
|
|
1243
|
+
const duration = Date.now() - activityMeta.startTime;
|
|
1244
|
+
|
|
1245
|
+
// STOPGAP: see the matching comment in agent() above and
|
|
1246
|
+
// docs/structured-errors-proposal.md -- the server currently
|
|
1247
|
+
// signals a missing member via plain response text rather than a
|
|
1248
|
+
// structured error. Surface it as a typed error, never `null`.
|
|
1249
|
+
if (outText.startsWith('Member "') && outText.includes('" not found.')) {
|
|
1250
|
+
console.error(`[Command API Error]`, outText);
|
|
1251
|
+
this.emit('activity:end', { ...activityMeta, error: outText, duration, success: false });
|
|
1252
|
+
throw new MemberNotFoundError(`[Workflow Error] ${outText}`, { details: { text: outText, member: opts.member_name || opts.member_id } });
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
if (result.isError) {
|
|
1256
|
+
const err = new CommandError(`[Command Failed] ${outText}`, { details: { text: outText, command: finalCmd } });
|
|
1257
|
+
this.emit('activity:end', { ...activityMeta, error: err.message, duration, success: false });
|
|
1258
|
+
throw err;
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
// `result.isError` is an MCP-transport-level flag only -- it does
|
|
1262
|
+
// NOT reflect the exit code of the underlying process the server
|
|
1263
|
+
// ran. A `bd`/git/etc. invocation that exits non-zero (e.g. a
|
|
1264
|
+
// malformed argument) still comes back with isError unset, so
|
|
1265
|
+
// without this check it was reported as success:true both to
|
|
1266
|
+
// callers and to the dashboard viewer's activity badge. Older
|
|
1267
|
+
// servers with no structuredContent.exitCode are left exactly as
|
|
1268
|
+
// before (exitCode undefined skips this branch).
|
|
1269
|
+
const exitCode = result.structuredContent && typeof result.structuredContent.exitCode === 'number'
|
|
1270
|
+
? result.structuredContent.exitCode
|
|
1271
|
+
: null;
|
|
1272
|
+
if (exitCode !== null && exitCode !== 0) {
|
|
1273
|
+
const err = new CommandError(`[Command Failed] Exit code ${exitCode}: ${outText}`, { details: { text: outText, command: finalCmd, exitCode } });
|
|
1274
|
+
this.emit('activity:end', { ...activityMeta, error: err.message, duration, success: false });
|
|
1275
|
+
throw err;
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
this.emit('activity:end', { ...activityMeta, duration, success: true, output: outText });
|
|
1279
|
+
return failSoft ? { ok: true, output: cleanOutput, error: null } : cleanOutput;
|
|
1280
|
+
} catch (error) {
|
|
1281
|
+
console.error(`[Command API Error]`, error.message || error);
|
|
1282
|
+
if (error instanceof WorkflowError) {
|
|
1283
|
+
// activity:end for typed errors was already emitted at the
|
|
1284
|
+
// throw site above (see the matching comment in agent()'s
|
|
1285
|
+
// catch); don't double-emit here.
|
|
1286
|
+
return softFail(error);
|
|
1287
|
+
}
|
|
1288
|
+
const duration = Date.now() - activityMeta.startTime;
|
|
1289
|
+
// apra-fleet-unw.10: see the matching comment in agent() above.
|
|
1290
|
+
if (error && error.code === 'ABORTED') {
|
|
1291
|
+
const cancelErr = new CancelledError(`[Workflow Error] command() dispatch cancelled: ${error.message || error}`, { details: { payload }, cause: error });
|
|
1292
|
+
this.emit('activity:end', { ...activityMeta, error: cancelErr.message, duration, success: false, cancelled: true });
|
|
1293
|
+
throw cancelErr;
|
|
1294
|
+
}
|
|
1295
|
+
this.emit('activity:end', { ...activityMeta, error: error.message || error, duration, success: false });
|
|
1296
|
+
return softFail(new FleetTransportError(`[Workflow Error] Transport failure while executing command: ${error.message || error}`, { details: { payload }, cause: error }));
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
/**
|
|
1301
|
+
* Executes the given async processor function for each item sequentially.
|
|
1302
|
+
*
|
|
1303
|
+
* `sequential(items, processor, opts)` is the single-processor primitive:
|
|
1304
|
+
* exactly one `processor(item, index, items)` function is applied to every
|
|
1305
|
+
* item, in order. It does NOT accept a variadic list of per-stage
|
|
1306
|
+
* processors -- that old `sequential(items, ...stages)` form silently
|
|
1307
|
+
* dropped every stage after the first (F7). Extra positional arguments
|
|
1308
|
+
* now throw a TypeError instead of being swallowed. For a genuine
|
|
1309
|
+
* multi-stage pipeline where each stage's output feeds the next, use
|
|
1310
|
+
* `pipeline(items, ...stages)`.
|
|
1311
|
+
*/
|
|
1312
|
+
async sequential(items, processor, opts = {}, ...rest) {
|
|
1313
|
+
if (rest.length > 0) {
|
|
1314
|
+
throw new TypeError(
|
|
1315
|
+
`sequential(items, processor, opts) accepts at most 3 arguments, got ${3 + rest.length}. ` +
|
|
1316
|
+
`sequential() no longer accepts a variadic list of per-stage processors -- use pipeline(items, ...stages) for multi-stage flows.`
|
|
1317
|
+
);
|
|
1318
|
+
}
|
|
1319
|
+
if (typeof processor !== 'function') {
|
|
1320
|
+
throw new TypeError(
|
|
1321
|
+
`sequential(items, processor, opts): the 2nd argument must be a single processor function, got ${processor === null ? 'null' : typeof processor}. ` +
|
|
1322
|
+
`The old sequential(items, ...stages) multi-stage form is no longer supported -- use pipeline(items, ...stages) instead.`
|
|
1323
|
+
);
|
|
1324
|
+
}
|
|
1325
|
+
if (opts === null || typeof opts !== 'object' || Array.isArray(opts)) {
|
|
1326
|
+
throw new TypeError(`sequential(items, processor, opts): the 3rd argument must be a plain options object, got ${opts === null ? 'null' : typeof opts}.`);
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
const results = [];
|
|
1330
|
+
for (let i = 0; i < items.length; i++) {
|
|
1331
|
+
try {
|
|
1332
|
+
const res = await processor(items[i], i, items);
|
|
1333
|
+
results.push(res);
|
|
1334
|
+
} catch (err) {
|
|
1335
|
+
this.log(`[Sequential Error] item ${i} failed at a stage: ${err.message}`);
|
|
1336
|
+
if (!opts.continueOnError) {
|
|
1337
|
+
// Fail-fast: rethrow without discarding results already
|
|
1338
|
+
// collected for prior items. Attach them to the error so
|
|
1339
|
+
// callers can recover partial progress.
|
|
1340
|
+
err.partialResults = results.slice();
|
|
1341
|
+
throw err;
|
|
1342
|
+
}
|
|
1343
|
+
results.push(null);
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
return results;
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
/**
|
|
1350
|
+
* Executes a chain of stage functions for each item, sequentially, where
|
|
1351
|
+
* each stage receives the previous stage's result for that item (the
|
|
1352
|
+
* first stage receives the raw item). This is the documented multi-stage
|
|
1353
|
+
* form that `sequential(items, ...stages)` used to provide before it was
|
|
1354
|
+
* narrowed to a single-processor primitive (see `sequential()` above).
|
|
1355
|
+
*
|
|
1356
|
+
* Failure semantics mirror `sequential()`: by default a stage error
|
|
1357
|
+
* aborts the whole pipeline run and rethrows with `err.partialResults`
|
|
1358
|
+
* populated; pass `{ continueOnError: true }` as a trailing plain-object
|
|
1359
|
+
* argument to instead record `null` for the failed item and continue
|
|
1360
|
+
* with the rest.
|
|
1361
|
+
*/
|
|
1362
|
+
async pipeline(items, ...stagesAndOpts) {
|
|
1363
|
+
let opts = {};
|
|
1364
|
+
let stages = stagesAndOpts;
|
|
1365
|
+
if (stagesAndOpts.length > 0 && typeof stagesAndOpts[stagesAndOpts.length - 1] !== 'function') {
|
|
1366
|
+
opts = stagesAndOpts[stagesAndOpts.length - 1];
|
|
1367
|
+
stages = stagesAndOpts.slice(0, -1);
|
|
1368
|
+
if (opts === null || typeof opts !== 'object' || Array.isArray(opts)) {
|
|
1369
|
+
throw new TypeError(`pipeline(items, ...stages, [opts]): the trailing non-function argument must be a plain options object, got ${opts === null ? 'null' : typeof opts}.`);
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
if (stages.length === 0) {
|
|
1373
|
+
throw new TypeError('pipeline(items, ...stages): at least one stage function is required.');
|
|
1374
|
+
}
|
|
1375
|
+
stages.forEach((stage, idx) => {
|
|
1376
|
+
if (typeof stage !== 'function') {
|
|
1377
|
+
throw new TypeError(`pipeline(items, ...stages): stage ${idx + 1} must be a function, got ${stage === null ? 'null' : typeof stage}.`);
|
|
1378
|
+
}
|
|
1379
|
+
});
|
|
1380
|
+
|
|
1381
|
+
const results = [];
|
|
1382
|
+
for (let i = 0; i < items.length; i++) {
|
|
1383
|
+
try {
|
|
1384
|
+
let value = items[i];
|
|
1385
|
+
for (const stage of stages) {
|
|
1386
|
+
value = await stage(value, i, items);
|
|
1387
|
+
}
|
|
1388
|
+
results.push(value);
|
|
1389
|
+
} catch (err) {
|
|
1390
|
+
this.log(`[Pipeline Error] item ${i} failed at a stage: ${err.message}`);
|
|
1391
|
+
if (!opts.continueOnError) {
|
|
1392
|
+
err.partialResults = results.slice();
|
|
1393
|
+
throw err;
|
|
1394
|
+
}
|
|
1395
|
+
results.push(null);
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
return results;
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
/**
|
|
1402
|
+
* Executes the given async processor function for each item in parallel.
|
|
1403
|
+
*
|
|
1404
|
+
* (apra-fleet-unw.9, F11) Each branch runs against its own shallow-copied
|
|
1405
|
+
* fork of the current run's store (see runStorage comment above): `phase`
|
|
1406
|
+
* and `group` are copied by value, so a `phase()` call made inside one
|
|
1407
|
+
* branch's processor mutates only that branch's copy and can never leak
|
|
1408
|
+
* into a sibling branch (or into activities dispatched from a sibling
|
|
1409
|
+
* branch that happens to still be in flight) -- this is the exact F11
|
|
1410
|
+
* "concurrent branches inherit whichever phase() was called last" bug.
|
|
1411
|
+
* `args`/`budget`/`runId` are copied by reference so they stay shared and
|
|
1412
|
+
* consistent across every branch of the same run. When `parallel()` is
|
|
1413
|
+
* called outside of any active run store (legacy direct-call usage),
|
|
1414
|
+
* branches simply run without forking anything, matching prior behavior.
|
|
1415
|
+
*
|
|
1416
|
+
* (apra-fleet-unw2.14, N6) When journaling is active, each branch fork
|
|
1417
|
+
* ALSO gets its OWN activity sub-sequence rooted at a deterministic,
|
|
1418
|
+
* scheduler-independent prefix. Before this, every branch shared the
|
|
1419
|
+
* run's single `activitySeq` counter, so the sequence number a given
|
|
1420
|
+
* agent()/command() call received depended on which branch's call
|
|
1421
|
+
* happened to increment the shared counter next -- non-deterministic
|
|
1422
|
+
* across runs. A resumed multi-streak run then computed different
|
|
1423
|
+
* sequence numbers than the journaled run, missed the replay cache, and
|
|
1424
|
+
* re-executed everything live (re-dispatching doers whose work already
|
|
1425
|
+
* happened). Now the prefix is `<parentPrefix><barrierIndex>:<i>:` where
|
|
1426
|
+
* `barrierIndex` numbers this parallel() barrier at the parent level (in
|
|
1427
|
+
* program order, assigned SYNCHRONOUSLY before any branch runs) and `i`
|
|
1428
|
+
* is the branch's STATIC index in `items` -- neither depends on runtime
|
|
1429
|
+
* completion/scheduling order. Each branch's own fresh `activitySeq`
|
|
1430
|
+
* then counts only that branch's calls, in the branch's own program
|
|
1431
|
+
* order. The result: identical replay keys for a given logical call site
|
|
1432
|
+
* regardless of how branches interleave. See journal.mjs
|
|
1433
|
+
* computeActivityKey for the full semantics.
|
|
1434
|
+
*/
|
|
1435
|
+
async parallel(items, processor, opts = {}) {
|
|
1436
|
+
const parentStore = this._store();
|
|
1437
|
+
// Assign this barrier's index SYNCHRONOUSLY, in program order, before
|
|
1438
|
+
// any branch is scheduled -- so it can never race with a sibling
|
|
1439
|
+
// parallel() call at the same store level. Only meaningful when
|
|
1440
|
+
// journaling is active (parallelSeq is null otherwise).
|
|
1441
|
+
const barrierIndex = (parentStore && parentStore.parallelSeq)
|
|
1442
|
+
? parentStore.parallelSeq.value++
|
|
1443
|
+
: null;
|
|
1444
|
+
return Promise.all(items.map((item, i) => {
|
|
1445
|
+
const runBranch = async () => {
|
|
1446
|
+
try {
|
|
1447
|
+
return await processor(item, i, items);
|
|
1448
|
+
} catch (err) {
|
|
1449
|
+
this.log(`[Parallel Error] item ${i} failed: ${err.message}`);
|
|
1450
|
+
if (!opts.continueOnError) {
|
|
1451
|
+
throw err;
|
|
1452
|
+
}
|
|
1453
|
+
return null;
|
|
1454
|
+
}
|
|
1455
|
+
};
|
|
1456
|
+
if (parentStore) {
|
|
1457
|
+
const branchStore = { ...parentStore };
|
|
1458
|
+
// Journaling active: give this branch its OWN hierarchical
|
|
1459
|
+
// sub-sequence so its replay keys are order-independent. The
|
|
1460
|
+
// prefix is fixed by the branch's static array index `i` and
|
|
1461
|
+
// the barrier index computed above -- not by scheduling.
|
|
1462
|
+
if (parentStore.activitySeq) {
|
|
1463
|
+
branchStore.seqPrefix = `${parentStore.seqPrefix || ''}${barrierIndex}:${i}:`;
|
|
1464
|
+
branchStore.activitySeq = { value: 0 };
|
|
1465
|
+
branchStore.parallelSeq = { value: 0 };
|
|
1466
|
+
}
|
|
1467
|
+
return runStorage.run(branchStore, runBranch);
|
|
1468
|
+
}
|
|
1469
|
+
return runBranch();
|
|
1470
|
+
}));
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
/**
|
|
1474
|
+
* (apra-fleet-unw2.14, N6) Computes the replay `sequence` component for
|
|
1475
|
+
* the next agent()/command() call in the current store, advancing the
|
|
1476
|
+
* store's local activity counter. At the top level this returns a plain
|
|
1477
|
+
* number (`0`,`1`,...); inside a `parallel()` branch it returns the
|
|
1478
|
+
* hierarchical, scheduler-independent string
|
|
1479
|
+
* `<seqPrefix><localSeq>` (e.g. `0:1:0`). Returns `null` when journaling
|
|
1480
|
+
* is not active for this run (so no replay-key machinery runs at all).
|
|
1481
|
+
* @param {object|undefined} store
|
|
1482
|
+
* @returns {number|string|null}
|
|
1483
|
+
*/
|
|
1484
|
+
_nextSequence(store) {
|
|
1485
|
+
if (!store || !store.activitySeq) return null;
|
|
1486
|
+
const local = store.activitySeq.value++;
|
|
1487
|
+
return store.seqPrefix ? `${store.seqPrefix}${local}` : local;
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
/**
|
|
1491
|
+
* (apra-fleet-unw2.14, N6) Builds the human-facing replay-divergence
|
|
1492
|
+
* warning, distinguishing a divergence detected INSIDE a `parallel()`
|
|
1493
|
+
* region from a sequential one. The two carry very different severity for
|
|
1494
|
+
* a human debugging a resume:
|
|
1495
|
+
*
|
|
1496
|
+
* - A SEQUENTIAL divergence is the suspicious case: the run's top-level
|
|
1497
|
+
* flow no longer matches the journal, which almost always means the
|
|
1498
|
+
* workflow script itself changed (a call added/removed/reordered, a
|
|
1499
|
+
* prompt/command edited, non-deterministic args) between the recording
|
|
1500
|
+
* and the resume. Everything from here on re-runs live.
|
|
1501
|
+
*
|
|
1502
|
+
* - A PARALLEL-region divergence is (post-N6) far less alarming: keys
|
|
1503
|
+
* inside `parallel()` are now scheduler-independent, so a divergence
|
|
1504
|
+
* here is NOT caused by branch interleaving. It usually means either
|
|
1505
|
+
* (a) the journal was written by a pre-N6 build (old shared global
|
|
1506
|
+
* counter -- see computeActivityKey's OLD-FORMAT note; regenerate the
|
|
1507
|
+
* journal to fix), or (b) a branch is internally non-deterministic
|
|
1508
|
+
* (dispatches a different number/order of calls across runs) or the
|
|
1509
|
+
* set/order of parallel branches changed.
|
|
1510
|
+
* @param {{ sequence: number|string, type: string, member?: string, inParallel: boolean }} parts
|
|
1511
|
+
* @returns {string}
|
|
1512
|
+
*/
|
|
1513
|
+
_divergenceWarning({ sequence, type, member, inParallel }) {
|
|
1514
|
+
const base = `[Journal] Replay divergence at sequence ${sequence} (${type}, member: ${member}) -- switching to live execution from this point onward.`;
|
|
1515
|
+
if (inParallel) {
|
|
1516
|
+
return base + ' This divergence is INSIDE a parallel() region; branch interleaving is NOT the cause (replay keys are order-independent since apra-fleet-unw2.14/N6). Likely a pre-N6 (old-format) journal, an internally non-deterministic branch, or a changed set/order of parallel branches -- regenerate the journal from a fresh run if it predates N6.';
|
|
1517
|
+
}
|
|
1518
|
+
return base + ' This is a SEQUENTIAL (top-level) divergence: the run no longer matches the journal, most likely because the workflow script or its args changed between recording and resume.';
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
async transform(label, func, context) {
|
|
1522
|
+
const id = randomUUID();
|
|
1523
|
+
const activityMeta = {
|
|
1524
|
+
id, type: 'transform', label, phase: this._currentPhase(), runId: this._currentRunId(), startTime: Date.now()
|
|
1525
|
+
};
|
|
1526
|
+
this.emit('activity:start', activityMeta);
|
|
1527
|
+
|
|
1528
|
+
const transformationFn = func || ((data) => data); // pass as-is default
|
|
1529
|
+
|
|
1530
|
+
try {
|
|
1531
|
+
let result = await transformationFn(context);
|
|
1532
|
+
const duration = Date.now() - activityMeta.startTime;
|
|
1533
|
+
|
|
1534
|
+
let stringifiedOutput = result;
|
|
1535
|
+
if (typeof result !== 'string' && result !== undefined && result !== null) {
|
|
1536
|
+
try { stringifiedOutput = JSON.stringify(result, null, 2); } catch(e) {}
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
let stringifiedInput = context;
|
|
1540
|
+
if (typeof context !== 'string' && context !== undefined && context !== null) {
|
|
1541
|
+
try { stringifiedInput = JSON.stringify(context, null, 2); } catch(e) {}
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
this.emit('activity:end', { ...activityMeta, duration, success: true, input: stringifiedInput, output: stringifiedOutput });
|
|
1545
|
+
return result;
|
|
1546
|
+
} catch (e) {
|
|
1547
|
+
const duration = Date.now() - activityMeta.startTime;
|
|
1548
|
+
let stringifiedInput = context;
|
|
1549
|
+
if (typeof context !== 'string' && context !== undefined && context !== null) {
|
|
1550
|
+
try { stringifiedInput = JSON.stringify(context, null, 2); } catch(e) {}
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
this.emit('activity:end', { ...activityMeta, duration, success: false, error: e.message, input: stringifiedInput });
|
|
1554
|
+
const err = new Error(`[Workflow Error] Transform failed: ${e.message}`);
|
|
1555
|
+
throw err;
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
async workflow(nameOrRef, args = {}) {
|
|
1560
|
+
// Run another script inline. Needs script runner logic.
|
|
1561
|
+
throw new Error("Nested workflows not yet implemented");
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
// Shared primitive bindings (agent/command/parallel/etc.) used by both
|
|
1565
|
+
// the legacy `createContext()` and the per-run `runWithContext()` below.
|
|
1566
|
+
// The primitives themselves are always bound to `this` -- they don't
|
|
1567
|
+
// capture `args`/`phase`/`budget` directly; instead they look those up
|
|
1568
|
+
// dynamically via `this._store()`/`this._current*()` at call time (see
|
|
1569
|
+
// the runStorage comment above this class), so the SAME bound functions
|
|
1570
|
+
// correctly resolve to whichever run (or the legacy instance-level
|
|
1571
|
+
// fields) is active when they're actually invoked.
|
|
1572
|
+
_bindPrimitives() {
|
|
1573
|
+
return {
|
|
1574
|
+
agent: this.agent.bind(this),
|
|
1575
|
+
command: this.command.bind(this),
|
|
1576
|
+
sequential: this.sequential.bind(this),
|
|
1577
|
+
pipeline: this.pipeline.bind(this),
|
|
1578
|
+
parallel: this.parallel.bind(this),
|
|
1579
|
+
transform: this.transform.bind(this),
|
|
1580
|
+
nullTransform: () => null,
|
|
1581
|
+
log: this.log.bind(this),
|
|
1582
|
+
phase: this.phase.bind(this),
|
|
1583
|
+
publishState: this.publishState.bind(this),
|
|
1584
|
+
workflow: this.workflow.bind(this),
|
|
1585
|
+
group: this.group.bind(this),
|
|
1586
|
+
endGroup: this.endGroup.bind(this)
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
// A helper to inject the workflow globals into a user script context.
|
|
1591
|
+
//
|
|
1592
|
+
// Legacy / direct-call form: NOT run-scoped. `args`/`budget` here are the
|
|
1593
|
+
// legacy instance-level fields (`this.args`/`this.budget`), exactly as
|
|
1594
|
+
// before apra-fleet-unw.9 -- preserved for existing direct `wf.method()`
|
|
1595
|
+
// callers and tests that never go through `WorkflowEngine.executeFile()`.
|
|
1596
|
+
// For per-run isolation (the fix for the concurrent-execution bug this
|
|
1597
|
+
// context object exists to prevent), use `runWithContext()` instead,
|
|
1598
|
+
// which `WorkflowEngine.executeFile()` calls internally.
|
|
1599
|
+
createContext(args = this.args) {
|
|
1600
|
+
return {
|
|
1601
|
+
...this._bindPrimitives(),
|
|
1602
|
+
args,
|
|
1603
|
+
budget: this.budget
|
|
1604
|
+
};
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
/**
|
|
1608
|
+
* Runs `entryFn(context)` inside a fresh, isolated per-run store (see the
|
|
1609
|
+
* runStorage comment above this class): its own `args`, `phase`, `group`,
|
|
1610
|
+
* and `budget` accounting, plus a unique `runId` carried on every
|
|
1611
|
+
* activity/log/state event emitted during the run. Concurrent calls to
|
|
1612
|
+
* `runWithContext()` (e.g. two overlapping `WorkflowEngine.executeFile()`
|
|
1613
|
+
* calls) on the SAME `FleetWorkflow` instance no longer corrupt each
|
|
1614
|
+
* other's `args` or phase attribution -- each gets its own store, and
|
|
1615
|
+
* `runStorage` (an `AsyncLocalStorage`) threads it automatically through
|
|
1616
|
+
* every `await` inside `entryFn`.
|
|
1617
|
+
*
|
|
1618
|
+
* The `FleetWorkflow`'s `EventEmitter` remains shared (a dashboard viewer
|
|
1619
|
+
* subscribes to it once, globally); every event carries the originating
|
|
1620
|
+
* run's `runId` so concurrent runs' events stay distinguishable there.
|
|
1621
|
+
*
|
|
1622
|
+
* @param {any} args - Arguments for this run, exposed as `context.args`.
|
|
1623
|
+
* @param {(context: object) => Promise<any>} entryFn - The workflow
|
|
1624
|
+
* script's entry point (`main`/`run`/`default`), called with this run's
|
|
1625
|
+
* context object.
|
|
1626
|
+
* @param {{ runId?: string, journalEnabled?: boolean, replay?: {completedByKey: Map<string,object>, diverged: boolean} }} [opts] -
|
|
1627
|
+
* (apra-fleet-unw.10) `runId`: optional caller-supplied run id, so
|
|
1628
|
+
* `WorkflowEngine.executeFile()` can know the run's id up front (to
|
|
1629
|
+
* attach it to the `end` event it emits from its own try/finally)
|
|
1630
|
+
* without this method having to report it back out-of-band. Defaults
|
|
1631
|
+
* to a fresh UUID when omitted, matching the pre-unw.10 behavior for
|
|
1632
|
+
* any other/legacy caller.
|
|
1633
|
+
* (apra-fleet-unw.11, F6) `journalEnabled`/`replay`: journal/resume
|
|
1634
|
+
* wiring from `WorkflowEngine.executeFile()`. `journalEnabled` gates
|
|
1635
|
+
* the per-run activity sequence counter (`store.activitySeq`) that
|
|
1636
|
+
* `agent()`/`command()` use to compute deterministic replay keys --
|
|
1637
|
+
* when omitted/false, that counter is never created and
|
|
1638
|
+
* `agent()`/`command()` never compute or attach replay-related fields
|
|
1639
|
+
* to their activity events, so behavior/output is unchanged from
|
|
1640
|
+
* before this feature existed. `replay` (only meaningful when
|
|
1641
|
+
* `journalEnabled` is true) is the loaded journal's
|
|
1642
|
+
* `completedByKey`/`diverged` state (see journal.mjs `loadJournal()`);
|
|
1643
|
+
* `diverged` is mutated in place by `agent()`/`command()` the first
|
|
1644
|
+
* time a call's replay key isn't found as a completed/successful
|
|
1645
|
+
* record in the journal, permanently switching the rest of the run to
|
|
1646
|
+
* live execution (partial replay, Claude-CLI style).
|
|
1647
|
+
*/
|
|
1648
|
+
async runWithContext(args, entryFn, opts = {}) {
|
|
1649
|
+
const runId = opts.runId || randomUUID();
|
|
1650
|
+
const budget = {
|
|
1651
|
+
total: null,
|
|
1652
|
+
_spent: 0,
|
|
1653
|
+
_pricedReal: 0,
|
|
1654
|
+
_pricedFallback: 0,
|
|
1655
|
+
spent: () => budget._spent,
|
|
1656
|
+
remaining: () => budget.total === null ? Infinity : (budget.total - budget._spent),
|
|
1657
|
+
pricingSummary: () => ({ real: budget._pricedReal, fallback: budget._pricedFallback })
|
|
1658
|
+
};
|
|
1659
|
+
// (apra-fleet-unw.10) Per-run AbortController backing cooperative
|
|
1660
|
+
// cancellation: agent()/command() default to `store.signal` (via
|
|
1661
|
+
// _currentSignal()) so requestStop() can abort every in-flight and
|
|
1662
|
+
// future dispatch of THIS run without the workflow script having to
|
|
1663
|
+
// thread a signal through itself. Tracked in `_activeControllers` for
|
|
1664
|
+
// the lifetime of the run only -- removed in `finally` below so a
|
|
1665
|
+
// late requestStop() call after the run has already finished is a
|
|
1666
|
+
// no-op instead of leaking controllers across runs.
|
|
1667
|
+
const controller = new AbortController();
|
|
1668
|
+
this._activeControllers.set(runId, controller);
|
|
1669
|
+
const store = {
|
|
1670
|
+
runId,
|
|
1671
|
+
args,
|
|
1672
|
+
phase: null,
|
|
1673
|
+
group: null,
|
|
1674
|
+
budget,
|
|
1675
|
+
signal: controller.signal,
|
|
1676
|
+
// (apra-fleet-unw.11, F6 / apra-fleet-unw2.14, N6) Per-run
|
|
1677
|
+
// activity sequencing for deterministic replay keys.
|
|
1678
|
+
//
|
|
1679
|
+
// `activitySeq` is a monotonic counter scoped to THIS store level
|
|
1680
|
+
// (the run's top-level flow, or -- after a `parallel()` fork -- a
|
|
1681
|
+
// single branch). At the top level it produces plain numeric
|
|
1682
|
+
// sequences 0,1,2,... in program order, exactly as before N6.
|
|
1683
|
+
//
|
|
1684
|
+
// `seqPrefix` is the hierarchical path prefix prepended to a
|
|
1685
|
+
// call's local sequence to form its replay key's `sequence`
|
|
1686
|
+
// component. It is empty ('') at the top level -- so top-level
|
|
1687
|
+
// keys stay numeric and backward-compatible -- and is extended by
|
|
1688
|
+
// `parallel()` per branch (see parallel() below) to
|
|
1689
|
+
// `<barrierIndex>:<branchIndex>:`, making every in-branch key
|
|
1690
|
+
// scheduler-INDEPENDENT (order of branch interleaving no longer
|
|
1691
|
+
// affects the key). See journal.mjs computeActivityKey for the
|
|
1692
|
+
// full semantics/limitations.
|
|
1693
|
+
//
|
|
1694
|
+
// `parallelSeq` numbers the `parallel()` barriers entered AT this
|
|
1695
|
+
// store level, in program order, so two sequential parallel()
|
|
1696
|
+
// calls at the same level get distinct barrier prefixes even if
|
|
1697
|
+
// no agent()/command() ran between them.
|
|
1698
|
+
//
|
|
1699
|
+
// All three are `null` unless journaling was requested for this
|
|
1700
|
+
// run at all (a normal, non-journaled run never enters any of the
|
|
1701
|
+
// replay-key code paths).
|
|
1702
|
+
activitySeq: opts.journalEnabled ? { value: 0 } : null,
|
|
1703
|
+
seqPrefix: '',
|
|
1704
|
+
parallelSeq: opts.journalEnabled ? { value: 0 } : null,
|
|
1705
|
+
replay: opts.journalEnabled ? (opts.replay || null) : null,
|
|
1706
|
+
// apra-fleet-dv5.6: fresh per run, shared by reference across
|
|
1707
|
+
// parallel() branches (like `budget` above) so a member's
|
|
1708
|
+
// pricing is only fetched once per run regardless of how many
|
|
1709
|
+
// branches dispatch to it.
|
|
1710
|
+
memberPricingCache: new Map()
|
|
1711
|
+
};
|
|
1712
|
+
const context = {
|
|
1713
|
+
...this._bindPrimitives(),
|
|
1714
|
+
args,
|
|
1715
|
+
budget
|
|
1716
|
+
};
|
|
1717
|
+
try {
|
|
1718
|
+
return await runStorage.run(store, () => entryFn(context));
|
|
1719
|
+
} finally {
|
|
1720
|
+
this._activeControllers.delete(runId);
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
}
|