@apralabs/apra-fleet 0.3.6 → 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/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
|
@@ -6,41 +6,119 @@ import { z } from 'zod';
|
|
|
6
6
|
import { getStrategy } from '../services/strategy.js';
|
|
7
7
|
import { getOsCommands } from '../os/index.js';
|
|
8
8
|
import { getProvider } from '../providers/index.js';
|
|
9
|
-
import { getAgentOS, touchAgent } from '../utils/agent-helpers.js';
|
|
9
|
+
import { getAgentOS, touchAgent, getStoredPid } from '../utils/agent-helpers.js';
|
|
10
10
|
import { updateAgent } from '../services/registry.js';
|
|
11
11
|
import { memberIdentifier, resolveMember } from '../utils/resolve-member.js';
|
|
12
|
-
import { isRetryable, authErrorAdvice } from '../utils/prompt-errors.js';
|
|
12
|
+
import { isRetryable, authErrorAdvice, workspaceNotTrustedAdvice } from '../utils/prompt-errors.js';
|
|
13
13
|
import { buildAuthEnvPrefix } from '../utils/auth-env.js';
|
|
14
14
|
import { writeStatusline } from '../services/statusline.js';
|
|
15
15
|
import { getModelOverride } from '../services/user-config.js';
|
|
16
16
|
import { ensureCloudReady } from '../services/cloud/lifecycle.js';
|
|
17
17
|
import { getStallDetector, resolveSessionLogPath } from '../services/stall/index.js';
|
|
18
|
-
import { provisionAgents, remoteAgentsDir } from '../services/agent-provisioner.js';
|
|
18
|
+
import { provisionAgents, remoteAgentsDir, loadCanonicalAgentSet } from '../services/agent-provisioner.js';
|
|
19
19
|
import { escapeWindowsArg, escapeDoubleQuoted } from '../os/os-commands.js';
|
|
20
20
|
import { resolveTilde } from './execute-command.js';
|
|
21
21
|
import { clearStoredPid } from '../utils/agent-helpers.js';
|
|
22
|
-
import { tryKillPid } from '../utils/pid-helpers.js';
|
|
23
|
-
import {
|
|
22
|
+
import { tryKillPid, isPidAlive } from '../utils/pid-helpers.js';
|
|
23
|
+
import { recoverOrphanedDispatch, isRemoteProcessAlive } from '../services/orphan-recovery.js';
|
|
24
|
+
import { seedWorkspaceTrust } from '../utils/workspace-trust.js';
|
|
25
|
+
import { durableOutputPath } from '../os/linux.js';
|
|
26
|
+
import { LogScope, maskSecrets, truncateForLog, logWarn } from '../utils/log-helpers.js';
|
|
24
27
|
import { getLogPreviewChars } from '../services/user-config.js';
|
|
28
|
+
import { validateSubstitutionKeys, applySubstitutions } from '../services/substitution-engine.js';
|
|
29
|
+
import { sessionRegistry } from '../services/session-registry.js';
|
|
30
|
+
import { getTokenIssuer } from '../services/token-issuer.js';
|
|
31
|
+
import { resolveExpectedDemand, checkContextAdmission, recordSessionUsage } from '../services/context-admission.js';
|
|
32
|
+
import { recordKnownSession, isKnownSession } from '../services/known-sessions.js';
|
|
33
|
+
import { resolveBudgetScope, evaluateBudget, recordAndEvaluate } from '../services/budget-awareness.js';
|
|
34
|
+
import { sendMessage } from './send-message.js';
|
|
35
|
+
import { registerPending } from '../services/pending-responses.js';
|
|
36
|
+
import { isMaxTurnsResponse } from '../providers/provider.js';
|
|
25
37
|
export const executePromptSchema = z.object({
|
|
26
38
|
...memberIdentifier,
|
|
27
39
|
prompt: z.string().describe('The prompt to send to the LLM on the remote member'),
|
|
28
|
-
resume: z.boolean().default(true).describe('
|
|
29
|
-
|
|
30
|
-
|
|
40
|
+
resume: z.union([z.boolean(), z.string()]).default(true).describe('Session-resume control (default: true). ' +
|
|
41
|
+
'true = best-effort resume of the member\'s stored last session (a stale/unknown stored session transparently falls back to a fresh session). ' +
|
|
42
|
+
'false = always start a fresh session. ' +
|
|
43
|
+
'A session-id STRING = EXPLICIT resume of exactly that session, preferred over the member\'s stored session -- the caller asserts this prompt depends on that session\'s prior context, so an unknown/expired id is a TERMINAL error ' +
|
|
44
|
+
'(structured {isError, reason: "session_not_found"}, NO LLM call, and NO fresh-session fallback) rather than a silent wrong-context dispatch.'),
|
|
45
|
+
timeout_s: z.number().default(300).describe('Inactivity timeout in seconds -- the command is killed after this many seconds without any stdout/stderr output (default: 300s / 5 minutes)'),
|
|
46
|
+
max_total_s: z.number().optional().describe('Hard ceiling in seconds -- the command is killed after this total elapsed time regardless of activity. If omitted, there is no total time limit.'),
|
|
31
47
|
max_turns: z.number().min(1).max(500).optional().describe('Max turns for claude -p (default: 50)'),
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
}
|
|
35
|
-
|
|
48
|
+
model: z.string().optional().describe('Model tier ("cheap", "standard", "premium") or a specific model ID for power users. Prefer tier names -- the server resolves them to the correct model per provider. If omitted, defaults to the standard tier. Applies to both new and resumed sessions.'),
|
|
49
|
+
substitutions: z.record(z.string(), z.string()).optional().describe('Optional map of token name to replacement value. ' +
|
|
50
|
+
'When provided, every occurrence of {{name}} in the prompt is replaced before the prompt is staged on the member. ' +
|
|
51
|
+
'Keys must match [A-Za-z_][A-Za-z0-9_]*. Missing tokens cause the call to fail with no CLI invoked. ' +
|
|
52
|
+
'Extra keys are silently ignored. Values are never logged.'),
|
|
53
|
+
agent: z.string().optional().describe('Optional agent name to activate. ' +
|
|
54
|
+
'For Claude: invokes claude --agent <name>. ' +
|
|
55
|
+
'For Gemini: prepends @<name> to the prompt on every dispatch. ' +
|
|
56
|
+
'For AGY: prepends @<name> to the prompt on every dispatch (same as Gemini). ' +
|
|
57
|
+
'Substitution runs before the @<name> prepend. ' +
|
|
58
|
+
'Agent file must exist at the provider-specific path on the member: ' +
|
|
59
|
+
'Claude: <workFolder>/.claude/agents/<name>.md or ~/.claude/agents/<name>.md; ' +
|
|
60
|
+
'Gemini: <workFolder>/.gemini/agents/<name>.md or ~/.gemini/agents/<name>.md; ' +
|
|
61
|
+
'AGY: <workFolder>/.gemini/antigravity-cli/agents/<name>.md or ~/.gemini/antigravity-cli/agents/<name>.md -- ' +
|
|
62
|
+
'the call is rejected with a clear error if neither is present.'),
|
|
63
|
+
sprint_id: z.string().optional().describe('Opaque identity of the sprint issuing this dispatch (apra-fleet-eft.29.1). ' +
|
|
64
|
+
'When provided, the server-side member-reservation check (see reservedBy below) ' +
|
|
65
|
+
'compares this value directly against the reservation instead of falling back to ' +
|
|
66
|
+
'this server process\'s APRA_FLEET_SPRINT_ID env var -- the same per-call value ' +
|
|
67
|
+
'the caller passed to member_reservation reserve/release. Callers that never set a ' +
|
|
68
|
+
'reservation, or that reserved and dispatch in the same process, should omit this; ' +
|
|
69
|
+
'omitting it preserves the pre-existing env-var-based behavior exactly.'),
|
|
70
|
+
expected_context_tokens: z.number().positive().optional().describe('Optional estimate (apra-fleet-eft.81.1) of how many tokens this dispatch will add ' +
|
|
71
|
+
'to the target session\'s context. When set (or context_size is set), the server ' +
|
|
72
|
+
'compares it against the session\'s remaining context-window headroom BEFORE ' +
|
|
73
|
+
'invoking the LLM: too little headroom rejects the call with ' +
|
|
74
|
+
'{reason: "insufficient_context_headroom", detail: {demand, headroom, window}} and no ' +
|
|
75
|
+
'spawn; a fit that lands inside the safety margin still proceeds but attaches a ' +
|
|
76
|
+
'structured contextWarning. Wins over context_size when both are set. Omitting both ' +
|
|
77
|
+
'fields disables the check entirely -- pre-existing behavior is unchanged.'),
|
|
78
|
+
context_size: z.enum(['S', 'M', 'L']).optional().describe('Optional size-bucket shorthand for expected_context_tokens (apra-fleet-eft.81.1): ' +
|
|
79
|
+
'S/M/L map to configured token estimates (fleet defaults, overridable via ' +
|
|
80
|
+
'config.json\'s contextAdmission.sizeBucketTokens). Ignored when expected_context_tokens ' +
|
|
81
|
+
'is also set. The auto-sprint engine supplies this from the dispatched task\'s size ' +
|
|
82
|
+
'metadata.'),
|
|
83
|
+
}).strict();
|
|
84
|
+
function buildFailureMessage(agentName, result, provider, parsed) {
|
|
36
85
|
const output = result.stderr || result.stdout;
|
|
37
|
-
|
|
86
|
+
// apra-fleet-p4f.2: prefer the already-parsed structured signal over the
|
|
87
|
+
// stderr/stdout regex scan -- a max_turns-exhausted transcript can still
|
|
88
|
+
// have auth-like noise in stderr (a stale warning, an unrelated retry
|
|
89
|
+
// message, etc.) that would otherwise misclassify it as an auth failure.
|
|
90
|
+
const category = isMaxTurnsResponse(parsed) ? 'max_turns' : provider.classifyError(output);
|
|
91
|
+
if (category === 'max_turns') {
|
|
92
|
+
return `[FAIL] Prompt on "${agentName}" was stopped after exhausting its turn limit (max_turns), not a genuine failure -- the model ran out of turns before finishing:
|
|
93
|
+
${output}`;
|
|
94
|
+
}
|
|
38
95
|
return category === 'auth'
|
|
39
96
|
? authErrorAdvice(agentName)
|
|
40
|
-
:
|
|
97
|
+
: `[FAIL] Prompt failed on "${agentName}":
|
|
41
98
|
${output}`;
|
|
42
99
|
}
|
|
43
100
|
const SERVER_RETRY_DELAY_MS = 5000;
|
|
101
|
+
// A prompt written whole into a single remote exec command line can exceed
|
|
102
|
+
// the SSH exec channel's / Windows CreateProcess's command-line ceiling once
|
|
103
|
+
// the Windows path's UTF-16LE + base64 -EncodedCommand encoding (~2.67x
|
|
104
|
+
// inflation) is applied -- observed live (2026-07-30, fleet-win-dev1): a
|
|
105
|
+
// Review dispatch embedding full `bd show --json` output (description +
|
|
106
|
+
// acceptance criteria) for 5 beads produced a garbled "Unable to exec ..."
|
|
107
|
+
// response instead of real review output, because the encoded command line
|
|
108
|
+
// was too long for the remote shell to exec at all. Doer dispatches (small,
|
|
109
|
+
// just branch + bead ids) never hit this; only the larger Review-phase
|
|
110
|
+
// prompts do -- and only on Windows, where the encoding overhead is worst.
|
|
111
|
+
// Chunking keeps every single exec command line bounded regardless of total
|
|
112
|
+
// prompt size, on both OS paths (POSIX has a much higher real-world ceiling
|
|
113
|
+
// but shares the same underlying single-exec-command-line hazard).
|
|
114
|
+
const REMOTE_PROMPT_CHUNK_CHARS = 4000;
|
|
115
|
+
function chunkContent(content) {
|
|
116
|
+
const chunks = [];
|
|
117
|
+
for (let i = 0; i < content.length; i += REMOTE_PROMPT_CHUNK_CHARS) {
|
|
118
|
+
chunks.push(content.slice(i, i + REMOTE_PROMPT_CHUNK_CHARS));
|
|
119
|
+
}
|
|
120
|
+
return chunks.length > 0 ? chunks : [''];
|
|
121
|
+
}
|
|
44
122
|
async function writePromptFile(agent, strategy, promptFilePath, content) {
|
|
45
123
|
if (agent.agentType === 'local') {
|
|
46
124
|
fs.writeFileSync(promptFilePath, content, 'utf-8');
|
|
@@ -49,24 +127,41 @@ async function writePromptFile(agent, strategy, promptFilePath, content) {
|
|
|
49
127
|
const agentOs = getAgentOS(agent);
|
|
50
128
|
const promptFileName = path.basename(promptFilePath);
|
|
51
129
|
const remoteDir = path.dirname(promptFilePath);
|
|
130
|
+
const chunks = chunkContent(content);
|
|
52
131
|
if (agentOs === 'windows') {
|
|
53
132
|
const escapedFolder = escapeWindowsArg(remoteDir);
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
133
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
134
|
+
const setup = i === 0 ? `New-Item -Path '${escapedFolder}' -ItemType Directory -Force | Out-Null; ` : '';
|
|
135
|
+
const cmdlet = i === 0 ? 'Set-Content' : 'Add-Content';
|
|
136
|
+
const psScript = `${setup}Set-Location "${escapedFolder}"; ${cmdlet} -Path "${promptFileName}" -Value '${chunks[i].replace(/'/g, "''")}' -NoNewline -Encoding UTF8`;
|
|
137
|
+
const encoded = Buffer.from(psScript, 'utf16le').toString('base64');
|
|
138
|
+
// eslint-disable-next-line no-await-in-loop -- each chunk must land before the next appends
|
|
139
|
+
await strategy.execCommand(`powershell -EncodedCommand ${encoded}`);
|
|
140
|
+
}
|
|
57
141
|
}
|
|
58
142
|
else {
|
|
59
|
-
const b64 = Buffer.from(content).toString('base64');
|
|
60
143
|
const escapedFolder = escapeDoubleQuoted(remoteDir);
|
|
61
|
-
|
|
144
|
+
for (let i = 0; i < chunks.length; i++) {
|
|
145
|
+
const b64 = Buffer.from(chunks[i]).toString('base64');
|
|
146
|
+
const redirect = i === 0 ? '>' : '>>';
|
|
147
|
+
const mkdirPrefix = i === 0 ? `mkdir -p "${escapedFolder}" && ` : '';
|
|
148
|
+
// eslint-disable-next-line no-await-in-loop -- each chunk must land before the next appends
|
|
149
|
+
await strategy.execCommand(`${mkdirPrefix}cd "${escapedFolder}" && echo '${b64}' | base64 -d ${redirect} ${promptFileName}`);
|
|
150
|
+
}
|
|
62
151
|
}
|
|
63
152
|
}
|
|
64
|
-
async function deletePromptFile(agent, strategy, promptFilePath) {
|
|
153
|
+
async function deletePromptFile(agent, strategy, promptFilePath, extraPaths = []) {
|
|
65
154
|
if (agent.agentType === 'local') {
|
|
66
155
|
try {
|
|
67
156
|
fs.unlinkSync(promptFilePath);
|
|
68
157
|
}
|
|
69
158
|
catch { /* ignore */ }
|
|
159
|
+
for (const p of extraPaths) {
|
|
160
|
+
try {
|
|
161
|
+
fs.unlinkSync(p);
|
|
162
|
+
}
|
|
163
|
+
catch { /* ignore */ }
|
|
164
|
+
}
|
|
70
165
|
return;
|
|
71
166
|
}
|
|
72
167
|
const agentOs = getAgentOS(agent);
|
|
@@ -80,7 +175,10 @@ async function deletePromptFile(agent, strategy, promptFilePath) {
|
|
|
80
175
|
}
|
|
81
176
|
else {
|
|
82
177
|
const escapedFolder = escapeDoubleQuoted(remoteDir);
|
|
83
|
-
|
|
178
|
+
// apra-fleet-6z8.1: the durable stdout mirror is cleaned up in the SAME
|
|
179
|
+
// round trip as the prompt file -- no extra exec per dispatch.
|
|
180
|
+
const extras = extraPaths.map(p => ` "${escapeDoubleQuoted(p)}"`).join('');
|
|
181
|
+
await strategy.execCommand(`cd "${escapedFolder}" && rm -f ${promptFileName}${extras}`).catch(() => { });
|
|
84
182
|
}
|
|
85
183
|
}
|
|
86
184
|
export function resolveModelForTier(agent, tier, provider) {
|
|
@@ -92,6 +190,20 @@ export function resolveModelForTier(agent, tier, provider) {
|
|
|
92
190
|
return provider.modelForTier(tier);
|
|
93
191
|
}
|
|
94
192
|
const SECURE_TOKEN_RE = /\{\{secure\.[a-zA-Z0-9_-]{1,64}\}\}/;
|
|
193
|
+
/**
|
|
194
|
+
* The sprint id this server process dispatches on behalf of, or undefined when
|
|
195
|
+
* run outside a sprint (e.g. a manual cli.mjs invocation). Sourced from
|
|
196
|
+
* APRA_FLEET_SPRINT_ID, which the auto-sprint spawner stamps into the per-sprint
|
|
197
|
+
* server's environment (apra-fleet-eft.10.3). Read on every dispatch so a
|
|
198
|
+
* reservation set/cleared mid-run is observed without a restart.
|
|
199
|
+
*/
|
|
200
|
+
export function currentSprintId() {
|
|
201
|
+
const raw = process.env.APRA_FLEET_SPRINT_ID;
|
|
202
|
+
if (typeof raw !== 'string')
|
|
203
|
+
return undefined;
|
|
204
|
+
const trimmed = raw.trim();
|
|
205
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
206
|
+
}
|
|
95
207
|
export const inFlightAgents = new Set();
|
|
96
208
|
// Member ids whose remote agent files (planner.md, doer.md, _shared/, schemas/, ...)
|
|
97
209
|
// have already been probed/refreshed this server process uptime -- the #336
|
|
@@ -128,17 +240,192 @@ async function ensureAgentFilesProvisioned(agent) {
|
|
|
128
240
|
}
|
|
129
241
|
}
|
|
130
242
|
// All exit paths from executePrompt clear busy state via the finally block (inFlightAgents.delete + writeStatusline):
|
|
131
|
-
// (a) normal success: result.code === 0
|
|
132
|
-
// (b) non-zero exit from execCommand: result.code !== 0
|
|
133
|
-
// (c) exception in try block (auth, network, crash)
|
|
134
|
-
// (d) AbortSignal/MCP client cancellation
|
|
135
|
-
// (e) stale session retry
|
|
136
|
-
// (f) server overload retry
|
|
243
|
+
// (a) normal success: result.code === 0 -> finally sets idle and removes agent from inFlight
|
|
244
|
+
// (b) non-zero exit from execCommand: result.code !== 0 -> finally sets idle and removes agent from inFlight
|
|
245
|
+
// (c) exception in try block (auth, network, crash) -> catch records error type; finally sets offline or idle
|
|
246
|
+
// (d) AbortSignal/MCP client cancellation -> abortHandler kills PID, execCommand resolves, finally clears
|
|
247
|
+
// (e) stale session retry -> retried without session ID; finally clears on success or failure
|
|
248
|
+
// (f) server overload retry -> retried after delay; finally clears on success or failure
|
|
137
249
|
// (g) early returns before inFlightAgents.add: busy state never entered
|
|
250
|
+
/**
|
|
251
|
+
* apra-fleet-idb: liveness probe for a busy-locked member's backing process.
|
|
252
|
+
* An inFlightAgents entry can outlive the process it was guarding -- a child
|
|
253
|
+
* reaped without its 'close'/'error' handler ever firing (e.g. a hung SSH
|
|
254
|
+
* channel that never signals exit, so clearStoredPid never runs), or an
|
|
255
|
+
* interactive member's underlying claude process dying/disconnecting after
|
|
256
|
+
* its session was registered -- permanently wedging the member: every future
|
|
257
|
+
* dispatch would keep returning busy even though fleet_status's own
|
|
258
|
+
* independent live-process check (src/tools/check-status.ts's
|
|
259
|
+
* fleetProcessCheck) would report idle. Returns the confirmed-dead pid (used
|
|
260
|
+
* only for the release warning) when the lock should self-heal, or undefined
|
|
261
|
+
* when the member is genuinely busy.
|
|
262
|
+
*
|
|
263
|
+
* Conservative on ambiguity, deliberately: NO captured pid at all (neither an
|
|
264
|
+
* interactive session pid nor a subprocess pid) is treated as still busy, not
|
|
265
|
+
* as evidence of staleness -- a dispatch that has not reached its pid-capture
|
|
266
|
+
* step yet must never be raced by a concurrent "self-heal" attempt. Only a
|
|
267
|
+
* DEFINITIVE dead-pid reading releases the lock.
|
|
268
|
+
*/
|
|
269
|
+
async function findDeadLockPid(agent, workspaceId) {
|
|
270
|
+
// Interactive sessions are always local (register_member's interactive
|
|
271
|
+
// bootstrap is gated to isLocal members) -- the same local
|
|
272
|
+
// process.kill(pid, 0) probe the eft.28.1 dead-session guard uses further
|
|
273
|
+
// below applies directly here. Falls back to the durable lastKnownPid
|
|
274
|
+
// anchor exactly like that guard does, so a disconnected-then-reconnected
|
|
275
|
+
// session (pid lost on the live SessionState) is still checkable.
|
|
276
|
+
const session = sessionRegistry.get(workspaceId, agent.id);
|
|
277
|
+
const interactivePid = session?.pid ?? sessionRegistry.lastKnownPid(workspaceId, agent.id);
|
|
278
|
+
if (interactivePid !== undefined && !isPidAlive(interactivePid)) {
|
|
279
|
+
return interactivePid;
|
|
280
|
+
}
|
|
281
|
+
// Subprocess dispatch pid (local strategy or remote-over-SSH/relay). A
|
|
282
|
+
// remote pid lives in a DIFFERENT machine's pid namespace -- process.kill()
|
|
283
|
+
// -based isPidAlive is meaningless there (it would almost always read back
|
|
284
|
+
// ESRCH for a pid that simply does not exist on THIS machine, wrongly
|
|
285
|
+
// declaring a genuinely-alive remote session dead and racing a duplicate
|
|
286
|
+
// dispatch onto it). Probe it the same way orphan-recovery's lease-of-life
|
|
287
|
+
// gate does instead: a fresh, independent SSH round trip, never the
|
|
288
|
+
// (possibly wedged) channel that produced the stale lock.
|
|
289
|
+
const subprocessPid = getStoredPid(agent.id);
|
|
290
|
+
if (subprocessPid !== undefined) {
|
|
291
|
+
const alive = agent.agentType === 'local'
|
|
292
|
+
? isPidAlive(subprocessPid)
|
|
293
|
+
: await isRemoteProcessAlive(getStrategy(agent), subprocessPid);
|
|
294
|
+
if (!alive)
|
|
295
|
+
return subprocessPid;
|
|
296
|
+
}
|
|
297
|
+
return undefined;
|
|
298
|
+
}
|
|
299
|
+
// apra-fleet-eft.28.1: how often the interactive wait re-checks that the
|
|
300
|
+
// target member's claude process is still alive. This is the dispatch-level
|
|
301
|
+
// liveness/no-progress bound -- the member's process can die AFTER the
|
|
302
|
+
// pre-dispatch liveness check above (e.g. mid-turn, right after send_message
|
|
303
|
+
// lands) with no further signal ever arriving, so the wait for
|
|
304
|
+
// respond_to_message must not be the sole backstop up to the full timeout_s
|
|
305
|
+
// (which can be 3600s). A short, fixed poll interval keeps the surfaced
|
|
306
|
+
// error well under the playbook's <10min budget regardless of how large
|
|
307
|
+
// timeout_s is.
|
|
308
|
+
const INTERACTIVE_LIVENESS_POLL_MS = 5000;
|
|
309
|
+
/** Raised by waitForInteractiveResponse when the member's claude process is
|
|
310
|
+
* confirmed dead while a response is still pending -- distinguished from a
|
|
311
|
+
* plain "nobody answered in time" timeout so the caller can surface a more
|
|
312
|
+
* actionable terminal error. */
|
|
313
|
+
class InteractiveSessionDiedError extends Error {
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Waits for the member's respond_to_message reply, racing that wait against
|
|
317
|
+
* a periodic PID-liveness poll of the same session. Resolves/rejects as soon
|
|
318
|
+
* as either side settles -- a dead PID short-circuits the wait instead of
|
|
319
|
+
* letting it run out the full timeoutMs.
|
|
320
|
+
*/
|
|
321
|
+
function waitForInteractiveResponse(agent, workspaceId, msgid, timeoutMs, scope) {
|
|
322
|
+
return new Promise((resolve, reject) => {
|
|
323
|
+
let settled = false;
|
|
324
|
+
const poller = setInterval(() => {
|
|
325
|
+
if (settled)
|
|
326
|
+
return;
|
|
327
|
+
const session = sessionRegistry.get(workspaceId, agent.id);
|
|
328
|
+
// apra-fleet-eft.50.1: fall back to the durable launch-pid anchor when the
|
|
329
|
+
// live session lost its pid on a reconnect, so this in-flight poll can
|
|
330
|
+
// still detect a dead persistent process on a retry that reused the
|
|
331
|
+
// reconnected session -- not only when the session still carries its pid.
|
|
332
|
+
const pid = session?.pid ?? sessionRegistry.lastKnownPid(workspaceId, agent.id);
|
|
333
|
+
if (pid !== undefined && !isPidAlive(pid)) {
|
|
334
|
+
settled = true;
|
|
335
|
+
clearInterval(poller);
|
|
336
|
+
scope.info(`[interactive] member process pid=${pid} died while awaiting a response -- aborting wait`);
|
|
337
|
+
sessionRegistry.unregister(workspaceId, agent.id);
|
|
338
|
+
reject(new InteractiveSessionDiedError(`member claude process (pid ${pid}) died while waiting for a response`));
|
|
339
|
+
}
|
|
340
|
+
}, INTERACTIVE_LIVENESS_POLL_MS);
|
|
341
|
+
registerPending(msgid, timeoutMs).then((res) => {
|
|
342
|
+
if (settled)
|
|
343
|
+
return;
|
|
344
|
+
settled = true;
|
|
345
|
+
clearInterval(poller);
|
|
346
|
+
resolve(res);
|
|
347
|
+
}, (err) => {
|
|
348
|
+
if (settled)
|
|
349
|
+
return;
|
|
350
|
+
settled = true;
|
|
351
|
+
clearInterval(poller);
|
|
352
|
+
reject(err);
|
|
353
|
+
});
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Interactive routing (apra-fleet-2xs.8): pushes the prompt to a connected
|
|
358
|
+
* member's live session via send_message and waits for that member to call
|
|
359
|
+
* respond_to_message with the matching reply_to. No subprocess, no SSH, no
|
|
360
|
+
* prompt file, no stall detector on a log file -- the session is a
|
|
361
|
+
* long-lived interactive process, not something this call spawns or owns.
|
|
362
|
+
*/
|
|
363
|
+
async function executePromptInteractive(agent, renderedPrompt, input, workspaceId, heuristicWarningSuffix) {
|
|
364
|
+
const timeoutS = input.timeout_s ?? 300;
|
|
365
|
+
const scope = new LogScope('execute_prompt', `[interactive] timeout=${timeoutS}s ${truncateForLog(maskSecrets(input.prompt))}`, agent);
|
|
366
|
+
const sendResult = await sendMessage({ member_id: agent.id, content: renderedPrompt }, workspaceId);
|
|
367
|
+
const parsed = JSON.parse(sendResult);
|
|
368
|
+
if (parsed.error) {
|
|
369
|
+
scope.abort(`send failed: ${parsed.error}`);
|
|
370
|
+
return `[FAIL] Failed to deliver prompt to "${agent.friendlyName}" (interactive session): ${parsed.error}`;
|
|
371
|
+
}
|
|
372
|
+
try {
|
|
373
|
+
const response = await waitForInteractiveResponse(agent, workspaceId, parsed.msgid, timeoutS * 1000, scope);
|
|
374
|
+
scope.ok('interactive response received');
|
|
375
|
+
let output = `[RESULT] Response from ${agent.friendlyName}:\n\n${response}`;
|
|
376
|
+
if (heuristicWarningSuffix)
|
|
377
|
+
output += heuristicWarningSuffix;
|
|
378
|
+
return output;
|
|
379
|
+
}
|
|
380
|
+
catch (err) {
|
|
381
|
+
if (err instanceof InteractiveSessionDiedError) {
|
|
382
|
+
scope.abort(err.message);
|
|
383
|
+
return `[ERROR] "${agent.friendlyName}"'s interactive claude process died while this dispatch was waiting for a response (${err.message}). The prompt was delivered but nothing will ever answer it -- re-launch the member (re-run register_member) before retrying.`;
|
|
384
|
+
}
|
|
385
|
+
scope.abort(`interactive timeout: ${err.message}`);
|
|
386
|
+
// apra-fleet-eft.74.2: self-heal on interactive-route timeout. A session
|
|
387
|
+
// with no verifiable live pid that just timed out is a phantom channel
|
|
388
|
+
// (the eft.74 wedge): re-routing the NEXT execute_prompt to it would
|
|
389
|
+
// silently re-burn the full timeout_s, forever (observed 5x 900s). Evict
|
|
390
|
+
// it here so the next dispatch finds no interactive session and falls back
|
|
391
|
+
// to the subprocess path. A session that DOES have a verifiably live pid is
|
|
392
|
+
// left registered -- the member is alive, merely slow, so a later dispatch
|
|
393
|
+
// may legitimately reach it interactively again.
|
|
394
|
+
const timedOutSession = sessionRegistry.get(workspaceId, agent.id);
|
|
395
|
+
const timedOutPid = timedOutSession?.pid ?? sessionRegistry.lastKnownPid(workspaceId, agent.id);
|
|
396
|
+
const hasVerifiableLivePid = timedOutPid !== undefined && isPidAlive(timedOutPid);
|
|
397
|
+
if (!hasVerifiableLivePid) {
|
|
398
|
+
sessionRegistry.unregister(workspaceId, agent.id);
|
|
399
|
+
scope.info(`[interactive] timed-out session for "${agent.friendlyName}" has no verifiable live pid (pid=${timedOutPid ?? 'none'}) -- evicting so the next dispatch falls back to subprocess`);
|
|
400
|
+
}
|
|
401
|
+
return `[FAIL] Timed out waiting for "${agent.friendlyName}" to respond (interactive session, ${timeoutS}s). The prompt was delivered; the member may still respond late, but this call has given up waiting.`;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
138
404
|
export async function executePrompt(input, extra) {
|
|
139
405
|
if (SECURE_TOKEN_RE.test(input.prompt)) {
|
|
140
406
|
return 'error: execute_prompt prompt contains {{secure.NAME}} token. Secrets must never be passed to LLM prompts. Use execute_command with {{secure.NAME}} instead.';
|
|
141
407
|
}
|
|
408
|
+
// Validate substitution keys before any I/O or member resolution.
|
|
409
|
+
if (input.substitutions !== undefined) {
|
|
410
|
+
const keyCheck = validateSubstitutionKeys('execute_prompt', input.substitutions);
|
|
411
|
+
if (!keyCheck.ok)
|
|
412
|
+
return keyCheck.error;
|
|
413
|
+
}
|
|
414
|
+
// Apply substitutions to the prompt string (or emit heuristic warning when omitted).
|
|
415
|
+
let renderedPrompt = input.prompt;
|
|
416
|
+
let heuristicWarningSuffix = '';
|
|
417
|
+
if (input.substitutions !== undefined) {
|
|
418
|
+
const result = applySubstitutions('execute_prompt', [{ label: 'prompt', content: input.prompt }], input.substitutions);
|
|
419
|
+
if (!result.ok)
|
|
420
|
+
return result.error;
|
|
421
|
+
renderedPrompt = result.outputs[0];
|
|
422
|
+
}
|
|
423
|
+
else {
|
|
424
|
+
const warnResult = applySubstitutions('execute_prompt', [{ label: 'prompt', content: input.prompt }], undefined);
|
|
425
|
+
if (warnResult.ok && warnResult.warning) {
|
|
426
|
+
heuristicWarningSuffix = `\n\n[WARN] ${warnResult.warning}`;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
142
429
|
const promptFileName = `.fleet-task.md`;
|
|
143
430
|
const agentOrError = resolveMember(input.member_id, input.member_name);
|
|
144
431
|
if (typeof agentOrError === 'string')
|
|
@@ -148,15 +435,181 @@ export async function executePrompt(input, extra) {
|
|
|
148
435
|
agent = await ensureCloudReady(agentOrError); // auto-start if stopped
|
|
149
436
|
}
|
|
150
437
|
catch (err) {
|
|
151
|
-
return
|
|
438
|
+
return `[FAIL] Failed to execute prompt on "${agentOrError.friendlyName}": ${err.message}`;
|
|
439
|
+
}
|
|
440
|
+
// Server-side member reservation enforcement (apra-fleet-eft.10.3): a member
|
|
441
|
+
// reserved by a DIFFERENT sprint may not be dispatched to. Mirrors the
|
|
442
|
+
// inFlightAgents busy-rejection error path -- the error names the owning
|
|
443
|
+
// sprint. A dispatch from the owning sprint (matching APRA_FLEET_SPRINT_ID)
|
|
444
|
+
// or against an unreserved member proceeds unchanged, so behavior with no
|
|
445
|
+
// reservations is identical to before. Checked before any busy state is
|
|
446
|
+
// entered, closing the manual-CLI bypass the ledger alone could not.
|
|
447
|
+
//
|
|
448
|
+
// apra-fleet-eft.29.1: currentSprintId() alone (APRA_FLEET_SPRINT_ID on
|
|
449
|
+
// THIS server process) is only correct when the launcher spawns a private
|
|
450
|
+
// per-sprint server and stamps its env -- it is not for the eft.7.1
|
|
451
|
+
// CLI/shared-fleet-server path, where cli.mjs attaches to an existing,
|
|
452
|
+
// long-lived HTTP singleton it never spawns and so can never stamp. There,
|
|
453
|
+
// APRA_FLEET_SPRINT_ID is unset (or stale from a different run), so a
|
|
454
|
+
// member reserved by ITS OWN owning sprint was rejected as if from another
|
|
455
|
+
// sprint. Prefer the per-call `sprint_id` -- the exact same opaque token
|
|
456
|
+
// the caller already passed to member_reservation reserve/release (see
|
|
457
|
+
// createMemberReservationClient / sprintMutexId in
|
|
458
|
+
// packages/apra-fleet-se/fleet-sprint/runner.js) -- and fall back to
|
|
459
|
+
// currentSprintId() only when the caller omits it, so existing
|
|
460
|
+
// env-var-based callers/tests are unaffected.
|
|
461
|
+
const owningSprint = agent.reservedBy ?? null;
|
|
462
|
+
const dispatchSprintId = input.sprint_id ?? currentSprintId();
|
|
463
|
+
if (owningSprint && owningSprint !== dispatchSprintId) {
|
|
464
|
+
return {
|
|
465
|
+
text: `[-] Member "${agent.friendlyName}" is reserved by sprint "${owningSprint}" and cannot accept a dispatch from another sprint. Wait for that sprint to release it, or force-release the reservation to recover.`,
|
|
466
|
+
structuredContent: { isError: true, reason: 'reserved' },
|
|
467
|
+
};
|
|
152
468
|
}
|
|
153
469
|
if (inFlightAgents.has(agent.id)) {
|
|
154
|
-
|
|
470
|
+
// apra-fleet-idb: before honoring the busy rejection, verify the locked
|
|
471
|
+
// session actually still has a live backing process -- see
|
|
472
|
+
// findDeadLockPid's docstring for the full rationale. This is what keeps
|
|
473
|
+
// fleet_status (which decides busy/idle from its own independent live
|
|
474
|
+
// process check) and this dispatch gate from ever disagreeing: a stale
|
|
475
|
+
// lock self-heals here instead of permanently wedging the member.
|
|
476
|
+
const staleLockPid = await findDeadLockPid(agent, getTokenIssuer().workspaceId());
|
|
477
|
+
if (staleLockPid !== undefined) {
|
|
478
|
+
logWarn('busy_lock', `orphaned busy-lock for "${agent.friendlyName}" -- locked pid=${staleLockPid} is confirmed dead; releasing the stale lock and proceeding with this dispatch instead of rejecting it as busy`, agent);
|
|
479
|
+
inFlightAgents.delete(agent.id);
|
|
480
|
+
getStallDetector().remove(agent.id);
|
|
481
|
+
writeStatusline(new Map([[agent.id, 'idle']]));
|
|
482
|
+
}
|
|
483
|
+
else {
|
|
484
|
+
return {
|
|
485
|
+
text: `[FAIL] execute_prompt is already running for "${agent.friendlyName}". Wait for the current call to finish before sending another.`,
|
|
486
|
+
structuredContent: { isError: true, reason: 'busy' },
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
// No-LLM members (apra-fleet-us9.14) are plain command executors -- neither
|
|
491
|
+
// execute_prompt mode applies (there is no LLM to prompt in either a
|
|
492
|
+
// subprocess or an interactive session). Rejected here, before any busy
|
|
493
|
+
// state is entered, rather than relying on NoneProvider's methods to throw
|
|
494
|
+
// deeper in either dispatch path.
|
|
495
|
+
if (agent.llmProvider === 'none') {
|
|
496
|
+
return `[FAIL] "${agent.friendlyName}" has no LLM provider (llm_provider: "none") -- it is a plain command executor. Use execute_command instead.`;
|
|
497
|
+
}
|
|
498
|
+
// Interactive routing (apra-fleet-2xs.8/us9.8, docs/cloud-fleet-architecture.md
|
|
499
|
+
// section 6): if this member has a live MCP session connected right now,
|
|
500
|
+
// route via send_message + wait-for-response instead of spawning a
|
|
501
|
+
// subprocess. Decided tier-2-locally against THIS machine's session
|
|
502
|
+
// registry only (never caller/hub-side state, per apra-fleet-2xs.8's own
|
|
503
|
+
// scope note) -- so behavior is unaffected by whether execute_prompt is
|
|
504
|
+
// invoked directly (Phase 1) or relayed through a future hub. Falls
|
|
505
|
+
// through to the unchanged subprocess/SSH path below for every member
|
|
506
|
+
// without a live session (the common case today, and always for members
|
|
507
|
+
// that never opt into an interactive session).
|
|
508
|
+
//
|
|
509
|
+
// Gated by capability, not provider name (apra-fleet-cqa, eft.74 follow-up):
|
|
510
|
+
// mode (b) -- server-push mid-session prompt injection -- was POC-proven on
|
|
511
|
+
// Claude via the provider-branded `notifications/claude/channel` capability
|
|
512
|
+
// (apra-fleet-us9.9's survey, docs/interactive-injection-provider-survey.md),
|
|
513
|
+
// but the routing decision itself must be provider-agnostic: whatever the
|
|
514
|
+
// provider, a session is only an interactive-routing candidate if it
|
|
515
|
+
// actually declared that capability at MCP initialize time (recorded as
|
|
516
|
+
// SessionState.channelCapable below). Gemini/Codex are confirmed [FAIL]
|
|
517
|
+
// today (no equivalent push mechanism) and so never end up channelCapable in
|
|
518
|
+
// practice, but that is a fact about what each provider adapter currently
|
|
519
|
+
// advertises, not a name-based pre-filter here -- any provider that
|
|
520
|
+
// implements the same MCP channel capability is picked up automatically. A
|
|
521
|
+
// member CAN still have a live sessionRegistry entry (registerMcpEndpoint
|
|
522
|
+
// gives it basic MCP tool access, apra-fleet-fnz.1-3) without that meaning
|
|
523
|
+
// it can receive or act on this push -- routing to it anyway would silently
|
|
524
|
+
// spend the full timeout_s waiting for a response that can never arrive.
|
|
525
|
+
const workspaceId = getTokenIssuer().workspaceId();
|
|
526
|
+
const rawSession = sessionRegistry.get(workspaceId, agent.id);
|
|
527
|
+
// apra-fleet-eft.74.1: interactive routing requires the EXPLICIT channel
|
|
528
|
+
// opt-in handshake, not mere JWT registration. A plain subprocess
|
|
529
|
+
// connect-back (a Doer that opened an MCP tool-access session with a member
|
|
530
|
+
// JWT but never declared the `claude/channel` capability) registers a live
|
|
531
|
+
// `server` here, yet can never receive the `notifications/claude/channel`
|
|
532
|
+
// push -- routing to it would enqueue a message nothing reads and burn the
|
|
533
|
+
// full timeout_s on every later dispatch (the eft.74 wedge). Only a
|
|
534
|
+
// channel-capable session is an interactive-routing candidate; anything else
|
|
535
|
+
// (including that Doer's live tool session, which must be left untouched)
|
|
536
|
+
// falls through to the unchanged subprocess path below.
|
|
537
|
+
let interactiveSession = rawSession?.channelCapable ? rawSession : undefined;
|
|
538
|
+
// apra-fleet-eft.50.1: resolve the pid to test FRESH on every dispatch
|
|
539
|
+
// (never cached from a prior attempt) and fall back to the durable
|
|
540
|
+
// launch-pid anchor when this reused session lost its own pid on a
|
|
541
|
+
// reconnect. This is what re-arms the dead-session guard on a retry attempt
|
|
542
|
+
// 2+ exactly as on attempt 1: the specific eft.50 ordering (attempt 1 fails
|
|
543
|
+
// clean, attempt 2 targets a now-dead reconnected session) used to slip
|
|
544
|
+
// through here because the reconnected SessionState had pid=undefined, so the
|
|
545
|
+
// check below was skipped and the caller hung on the dead channel.
|
|
546
|
+
const interactivePid = interactiveSession?.pid
|
|
547
|
+
?? sessionRegistry.lastKnownPid(workspaceId, agent.id);
|
|
548
|
+
if (interactiveSession?.server && interactivePid !== undefined && !isPidAlive(interactivePid)) {
|
|
549
|
+
// apra-fleet-eft.28.1/eft.28.5: never reuse a persistent interactive
|
|
550
|
+
// session whose underlying member claude process has already died. Before
|
|
551
|
+
// eft.28.1, a dead launch-time process (e.g. it crashed before ever
|
|
552
|
+
// producing a plan) left a `server` entry in sessionRegistry that looked
|
|
553
|
+
// reusable -- send_message would happily enqueue to it, but nothing would
|
|
554
|
+
// ever call respond_to_message, so the caller silently burned the full
|
|
555
|
+
// timeout_s (observed up to 3600s in apra-fleet-eft.28) with zero
|
|
556
|
+
// fleet-server log output and no watchdog coverage.
|
|
557
|
+
//
|
|
558
|
+
// eft.28.5 changes what happens once the death is detected: instead of
|
|
559
|
+
// surfacing a terminal dispatch_failed error that forces a manual
|
|
560
|
+
// register_member, EVICT the dead session and FALL THROUGH to a fresh
|
|
561
|
+
// non-interactive (subprocess) dispatch below -- i.e. re-dispatch fresh
|
|
562
|
+
// instead of blocking on waitForInteractiveResponse. The bug in
|
|
563
|
+
// apra-fleet-eft.28 was precisely that a dead session was reused "rather
|
|
564
|
+
// than detecting its death and spawning a fresh dispatch"; this does the
|
|
565
|
+
// spawning. If the fresh subprocess dispatch itself cannot start it
|
|
566
|
+
// returns its own terminal error, so nothing ever hangs.
|
|
567
|
+
//
|
|
568
|
+
// The liveness check now fires for connect-back interactive sessions too:
|
|
569
|
+
// http-transport carries the launch-time pid forward across re-registration
|
|
570
|
+
// (eft.28.5), so `pid` is no longer undefined for a member that registered
|
|
571
|
+
// via register_member and then connected back -- the exact real-fleet
|
|
572
|
+
// repro that evaded eft.28.1.
|
|
573
|
+
//
|
|
574
|
+
// apra-fleet-eft.50.1: eft.28.5's carry-forward still lost the pid when a
|
|
575
|
+
// reconnect happened AFTER the prior SessionState was already unregistered
|
|
576
|
+
// (priorPid lookup found nothing), so a retry attempt 2+ reused a
|
|
577
|
+
// pid=undefined session and hung. `interactivePid` above now back-stops
|
|
578
|
+
// that with sessionRegistry.lastKnownPid, the durable per-member launch-pid
|
|
579
|
+
// anchor, so this guard re-arms on EVERY dispatch attempt that reuses an
|
|
580
|
+
// interactive session, not just the first. It stays undefined only for
|
|
581
|
+
// sessions that never had a captured PID at all (e.g. tests, or a provider
|
|
582
|
+
// that never went through register_member's local spawn path); those are
|
|
583
|
+
// left to the pre-existing interactive behavior, unchanged.
|
|
584
|
+
const deadScope = new LogScope('execute_prompt', `[interactive] session liveness check pid=${interactivePid}`, agent);
|
|
585
|
+
sessionRegistry.unregister(workspaceId, agent.id);
|
|
586
|
+
deadScope.info(`member claude process (pid ${interactivePid}) for "${agent.friendlyName}" is dead -- evicting the stale interactive session and re-dispatching fresh (non-interactive)`);
|
|
587
|
+
interactiveSession = undefined;
|
|
588
|
+
}
|
|
589
|
+
if (interactiveSession?.server) {
|
|
590
|
+
inFlightAgents.add(agent.id);
|
|
591
|
+
writeStatusline(new Map([[agent.id, 'busy']]));
|
|
592
|
+
try {
|
|
593
|
+
return await executePromptInteractive(agent, renderedPrompt, input, workspaceId, heuristicWarningSuffix);
|
|
594
|
+
}
|
|
595
|
+
finally {
|
|
596
|
+
inFlightAgents.delete(agent.id);
|
|
597
|
+
writeStatusline(new Map([[agent.id, 'idle']]));
|
|
598
|
+
}
|
|
155
599
|
}
|
|
156
600
|
inFlightAgents.add(agent.id);
|
|
157
601
|
await ensureAgentFilesProvisioned(agent);
|
|
158
602
|
const stallDetector = getStallDetector();
|
|
159
603
|
let clearedByStall = false;
|
|
604
|
+
// apra-fleet-3c9.1: a CONFIRMED stall must not only kill the remote pid but
|
|
605
|
+
// also cancel the in-flight strategy.execCommand() promise. Before this, the
|
|
606
|
+
// client kept waiting out its full deriveTimeoutMs deadline after the
|
|
607
|
+
// server-side work had already died (the 60.5-min hung dispatch in
|
|
608
|
+
// apra-fleet-3c9). onStall aborts this controller; its signal is merged into
|
|
609
|
+
// the signal handed to every execCommand below (see dispatchSignal), so a
|
|
610
|
+
// confirmed stall settles the pending dispatch immediately and surfaces a
|
|
611
|
+
// typed 'stalled' error instead of hanging.
|
|
612
|
+
const stallAbortController = new AbortController();
|
|
160
613
|
stallDetector.add(agent.id, {
|
|
161
614
|
sessionId: null,
|
|
162
615
|
logFilePath: null,
|
|
@@ -174,6 +627,21 @@ export async function executePrompt(input, extra) {
|
|
|
174
627
|
// a new execute_prompt that may have already claimed the member.
|
|
175
628
|
inFlightAgents.delete(agent.id);
|
|
176
629
|
clearedByStall = true;
|
|
630
|
+
// apra-fleet-6z8.2: a CONFIRMED stall means the remote turn made no
|
|
631
|
+
// progress of any kind for the whole threshold. Clearing bookkeeping
|
|
632
|
+
// alone left that wedged process running indefinitely on the member --
|
|
633
|
+
// burning its LLM session, holding its work folder, and colliding with
|
|
634
|
+
// whatever dispatch takes the member next. Kill the tracked pid too.
|
|
635
|
+
// Best-effort and never awaited: onStall is a fire-and-forget callback
|
|
636
|
+
// from the poll loop, and tryKillPid already swallows its own errors.
|
|
637
|
+
void tryKillPid(agent, strategy, cmds).catch(() => { });
|
|
638
|
+
// apra-fleet-3c9.1: killing the remote pid alone left the pending
|
|
639
|
+
// execCommand promise still awaiting its full deadline. Abort it now so
|
|
640
|
+
// the dispatch settles promptly and returns a typed 'stalled' error.
|
|
641
|
+
try {
|
|
642
|
+
stallAbortController.abort();
|
|
643
|
+
}
|
|
644
|
+
catch { /* best-effort */ }
|
|
177
645
|
},
|
|
178
646
|
});
|
|
179
647
|
const tmpDir = agent.agentType === 'local' ? os.tmpdir() : '/tmp';
|
|
@@ -209,14 +677,48 @@ export async function executePrompt(input, extra) {
|
|
|
209
677
|
else {
|
|
210
678
|
resolvedModel = tiers[resolvedModel] ?? resolvedModel;
|
|
211
679
|
}
|
|
212
|
-
const deprecationWarning = input.dangerously_skip_permissions
|
|
213
|
-
? '⚠️ DEPRECATION: dangerously_skip_permissions is deprecated and ignored. Use update_member(unattended="dangerous") instead.\n\n'
|
|
214
|
-
: '';
|
|
215
680
|
const scope = new LogScope('execute_prompt', `[${resolvedModel}] resume=${input.resume} timeout=${input.timeout_s ?? 300}s ${truncateForLog(maskSecrets(input.prompt), getLogPreviewChars())}`, agent);
|
|
216
|
-
|
|
681
|
+
// Resume semantics (apra-fleet-eft.78.1). `resume` is boolean | string:
|
|
682
|
+
// - true -> best-effort resume of the member's stored last session; a
|
|
683
|
+
// stale/unknown stored session transparently retries fresh.
|
|
684
|
+
// - false -> always a fresh session.
|
|
685
|
+
// - string -> EXPLICIT session-id resume: resume exactly this id, preferring
|
|
686
|
+
// it over agent.sessionId. The caller asserts the prompt depends
|
|
687
|
+
// on that session's context, so an unknown/expired id is a
|
|
688
|
+
// TERMINAL session_not_found (handled just below) and NO
|
|
689
|
+
// fresh-session fallback is ever applied (see the retry paths).
|
|
690
|
+
const explicitResumeId = typeof input.resume === 'string' && input.resume.length > 0 ? input.resume : undefined;
|
|
691
|
+
const resumeRequested = input.resume === true || explicitResumeId !== undefined;
|
|
692
|
+
const resumeTargetId = explicitResumeId ?? agent.sessionId;
|
|
693
|
+
// An explicit-id resume must never silently degrade to a fresh session: that
|
|
694
|
+
// is exactly the wrong-context dispatch this feature forbids. resume=true and
|
|
695
|
+
// resume=false keep their pre-existing transparent recovery.
|
|
696
|
+
const allowFreshSessionFallback = explicitResumeId === undefined;
|
|
697
|
+
const resuming = !!(resumeRequested && resumeTargetId && provider.supportsResume());
|
|
217
698
|
const mintedId = (provider.name === 'claude' || provider.name === 'gemini' || provider.name === 'agy')
|
|
218
|
-
? (resuming ?
|
|
219
|
-
: (resuming ?
|
|
699
|
+
? (resuming ? resumeTargetId : uuid())
|
|
700
|
+
: (resuming ? resumeTargetId : undefined);
|
|
701
|
+
// Terminal session-not-found gate for explicit-id resumes (apra-fleet-eft.78.1).
|
|
702
|
+
// Checked BEFORE any spawn (writePromptFile / the LLM invocation): if the
|
|
703
|
+
// caller named a session the server has never issued for this member -- and it
|
|
704
|
+
// is not the member's currently-stored session -- there is no context to
|
|
705
|
+
// resume. Reject with a structured session_not_found and make NO LLM call,
|
|
706
|
+
// so an orchestrator can rebuild a self-contained prompt and re-dispatch fresh
|
|
707
|
+
// deliberately, rather than getting a silent blank-session response.
|
|
708
|
+
if (explicitResumeId !== undefined) {
|
|
709
|
+
const resumable = provider.supportsResume()
|
|
710
|
+
&& (isKnownSession(agent.id, explicitResumeId) || explicitResumeId === agent.sessionId);
|
|
711
|
+
if (!resumable) {
|
|
712
|
+
scope.abort(`explicit resume rejected -- session "${explicitResumeId}" is unknown/expired (no LLM call)`);
|
|
713
|
+
inFlightAgents.delete(agent.id);
|
|
714
|
+
stallDetector.remove(agent.id);
|
|
715
|
+
writeStatusline(new Map([[agent.id, 'idle']]));
|
|
716
|
+
return {
|
|
717
|
+
text: `[FAIL] execute_prompt on "${agent.friendlyName}" rejected -- session "${explicitResumeId}" cannot be resumed (unknown or expired). No LLM call was made. Rebuild the context and re-dispatch with a full, self-contained prompt (resume=false), or resume=true for best-effort recovery.`,
|
|
718
|
+
structuredContent: { isError: true, reason: 'session_not_found', sessionId: explicitResumeId },
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
}
|
|
220
722
|
const promptOpts = {
|
|
221
723
|
folder: resolvedWorkFolder,
|
|
222
724
|
promptFile: promptFileName,
|
|
@@ -227,15 +729,152 @@ export async function executePrompt(input, extra) {
|
|
|
227
729
|
tier: resolvedTier,
|
|
228
730
|
maxTurns: input.max_turns,
|
|
229
731
|
inv: scope.getInv(),
|
|
732
|
+
agentName: input.agent,
|
|
230
733
|
};
|
|
231
734
|
const claudeCmd = authPrefix + cmds.buildAgentPromptCommand(provider, promptOpts);
|
|
735
|
+
// apra-fleet-6z8.1: the per-invocation durable stdout mirror the unix prompt
|
|
736
|
+
// wrapper tees to (see durableOutputPath / buildAgentPromptCommand). Windows
|
|
737
|
+
// members have no such companion tee, so recovery is skipped for them.
|
|
738
|
+
const durablePath = getAgentOS(agent) === 'windows' ? undefined : durableOutputPath(scope.getInv());
|
|
739
|
+
const dispatchStartedAt = Date.now();
|
|
232
740
|
const timeoutMs = (input.timeout_s ?? 300) * 1000;
|
|
233
741
|
const maxTotalMs = input.max_total_s !== undefined ? input.max_total_s * 1000 : undefined;
|
|
742
|
+
// apra-fleet-y8q.1: every retry below (dispatch-exception, stale-session,
|
|
743
|
+
// server-overloaded) re-dispatches with a FRESH session but used to reuse the
|
|
744
|
+
// SAME full timeoutMs/maxTotalMs as the original attempt -- so a single
|
|
745
|
+
// dispatch could burn up to ~2x max_total_s server-side (original attempt +
|
|
746
|
+
// one full-budget retry), well past what the client's deriveTimeoutMs()
|
|
747
|
+
// (packages/apra-fleet-client/src/client/api.mjs) budgets for the whole
|
|
748
|
+
// tools/call (max_total_s*1000 + a fixed grace margin). That let the
|
|
749
|
+
// client's hard timeout fire before the server's own retry-and-report path
|
|
750
|
+
// ever got a chance, hiding a clean typed server error behind a raw client
|
|
751
|
+
// transport timeout. Share ONE deadline budget across the original attempt
|
|
752
|
+
// and any single retry: cap a retry's maxTotalMs (and its inactivity
|
|
753
|
+
// timeoutMs, so it can't independently outlast the shared ceiling) to
|
|
754
|
+
// whatever remains of max_total_s since dispatchStartedAt, and skip the
|
|
755
|
+
// retry entirely once that budget is exhausted -- so total wall-clock time
|
|
756
|
+
// for this call never exceeds max_total_s, which is exactly what the client
|
|
757
|
+
// is prepared to wait for. When max_total_s is absent there is no hard
|
|
758
|
+
// ceiling to share, so retries keep their full timeout_s (unchanged,
|
|
759
|
+
// pre-existing behavior).
|
|
760
|
+
function retryBudget() {
|
|
761
|
+
if (maxTotalMs === undefined)
|
|
762
|
+
return { timeoutMs, maxTotalMs: undefined, exhausted: false };
|
|
763
|
+
const remaining = Math.max(0, maxTotalMs - (Date.now() - dispatchStartedAt));
|
|
764
|
+
return { timeoutMs: Math.min(timeoutMs, remaining), maxTotalMs: remaining, exhausted: remaining <= 0 };
|
|
765
|
+
}
|
|
766
|
+
// Agent file validation -- verify named agent exists before any CLI invocation
|
|
767
|
+
if (input.agent) {
|
|
768
|
+
const provName = provider.name;
|
|
769
|
+
// AGY uses ~/.gemini/antigravity-cli/ as its config root, not ~/.agy/
|
|
770
|
+
const agentRelDir = provName === 'agy' ? '.gemini/antigravity-cli/agents' : `.${provName}/agents`;
|
|
771
|
+
let agentFound = false;
|
|
772
|
+
if (agent.agentType === 'local') {
|
|
773
|
+
const projPath = path.join(resolvedWorkFolder, agentRelDir, `${input.agent}.md`);
|
|
774
|
+
const userPath = path.join(os.homedir(), agentRelDir, `${input.agent}.md`);
|
|
775
|
+
agentFound = fs.existsSync(projPath) || fs.existsSync(userPath);
|
|
776
|
+
if (!agentFound) {
|
|
777
|
+
inFlightAgents.delete(agent.id);
|
|
778
|
+
stallDetector.remove(agent.id);
|
|
779
|
+
writeStatusline(new Map([[agent.id, 'idle']]));
|
|
780
|
+
return `execute_prompt: agent "${input.agent}" not found.\n\nExpected at:\n ${projPath.replace(/\\/g, '/')}\n ${userPath.replace(/\\/g, '/')}`;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
else {
|
|
784
|
+
// Canonical PM role agents (planner/doer/reviewer/plan-reviewer/...) are
|
|
785
|
+
// already guaranteed present in ~/${agentRelDir} by
|
|
786
|
+
// ensureAgentFilesProvisioned() above (ln ~576, which ran provisionAgents()
|
|
787
|
+
// for this exact member earlier in this same call) -- trust that instead
|
|
788
|
+
// of re-probing the remote here. This also SIDESTEPS the bug this check
|
|
789
|
+
// used to have: the old code hand-rolled a POSIX-only
|
|
790
|
+
// `test -f ... || test -f ...` command run via strategy.execCommand(),
|
|
791
|
+
// which throws a PowerShell parser error (not a POSIX shell) on every
|
|
792
|
+
// Windows remote -- a nonzero exit that this check misread as "agent not
|
|
793
|
+
// found" even when the file genuinely existed (apra-fleet P0 bug, fleet-
|
|
794
|
+
// sprint via a Windows remote member always failed plan-review with
|
|
795
|
+
// "agent 'plan-reviewer' not found").
|
|
796
|
+
const canonicalRelPath = `${input.agent}.md`;
|
|
797
|
+
agentFound = remoteAgentsDir(provName) !== null
|
|
798
|
+
&& loadCanonicalAgentSet(provName).some((f) => f.relPath === canonicalRelPath);
|
|
799
|
+
if (!agentFound) {
|
|
800
|
+
// Not part of the canonical PM set (e.g. a project-local custom
|
|
801
|
+
// agent) -- fall back to a REAL existence probe, built platform-aware
|
|
802
|
+
// via this repo's own getOsCommands() abstraction (src/os/*.ts,
|
|
803
|
+
// already used the same way by list-members.ts/member-detail.ts for
|
|
804
|
+
// credential-file checks) instead of a single hardcoded shell dialect.
|
|
805
|
+
const cmds = getOsCommands(getAgentOS(agent));
|
|
806
|
+
const projPath = `${resolvedWorkFolder}/${agentRelDir}/${input.agent}.md`;
|
|
807
|
+
const userPath = `~/${agentRelDir}/${input.agent}.md`;
|
|
808
|
+
const [projResult, userResult] = await Promise.all([
|
|
809
|
+
strategy.execCommand(cmds.credentialFileCheck(projPath), 10000),
|
|
810
|
+
strategy.execCommand(cmds.credentialFileCheck(userPath), 10000),
|
|
811
|
+
]);
|
|
812
|
+
agentFound = projResult.stdout.includes('found') || userResult.stdout.includes('found');
|
|
813
|
+
}
|
|
814
|
+
if (!agentFound) {
|
|
815
|
+
inFlightAgents.delete(agent.id);
|
|
816
|
+
stallDetector.remove(agent.id);
|
|
817
|
+
writeStatusline(new Map([[agent.id, 'idle']]));
|
|
818
|
+
return `execute_prompt: agent "${input.agent}" not found on "${agent.friendlyName}".\n\nExpected at:\n ${resolvedWorkFolder}/${agentRelDir}/${input.agent}.md\n ~/${agentRelDir}/${input.agent}.md`;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
// Context-headroom admission control (apra-fleet-eft.81.1): a declared
|
|
823
|
+
// demand is checked against this session's remaining headroom BEFORE any
|
|
824
|
+
// CLI is spawned. No declared demand (both fields omitted) means this
|
|
825
|
+
// block is skipped entirely -- pre-existing behavior is unchanged.
|
|
826
|
+
const contextDemand = resolveExpectedDemand(input.expected_context_tokens, input.context_size);
|
|
827
|
+
let contextWarning;
|
|
828
|
+
if (contextDemand !== undefined) {
|
|
829
|
+
const admission = checkContextAdmission({
|
|
830
|
+
provider: provider.name,
|
|
831
|
+
resolvedModel,
|
|
832
|
+
sessionId: mintedId,
|
|
833
|
+
demand: contextDemand,
|
|
834
|
+
});
|
|
835
|
+
if (!admission.allowed) {
|
|
836
|
+
scope.abort(`insufficient context headroom: demand=${admission.detail.demand} headroom=${admission.detail.headroom} window=${admission.detail.window}`);
|
|
837
|
+
inFlightAgents.delete(agent.id);
|
|
838
|
+
stallDetector.remove(agent.id);
|
|
839
|
+
writeStatusline(new Map([[agent.id, 'idle']]));
|
|
840
|
+
return {
|
|
841
|
+
text: `[FAIL] execute_prompt on "${agent.friendlyName}" rejected -- insufficient context headroom (demand=${admission.detail.demand}, headroom=${admission.detail.headroom}, window=${admission.detail.window}). Start a fresh session, shrink the task, or split it.`,
|
|
842
|
+
structuredContent: { isError: true, reason: 'insufficient_context_headroom', detail: admission.detail },
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
if (admission.warning) {
|
|
846
|
+
contextWarning = { message: admission.warning, detail: admission.detail };
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
// Usage/budget admission (apra-fleet-eft.80.2): when a budget is configured
|
|
850
|
+
// for this member (or its workspace), a hard-threshold crossing rejects the
|
|
851
|
+
// NEW dispatch BEFORE any LLM is spawned -- never killing an in-flight call.
|
|
852
|
+
// No configured budget (the common case) means resolveBudgetScope returns
|
|
853
|
+
// undefined and this block is skipped entirely -- behavior is unchanged.
|
|
854
|
+
const budgetScope = resolveBudgetScope([agent.id, workspaceId]);
|
|
855
|
+
if (budgetScope) {
|
|
856
|
+
const preBudget = await evaluateBudget({ scope: budgetScope, agent, provider });
|
|
857
|
+
if (preBudget?.exhausted) {
|
|
858
|
+
scope.abort(`budget exhausted: scope=${budgetScope} spent=${preBudget.block.spent} budget=${preBudget.block.budget} source=${preBudget.block.source}`);
|
|
859
|
+
inFlightAgents.delete(agent.id);
|
|
860
|
+
stallDetector.remove(agent.id);
|
|
861
|
+
writeStatusline(new Map([[agent.id, 'idle']]));
|
|
862
|
+
return {
|
|
863
|
+
text: `[FAIL] execute_prompt on "${agent.friendlyName}" rejected -- budget exhausted (scope=${budgetScope}, spent=${preBudget.block.spent}, budget=${preBudget.block.budget} ${preBudget.block.unit}, source=${preBudget.block.source}). No LLM call was made; raise or reset the budget to resume.`,
|
|
864
|
+
structuredContent: { isError: true, reason: 'budget_exhausted', budgetUsage: preBudget.block },
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
}
|
|
234
868
|
// Kill any leftover session from a previous (possibly zombie) execute_prompt call
|
|
235
869
|
await tryKillPid(agent, strategy, cmds);
|
|
236
|
-
// Write the prompt to the
|
|
237
|
-
await writePromptFile(agent, strategy, promptFilePath,
|
|
870
|
+
// Write the rendered prompt (with substitutions applied) to the prompt file before execution
|
|
871
|
+
await writePromptFile(agent, strategy, promptFilePath, renderedPrompt);
|
|
872
|
+
// apra-fleet-6z8.1: remembered for the lease-of-life gate below -- the pid
|
|
873
|
+
// outlives the SSH channel that reported it, and is the only way to tell a
|
|
874
|
+
// fabricated "exit 0 / empty" close apart from a real one.
|
|
875
|
+
let capturedPid;
|
|
238
876
|
const onPidCaptured = (pid) => {
|
|
877
|
+
capturedPid = pid;
|
|
239
878
|
scope.info(`pid=${pid}`);
|
|
240
879
|
if (mintedId) {
|
|
241
880
|
try {
|
|
@@ -254,52 +893,264 @@ export async function executePrompt(input, extra) {
|
|
|
254
893
|
tryKillPid(agent, strategy, cmds).catch(() => { });
|
|
255
894
|
};
|
|
256
895
|
extra?.signal?.addEventListener('abort', abortHandler);
|
|
896
|
+
// apra-fleet-3c9.1: the signal handed to execCommand fires on EITHER the MCP
|
|
897
|
+
// client's cancellation OR a confirmed stall (stallAbortController). Merging
|
|
898
|
+
// them means a stall aborts the pending dispatch exactly as a client cancel
|
|
899
|
+
// would, while a live (non-stalled) dispatch -- whose controller is never
|
|
900
|
+
// aborted -- is left completely untouched.
|
|
901
|
+
const dispatchSignal = extra?.signal
|
|
902
|
+
? AbortSignal.any([extra.signal, stallAbortController.signal])
|
|
903
|
+
: stallAbortController.signal;
|
|
257
904
|
// Mark agent as busy in statusline
|
|
258
905
|
writeStatusline(new Map([[agent.id, 'busy']]));
|
|
259
906
|
let _epExitCode = 'error';
|
|
260
907
|
let _epError;
|
|
261
908
|
let _epUsage;
|
|
262
909
|
let _epOffline = false;
|
|
910
|
+
// apra-fleet-6a7.1: gates the exit-0/empty-stdout workspace_not_trusted
|
|
911
|
+
// self-heal-and-retry below to exactly one attempt per call, mirroring
|
|
912
|
+
// runGitStep's authHealAttempted shape (fleet-sprint/runner.js:616) -- a
|
|
913
|
+
// repeat trust failure after the heal is terminal, never looped.
|
|
914
|
+
let trustHealAttempted = false;
|
|
263
915
|
try {
|
|
264
|
-
let result
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
916
|
+
let result;
|
|
917
|
+
try {
|
|
918
|
+
result = await strategy.execCommand(claudeCmd, timeoutMs, maxTotalMs, onPidCaptured, dispatchSignal);
|
|
919
|
+
}
|
|
920
|
+
catch (dispatchErr) {
|
|
921
|
+
// apra-fleet-02s.1: a genuine command-execution exception (e.g. an
|
|
922
|
+
// inactivity timeout, or any other error strategy.execCommand throws)
|
|
923
|
+
// used to be unconditionally unretried here -- it bypasses both retry
|
|
924
|
+
// mechanisms below, since those only fire on a non-throwing nonzero
|
|
925
|
+
// exit, never on a thrown exception. Retry once with a fresh session
|
|
926
|
+
// before giving up, mirroring the stale-session/server-overloaded
|
|
927
|
+
// retries' bounded, single-attempt shape. Skip the retry if the client
|
|
928
|
+
// itself cancelled the request -- there is nothing to recover from a
|
|
929
|
+
// deliberate cancellation.
|
|
930
|
+
if (extra?.signal?.aborted)
|
|
931
|
+
throw dispatchErr;
|
|
932
|
+
// apra-fleet-3c9.1: a stall-triggered abort is terminal. onStall already
|
|
933
|
+
// killed the remote process and its session is gone, so retrying in a
|
|
934
|
+
// fresh session would just re-dispatch onto a member we just tore down.
|
|
935
|
+
// Let the exception surface to the outer catch, which classifies it as a
|
|
936
|
+
// typed 'stalled' error instead of retrying or hanging.
|
|
937
|
+
if (stallAbortController.signal.aborted)
|
|
938
|
+
throw dispatchErr;
|
|
939
|
+
// apra-fleet-eft.78.1: an explicit-id resume must NOT retry in a fresh
|
|
940
|
+
// session (that would run a context-dependent delta prompt with no
|
|
941
|
+
// context). Let the exception surface as dispatch_failed instead.
|
|
942
|
+
if (!allowFreshSessionFallback)
|
|
943
|
+
throw dispatchErr;
|
|
944
|
+
// apra-fleet-y8q.1: no budget left to share with a retry (the original
|
|
945
|
+
// attempt already consumed the whole max_total_s) -- retrying here would
|
|
946
|
+
// just re-burn a fresh full budget past what the client is waiting for.
|
|
947
|
+
// Let the original exception surface instead of retrying blind.
|
|
948
|
+
const budget = retryBudget();
|
|
949
|
+
if (budget.exhausted)
|
|
950
|
+
throw dispatchErr;
|
|
951
|
+
scope.info(`[${resolvedModel}] retrying -- dispatch exception: ${dispatchErr.message}`);
|
|
282
952
|
await tryKillPid(agent, strategy, cmds);
|
|
283
|
-
await new Promise(r => setTimeout(r, SERVER_RETRY_DELAY_MS));
|
|
284
953
|
const freshOpts = { ...promptOpts, sessionId: (provider.name === 'claude' || provider.name === 'gemini' || provider.name === 'agy') ? uuid() : undefined, resuming: false };
|
|
285
954
|
const retryCmd = authPrefix + cmds.buildAgentPromptCommand(provider, freshOpts);
|
|
286
|
-
result = await strategy.execCommand(retryCmd, timeoutMs, maxTotalMs, onPidCaptured,
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
955
|
+
result = await strategy.execCommand(retryCmd, budget.timeoutMs, budget.maxTotalMs, onPidCaptured, dispatchSignal);
|
|
956
|
+
}
|
|
957
|
+
let parsed = provider.parseResponse(result);
|
|
958
|
+
if (parsed.usage)
|
|
959
|
+
_epUsage = parsed.usage;
|
|
960
|
+
// apra-fleet-eft.40.3: workspace-not-trusted degrades composed permissions
|
|
961
|
+
// (project-scoped allow entries silently dropped) without killing the CLI process --
|
|
962
|
+
// from there, unattended -p cannot auto-approve or prompt, so tools get denied and
|
|
963
|
+
// the turn eventually fails. Blindly falling through to the stale-session /
|
|
964
|
+
// server-overloaded retries below just repeats the same degraded dispatch against a
|
|
965
|
+
// workspace that is still untrusted, and can walk into eft.28's dead-session hang.
|
|
966
|
+
// Classify and fail fast here, before either retry path, naming
|
|
967
|
+
// ensureWorkspaceTrusted (apra-fleet-eft.40.1/40.2) as the remediation.
|
|
968
|
+
if (result.code !== 0 && provider.classifyError(result.stderr || result.stdout) === 'workspace_not_trusted') {
|
|
969
|
+
return {
|
|
970
|
+
text: `[FAIL] ${workspaceNotTrustedAdvice(agent.friendlyName)}\n${result.stderr || result.stdout}`,
|
|
971
|
+
structuredContent: { isError: true, reason: 'workspace_not_trusted' },
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
// Stale session retry -- fresh session ID, no resume. apra-fleet-eft.78.1:
|
|
975
|
+
// ONLY the best-effort resume=true mode gets this transparent retry-fresh
|
|
976
|
+
// recovery. An explicit session-id resume (string) deliberately does NOT --
|
|
977
|
+
// its caller asserted context dependence, so a not-found id is terminal.
|
|
978
|
+
if (result.code !== 0 && input.resume === true && agent.sessionId) {
|
|
979
|
+
// apra-fleet-y8q.1: share the remaining max_total_s budget with this
|
|
980
|
+
// retry too -- skip it outright once exhausted (see retryBudget above).
|
|
981
|
+
const staleBudget = retryBudget();
|
|
982
|
+
if (!staleBudget.exhausted) {
|
|
983
|
+
scope.info(`[${resolvedModel}] retrying -- stale session`);
|
|
984
|
+
await tryKillPid(agent, strategy, cmds);
|
|
985
|
+
const freshOpts = { ...promptOpts, sessionId: (provider.name === 'claude' || provider.name === 'gemini' || provider.name === 'agy') ? uuid() : undefined, resuming: false };
|
|
986
|
+
const retryCmd = authPrefix + cmds.buildAgentPromptCommand(provider, freshOpts);
|
|
987
|
+
result = await strategy.execCommand(retryCmd, staleBudget.timeoutMs, staleBudget.maxTotalMs, onPidCaptured, dispatchSignal);
|
|
988
|
+
parsed = provider.parseResponse(result);
|
|
989
|
+
if (parsed.usage)
|
|
990
|
+
_epUsage = parsed.usage;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
// Server/overloaded error retry -- single attempt after delay. Skipped for
|
|
994
|
+
// an explicit-id resume (apra-fleet-eft.78.1): the retry starts a fresh
|
|
995
|
+
// session, which would discard the exact context the caller asked to resume.
|
|
996
|
+
if (result.code !== 0 && allowFreshSessionFallback && isRetryable(provider.classifyError(result.stderr || result.stdout))) {
|
|
997
|
+
// apra-fleet-y8q.1: share the remaining max_total_s budget with this
|
|
998
|
+
// retry too -- skip it outright once exhausted (see retryBudget above).
|
|
999
|
+
const overloadBudget = retryBudget();
|
|
1000
|
+
if (!overloadBudget.exhausted) {
|
|
1001
|
+
scope.info(`[${resolvedModel}] retrying -- server overloaded`);
|
|
1002
|
+
await tryKillPid(agent, strategy, cmds);
|
|
1003
|
+
await new Promise(r => setTimeout(r, SERVER_RETRY_DELAY_MS));
|
|
1004
|
+
const freshOpts = { ...promptOpts, sessionId: (provider.name === 'claude' || provider.name === 'gemini' || provider.name === 'agy') ? uuid() : undefined, resuming: false };
|
|
1005
|
+
const retryCmd = authPrefix + cmds.buildAgentPromptCommand(provider, freshOpts);
|
|
1006
|
+
result = await strategy.execCommand(retryCmd, overloadBudget.timeoutMs, overloadBudget.maxTotalMs, onPidCaptured, dispatchSignal);
|
|
1007
|
+
parsed = provider.parseResponse(result);
|
|
1008
|
+
if (parsed.usage)
|
|
1009
|
+
_epUsage = parsed.usage;
|
|
1010
|
+
}
|
|
290
1011
|
}
|
|
291
1012
|
_epExitCode = result.code;
|
|
292
1013
|
if (result.code !== 0) {
|
|
293
|
-
|
|
1014
|
+
// apra-fleet-391: surface an auth failure as a STRUCTURED reason (not
|
|
1015
|
+
// just prose in `text`) so callers -- notably fleet-sprint's
|
|
1016
|
+
// isAuthDispatchError -- can key off it directly instead of regexing
|
|
1017
|
+
// the message string. Overloading 'nonzero_exit' for this case was
|
|
1018
|
+
// what made auth self-heal impossible to wire reliably upstream.
|
|
1019
|
+
const failureCategory = isMaxTurnsResponse(parsed)
|
|
1020
|
+
? 'max_turns'
|
|
1021
|
+
: provider.classifyError(result.stderr || result.stdout);
|
|
1022
|
+
return {
|
|
1023
|
+
text: buildFailureMessage(agent.friendlyName, result, provider, parsed),
|
|
1024
|
+
structuredContent: {
|
|
1025
|
+
isError: true,
|
|
1026
|
+
reason: failureCategory === 'max_turns'
|
|
1027
|
+
? 'max_turns_exhausted'
|
|
1028
|
+
: failureCategory === 'auth'
|
|
1029
|
+
? 'auth'
|
|
1030
|
+
: failureCategory === 'server'
|
|
1031
|
+
? 'server'
|
|
1032
|
+
: failureCategory === 'overloaded'
|
|
1033
|
+
? 'overloaded'
|
|
1034
|
+
: failureCategory === 'workspace_not_trusted'
|
|
1035
|
+
? 'workspace_not_trusted'
|
|
1036
|
+
: 'nonzero_exit',
|
|
1037
|
+
// apra-fleet-63x.1: a nonzero exit -- most commonly max_turns_exhausted,
|
|
1038
|
+
// where the CLI ran real turns and burned real tokens before hitting its
|
|
1039
|
+
// ceiling -- still has a REAL parsed usage figure sitting in _epUsage
|
|
1040
|
+
// (captured just above from `parsed.usage` regardless of exit code).
|
|
1041
|
+
// This branch used to return no `usage` field at all on any failure,
|
|
1042
|
+
// so FleetWorkflow.agent() (packages/apra-fleet-workflow/src/workflow/
|
|
1043
|
+
// index.mjs, apra-fleet-202.3) saw hasRealUsage=false and never priced
|
|
1044
|
+
// it, silently under-counting a sprint's tracked spend (observed: a
|
|
1045
|
+
// 10-hour run with dozens of max_turns exhaustions reporting
|
|
1046
|
+
// stats.totalCost of $0). Attach it here whenever it's available so
|
|
1047
|
+
// the caller can record the real partial cost instead of nothing.
|
|
1048
|
+
...(_epUsage ? { usage: { input_tokens: _epUsage.input_tokens, output_tokens: _epUsage.output_tokens, total_tokens: _epUsage.input_tokens + _epUsage.output_tokens } } : {}),
|
|
1049
|
+
},
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
// Exit 0 but the provider parser extracted NOTHING (no result text)
|
|
1053
|
+
// -- observed live (apra-fleet-eft.14, 2026-07-19 stabilization loop):
|
|
1054
|
+
// the claude CLI can die silently mid-turn (member-side session
|
|
1055
|
+
// transcript stops at a tool_result with no final assistant message)
|
|
1056
|
+
// and still exit 0 with EMPTY stdout, so parseResponse falls through
|
|
1057
|
+
// to its plain-text fallback with result: ''. Returning that as a
|
|
1058
|
+
// success used to hand callers a display wrapper with nothing inside,
|
|
1059
|
+
// which schema-extraction layers then misreported as "LLM returned
|
|
1060
|
+
// invalid JSON". Classify it at the source as a typed dispatch error
|
|
1061
|
+
// instead, with stderr's tail attached for diagnosis.
|
|
1062
|
+
//
|
|
1063
|
+
// apra-fleet-6z8.1 (lease-of-life gate): before declaring that, cross-check
|
|
1064
|
+
// whether the captured pid is STILL ALIVE via a fresh short exec. ssh.ts
|
|
1065
|
+
// substitutes code 0 when the channel closes without ever receiving an
|
|
1066
|
+
// 'exit' event, so "exit 0 + empty" is ALSO exactly what a torn-down
|
|
1067
|
+
// channel over a perfectly healthy, still-running turn looks like (live
|
|
1068
|
+
// evidence: pid 89858 running 2+ minutes past the close). Declaring
|
|
1069
|
+
// empty_response there orphans the CLI and invites a duplicate concurrent
|
|
1070
|
+
// dispatch of the same scope. A confirmed-dead pid keeps today's behavior
|
|
1071
|
+
// verbatim.
|
|
1072
|
+
if (!parsed.result || parsed.result.trim() === '') {
|
|
1073
|
+
const recovery = await recoverOrphanedDispatch({
|
|
1074
|
+
strategy,
|
|
1075
|
+
cmds,
|
|
1076
|
+
pid: capturedPid,
|
|
1077
|
+
durablePath,
|
|
1078
|
+
unsupported: getAgentOS(agent) === 'windows',
|
|
1079
|
+
maxWaitMs: maxTotalMs !== undefined ? Math.max(maxTotalMs - (Date.now() - dispatchStartedAt), 0) : undefined,
|
|
1080
|
+
scope,
|
|
1081
|
+
});
|
|
1082
|
+
if (recovery.status === 'timeout') {
|
|
1083
|
+
scope.info(`orphan recovery timed out after ${Math.round((recovery.waitedMs ?? 0) / 1000)}s -- pid killed`);
|
|
1084
|
+
return {
|
|
1085
|
+
text: `[FAIL] execute_prompt on "${agent.friendlyName}" lost its SSH channel while the member CLI (pid ${capturedPid}) was still running, and that process was still alive after the recovery window (${Math.round((recovery.waitedMs ?? 0) / 1000)}s). The process has been killed; no result was recovered. This is NOT an empty response -- do not treat it as a failed turn without checking the member's session transcript first.`,
|
|
1086
|
+
structuredContent: { isError: true, reason: 'orphan_recovery_timeout' },
|
|
1087
|
+
};
|
|
1088
|
+
}
|
|
1089
|
+
if (recovery.status === 'recovered' && recovery.stdout) {
|
|
1090
|
+
// Feed the durable output through the normal provider parse path,
|
|
1091
|
+
// exactly as if it had arrived on the original channel.
|
|
1092
|
+
const recoveredParsed = provider.parseResponse({ stdout: recovery.stdout, stderr: result.stderr ?? '', code: 0 });
|
|
1093
|
+
if (recoveredParsed.result && recoveredParsed.result.trim() !== '') {
|
|
1094
|
+
scope.info(`recovered the real result from the durable output file after a false-alarm empty_response (waited ${Math.round((recovery.waitedMs ?? 0) / 1000)}s)`);
|
|
1095
|
+
parsed = recoveredParsed;
|
|
1096
|
+
if (parsed.usage)
|
|
1097
|
+
_epUsage = parsed.usage;
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
// apra-fleet-6a7.1: the code!==0 workspace_not_trusted classification
|
|
1101
|
+
// above (~line 1048) never sees this branch -- exit 0 + empty stdout is
|
|
1102
|
+
// a SEPARATE path, but live evidence (apra-fleet-2g2, fleet-win-dev1,
|
|
1103
|
+
// 2026-08-02) showed it can be caused by the exact same trust-gate
|
|
1104
|
+
// failure: exited 0, empty stdout, and the stderr tail contained the
|
|
1105
|
+
// exact matched phrase, so the code!==0 classifier never ran. Classify
|
|
1106
|
+
// it here too and -- unlike that path, which only advises a manual fix
|
|
1107
|
+
// -- self-heal via the same seedWorkspaceTrust/ensureWorkspaceTrusted
|
|
1108
|
+
// path compose_permissions already uses, then retry the dispatch
|
|
1109
|
+
// exactly once (gated by trustHealAttempted, mirroring runGitStep's
|
|
1110
|
+
// onAuthFailure shape: a repeat failure after the heal is terminal, not
|
|
1111
|
+
// looped).
|
|
1112
|
+
if ((!parsed.result || parsed.result.trim() === '')
|
|
1113
|
+
&& provider.classifyError(result.stderr || result.stdout) === 'workspace_not_trusted'
|
|
1114
|
+
&& !trustHealAttempted) {
|
|
1115
|
+
trustHealAttempted = true;
|
|
1116
|
+
scope.info(`[${resolvedModel}] exit-0/empty-stdout classified as workspace_not_trusted -- self-healing (seedWorkspaceTrust) once, then retrying the dispatch`);
|
|
1117
|
+
await seedWorkspaceTrust(agent, strategy, 'execute_prompt');
|
|
1118
|
+
const healBudget = retryBudget();
|
|
1119
|
+
if (!healBudget.exhausted) {
|
|
1120
|
+
await tryKillPid(agent, strategy, cmds);
|
|
1121
|
+
const freshOpts = { ...promptOpts, sessionId: (provider.name === 'claude' || provider.name === 'gemini' || provider.name === 'agy') ? uuid() : undefined, resuming: false };
|
|
1122
|
+
const retryCmd = authPrefix + cmds.buildAgentPromptCommand(provider, freshOpts);
|
|
1123
|
+
result = await strategy.execCommand(retryCmd, healBudget.timeoutMs, healBudget.maxTotalMs, onPidCaptured, dispatchSignal);
|
|
1124
|
+
parsed = provider.parseResponse(result);
|
|
1125
|
+
if (parsed.usage)
|
|
1126
|
+
_epUsage = parsed.usage;
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
if (!parsed.result || parsed.result.trim() === '') {
|
|
1130
|
+
const stderrTail = (result.stderr || '').trim().slice(-500);
|
|
1131
|
+
const trustClassified = provider.classifyError(result.stderr || result.stdout) === 'workspace_not_trusted';
|
|
1132
|
+
return {
|
|
1133
|
+
text: trustClassified
|
|
1134
|
+
? `[FAIL] ${workspaceNotTrustedAdvice(agent.friendlyName)}\n${stderrTail}`
|
|
1135
|
+
: `[FAIL] execute_prompt on "${agent.friendlyName}" exited 0 but produced no parseable output (empty result -- the member CLI likely died mid-turn without printing its result envelope).${stderrTail ? `\n[stderr tail]\n${stderrTail}` : ''}`,
|
|
1136
|
+
structuredContent: { isError: true, reason: trustClassified ? 'workspace_not_trusted' : 'empty_response' },
|
|
1137
|
+
};
|
|
1138
|
+
}
|
|
294
1139
|
}
|
|
295
1140
|
// Session-id assertion: returned id must match the one we minted/resumed
|
|
296
|
-
|
|
1141
|
+
// Exception: AGY owns its session generation, so we always accept its returned ID
|
|
1142
|
+
if (provider.name !== 'agy' && mintedId && parsed.sessionId && parsed.sessionId !== mintedId) {
|
|
297
1143
|
scope.info(`session-id mismatch: expected=${mintedId} got=${parsed.sessionId} -- not persisting`);
|
|
298
1144
|
touchAgent(agent.id, undefined);
|
|
299
1145
|
}
|
|
300
1146
|
else {
|
|
301
|
-
touchAgent(agent.id,
|
|
1147
|
+
touchAgent(agent.id, parsed.sessionId ?? mintedId);
|
|
302
1148
|
}
|
|
1149
|
+
// apra-fleet-eft.78.1: mark the session this dispatch actually landed on as
|
|
1150
|
+
// known/resumable for this member, so a later explicit-id resume of it
|
|
1151
|
+
// passes the terminal session_not_found gate above instead of being
|
|
1152
|
+
// rejected as unknown.
|
|
1153
|
+
recordKnownSession(agent.id, parsed.sessionId ?? mintedId);
|
|
303
1154
|
if (mintedId) {
|
|
304
1155
|
try {
|
|
305
1156
|
stallDetector.update(agent.id, {
|
|
@@ -319,25 +1170,65 @@ export async function executePrompt(input, extra) {
|
|
|
319
1170
|
output: prev.output + parsed.usage.output_tokens,
|
|
320
1171
|
},
|
|
321
1172
|
});
|
|
1173
|
+
// Per-session cumulative tracking for context-headroom admission
|
|
1174
|
+
// (apra-fleet-eft.81.1) -- separate from the per-member lifetime total
|
|
1175
|
+
// just above. Keyed by whichever session id this dispatch actually
|
|
1176
|
+
// landed on (the returned id, falling back to the minted/resumed one),
|
|
1177
|
+
// so the NEXT admission check on this same session sees this dispatch's
|
|
1178
|
+
// usage already accounted for.
|
|
1179
|
+
recordSessionUsage(parsed.sessionId ?? mintedId, parsed.usage);
|
|
1180
|
+
}
|
|
1181
|
+
// Usage/budget accounting (apra-fleet-eft.80.2): account this dispatch's
|
|
1182
|
+
// token usage against the scope's budget (self-metered only when the
|
|
1183
|
+
// provider has no native getUsage()), then attach the usage block to the
|
|
1184
|
+
// result when the warning band is crossed. Nothing is attached below the
|
|
1185
|
+
// band, and nothing happens at all when no budget is configured.
|
|
1186
|
+
let budgetUsage;
|
|
1187
|
+
if (budgetScope && parsed.usage) {
|
|
1188
|
+
const postBudget = await recordAndEvaluate({ scope: budgetScope, agent, provider, tier: resolvedTier, usage: parsed.usage });
|
|
1189
|
+
if (postBudget?.warned)
|
|
1190
|
+
budgetUsage = postBudget.block;
|
|
322
1191
|
}
|
|
323
|
-
let output =
|
|
1192
|
+
let output = `[RESULT] Response from ${agent.friendlyName}:
|
|
324
1193
|
|
|
325
1194
|
${parsed.result}`;
|
|
326
|
-
if (parsed.usage)
|
|
327
|
-
output += `
|
|
328
|
-
Tokens: input=${parsed.usage.input_tokens} output=${parsed.usage.output_tokens}`;
|
|
329
1195
|
if (parsed.sessionId)
|
|
330
1196
|
output += `
|
|
331
1197
|
|
|
332
1198
|
---
|
|
333
1199
|
session: ${parsed.sessionId}`;
|
|
334
|
-
|
|
1200
|
+
if (heuristicWarningSuffix)
|
|
1201
|
+
output += heuristicWarningSuffix;
|
|
1202
|
+
return {
|
|
1203
|
+
text: output,
|
|
1204
|
+
structuredContent: {
|
|
1205
|
+
response: parsed.result,
|
|
1206
|
+
...(_epUsage ? { usage: { input_tokens: _epUsage.input_tokens, output_tokens: _epUsage.output_tokens, total_tokens: _epUsage.input_tokens + _epUsage.output_tokens } } : {}),
|
|
1207
|
+
...(parsed.sessionId ? { sessionId: parsed.sessionId } : {}),
|
|
1208
|
+
...(contextWarning ? { contextWarning } : {}),
|
|
1209
|
+
...(budgetUsage ? { budgetUsage } : {}),
|
|
1210
|
+
},
|
|
1211
|
+
};
|
|
335
1212
|
}
|
|
336
1213
|
catch (err) {
|
|
1214
|
+
// apra-fleet-3c9.1: a confirmed stall aborted the in-flight execCommand (and
|
|
1215
|
+
// NOT the MCP client). Surface it as a typed 'stalled' error so the dispatch
|
|
1216
|
+
// settles here -- well under the client hard timeout -- instead of being
|
|
1217
|
+
// mislabeled dispatch_failed or waiting out the full deadline.
|
|
1218
|
+
if (stallAbortController.signal.aborted && !extra?.signal?.aborted) {
|
|
1219
|
+
_epError = 'dispatch aborted by confirmed stall';
|
|
1220
|
+
return {
|
|
1221
|
+
text: `[FAIL] execute_prompt on "${agent.friendlyName}" was aborted after a confirmed stall -- the remote turn made no progress for the stall threshold, its process was killed, and the in-flight dispatch was cancelled immediately rather than waiting out the client timeout.`,
|
|
1222
|
+
structuredContent: { isError: true, reason: 'stalled' },
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
337
1225
|
// Only mark offline for genuine SSH/network connection failures, not for cancellations
|
|
338
1226
|
_epOffline = !!(err.message && /ssh|network|econnrefused|ehostunreach|connection timed out/i.test(err.message));
|
|
339
1227
|
_epError = err.message;
|
|
340
|
-
return
|
|
1228
|
+
return {
|
|
1229
|
+
text: `[FAIL] Failed to execute prompt on "${agent.friendlyName}": ${err.message}`,
|
|
1230
|
+
structuredContent: { isError: true, reason: 'dispatch_failed' },
|
|
1231
|
+
};
|
|
341
1232
|
}
|
|
342
1233
|
finally {
|
|
343
1234
|
extra?.signal?.removeEventListener('abort', abortHandler);
|
|
@@ -348,14 +1239,14 @@ session: ${parsed.sessionId}`;
|
|
|
348
1239
|
scope.fail(`exit=${_epExitCode}${_epTok}`);
|
|
349
1240
|
else
|
|
350
1241
|
scope.ok(`exit=0${_epTok}`);
|
|
351
|
-
// Skip if stall detector already cleared state
|
|
1242
|
+
// Skip if stall detector already cleared state -- a new execute_prompt may have
|
|
352
1243
|
// claimed inFlightAgents and set busy again; clobbering it here would be wrong.
|
|
353
1244
|
if (!clearedByStall) {
|
|
354
1245
|
writeStatusline(new Map([[agent.id, _epOffline ? 'offline' : 'idle']]));
|
|
355
1246
|
inFlightAgents.delete(agent.id);
|
|
356
1247
|
}
|
|
357
1248
|
stallDetector.remove(agent.id);
|
|
358
|
-
await deletePromptFile(agent, strategy, promptFilePath);
|
|
1249
|
+
await deletePromptFile(agent, strategy, promptFilePath, durablePath ? [durablePath] : []);
|
|
359
1250
|
}
|
|
360
1251
|
}
|
|
361
1252
|
//# sourceMappingURL=execute-prompt.js.map
|