@chankov/agent-fleet 0.0.3 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/commands/setup-agent-fleet.md +1 -1
- package/.opencode/commands/af-setup-agent-fleet.md +1 -1
- package/.pi/harnesses/agent-hub/README.md +199 -16
- package/.pi/harnesses/agent-hub/access-approval.ts +135 -0
- package/.pi/harnesses/agent-hub/delegate.ts +32 -9
- package/.pi/harnesses/agent-hub/drift-watchdog.js +165 -0
- package/.pi/harnesses/agent-hub/footer.ts +29 -0
- package/.pi/harnesses/agent-hub/helpers.ts +49 -0
- package/.pi/harnesses/agent-hub/index.ts +1033 -242
- package/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
- package/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
- package/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
- package/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
- package/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
- package/.pi/harnesses/agent-hub/monitor-session-bridge.ts +11 -0
- package/.pi/harnesses/agent-hub/package.json +5 -4
- package/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
- package/.pi/harnesses/agent-hub/run-budget.js +155 -0
- package/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
- package/.pi/harnesses/agent-hub/spawn.ts +161 -94
- package/.pi/harnesses/agent-hub/version.ts +18 -0
- package/.pi/harnesses/coms/README.md +10 -0
- package/.pi/harnesses/coms/index.ts +2 -0
- package/.pi/harnesses/coms/package.json +5 -4
- package/.pi/harnesses/coms/version.ts +18 -0
- package/.pi/harnesses/damage-control-continue/README.md +32 -31
- package/.pi/harnesses/damage-control-continue/index.ts +23 -9
- package/.pi/harnesses/damage-control-continue/package.json +5 -4
- package/.pi/harnesses/damage-control-continue/version.ts +18 -0
- package/.pi/harnesses/{damage-control/shared.ts → lib/damage-control-shared.ts} +20 -6
- package/.pi/prompts/setup-agent-fleet.md +1 -1
- package/.versions/0.0.4/.claude/commands/build.md +44 -0
- package/.versions/0.0.4/.claude/commands/code-simplify.md +22 -0
- package/.versions/0.0.4/.claude/commands/design-agent.md +14 -0
- package/.versions/0.0.4/.claude/commands/doctor-agent-fleet.md +17 -0
- package/.versions/0.0.4/.claude/commands/orchestrate.md +112 -0
- package/.versions/0.0.4/.claude/commands/plan.md +16 -0
- package/.versions/0.0.4/.claude/commands/prime.md +22 -0
- package/.versions/0.0.4/.claude/commands/review.md +16 -0
- package/.versions/0.0.4/.claude/commands/setup-agent-fleet.md +25 -0
- package/.versions/0.0.4/.claude/commands/ship.md +72 -0
- package/.versions/0.0.4/.claude/commands/spec.md +15 -0
- package/.versions/0.0.4/.claude/commands/test.md +19 -0
- package/.versions/0.0.4/.claude/commands/webperf.md +32 -0
- package/.versions/0.0.4/.claude/orchestrate-teams.yaml +24 -0
- package/.versions/0.0.4/.opencode/commands/af-build.md +17 -0
- package/.versions/0.0.4/.opencode/commands/af-code-simplify.md +16 -0
- package/.versions/0.0.4/.opencode/commands/af-compound.md +16 -0
- package/.versions/0.0.4/.opencode/commands/af-design-agent.md +15 -0
- package/.versions/0.0.4/.opencode/commands/af-doctor-agent-fleet.md +17 -0
- package/.versions/0.0.4/.opencode/commands/af-orchestrate.md +112 -0
- package/.versions/0.0.4/.opencode/commands/af-plan.md +16 -0
- package/.versions/0.0.4/.opencode/commands/af-prime.md +22 -0
- package/.versions/0.0.4/.opencode/commands/af-review.md +15 -0
- package/.versions/0.0.4/.opencode/commands/af-setup-agent-fleet.md +15 -0
- package/.versions/0.0.4/.opencode/commands/af-ship.md +16 -0
- package/.versions/0.0.4/.opencode/commands/af-spec.md +16 -0
- package/.versions/0.0.4/.opencode/commands/af-test.md +21 -0
- package/.versions/0.0.4/.opencode/commands/af-webperf.md +32 -0
- package/.versions/0.0.4/.opencode/orchestrate-teams.yaml +24 -0
- package/.versions/0.0.4/.pi/agents/dispatch-policy.yaml +32 -0
- package/.versions/0.0.4/.pi/agents/model-profiles.yaml +20 -0
- package/.versions/0.0.4/.pi/agents/peers.yaml +146 -0
- package/.versions/0.0.4/.pi/agents/teams.yaml +39 -0
- package/.versions/0.0.4/.pi/damage-control-rules.yaml +297 -0
- package/.versions/0.0.4/.pi/extensions/agent-fleet-update-check/README.md +58 -0
- package/.versions/0.0.4/.pi/extensions/agent-fleet-update-check/index.ts +161 -0
- package/{.pi/harnesses/damage-control → .versions/0.0.4/.pi/extensions/agent-fleet-update-check}/package.json +1 -1
- package/.versions/0.0.4/.pi/extensions/btw/README.md +118 -0
- package/.versions/0.0.4/.pi/extensions/btw/index.ts +917 -0
- package/.versions/0.0.4/.pi/extensions/btw/package.json +6 -0
- package/.versions/0.0.4/.pi/extensions/btw/state.js +179 -0
- package/.versions/0.0.4/.pi/extensions/chrome-devtools-mcp/README.md +58 -0
- package/.versions/0.0.4/.pi/extensions/chrome-devtools-mcp/index.ts +92 -0
- package/.versions/0.0.4/.pi/extensions/chrome-devtools-mcp/package.json +6 -0
- package/.versions/0.0.4/.pi/extensions/compact-and-continue/README.md +42 -0
- package/.versions/0.0.4/.pi/extensions/compact-and-continue/index.ts +120 -0
- package/.versions/0.0.4/.pi/extensions/compact-and-continue/package.json +6 -0
- package/.versions/0.0.4/.pi/extensions/mcp-bridge/README.md +46 -0
- package/.versions/0.0.4/.pi/extensions/mcp-bridge/index.ts +206 -0
- package/.versions/0.0.4/.pi/extensions/mcp-bridge/package.json +6 -0
- package/.versions/0.0.4/.pi/extensions/package-lock.json +1143 -0
- package/.versions/0.0.4/.pi/extensions/package.json +9 -0
- package/.versions/0.0.4/.pi/extensions/pi-voice-stt/README.md +201 -0
- package/.versions/0.0.4/.pi/extensions/pi-voice-stt/config.ts +198 -0
- package/.versions/0.0.4/.pi/extensions/pi-voice-stt/examples/stt.json +35 -0
- package/.versions/0.0.4/.pi/extensions/pi-voice-stt/index.ts +248 -0
- package/.versions/0.0.4/.pi/extensions/pi-voice-stt/package.json +6 -0
- package/.versions/0.0.4/.pi/extensions/pi-voice-stt/providers.ts +214 -0
- package/.versions/0.0.4/.pi/extensions/pi-voice-stt/recorder.ts +158 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/README.md +798 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/access-approval.ts +135 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/artifacts.js +92 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/backend-policy.js +153 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/delegate.ts +386 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/drift-watchdog.js +165 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/evidence-rules.js +96 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/footer.ts +29 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/helpers.ts +214 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/index.ts +8045 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/monitor-control.ts +9 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/monitor-lifecycle.ts +13 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/monitor-publisher.ts +59 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/monitor-recovery.ts +3 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/monitor-runtime.ts +3 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/monitor-session-bridge.ts +11 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/package.json +7 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/research-retention.js +34 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/research-watchdog.ts +40 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/return-contract.js +215 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/run-budget.js +155 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/safety-routing.ts +22 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/scope-gate.js +103 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/spawn.ts +246 -0
- package/.versions/0.0.4/.pi/harnesses/agent-hub/version.ts +18 -0
- package/.versions/0.0.4/.pi/harnesses/ask-user-remote/README.md +18 -0
- package/.versions/0.0.4/.pi/harnesses/ask-user-remote/index.ts +293 -0
- package/.versions/0.0.4/.pi/harnesses/ask-user-remote/race-core.js +106 -0
- package/.versions/0.0.4/.pi/harnesses/coms/README.md +92 -0
- package/.versions/0.0.4/.pi/harnesses/coms/index.ts +1745 -0
- package/.versions/0.0.4/.pi/harnesses/coms/package.json +7 -0
- package/.versions/0.0.4/.pi/harnesses/coms/version.ts +18 -0
- package/.versions/0.0.4/.pi/harnesses/damage-control-continue/README.md +117 -0
- package/.versions/0.0.4/.pi/harnesses/damage-control-continue/index.ts +536 -0
- package/.versions/0.0.4/.pi/harnesses/damage-control-continue/package.json +7 -0
- package/.versions/0.0.4/.pi/harnesses/damage-control-continue/version.ts +18 -0
- package/.versions/0.0.4/.pi/harnesses/lib/damage-control-shared.ts +197 -0
- package/.versions/0.0.4/.pi/harnesses/lib/herdr-client.ts +458 -0
- package/.versions/0.0.4/.pi/harnesses/lib/herdr-presence.ts +288 -0
- package/.versions/0.0.4/.pi/harnesses/package-lock.json +35 -0
- package/.versions/0.0.4/.pi/harnesses/package.json +9 -0
- package/.versions/0.0.4/.pi/prompts/build.md +24 -0
- package/.versions/0.0.4/.pi/prompts/code-simplify.md +22 -0
- package/.versions/0.0.4/.pi/prompts/doctor-agent-fleet.md +15 -0
- package/.versions/0.0.4/.pi/prompts/plan.md +16 -0
- package/.versions/0.0.4/.pi/prompts/review.md +16 -0
- package/.versions/0.0.4/.pi/prompts/setup-agent-fleet.md +27 -0
- package/.versions/0.0.4/.pi/prompts/ship.md +17 -0
- package/.versions/0.0.4/.pi/prompts/spec.md +15 -0
- package/.versions/0.0.4/.pi/prompts/test.md +19 -0
- package/.versions/0.0.4/.pi/skills/bowser/SKILL.md +145 -0
- package/.versions/0.0.4/.version +1 -0
- package/.versions/0.0.4/agents/architect.md +23 -0
- package/.versions/0.0.4/agents/bowser.md +26 -0
- package/.versions/0.0.4/agents/builder.md +53 -0
- package/.versions/0.0.4/agents/code-reviewer.md +205 -0
- package/.versions/0.0.4/agents/deep-researcher.md +31 -0
- package/.versions/0.0.4/agents/documenter.md +18 -0
- package/.versions/0.0.4/agents/orchestrator.md +54 -0
- package/.versions/0.0.4/agents/plan-reviewer.md +60 -0
- package/.versions/0.0.4/agents/planner.md +69 -0
- package/.versions/0.0.4/agents/releaser.md +24 -0
- package/.versions/0.0.4/agents/researcher.md +28 -0
- package/.versions/0.0.4/agents/security-auditor.md +166 -0
- package/.versions/0.0.4/agents/test-engineer.md +151 -0
- package/.versions/0.0.4/agents/web-debugger.md +42 -0
- package/.versions/0.0.4/agents/web-performance-auditor.md +192 -0
- package/.versions/0.0.4/codex/CONDUCTOR.md +148 -0
- package/.versions/0.0.4/docs/ARCHITECTURE.md +210 -0
- package/.versions/0.0.4/docs/agent-fleet-setup.md +366 -0
- package/.versions/0.0.4/docs/claude-code-coms-bridge.md +103 -0
- package/.versions/0.0.4/docs/codex-remote-conductor.md +170 -0
- package/.versions/0.0.4/docs/coms-hermes-bridge.md +121 -0
- package/.versions/0.0.4/docs/getting-started.md +183 -0
- package/.versions/0.0.4/docs/npm-install.md +337 -0
- package/.versions/0.0.4/docs/opencode-setup.md +248 -0
- package/.versions/0.0.4/docs/pi-extensions.md +288 -0
- package/.versions/0.0.4/docs/pi-setup.md +463 -0
- package/.versions/0.0.4/docs/skill-anatomy.md +150 -0
- package/.versions/0.0.4/hermes/README.md +228 -0
- package/.versions/0.0.4/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
- package/.versions/0.0.4/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-cap.test.py +15 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-discovery.test.py +19 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-envelope.test.py +13 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-forged-owner.test.py +11 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-lease-list.test.py +9 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-multihub.test.py +17 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter-output.test.py +34 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +151 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/adapter.test.py +39 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/plugin-api-validation.test.py +12 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
- package/.versions/0.0.4/hermes/plugins/agent-fleet-monitor/dashboard/review-live-wiring.red.test.py +22 -0
- package/.versions/0.0.4/hermes/skills/hub-conductor/SKILL.md +84 -0
- package/.versions/0.0.4/hermes/skills/hub-liaison/SKILL.md +84 -0
- package/.versions/0.0.4/hooks/SIMPLIFY-IGNORE.md +90 -0
- package/.versions/0.0.4/hooks/coms-stop-hook.mjs +73 -0
- package/.versions/0.0.4/hooks/hooks.json +14 -0
- package/.versions/0.0.4/hooks/session-start.sh +74 -0
- package/.versions/0.0.4/hooks/simplify-ignore.sh +302 -0
- package/.versions/0.0.4/justfile +256 -0
- package/.versions/0.0.4/references/accessibility-checklist.md +160 -0
- package/.versions/0.0.4/references/definition-of-done.md +67 -0
- package/.versions/0.0.4/references/fleet-coordination-patterns.md +151 -0
- package/.versions/0.0.4/references/observability-checklist.md +91 -0
- package/.versions/0.0.4/references/orchestration-patterns.md +370 -0
- package/.versions/0.0.4/references/performance-checklist.md +153 -0
- package/.versions/0.0.4/references/prompting-patterns.md +380 -0
- package/.versions/0.0.4/references/security-checklist.md +179 -0
- package/.versions/0.0.4/references/testing-patterns.md +236 -0
- package/.versions/0.0.4/scripts/codex-conductor.ts +41 -0
- package/.versions/0.0.4/scripts/codex-remote-control.ts +167 -0
- package/.versions/0.0.4/scripts/coms-claude-bridge.ts +286 -0
- package/.versions/0.0.4/scripts/coms-cli.ts +484 -0
- package/.versions/0.0.4/scripts/coms-hermes-bridge.ts +403 -0
- package/.versions/0.0.4/scripts/hermes-monitor-capability-runner.ts +25 -0
- package/.versions/0.0.4/scripts/hermes-monitor-scenario.ts +7 -0
- package/.versions/0.0.4/scripts/lib/claude-bridge-core.ts +100 -0
- package/.versions/0.0.4/scripts/lib/codex-conductor.ts +88 -0
- package/.versions/0.0.4/scripts/lib/codex-remote-control.ts +480 -0
- package/.versions/0.0.4/scripts/lib/coms-envelope.ts +539 -0
- package/.versions/0.0.4/scripts/lib/fake-herdr-server.ts +88 -0
- package/.versions/0.0.4/scripts/lib/herdr-layout.ts +263 -0
- package/.versions/0.0.4/scripts/lib/hermes-bridge-core.ts +238 -0
- package/.versions/0.0.4/scripts/lib/hermes-monitor-herdr.ts +28 -0
- package/.versions/0.0.4/scripts/lib/hermes-monitor-model.ts +9 -0
- package/.versions/0.0.4/scripts/lib/hermes-monitor-registry.ts +6 -0
- package/.versions/0.0.4/scripts/lib/hermes-monitor-socket.ts +118 -0
- package/.versions/0.0.4/scripts/lib/hermes-monitor-store.ts +31 -0
- package/.versions/0.0.4/scripts/lib/persona-banner.ts +62 -0
- package/.versions/0.0.4/scripts/lib/spawn-stagger.ts +101 -0
- package/.versions/0.0.4/scripts/lib/team-project.ts +184 -0
- package/.versions/0.0.4/scripts/lib/team-snapshot.ts +147 -0
- package/.versions/0.0.4/scripts/peer-banner.ts +40 -0
- package/.versions/0.0.4/scripts/team-snapshot.ts +238 -0
- package/.versions/0.0.4/scripts/team-up.ts +333 -0
- package/.versions/0.0.4/skills/_internal/grilling.md +11 -0
- package/.versions/0.0.4/skills/browser-testing-with-devtools/SKILL.md +352 -0
- package/.versions/0.0.4/skills/code-review-and-quality/SKILL.md +381 -0
- package/.versions/0.0.4/skills/compound-learning/SKILL.md +137 -0
- package/.versions/0.0.4/skills/context-engineering/SKILL.md +291 -0
- package/.versions/0.0.4/skills/deprecation-and-migration/SKILL.md +206 -0
- package/.versions/0.0.4/skills/designing-agents/SKILL.md +394 -0
- package/.versions/0.0.4/skills/designing-agents/pi-harness-authoring.md +222 -0
- package/.versions/0.0.4/skills/frontend-ui-engineering/SKILL.md +328 -0
- package/.versions/0.0.4/skills/git-workflow-and-versioning/SKILL.md +316 -0
- package/.versions/0.0.4/skills/guided-workspace-setup/SKILL.md +535 -0
- package/.versions/0.0.4/skills/guided-workspace-setup/companion-manifest.json +33 -0
- package/.versions/0.0.4/skills/idea-refine/SKILL.md +182 -0
- package/.versions/0.0.4/skills/idea-refine/examples.md +238 -0
- package/.versions/0.0.4/skills/idea-refine/frameworks.md +99 -0
- package/.versions/0.0.4/skills/idea-refine/refinement-criteria.md +113 -0
- package/.versions/0.0.4/skills/idea-refine/scripts/idea-refine.sh +15 -0
- package/.versions/0.0.4/skills/incremental-implementation/SKILL.md +287 -0
- package/.versions/0.0.4/skills/interview-me/SKILL.md +226 -0
- package/.versions/0.0.4/skills/orchestration-verification/SKILL.md +181 -0
- package/.versions/0.0.4/skills/peer-coms/SKILL.md +90 -0
- package/.versions/0.0.4/skills/performance-optimization/SKILL.md +350 -0
- package/.versions/0.0.4/skills/planning-and-task-breakdown/SKILL.md +236 -0
- package/.versions/0.0.4/skills/security-and-hardening/SKILL.md +461 -0
- package/.versions/0.0.4/skills/spec-driven-development/SKILL.md +245 -0
- package/.versions/0.0.4/skills/using-agent-skills/SKILL.md +199 -0
- package/.versions/0.0.4/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/LICENSE +21 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/README.md +11 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/api-and-interface-design/SKILL.md +294 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/browser-testing-with-devtools/SKILL.md +317 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/ci-cd-and-automation/SKILL.md +390 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/code-review-and-quality/SKILL.md +396 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/code-simplification/SKILL.md +331 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/context-engineering/SKILL.md +289 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/debugging-and-error-recovery/SKILL.md +300 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/deprecation-and-migration/SKILL.md +247 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/documentation-and-adrs/SKILL.md +278 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/doubt-driven-development/SKILL.md +243 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/frontend-ui-engineering/SKILL.md +328 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/git-workflow-and-versioning/SKILL.md +355 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/idea-refine/SKILL.md +178 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/idea-refine/examples.md +238 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/idea-refine/frameworks.md +99 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/idea-refine/refinement-criteria.md +113 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/idea-refine/scripts/idea-refine.sh +15 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/incremental-implementation/SKILL.md +249 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/interview-me/SKILL.md +225 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/observability-and-instrumentation/SKILL.md +203 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/performance-optimization/SKILL.md +350 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/planning-and-task-breakdown/SKILL.md +234 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/security-and-hardening/SKILL.md +467 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/shipping-and-launch/SKILL.md +310 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/source-driven-development/SKILL.md +194 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/spec-driven-development/SKILL.md +206 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/test-driven-development/SKILL.md +383 -0
- package/.versions/0.0.4/vendor/agent-skills-upstream/skills/using-agent-skills/SKILL.md +191 -0
- package/CHANGELOG.md +53 -0
- package/README.md +3 -3
- package/agents/builder.md +1 -1
- package/agents/code-reviewer.md +1 -1
- package/agents/deep-researcher.md +3 -3
- package/agents/orchestrator.md +20 -11
- package/agents/plan-reviewer.md +3 -3
- package/agents/test-engineer.md +11 -4
- package/bin/lib/validate-overrides.js +19 -0
- package/bin/sync-harness-versions.js +94 -0
- package/docs/ARCHITECTURE.md +46 -1
- package/docs/agent-fleet-setup.md +10 -0
- package/docs/pi-extensions.md +49 -14
- package/docs/pi-setup.md +10 -4
- package/hermes/README.md +180 -0
- package/hermes/desktop-plugins/agent-fleet-monitor/plugin.js +19 -0
- package/hermes/desktop-plugins/agent-fleet-monitor/state.js +10 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-cap.test.py +15 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-discovery.test.py +19 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-envelope.test.py +13 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-forged-owner.test.py +11 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-lease-list.test.py +9 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-multihub.test.py +17 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/adapter-output.test.py +34 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/adapter.py +151 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/adapter.test.py +39 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/dist/index.js +10 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/manifest.json +11 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/plugin-api-validation.test.py +12 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/plugin_api.py +50 -0
- package/hermes/plugins/agent-fleet-monitor/dashboard/review-live-wiring.red.test.py +22 -0
- package/justfile +6 -10
- package/package.json +9 -4
- package/scripts/lib/fake-herdr-server.ts +88 -0
- package/scripts/lib/hermes-monitor-herdr.ts +28 -0
- package/scripts/lib/hermes-monitor-model.ts +9 -0
- package/scripts/lib/hermes-monitor-registry.ts +6 -0
- package/scripts/lib/hermes-monitor-socket.ts +118 -0
- package/scripts/lib/hermes-monitor-store.ts +31 -0
- package/skills/designing-agents/SKILL.md +2 -2
- package/skills/designing-agents/pi-harness-authoring.md +26 -13
- package/skills/guided-workspace-setup/SKILL.md +11 -8
- package/.pi/harnesses/damage-control/README.md +0 -65
- package/.pi/harnesses/damage-control/index.ts +0 -250
|
@@ -70,19 +70,32 @@ import {
|
|
|
70
70
|
type AutocompleteItem, truncateToWidth, visibleWidth,
|
|
71
71
|
} from "@mariozechner/pi-tui";
|
|
72
72
|
import { spawn, type ChildProcess } from "child_process";
|
|
73
|
-
import { spawnPiAgent, killPiTree } from "./spawn.ts";
|
|
73
|
+
import { spawnPiAgent, killPiTree, type PiRunControl, type Termination } from "./spawn.ts";
|
|
74
|
+
import { researchTerminationOutcome, researchWatchdogSpawnOptions } from "./research-watchdog.ts";
|
|
75
|
+
import { renderHubFooterLeft } from "./footer.ts";
|
|
76
|
+
import { HARNESS_VERSION, registerVersionStatus } from "./version.ts";
|
|
77
|
+
import { cancelLocalOwnedProcess, cancelLocalWaitOnly, monitorKeyForAgent } from "./monitor-control.ts";
|
|
78
|
+
import { createMonitorLifecycle, monitorLifecycleConfig } from "./monitor-lifecycle.ts";
|
|
79
|
+
import { MonitorRegistry } from "../../../scripts/lib/hermes-monitor-registry.ts";
|
|
80
|
+
import { MonitorStore } from "../../../scripts/lib/hermes-monitor-store.ts";
|
|
81
|
+
import { createMonitorSessionBridge } from "./monitor-session-bridge.ts";
|
|
82
|
+
import { MonitorRuntime } from "./monitor-runtime.ts";
|
|
83
|
+
import { monitorReconcileEvidence, stableMonitorHubId } from "./monitor-recovery.ts";
|
|
74
84
|
import {
|
|
75
85
|
AGENT_ID_ENV, ASK_ENDPOINT_ENV, EXEMPTIONS_FILE_ENV,
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
} from "
|
|
79
|
-
import {
|
|
86
|
+
exemptionsFilePath, type AccessRequest,
|
|
87
|
+
} from "../lib/damage-control-shared.ts";
|
|
88
|
+
import { clampDelegateDepth, DELEGATE_TREE_SPAWN_BUDGET, MAX_DELEGATE_DEPTH, normalizeAgentInput, parseTeamsYaml, safeAgentKey, safePathWithin, taskFingerprint, upsertTeamInYaml } from "./helpers.ts";
|
|
89
|
+
import { DEFAULT_HUB_MODE, DEFAULT_TASK_TIER, HUB_MODES, TASK_TIERS, budgetStatusLine, checkTurnBudget, normalizeHubMode, normalizeTaskTier, resolveTurnBudget, shouldRecycleSession } from "./run-budget.js";
|
|
90
|
+
import { DEFAULT_WATCHDOG_SETTING, WATCHDOG_SETTINGS, buildJudgePrompt, createDriftMonitor, normalizeWatchdogSetting, parseJudgeVerdict, resolveWatchdogActive } from "./drift-watchdog.js";
|
|
80
91
|
import { artifactPreviewFromText, formatInputArtifactsSection, resolveArtifactPaths, ARTIFACT_KINDS } from "./artifacts.js";
|
|
81
92
|
import { crossCheck, extractAssertionIds, parseStructuredReturn } from "./return-contract.js";
|
|
82
93
|
import { checkScope, diffAgainst, snapshotWorktree } from "./scope-gate.js";
|
|
83
94
|
import { validateEvidence } from "./evidence-rules.js";
|
|
84
95
|
import { comsRequiredRefusal, parseDispatchPolicy, resolveDispatchBackend } from "./backend-policy.js";
|
|
85
96
|
import { DEFAULT_RESEARCH_KEEP, parseResearchKeep, selectResearchPrunable } from "./research-retention.js";
|
|
97
|
+
import { requireSafetyHarness, resolveSafetyHarness } from "./safety-routing.ts";
|
|
98
|
+
import { createAccessApprovalRouter } from "./access-approval.ts";
|
|
86
99
|
import { readdirSync, readFileSync, existsSync, mkdirSync, unlinkSync, writeFileSync, rmSync } from "fs";
|
|
87
100
|
import {
|
|
88
101
|
formatPeerStatus,
|
|
@@ -185,6 +198,9 @@ interface AgentState {
|
|
|
185
198
|
contextPct: number;
|
|
186
199
|
sessionFile: string | null;
|
|
187
200
|
runCount: number;
|
|
201
|
+
// Runs served by the CURRENT accumulated session (-c resume chain). Reset on
|
|
202
|
+
// recycle; drives shouldRecycleSession together with the measured contextPct.
|
|
203
|
+
runsSinceFresh: number;
|
|
188
204
|
timer?: ReturnType<typeof setInterval>;
|
|
189
205
|
// Mid-turn delegation (delegate tool). Children parsed live from the event
|
|
190
206
|
// file, keyed by child id; rendered as nested rows under the card and kept
|
|
@@ -385,6 +401,27 @@ function extractNeedsResearch(output: string): string[] {
|
|
|
385
401
|
// to retain for /agents-cont resume (LRU, default 4);
|
|
386
402
|
// "all" disables pruning. Auto-research pipe helpers
|
|
387
403
|
// are always pruned as soon as they finish.
|
|
404
|
+
// recon-search-timeout-s: <1..3600>|off — parent-side deadline for each
|
|
405
|
+
// read/grep/find/ls call made by research helpers
|
|
406
|
+
// and read-only delegate children (default 120).
|
|
407
|
+
// mode: fast|standard|strict — default execution mode (see run-budget.js).
|
|
408
|
+
// fast = single-specialist path, standard = batched
|
|
409
|
+
// work with turn budgets (default), strict = full
|
|
410
|
+
// Verification Contract with wide budgets.
|
|
411
|
+
// max-dispatches-per-turn: <n>|off — dispatch_agent calls allowed per user turn
|
|
412
|
+
// (replaces the mode default; "off" = unlimited).
|
|
413
|
+
// max-research-per-turn: <n>|off — spawn_research calls allowed per user turn.
|
|
414
|
+
// turn-wall-time-s: <n>|off — wall-clock budget per user turn.
|
|
415
|
+
// agent-turn-timeout-s: <n>|off — whole-run deadline for each spawned
|
|
416
|
+
// specialist/research/delegate run (not per tool).
|
|
417
|
+
// session-recycle-runs: <n>|off — recycle a specialist's accumulated session
|
|
418
|
+
// after this many resumed runs (also recycled at
|
|
419
|
+
// ≥60% measured context regardless).
|
|
420
|
+
// watchdog: on|off|auto — drift watchdog default for dispatched
|
|
421
|
+
// specialists (default auto; see drift-watchdog.js).
|
|
422
|
+
// watchdog-judge-model: <model spec> — model for the drift judge (default:
|
|
423
|
+
// the researcher persona's model, else the
|
|
424
|
+
// dispatcher's).
|
|
388
425
|
|
|
389
426
|
interface AgentTeamOverrides {
|
|
390
427
|
language: string;
|
|
@@ -397,6 +434,19 @@ interface AgentTeamOverrides {
|
|
|
397
434
|
rulesDirs: string[];
|
|
398
435
|
docsPaths: string[];
|
|
399
436
|
researchKeep: number;
|
|
437
|
+
reconSearchTimeoutMs: number | null;
|
|
438
|
+
hubMode: string;
|
|
439
|
+
// Per-axis turn-budget overrides for run-budget.js resolveTurnBudget():
|
|
440
|
+
// number replaces the mode default, null = "off", undefined = keep default.
|
|
441
|
+
budgetOverrides: {
|
|
442
|
+
maxDispatches?: number | null;
|
|
443
|
+
maxResearch?: number | null;
|
|
444
|
+
wallMs?: number | null;
|
|
445
|
+
agentTurnMs?: number | null;
|
|
446
|
+
recycleRuns?: number | null;
|
|
447
|
+
};
|
|
448
|
+
watchdogSetting: string;
|
|
449
|
+
watchdogJudgeModel: string | null;
|
|
400
450
|
warnings: string[];
|
|
401
451
|
}
|
|
402
452
|
|
|
@@ -411,6 +461,11 @@ const DEFAULT_OVERRIDES: AgentTeamOverrides = {
|
|
|
411
461
|
rulesDirs: [],
|
|
412
462
|
docsPaths: [],
|
|
413
463
|
researchKeep: DEFAULT_RESEARCH_KEEP,
|
|
464
|
+
reconSearchTimeoutMs: 120_000,
|
|
465
|
+
hubMode: DEFAULT_HUB_MODE,
|
|
466
|
+
budgetOverrides: {},
|
|
467
|
+
watchdogSetting: DEFAULT_WATCHDOG_SETTING,
|
|
468
|
+
watchdogJudgeModel: null,
|
|
414
469
|
warnings: [],
|
|
415
470
|
};
|
|
416
471
|
|
|
@@ -424,6 +479,7 @@ function freshOverrides(): AgentTeamOverrides {
|
|
|
424
479
|
personaDelegateDepth: {},
|
|
425
480
|
rulesDirs: [],
|
|
426
481
|
docsPaths: [],
|
|
482
|
+
budgetOverrides: {},
|
|
427
483
|
warnings: [],
|
|
428
484
|
};
|
|
429
485
|
}
|
|
@@ -470,6 +526,51 @@ function parseAgentTeamOverrides(cwd: string): AgentTeamOverrides {
|
|
|
470
526
|
result.warnings.push(`research-keep "${value}" is not a non-negative integer or "all" — using the default (${DEFAULT_RESEARCH_KEEP})`);
|
|
471
527
|
}
|
|
472
528
|
}
|
|
529
|
+
if (key === "recon-search-timeout-s" && value) {
|
|
530
|
+
if (value.toLowerCase() === "off") {
|
|
531
|
+
result.reconSearchTimeoutMs = null;
|
|
532
|
+
} else if (/^\d+$/.test(value) && Number(value) >= 1 && Number(value) <= 3600) {
|
|
533
|
+
result.reconSearchTimeoutMs = Number(value) * 1000;
|
|
534
|
+
} else {
|
|
535
|
+
result.warnings.push(`recon-search-timeout-s "${value}" is not an integer from 1 to 3600 or "off" — using the default (120)`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
if (key === "mode" && value) {
|
|
539
|
+
const mode = normalizeHubMode(value);
|
|
540
|
+
if (mode) {
|
|
541
|
+
result.hubMode = mode;
|
|
542
|
+
} else {
|
|
543
|
+
result.warnings.push(`mode "${value}" is not one of ${HUB_MODES.join("|")} — using the default (${DEFAULT_HUB_MODE})`);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
if (key === "watchdog" && value) {
|
|
547
|
+
const setting = normalizeWatchdogSetting(value);
|
|
548
|
+
if (setting) {
|
|
549
|
+
result.watchdogSetting = setting;
|
|
550
|
+
} else {
|
|
551
|
+
result.warnings.push(`watchdog "${value}" is not one of ${WATCHDOG_SETTINGS.join("|")} — using the default (${DEFAULT_WATCHDOG_SETTING})`);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
if (key === "watchdog-judge-model" && value) result.watchdogJudgeModel = value;
|
|
555
|
+
// Turn-budget keys: a positive integer replaces the mode default, "off"
|
|
556
|
+
// disables the axis. Counts are unitless; *-s keys are seconds → ms.
|
|
557
|
+
const budgetKeys: Record<string, { field: keyof AgentTeamOverrides["budgetOverrides"]; scaleMs: boolean }> = {
|
|
558
|
+
"max-dispatches-per-turn": { field: "maxDispatches", scaleMs: false },
|
|
559
|
+
"max-research-per-turn": { field: "maxResearch", scaleMs: false },
|
|
560
|
+
"turn-wall-time-s": { field: "wallMs", scaleMs: true },
|
|
561
|
+
"agent-turn-timeout-s": { field: "agentTurnMs", scaleMs: true },
|
|
562
|
+
"session-recycle-runs": { field: "recycleRuns", scaleMs: false },
|
|
563
|
+
};
|
|
564
|
+
if (budgetKeys[key] && value) {
|
|
565
|
+
const { field, scaleMs } = budgetKeys[key];
|
|
566
|
+
if (value.toLowerCase() === "off") {
|
|
567
|
+
result.budgetOverrides[field] = null;
|
|
568
|
+
} else if (/^\d+$/.test(value) && Number(value) >= 1) {
|
|
569
|
+
result.budgetOverrides[field] = Number(value) * (scaleMs ? 1000 : 1);
|
|
570
|
+
} else {
|
|
571
|
+
result.warnings.push(`${key} "${value}" is not a positive integer or "off" — using the ${result.hubMode} mode default`);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
473
574
|
const slug = "[a-z0-9]+(?:-[a-z0-9]+)*";
|
|
474
575
|
const modelKey = key.match(new RegExp(`^model\\.(${slug})$`));
|
|
475
576
|
if (modelKey && value) result.personaModels[modelKey[1]] = value;
|
|
@@ -1136,45 +1237,9 @@ function scanAgentDirs(cwd: string): AgentDef[] {
|
|
|
1136
1237
|
return agents;
|
|
1137
1238
|
}
|
|
1138
1239
|
|
|
1139
|
-
//
|
|
1140
|
-
// Order: (1) the exact `-e` path this session was launched with (mirrors `just hub`,
|
|
1141
|
-
// robust to symlinks / consuming projects), (2) the repo-local harness under cwd.
|
|
1142
|
-
// `dirName` selects the variant: "damage-control" (hard-stop, aborts the turn) or
|
|
1143
|
-
// "damage-control-continue" (delivers feedback and keeps going). The dir-name regex
|
|
1144
|
-
// is anchored on the trailing slash so "damage-control" never matches the longer
|
|
1145
|
-
// "damage-control-continue/index.ts" path (and vice-versa). Returns an absolute
|
|
1146
|
-
// path, or null if that variant isn't present.
|
|
1147
|
-
function resolveDamageControlVariant(cwd: string, dirName: string): string | null {
|
|
1148
|
-
const argv = process.argv;
|
|
1149
|
-
const re = new RegExp(`${dirName}[/\\\\]index\\.ts$`);
|
|
1150
|
-
for (let i = 0; i < argv.length - 1; i++) {
|
|
1151
|
-
if (argv[i] === "-e" || argv[i] === "--extension") {
|
|
1152
|
-
const abs = resolve(argv[i + 1]);
|
|
1153
|
-
if (re.test(abs) && existsSync(abs)) return abs;
|
|
1154
|
-
}
|
|
1155
|
-
}
|
|
1156
|
-
const local = join(cwd, ".pi", "harnesses", dirName, "index.ts");
|
|
1157
|
-
return existsSync(local) ? local : null;
|
|
1158
|
-
}
|
|
1159
|
-
|
|
1160
|
-
// Persona names (lowercased) that read-only-research, so they get the continue
|
|
1161
|
-
// damage-control variant instead of the hard-stop one when dispatched directly.
|
|
1240
|
+
// Persona names whose read-only tools receive the research watchdog policy.
|
|
1162
1241
|
const RESEARCHER_PERSONAS = new Set(["researcher", "deep-researcher"]);
|
|
1163
1242
|
|
|
1164
|
-
// The hard-stop guardrail (aborts the turn) loaded into specialists that aren't
|
|
1165
|
-
// research helpers. Null → those subagents spawn unguarded, exactly as before.
|
|
1166
|
-
function resolveDamageControlExtension(cwd: string): string | null {
|
|
1167
|
-
return resolveDamageControlVariant(cwd, "damage-control");
|
|
1168
|
-
}
|
|
1169
|
-
|
|
1170
|
-
// The continue guardrail (blocks but feeds back, no abort) used for the
|
|
1171
|
-
// orchestrator/dispatcher main session and spawned research helpers. Falls back
|
|
1172
|
-
// to the hard-stop variant when continue isn't installed, so researchers stay
|
|
1173
|
-
// guarded either way.
|
|
1174
|
-
function resolveDamageControlContinueExtension(cwd: string): string | null {
|
|
1175
|
-
return resolveDamageControlVariant(cwd, "damage-control-continue") ?? resolveDamageControlExtension(cwd);
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
1243
|
// The delegate extension injected into specialists that declare `subagents:`.
|
|
1179
1244
|
// It lives next to this file; fall back to the conventional project path when
|
|
1180
1245
|
// import.meta resolution doesn't map to a real file (e.g. a bundling loader).
|
|
@@ -1709,6 +1774,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
1709
1774
|
const pendingReplies: Map<string, PendingReply> = new Map();
|
|
1710
1775
|
const inboundQueue: Map<string, InboundContext> = new Map();
|
|
1711
1776
|
let server: net.Server | null = null;
|
|
1777
|
+
let monitorLifecycle: ReturnType<typeof createMonitorLifecycle> | null = null;
|
|
1778
|
+
let monitorHubId: string | null = null;
|
|
1779
|
+
let monitorBridge: ReturnType<typeof createMonitorSessionBridge> | null = null;
|
|
1712
1780
|
let pingTimer: NodeJS.Timeout | null = null;
|
|
1713
1781
|
let keepaliveTimer: NodeJS.Timeout | null = null;
|
|
1714
1782
|
// herdr presence backend (active when this session runs inside a herdr
|
|
@@ -1737,12 +1805,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
1737
1805
|
// escalations land here, and spawned children read it through the
|
|
1738
1806
|
// AGENT_HUB_EXEMPTIONS_FILE env plumbing.
|
|
1739
1807
|
let exemptionsFile: string | null = null;
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1808
|
+
const accessApprovalRouter = createAccessApprovalRouter({
|
|
1809
|
+
getContext: () => currentCtx,
|
|
1810
|
+
getExemptionsFile: () => exemptionsFile,
|
|
1811
|
+
appendLog: (entry) => { try { pi.appendEntry("damage-control-log", entry); } catch { /* best-effort */ } },
|
|
1812
|
+
now: nowIso,
|
|
1813
|
+
});
|
|
1746
1814
|
|
|
1747
1815
|
const agentStates: Map<string, AgentState> = new Map();
|
|
1748
1816
|
// Read-only research helpers (Phase 4), keyed by numeric id (handle `rN`). Lives
|
|
@@ -1927,17 +1995,61 @@ than bulk-reading doc trees; when an entry point is a folder, start from its REA
|
|
|
1927
1995
|
or index file. If your work changes something the docs describe (architecture, public
|
|
1928
1996
|
APIs, commands, structure), say so in your final response so the docs can be updated.`;
|
|
1929
1997
|
}
|
|
1930
|
-
//
|
|
1931
|
-
//
|
|
1932
|
-
let
|
|
1933
|
-
// The continue variant (blocks but feeds back instead of aborting), loaded into
|
|
1934
|
-
// spawned research helpers (researcher / deep-researcher) so a blocked read lets
|
|
1935
|
-
// them adapt and keep going rather than dead-end the turn. The orchestrator/
|
|
1936
|
-
// dispatcher main session loads it via the `just hub` recipe.
|
|
1937
|
-
let damageControlContinueExtPath: string | null = null;
|
|
1998
|
+
// The one supported safety harness. Every native specialist, researcher, and
|
|
1999
|
+
// nested delegate receives it; a missing harness refuses child dispatch.
|
|
2000
|
+
let safetyHarnessPath: string | null = null;
|
|
1938
2001
|
// Resolved once at session_start: the delegate extension injected into
|
|
1939
2002
|
// specialists that declare `subagents:` (null → delegation disabled).
|
|
1940
2003
|
let delegateExtPath: string | null = null;
|
|
2004
|
+
// Per-tool deadline for read/grep/find/ls in research helpers/delegates. The
|
|
2005
|
+
// whole-run bound is separate: the turn budget's agentTurnMs (run-budget.js).
|
|
2006
|
+
let reconSearchTimeoutMs: number | null = 120_000;
|
|
2007
|
+
// ── Execution mode & per-turn budgets (run-budget.js) ──
|
|
2008
|
+
// hubMode: overrides-file default, switchable live via /hub-mode (session-
|
|
2009
|
+
// lifetime). Budgets are per USER TURN: counters reset in before_agent_start,
|
|
2010
|
+
// so exhaustion means "stop, summarize, ask" and the next user message opens
|
|
2011
|
+
// a fresh window. currentTurnStartedAt (above) doubles as the wall-clock base.
|
|
2012
|
+
let hubMode: string = DEFAULT_HUB_MODE;
|
|
2013
|
+
let budgetOverrides: AgentTeamOverrides["budgetOverrides"] = {};
|
|
2014
|
+
let turnDispatchCount = 0;
|
|
2015
|
+
let turnResearchCount = 0;
|
|
2016
|
+
// Task tier (complexity triage): declared by the dispatcher via set_task_tier,
|
|
2017
|
+
// reset each user turn. Null until declared; the first dispatch of a turn
|
|
2018
|
+
// assumes DEFAULT_TASK_TIER outside strict mode. Caps = min(mode, tier).
|
|
2019
|
+
let turnTaskTier: string | null = null;
|
|
2020
|
+
// Duplicate-dispatch guard: fingerprints of (agent, task) already dispatched
|
|
2021
|
+
// THIS turn. Auto-research resumes and /agents-restart call dispatchAgent
|
|
2022
|
+
// directly, so only real dispatcher tool calls are guarded.
|
|
2023
|
+
const turnDispatchFingerprints = new Set<string>();
|
|
2024
|
+
// ── Drift watchdog (drift-watchdog.js) ──
|
|
2025
|
+
// Hub-wide setting from the overrides file, live-switchable via /watchdog;
|
|
2026
|
+
// per-agent overrides ("on"/"off") win over it; a dispatch_agent `watchdog`
|
|
2027
|
+
// param wins over both.
|
|
2028
|
+
let watchdogSetting: string = DEFAULT_WATCHDOG_SETTING;
|
|
2029
|
+
let watchdogJudgeModel: string | null = null;
|
|
2030
|
+
const watchdogAgentOverrides = new Map<string, "on" | "off">();
|
|
2031
|
+
function currentBudget() {
|
|
2032
|
+
return resolveTurnBudget(hubMode, budgetOverrides, turnTaskTier);
|
|
2033
|
+
}
|
|
2034
|
+
function updateModeStatus() {
|
|
2035
|
+
try {
|
|
2036
|
+
widgetCtx?.ui?.setStatus("hub-mode", budgetStatusLine(hubMode, { dispatches: turnDispatchCount, research: turnResearchCount }, currentBudget(), turnTaskTier));
|
|
2037
|
+
} catch {}
|
|
2038
|
+
}
|
|
2039
|
+
// ── Per-turn cost report (/hub-report) ──
|
|
2040
|
+
interface TurnReport {
|
|
2041
|
+
startedAt: number;
|
|
2042
|
+
tier: string | null;
|
|
2043
|
+
dispatches: { agent: string; status: string; elapsed: number; billed: number; out: number }[];
|
|
2044
|
+
research: number;
|
|
2045
|
+
recycles: number;
|
|
2046
|
+
driftStops: number;
|
|
2047
|
+
refusals: number;
|
|
2048
|
+
}
|
|
2049
|
+
const freshTurnReport = (): TurnReport => ({ startedAt: Date.now(), tier: null, dispatches: [], research: 0, recycles: 0, driftStops: 0, refusals: 0 });
|
|
2050
|
+
let turnReport: TurnReport = freshTurnReport();
|
|
2051
|
+
let lastTurnReport: TurnReport | null = null;
|
|
2052
|
+
const sessionTotals = { turns: 0, dispatches: 0, research: 0, recycles: 0, driftStops: 0, refusals: 0, billed: 0, out: 0 };
|
|
1941
2053
|
// Session-wide delegated-spend counter (tokens across all delegate children),
|
|
1942
2054
|
// surfaced in the status line. Resets on session_start.
|
|
1943
2055
|
let delegatedTokens = 0;
|
|
@@ -2264,6 +2376,30 @@ APIs, commands, structure), say so in your final response so the docs can be upd
|
|
|
2264
2376
|
}
|
|
2265
2377
|
}
|
|
2266
2378
|
|
|
2379
|
+
function freshAgentState(def: AgentDef): AgentState {
|
|
2380
|
+
const key = safeAgentKey(def.name);
|
|
2381
|
+
const sessionFile = safePathWithin(sessionDir, `${key}.json`);
|
|
2382
|
+
return {
|
|
2383
|
+
def,
|
|
2384
|
+
status: "idle",
|
|
2385
|
+
task: "",
|
|
2386
|
+
toolCount: 0,
|
|
2387
|
+
elapsed: 0,
|
|
2388
|
+
lastWork: "",
|
|
2389
|
+
contextPct: 0,
|
|
2390
|
+
sessionFile: existsSync(sessionFile) ? sessionFile : null,
|
|
2391
|
+
runCount: 0,
|
|
2392
|
+
runsSinceFresh: 0,
|
|
2393
|
+
timeline: [],
|
|
2394
|
+
};
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2397
|
+
// Auto-size grid columns based on team size
|
|
2398
|
+
function recomputeGrid() {
|
|
2399
|
+
const size = agentStates.size;
|
|
2400
|
+
gridCols = size <= 3 ? size : size === 4 ? 2 : 3;
|
|
2401
|
+
}
|
|
2402
|
+
|
|
2267
2403
|
function activateTeam(teamName: string) {
|
|
2268
2404
|
activeTeamName = teamName;
|
|
2269
2405
|
const members = teams[teamName] || [];
|
|
@@ -2274,25 +2410,47 @@ APIs, commands, structure), say so in your final response so the docs can be upd
|
|
|
2274
2410
|
for (const member of members) {
|
|
2275
2411
|
const def = defsByName.get(member.toLowerCase());
|
|
2276
2412
|
if (!def) continue;
|
|
2277
|
-
|
|
2278
|
-
const sessionFile = safePathWithin(sessionDir, `${key}.json`);
|
|
2279
|
-
agentStates.set(def.name.toLowerCase(), {
|
|
2280
|
-
def,
|
|
2281
|
-
status: "idle",
|
|
2282
|
-
task: "",
|
|
2283
|
-
toolCount: 0,
|
|
2284
|
-
elapsed: 0,
|
|
2285
|
-
lastWork: "",
|
|
2286
|
-
contextPct: 0,
|
|
2287
|
-
sessionFile: existsSync(sessionFile) ? sessionFile : null,
|
|
2288
|
-
runCount: 0,
|
|
2289
|
-
timeline: [],
|
|
2290
|
-
});
|
|
2413
|
+
agentStates.set(def.name.toLowerCase(), freshAgentState(def));
|
|
2291
2414
|
}
|
|
2415
|
+
recomputeGrid();
|
|
2416
|
+
}
|
|
2292
2417
|
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2418
|
+
// ── Dynamic roster (add/drop/save; /agents-add, /agents-drop, team_adjust) ──
|
|
2419
|
+
// The system prompt is rebuilt every turn from agentStates, so a roster
|
|
2420
|
+
// change takes effect on the dispatcher's next turn with no restart.
|
|
2421
|
+
|
|
2422
|
+
function rosterAdd(name: string): { ok: boolean; message: string } {
|
|
2423
|
+
const key = normalizeAgentInput(name);
|
|
2424
|
+
const def = allAgentDefs.find(d => d.name.toLowerCase() === key);
|
|
2425
|
+
if (!def) {
|
|
2426
|
+
const available = allAgentDefs.map(d => d.name).sort().join(", ") || "(none)";
|
|
2427
|
+
return { ok: false, message: `No persona "${name}". Available: ${available}` };
|
|
2428
|
+
}
|
|
2429
|
+
if (agentStates.has(def.name.toLowerCase())) {
|
|
2430
|
+
return { ok: false, message: `${displayName(def.name)} is already in the active team` };
|
|
2431
|
+
}
|
|
2432
|
+
agentStates.set(def.name.toLowerCase(), freshAgentState(def));
|
|
2433
|
+
recomputeGrid();
|
|
2434
|
+
updateWidget();
|
|
2435
|
+
return { ok: true, message: `${displayName(def.name)} added to the active team` };
|
|
2436
|
+
}
|
|
2437
|
+
|
|
2438
|
+
function rosterDrop(name: string): { ok: boolean; message: string } {
|
|
2439
|
+
const key = normalizeAgentInput(name);
|
|
2440
|
+
const state = agentStates.get(key);
|
|
2441
|
+
if (!state) {
|
|
2442
|
+
return { ok: false, message: `"${name}" is not in the active team (${Array.from(agentStates.values()).map(s => s.def.name).join(", ") || "empty"})` };
|
|
2443
|
+
}
|
|
2444
|
+
if (state.status === "running") {
|
|
2445
|
+
return { ok: false, message: `${displayName(state.def.name)} is running — wait for it to finish or /agents-kill it first` };
|
|
2446
|
+
}
|
|
2447
|
+
if (agentStates.size <= 1) {
|
|
2448
|
+
return { ok: false, message: `${displayName(state.def.name)} is the last team member — add a replacement before dropping it` };
|
|
2449
|
+
}
|
|
2450
|
+
agentStates.delete(key);
|
|
2451
|
+
recomputeGrid();
|
|
2452
|
+
updateWidget();
|
|
2453
|
+
return { ok: true, message: `${displayName(state.def.name)} dropped from the active team (its session file is kept for re-adding)` };
|
|
2296
2454
|
}
|
|
2297
2455
|
|
|
2298
2456
|
// ── Grid Rendering ───────────────────────────
|
|
@@ -2974,14 +3132,49 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
|
|
|
2974
3132
|
};
|
|
2975
3133
|
}
|
|
2976
3134
|
|
|
3135
|
+
// One-shot drift judge (drift-watchdog.js layer 2): a cheap model reads the
|
|
3136
|
+
// original task + recent tool trail and answers ON_TRACK/DRIFTING/STUCK. It
|
|
3137
|
+
// runs WHILE the specialist keeps working; only a negative verdict stops the
|
|
3138
|
+
// run. Judge failures fail open — a broken judge must never kill good work.
|
|
3139
|
+
async function runDriftJudge(
|
|
3140
|
+
input: { agentLabel: string; agentKey: string; task: string; scopeGlobs: string[]; trail: string[]; violation: { rule: string; detail: string } },
|
|
3141
|
+
ctx: any,
|
|
3142
|
+
): Promise<{ verdict: string; reason: string } | null> {
|
|
3143
|
+
const researcherDef = allAgentDefs.find(d => d.name.toLowerCase() === "researcher");
|
|
3144
|
+
const model = watchdogJudgeModel
|
|
3145
|
+
?? (researcherDef ? resolvedModel(researcherDef) : null)
|
|
3146
|
+
?? (ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : "openrouter/google/gemini-3-flash-preview");
|
|
3147
|
+
const judgeSession = safePathWithin(sessionDir, `drift-judge-${input.agentKey}.json`);
|
|
3148
|
+
try { unlinkSync(judgeSession); } catch {}
|
|
3149
|
+
try {
|
|
3150
|
+
const res = await spawnPiAgent({
|
|
3151
|
+
model,
|
|
3152
|
+
tools: "read",
|
|
3153
|
+
thinking: "off",
|
|
3154
|
+
appendSystemPrompt: "You are a strict, terse runtime watchdog. Answer with exactly one VERDICT line.",
|
|
3155
|
+
sessionFile: judgeSession,
|
|
3156
|
+
prompt: buildJudgePrompt({ agent: input.agentLabel, task: input.task, scopeGlobs: input.scopeGlobs, trail: input.trail, violation: input.violation }),
|
|
3157
|
+
detached: true,
|
|
3158
|
+
turnDeadlineMs: 60_000,
|
|
3159
|
+
});
|
|
3160
|
+
if (res.spawnError || res.exitCode !== 0) return null;
|
|
3161
|
+
return parseJudgeVerdict(res.output);
|
|
3162
|
+
} catch {
|
|
3163
|
+
return null;
|
|
3164
|
+
} finally {
|
|
3165
|
+
try { unlinkSync(judgeSession); } catch {}
|
|
3166
|
+
}
|
|
3167
|
+
}
|
|
3168
|
+
|
|
2977
3169
|
async function dispatchAgent(
|
|
2978
3170
|
agentName: string,
|
|
2979
3171
|
task: string,
|
|
2980
3172
|
ctx: any,
|
|
2981
3173
|
inputArtifacts: InputArtifactPreview[] = [],
|
|
2982
3174
|
scopeGlobs: string[] = [],
|
|
2983
|
-
|
|
2984
|
-
|
|
3175
|
+
watchdogParam?: boolean,
|
|
3176
|
+
): Promise<{ output: string; exitCode: number; elapsed: number; billed?: number; out?: number }> {
|
|
3177
|
+
const key = normalizeAgentInput(agentName);
|
|
2985
3178
|
const state = agentStates.get(key);
|
|
2986
3179
|
if (!state) {
|
|
2987
3180
|
return Promise.resolve({
|
|
@@ -3015,7 +3208,10 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
|
|
|
3015
3208
|
|
|
3016
3209
|
const histEntry = historyStart("agent", displayName(state.def.name));
|
|
3017
3210
|
state.histEntry = histEntry;
|
|
3018
|
-
|
|
3211
|
+
const agentKey = safeAgentKey(state.def.name);
|
|
3212
|
+
const runNumber = state.runCount;
|
|
3213
|
+
const monitorKey = monitorKeyForAgent(state.def.name, state.runCount);
|
|
3214
|
+
const monitorStart = monitorBridge?.startChild({ key: monitorKey, id: `run-${agentKey}-${state.runCount}`, generation: 1, parentId: `hub-turn-${monitorHubId}`, specialist: agentKey }, process.env);
|
|
3019
3215
|
const startTime = Date.now();
|
|
3020
3216
|
state.timer = setInterval(() => {
|
|
3021
3217
|
state.elapsed = Date.now() - startTime;
|
|
@@ -3028,7 +3224,8 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
|
|
|
3028
3224
|
// at any point. A coms-preferring member with a live same-name pool peer
|
|
3029
3225
|
// is served by that peer; everything downstream (return contract, ASK_USER,
|
|
3030
3226
|
// research pipe, history) consumes the same result shape either way.
|
|
3031
|
-
const finishRun = (output: string, exitCode: number, opts?: { idle?: boolean; notice?: string }) => {
|
|
3227
|
+
const finishRun = async (output: string, exitCode: number, opts?: { idle?: boolean; notice?: string }) => {
|
|
3228
|
+
await monitorStart?.then(task => monitorBridge?.finalizeChildFor(task, output, exitCode === 0 ? "completed" : "failed"));
|
|
3032
3229
|
clearInterval(state.timer);
|
|
3033
3230
|
state.elapsed = Date.now() - startTime;
|
|
3034
3231
|
state.status = opts?.idle ? "idle" : exitCode === 0 ? "done" : "error";
|
|
@@ -3069,6 +3266,7 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
|
|
|
3069
3266
|
ctx.ui.notify(route.comsMissedNotice, "warning");
|
|
3070
3267
|
}
|
|
3071
3268
|
if (route.backend === "coms") {
|
|
3269
|
+
void monitorBridge?.registerWaitOnly(monitorKey, () => state.comsAbort?.());
|
|
3072
3270
|
const allowNativeFallback = (dispatchPolicy.substitutions[personaKey]?.fallback ?? "native") !== "none";
|
|
3073
3271
|
const timeoutMs = route.timeout_s ? route.timeout_s * 1000 : TIMEOUT_MS;
|
|
3074
3272
|
const comsRes = await dispatchViaComs(state, task, route.peerName, timeoutMs, allowNativeFallback, ctx, inputArtifacts, scopeGlobs);
|
|
@@ -3095,10 +3293,26 @@ You are serving a dispatched task as a standing peer; the dispatcher only receiv
|
|
|
3095
3293
|
: "openrouter/google/gemini-3-flash-preview");
|
|
3096
3294
|
|
|
3097
3295
|
// Session file for this agent
|
|
3098
|
-
const agentKey = safeAgentKey(state.def.name);
|
|
3099
|
-
const runNumber = state.runCount;
|
|
3100
3296
|
const agentSessionFile = safePathWithin(sessionDir, `${agentKey}.json`);
|
|
3101
3297
|
|
|
3298
|
+
// Session recycling: resuming an accumulated session re-bills its whole
|
|
3299
|
+
// context on every model call, and that — not output — is where degraded
|
|
3300
|
+
// sessions burned their tokens (85M of 102M observed tokens were cache
|
|
3301
|
+
// reads). Past the run/context threshold, start fresh: the task text plus
|
|
3302
|
+
// artifact paths must carry the state (they should anyway).
|
|
3303
|
+
const turnBudget = currentBudget();
|
|
3304
|
+
let sessionRecycled = false;
|
|
3305
|
+
if (state.sessionFile && shouldRecycleSession(state.runsSinceFresh, state.contextPct, turnBudget)) {
|
|
3306
|
+
try { unlinkSync(agentSessionFile); } catch {}
|
|
3307
|
+
state.sessionFile = null;
|
|
3308
|
+
state.runsSinceFresh = 0;
|
|
3309
|
+
state.contextPct = 0;
|
|
3310
|
+
sessionRecycled = true;
|
|
3311
|
+
turnReport.recycles++;
|
|
3312
|
+
sessionTotals.recycles++;
|
|
3313
|
+
ctx.ui.notify(`${displayName(state.def.name)}: session recycled (stale context) — starting fresh`, "info");
|
|
3314
|
+
}
|
|
3315
|
+
|
|
3102
3316
|
// Clarification protocol — every specialist learns to bubble up questions
|
|
3103
3317
|
// to the dispatcher instead of guessing.
|
|
3104
3318
|
const clarificationProtocol = `
|
|
@@ -3149,15 +3363,11 @@ for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked
|
|
|
3149
3363
|
return [role, override ? { ...r, model: override } : r];
|
|
3150
3364
|
}))
|
|
3151
3365
|
: null;
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
const dispatchDamageControl = RESEARCHER_PERSONAS.has(personaKey)
|
|
3158
|
-
? damageControlContinueExtPath
|
|
3159
|
-
: damageControlExtPath;
|
|
3160
|
-
const extensions = dispatchDamageControl ? [dispatchDamageControl] : [];
|
|
3366
|
+
// Fast mode is a single-specialist path: no nested delegation trees.
|
|
3367
|
+
const delegationActive = turnBudget.delegation && !!subagentRoles && !!delegateExtPath;
|
|
3368
|
+
const safety = requireSafetyHarness(safetyHarnessPath);
|
|
3369
|
+
if (!safety.ok) return finishRun(safety.error, 1);
|
|
3370
|
+
const extensions = [...safety.extensions];
|
|
3161
3371
|
let effectiveTools = state.def.tools;
|
|
3162
3372
|
let delegateEnv: Record<string, string> | undefined;
|
|
3163
3373
|
let delegationProtocol = "";
|
|
@@ -3178,8 +3388,10 @@ for decisions a human must make; use NEEDS_RESEARCH for facts that can be looked
|
|
|
3178
3388
|
parentTools: state.def.tools,
|
|
3179
3389
|
personaPrompt: state.def.systemPrompt,
|
|
3180
3390
|
eventDir: delegationDir,
|
|
3181
|
-
damageControl:
|
|
3391
|
+
damageControl: safetyHarnessPath || undefined,
|
|
3182
3392
|
delegateExt: delegateExtPath,
|
|
3393
|
+
reconSearchTimeoutMs,
|
|
3394
|
+
turnDeadlineMs: turnBudget.agentTurnMs,
|
|
3183
3395
|
cwd: ctx.cwd || process.cwd(),
|
|
3184
3396
|
}),
|
|
3185
3397
|
};
|
|
@@ -3210,11 +3422,37 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3210
3422
|
const thinkingLevel = resolveThinkingLevel(resolvedThinking(state.def));
|
|
3211
3423
|
const wantThinking = thinkingLevel !== "off";
|
|
3212
3424
|
|
|
3425
|
+
// ── Drift watchdog: layer-1 rules on the live stream, judge on escalation ──
|
|
3426
|
+
// Precedence: dispatch param > per-agent /watchdog override > hub setting.
|
|
3427
|
+
const watchdogArmed = resolveWatchdogActive(watchdogParam, watchdogAgentOverrides.get(key), watchdogSetting);
|
|
3428
|
+
const driftMonitor = watchdogArmed ? createDriftMonitor({ scopeGlobs }) : null;
|
|
3429
|
+
let driftControl: PiRunControl | undefined;
|
|
3430
|
+
let driftStop: { rule: string; detail: string; verdict: string; reason: string } | null = null;
|
|
3431
|
+
let judgeBusy = false;
|
|
3432
|
+
let judgeCooldownUntil = 0;
|
|
3433
|
+
const escalateDrift = (violation: { rule: string; detail: string }) => {
|
|
3434
|
+
if (!driftMonitor || judgeBusy || driftStop || Date.now() < judgeCooldownUntil) return;
|
|
3435
|
+
judgeBusy = true;
|
|
3436
|
+
void runDriftJudge(
|
|
3437
|
+
{ agentLabel: displayName(state.def.name), agentKey, task, scopeGlobs, trail: driftMonitor.trail(), violation },
|
|
3438
|
+
ctx,
|
|
3439
|
+
).then(v => {
|
|
3440
|
+
judgeBusy = false;
|
|
3441
|
+
judgeCooldownUntil = Date.now() + 90_000;
|
|
3442
|
+
if (v && (v.verdict === "drifting" || v.verdict === "stuck")) {
|
|
3443
|
+
driftStop = { ...violation, verdict: v.verdict, reason: v.reason };
|
|
3444
|
+
driftControl?.terminate("drift_stop");
|
|
3445
|
+
}
|
|
3446
|
+
}).catch(() => { judgeBusy = false; });
|
|
3447
|
+
};
|
|
3448
|
+
|
|
3213
3449
|
// Spawn via the shared helper — first run creates the session, subsequent
|
|
3214
3450
|
// runs resume it (-c). Stream events drive the card + zoom timeline.
|
|
3215
3451
|
// `detached` puts the specialist in its own process group so /agents-kill
|
|
3216
3452
|
// can SIGTERM the whole delegation tree (killPiTree).
|
|
3217
3453
|
let fullText = "";
|
|
3454
|
+
let runBilled = 0;
|
|
3455
|
+
let runOut = 0;
|
|
3218
3456
|
const res = await spawnPiAgent({
|
|
3219
3457
|
model,
|
|
3220
3458
|
tools: effectiveTools,
|
|
@@ -3226,9 +3464,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3226
3464
|
extensions,
|
|
3227
3465
|
env: { ...guardrailEnv(agentKey), ...(delegateEnv || {}) },
|
|
3228
3466
|
detached: true,
|
|
3467
|
+
// A research persona dispatched through a custom team is still a native
|
|
3468
|
+
// research helper, so it receives the same per-tool watchdog.
|
|
3469
|
+
...(RESEARCHER_PERSONAS.has(personaKey) ? { toolWatchdog: { timeoutMs: reconSearchTimeoutMs } } : {}),
|
|
3470
|
+
// Whole-run deadline from the active mode's budget (null in strict mode).
|
|
3471
|
+
turnDeadlineMs: turnBudget.agentTurnMs,
|
|
3229
3472
|
}, {
|
|
3230
|
-
onProcess: (p) => { state.proc = p; },
|
|
3473
|
+
onProcess: (p) => { state.proc = p; void monitorStart?.then(task => monitorBridge?.registerOwnedProcessFor(task, p)); },
|
|
3474
|
+
...(driftMonitor ? { onControl: (c: PiRunControl) => { driftControl = c; } } : {}),
|
|
3231
3475
|
onTextDelta: (delta) => {
|
|
3476
|
+
void monitorStart?.then(task => monitorBridge?.appendOutputFor(task, delta));
|
|
3232
3477
|
fullText += delta;
|
|
3233
3478
|
state.lastWork = fullText.split("\n").filter((l: string) => l.trim()).pop() || "";
|
|
3234
3479
|
appendTimelineText(state.timeline, "text", delta);
|
|
@@ -3250,10 +3495,25 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3250
3495
|
});
|
|
3251
3496
|
updateWidget();
|
|
3252
3497
|
state.zoomRender?.();
|
|
3498
|
+
const violation = driftMonitor?.onToolStart(toolName, argStr);
|
|
3499
|
+
if (violation) escalateDrift(violation);
|
|
3253
3500
|
},
|
|
3254
|
-
|
|
3501
|
+
onToolEnd: (toolName, _id, isError) => {
|
|
3502
|
+
const violation = driftMonitor?.onToolEnd(toolName, isError);
|
|
3503
|
+
if (violation) escalateDrift(violation);
|
|
3504
|
+
},
|
|
3505
|
+
onUsage: (usage, source) => {
|
|
3506
|
+
// Sum per-message usage; the agent_end usage restates the LAST
|
|
3507
|
+
// message, so it only counts when no message_end ever arrived.
|
|
3508
|
+
if (source === "message_end" || (runBilled === 0 && runOut === 0)) {
|
|
3509
|
+
runBilled += (usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0);
|
|
3510
|
+
runOut += usage.output || 0;
|
|
3511
|
+
}
|
|
3255
3512
|
if (contextWindow > 0) {
|
|
3256
|
-
|
|
3513
|
+
// Real context = fresh input + cache reads + cache writes. Counting
|
|
3514
|
+
// usage.input alone showed 1–20% while tens of thousands of cached
|
|
3515
|
+
// tokens were re-sent per step, so the restart advice never fired.
|
|
3516
|
+
state.contextPct = (((usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0)) / contextWindow) * 100;
|
|
3257
3517
|
updateWidget();
|
|
3258
3518
|
}
|
|
3259
3519
|
},
|
|
@@ -3269,6 +3529,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3269
3529
|
|
|
3270
3530
|
// The process could not be spawned at all (proc `error` event).
|
|
3271
3531
|
if (res.spawnError) {
|
|
3532
|
+
await monitorStart?.then(task => monitorBridge?.finalizeChildFor(task, `Error spawning agent: ${res.spawnError}`, "failed"));
|
|
3272
3533
|
state.status = "error";
|
|
3273
3534
|
state.lastWork = `Error: ${res.spawnError}`;
|
|
3274
3535
|
state.killedByOperator = false;
|
|
@@ -3288,12 +3549,55 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3288
3549
|
|
|
3289
3550
|
const full = res.output;
|
|
3290
3551
|
const code = res.exitCode;
|
|
3552
|
+
if (res.termination) {
|
|
3553
|
+
const reason = res.termination.reason;
|
|
3554
|
+
const tool = res.termination.tool;
|
|
3555
|
+
state.status = "error";
|
|
3556
|
+
state.lastWork = reason === "tool_timeout"
|
|
3557
|
+
? `tool_timeout: ${tool?.toolName || "tool"} (${tool?.toolCallId || "unknown"})`
|
|
3558
|
+
: reason === "turn_timeout"
|
|
3559
|
+
? `turn_timeout after ${Math.round(state.elapsed / 1000)}s`
|
|
3560
|
+
: reason === "drift_stop"
|
|
3561
|
+
? `drift_stop: ${driftStop?.verdict || "watchdog"} (${driftStop?.rule || "rule"})`
|
|
3562
|
+
: "cancelled by caller";
|
|
3563
|
+
updateWidget();
|
|
3564
|
+
state.zoomRender?.(true);
|
|
3565
|
+
historyEnd(histEntry, "error");
|
|
3566
|
+
const onTerminate = state.onTerminate;
|
|
3567
|
+
state.onTerminate = undefined;
|
|
3568
|
+
onTerminate?.();
|
|
3569
|
+
if (reason === "drift_stop") {
|
|
3570
|
+
turnReport.driftStops++;
|
|
3571
|
+
sessionTotals.driftStops++;
|
|
3572
|
+
ctx.ui.notify(`${displayName(state.def.name)} stopped by the drift watchdog (${driftStop?.verdict || "verdict"}: ${driftStop?.reason || driftStop?.detail || "no reason"})`, "warning");
|
|
3573
|
+
}
|
|
3574
|
+
const explanation = reason === "tool_timeout"
|
|
3575
|
+
? `exceeded its per-tool watchdog on ${tool?.toolName || "tool"} (${tool?.toolCallId || "unknown"})`
|
|
3576
|
+
: reason === "turn_timeout"
|
|
3577
|
+
? `exceeded the per-run deadline (${Math.round(state.elapsed / 1000)}s; agent-turn-timeout-s / mode budget). ` +
|
|
3578
|
+
`Do NOT re-dispatch the same task unchanged — split it into smaller pieces, or ask the user to raise the deadline`
|
|
3579
|
+
: reason === "drift_stop"
|
|
3580
|
+
? `was stopped by the drift watchdog. Rule "${driftStop?.rule || "unknown"}" fired (${driftStop?.detail || "no detail"}); ` +
|
|
3581
|
+
`judge verdict ${(driftStop?.verdict || "drifting").toUpperCase()}: ${driftStop?.reason || "(no reason given)"}. ` +
|
|
3582
|
+
`Re-dispatch ONCE with a corrected, NARROWED task that addresses this verdict — never repeat the same task unchanged. ` +
|
|
3583
|
+
`If you believe the watchdog is wrong, tell the user; they can disable it with /watchdog ${key} off`
|
|
3584
|
+
: "was cancelled by its caller";
|
|
3585
|
+
return {
|
|
3586
|
+
output: `${reason}: agent ${displayName(state.def.name)} ${explanation}; terminationConfirmed=${res.termination.confirmed}.` +
|
|
3587
|
+
(full.trim() ? `\n\nPartial output before termination:\n${full.slice(-2000)}` : ""),
|
|
3588
|
+
exitCode: reason === "cancelled" ? 130 : reason === "drift_stop" ? 125 : 124,
|
|
3589
|
+
elapsed: state.elapsed,
|
|
3590
|
+
billed: runBilled,
|
|
3591
|
+
out: runOut,
|
|
3592
|
+
};
|
|
3593
|
+
}
|
|
3291
3594
|
|
|
3292
3595
|
// Operator kill (Phase 2). The exit was a SIGTERM from /agents-kill or
|
|
3293
3596
|
// /agents-restart, not a real completion: free the card (status → idle),
|
|
3294
3597
|
// fire any restart waiter, and return a message that tells the dispatcher
|
|
3295
3598
|
// LLM not to auto-retry. /agents-restart handles the fresh re-dispatch.
|
|
3296
3599
|
if (state.killedByOperator) {
|
|
3600
|
+
await monitorStart?.then(task => monitorBridge?.finalizeChildFor(task, "operator killed run", "cancelled"));
|
|
3297
3601
|
// !! (not `=== true`): TS otherwise narrows the field to the `false`
|
|
3298
3602
|
// assigned during setup — the concurrent /agents-restart mutation that
|
|
3299
3603
|
// makes this true is invisible to the checker across the await.
|
|
@@ -3318,11 +3622,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3318
3622
|
};
|
|
3319
3623
|
}
|
|
3320
3624
|
|
|
3625
|
+
await monitorStart?.then(task => monitorBridge?.finalizeChildFor(task, full, code === 0 ? "completed" : "failed"));
|
|
3321
3626
|
state.status = code === 0 ? "done" : "error";
|
|
3322
3627
|
|
|
3323
3628
|
// Mark session file as available for resume
|
|
3324
3629
|
if (code === 0) {
|
|
3325
3630
|
state.sessionFile = agentSessionFile;
|
|
3631
|
+
state.runsSinceFresh++;
|
|
3326
3632
|
}
|
|
3327
3633
|
|
|
3328
3634
|
state.lastWork = full.split("\n").filter((l: string) => l.trim()).pop() || "";
|
|
@@ -3353,11 +3659,16 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3353
3659
|
? `${full}${errBlock}`
|
|
3354
3660
|
: `Agent "${displayName(state.def.name)}" exited with code ${code} and produced no output.${errBlock}`;
|
|
3355
3661
|
}
|
|
3662
|
+
if (sessionRecycled) {
|
|
3663
|
+
output = `(ℹ ${displayName(state.def.name)}'s session was recycled before this run — it has no memory of earlier dispatches; state must travel via task text/artifacts.)\n\n${output}`;
|
|
3664
|
+
}
|
|
3356
3665
|
|
|
3357
3666
|
return {
|
|
3358
3667
|
output,
|
|
3359
3668
|
exitCode: code ?? 1,
|
|
3360
3669
|
elapsed: state.elapsed,
|
|
3670
|
+
billed: runBilled,
|
|
3671
|
+
out: runOut,
|
|
3361
3672
|
};
|
|
3362
3673
|
}
|
|
3363
3674
|
|
|
@@ -3426,8 +3737,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3426
3737
|
updateResearchWidget();
|
|
3427
3738
|
}
|
|
3428
3739
|
|
|
3429
|
-
// Env plumbing for spawned children: the shared exemptions file
|
|
3430
|
-
// damage-control variants honor pre-granted exemptions from it) and, when
|
|
3740
|
+
// Env plumbing for spawned children: the shared exemptions file and, when
|
|
3431
3741
|
// coms is up, the endpoint damage-control-continue escalates blocked path
|
|
3432
3742
|
// access to (access_request → user dialog in this hub). spawnPiAgent
|
|
3433
3743
|
// spreads process.env, so delegate grandchildren inherit these for free.
|
|
@@ -3447,7 +3757,11 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3447
3757
|
prompt: string,
|
|
3448
3758
|
ctx: any,
|
|
3449
3759
|
inputArtifacts: InputArtifactPreview[] = [],
|
|
3450
|
-
|
|
3760
|
+
signal?: AbortSignal,
|
|
3761
|
+
): Promise<{ output: string; exitCode: number; elapsed: number; termination?: Termination }> {
|
|
3762
|
+
const safety = requireSafetyHarness(safetyHarnessPath);
|
|
3763
|
+
if (!safety.ok) return { output: safety.error, exitCode: 1, elapsed: 0 };
|
|
3764
|
+
|
|
3451
3765
|
state.status = "running";
|
|
3452
3766
|
state.task = prompt;
|
|
3453
3767
|
state.toolCount = 0;
|
|
@@ -3482,11 +3796,14 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3482
3796
|
sessionFile: sessionPath,
|
|
3483
3797
|
resume: !!state.sessionFile,
|
|
3484
3798
|
prompt: appendInputArtifacts(prompt, inputArtifacts),
|
|
3485
|
-
//
|
|
3486
|
-
|
|
3487
|
-
// aborting the whole research turn.
|
|
3488
|
-
extensions: damageControlContinueExtPath ? [damageControlContinueExtPath] : [],
|
|
3799
|
+
// A blocked read feeds back so the helper can adapt without aborting.
|
|
3800
|
+
extensions: safety.extensions,
|
|
3489
3801
|
env: guardrailEnv(`research-r${state.id}`),
|
|
3802
|
+
// Shared native-research policy: owns a child group and applies the
|
|
3803
|
+
// configured per-tool deadline (including explicit `off`/null).
|
|
3804
|
+
...researchWatchdogSpawnOptions(reconSearchTimeoutMs, signal),
|
|
3805
|
+
// Whole-run deadline from the active mode's budget (null in strict mode).
|
|
3806
|
+
turnDeadlineMs: currentBudget().agentTurnMs,
|
|
3490
3807
|
}, {
|
|
3491
3808
|
onProcess: (p) => { state.proc = p; },
|
|
3492
3809
|
onTextDelta: (delta) => {
|
|
@@ -3514,7 +3831,8 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3514
3831
|
},
|
|
3515
3832
|
onUsage: (usage) => {
|
|
3516
3833
|
if (contextWindow > 0) {
|
|
3517
|
-
|
|
3834
|
+
// Same context truth as dispatchAgent: include cache reads/writes.
|
|
3835
|
+
state.contextPct = (((usage.input || 0) + (usage.cacheRead || 0) + (usage.cacheWrite || 0)) / contextWindow) * 100;
|
|
3518
3836
|
updateResearchWidget();
|
|
3519
3837
|
}
|
|
3520
3838
|
},
|
|
@@ -3543,6 +3861,23 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3543
3861
|
|
|
3544
3862
|
const full = res.output;
|
|
3545
3863
|
const code = res.exitCode;
|
|
3864
|
+
const termination = res.termination;
|
|
3865
|
+
if (termination) {
|
|
3866
|
+
const outcome = researchTerminationOutcome(state.id, termination);
|
|
3867
|
+
state.status = "error";
|
|
3868
|
+
state.finishedAt = Date.now();
|
|
3869
|
+
state.lastWork = outcome.lastWork;
|
|
3870
|
+
updateResearchWidget();
|
|
3871
|
+
state.zoomRender?.(true);
|
|
3872
|
+
historyEnd(histEntry, "error");
|
|
3873
|
+
pruneResearch();
|
|
3874
|
+
return {
|
|
3875
|
+
output: outcome.output,
|
|
3876
|
+
exitCode: outcome.exitCode,
|
|
3877
|
+
elapsed: state.elapsed,
|
|
3878
|
+
termination,
|
|
3879
|
+
};
|
|
3880
|
+
}
|
|
3546
3881
|
|
|
3547
3882
|
// Operator kill (via /agents-kill rN|all or its research-* aliases).
|
|
3548
3883
|
// Resolve gracefully so a spawn_research tool call awaiting this helper
|
|
@@ -3740,95 +4075,10 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
3740
4075
|
);
|
|
3741
4076
|
}
|
|
3742
4077
|
|
|
3743
|
-
// A headless child's
|
|
3744
|
-
//
|
|
3745
|
-
// server of its own, so we hold the connection open and write the decision
|
|
3746
|
-
// line when the user answers. The child fails closed after its own timeout;
|
|
3747
|
-
// a late "allow" still lands in the exemptions file, so the next attempt
|
|
3748
|
-
// (from any child) passes.
|
|
4078
|
+
// A headless child's protected-path block is routed to the serialized,
|
|
4079
|
+
// fail-closed approval controller. The socket remains open until a decision.
|
|
3749
4080
|
function handleAccessRequest(socket: net.Socket, req: AccessRequest): void {
|
|
3750
|
-
|
|
3751
|
-
const reply: AccessDecision = { type: "access_decision", msg_id: req.msg_id, decision };
|
|
3752
|
-
try { socket.write(JSON.stringify(reply) + "\n"); } catch { /* child may have timed out */ }
|
|
3753
|
-
try { socket.end(); } catch { /* ignore */ }
|
|
3754
|
-
};
|
|
3755
|
-
const agent = (typeof req.agent === "string" && req.agent) || req.sender_session || "unknown-agent";
|
|
3756
|
-
const pattern = typeof req.pattern === "string" ? req.pattern : "";
|
|
3757
|
-
if (!pattern) {
|
|
3758
|
-
respond("deny");
|
|
3759
|
-
return;
|
|
3760
|
-
}
|
|
3761
|
-
const cacheKey = `${agent}::${pattern}`;
|
|
3762
|
-
|
|
3763
|
-
// Already granted session-wide (an earlier ask or /allow) — no dialog.
|
|
3764
|
-
if (fileExemptionsFor(exemptionsFile ?? undefined, agent).some((e) => e.pattern === pattern)) {
|
|
3765
|
-
respond("allow_all");
|
|
3766
|
-
return;
|
|
3767
|
-
}
|
|
3768
|
-
if (accessDenyCache.has(cacheKey)) {
|
|
3769
|
-
respond("deny");
|
|
3770
|
-
return;
|
|
3771
|
-
}
|
|
3772
|
-
// The same ask is already on screen (e.g. delegate children racing) — share the outcome.
|
|
3773
|
-
const pending = pendingAccessAsks.get(cacheKey);
|
|
3774
|
-
if (pending) {
|
|
3775
|
-
pending.then(respond).catch(() => respond("deny"));
|
|
3776
|
-
return;
|
|
3777
|
-
}
|
|
3778
|
-
|
|
3779
|
-
const ask: Promise<AccessDecisionChoice> = accessAskQueue.then(async (): Promise<AccessDecisionChoice> => {
|
|
3780
|
-
const ctx = currentCtx;
|
|
3781
|
-
if (!ctx || !ctx.hasUI) return "deny";
|
|
3782
|
-
const DENY = "Deny (keep blocked)";
|
|
3783
|
-
const ONCE = "Allow once";
|
|
3784
|
-
const AGENT = `Allow for ${agent} (this session)`;
|
|
3785
|
-
const ALL = "Allow for all agents (this session)";
|
|
3786
|
-
try {
|
|
3787
|
-
ctx.ui.notify(
|
|
3788
|
-
`🛡️ Access request from ${agent}: ${req.rule}\n tool: ${req.tool}\n attempted: ${String(req.invocation || "").slice(0, 200)}`,
|
|
3789
|
-
"warning",
|
|
3790
|
-
);
|
|
3791
|
-
// Generous timeout — the child gives up (fail closed) long before
|
|
3792
|
-
// this; keeping the dialog up lets a late answer persist below.
|
|
3793
|
-
const choice = await ctx.ui.select(
|
|
3794
|
-
`🛡️ ${agent} requests access: ${pattern}`,
|
|
3795
|
-
[DENY, ONCE, AGENT, ALL],
|
|
3796
|
-
{ timeout: 600_000 },
|
|
3797
|
-
);
|
|
3798
|
-
if (choice === ONCE) return "allow_once";
|
|
3799
|
-
if (choice === AGENT) return "allow_agent";
|
|
3800
|
-
if (choice === ALL) return "allow_all";
|
|
3801
|
-
// Only an explicit Deny is cached; a dismissed/timed-out dialog may be re-asked.
|
|
3802
|
-
if (choice === DENY) accessDenyCache.add(cacheKey);
|
|
3803
|
-
return "deny";
|
|
3804
|
-
} catch {
|
|
3805
|
-
return "deny";
|
|
3806
|
-
}
|
|
3807
|
-
});
|
|
3808
|
-
accessAskQueue = ask.catch(() => {});
|
|
3809
|
-
pendingAccessAsks.set(cacheKey, ask);
|
|
3810
|
-
ask.then((decision) => {
|
|
3811
|
-
pendingAccessAsks.delete(cacheKey);
|
|
3812
|
-
if ((decision === "allow_agent" || decision === "allow_all") && exemptionsFile) {
|
|
3813
|
-
try {
|
|
3814
|
-
appendExemptionToFile(exemptionsFile, {
|
|
3815
|
-
pattern,
|
|
3816
|
-
scope: "session",
|
|
3817
|
-
agent: decision === "allow_agent" ? agent : undefined,
|
|
3818
|
-
grantedVia: "escalation",
|
|
3819
|
-
grantedAt: nowIso(),
|
|
3820
|
-
});
|
|
3821
|
-
} catch { /* best-effort — allow_once semantics still hold via the reply */ }
|
|
3822
|
-
}
|
|
3823
|
-
try { pi.appendEntry("damage-control-log", { action: `escalation_${decision}`, agent, pattern, tool: req.tool, rule: req.rule }); } catch { /* best-effort */ }
|
|
3824
|
-
try {
|
|
3825
|
-
currentCtx?.ui.notify(
|
|
3826
|
-
`🛡️ Access ${decision === "deny" ? "denied" : `granted (${decision.replace(/_/g, " ")})`}: ${pattern} — ${agent}`,
|
|
3827
|
-
decision === "deny" ? "warning" : "info",
|
|
3828
|
-
);
|
|
3829
|
-
} catch { /* ignore */ }
|
|
3830
|
-
respond(decision);
|
|
3831
|
-
}).catch(() => respond("deny"));
|
|
4081
|
+
void accessApprovalRouter.handle(socket, req);
|
|
3832
4082
|
}
|
|
3833
4083
|
|
|
3834
4084
|
function connHandler(socket: net.Socket): void {
|
|
@@ -4235,11 +4485,54 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
4235
4485
|
agent: Type.String({ description: "Agent name (case-insensitive)" }),
|
|
4236
4486
|
task: Type.String({ description: "Task description for the agent to execute" }),
|
|
4237
4487
|
artifacts: Type.Optional(Type.Array(Type.String({ description: "Optional repo-relative or session-artifact-relative input artifact path. The hub injects only path + one-line preview; the specialist must read the file itself." }))),
|
|
4238
|
-
scope: Type.Optional(Type.Array(Type.String({ description: "Optional advisory file scope globs for writable agents. Changes outside are reported in details.scopeViolations; nothing is auto-reverted." }))),
|
|
4488
|
+
scope: Type.Optional(Type.Array(Type.String({ description: "Optional advisory file scope globs for writable agents. Changes outside are reported in details.scopeViolations; nothing is auto-reverted. Also arms the drift watchdog's live out-of-scope rule." }))),
|
|
4489
|
+
watchdog: Type.Optional(Type.Boolean({ description: "Force the drift watchdog on/off for THIS dispatch (default: per-agent /watchdog override, then the hub-wide setting)." })),
|
|
4239
4490
|
}),
|
|
4240
4491
|
|
|
4241
4492
|
async execute(_toolCallId, params, _signal, onUpdate, ctx) {
|
|
4242
|
-
const {
|
|
4493
|
+
const { task, artifacts, scope, watchdog } = params as { agent: string; task: string; artifacts?: string[]; scope?: string[]; watchdog?: boolean };
|
|
4494
|
+
// Display names / underscores resolve to the persona slug key space, so
|
|
4495
|
+
// `agent: "Test Engineer"` never burns a dispatch on a lookup error.
|
|
4496
|
+
const agent = normalizeAgentInput((params as { agent: string }).agent);
|
|
4497
|
+
// Unclassified turn: assume the default tier (outside strict, whose full
|
|
4498
|
+
// contract runs uncapped by tiers). The prompt asks for set_task_tier
|
|
4499
|
+
// FIRST; this is the fail-safe, not the intended path.
|
|
4500
|
+
if (turnTaskTier === null && hubMode !== "strict") {
|
|
4501
|
+
turnTaskTier = DEFAULT_TASK_TIER;
|
|
4502
|
+
turnReport.tier = turnTaskTier;
|
|
4503
|
+
updateModeStatus();
|
|
4504
|
+
}
|
|
4505
|
+
// Turn-budget gate: refuse BEFORE any spawn. The dispatcher must stop,
|
|
4506
|
+
// summarize, and ask the user; a new user turn opens a fresh window.
|
|
4507
|
+
const budgetRefusal = checkTurnBudget(
|
|
4508
|
+
"dispatch",
|
|
4509
|
+
{ dispatches: turnDispatchCount, research: turnResearchCount },
|
|
4510
|
+
currentBudget(),
|
|
4511
|
+
Date.now() - (currentTurnStartedAt || Date.now()),
|
|
4512
|
+
hubMode,
|
|
4513
|
+
);
|
|
4514
|
+
if (budgetRefusal) {
|
|
4515
|
+
turnReport.refusals++;
|
|
4516
|
+
sessionTotals.refusals++;
|
|
4517
|
+
return {
|
|
4518
|
+
content: [{ type: "text", text: budgetRefusal.message }],
|
|
4519
|
+
details: { agent, task, status: "budget_refused", reason: budgetRefusal.reason, elapsed: 0, exitCode: 1, fullOutput: "" },
|
|
4520
|
+
};
|
|
4521
|
+
}
|
|
4522
|
+
// Duplicate-dispatch guard: the same agent with a near-identical task in
|
|
4523
|
+
// one turn is running in circles — the result already exists.
|
|
4524
|
+
const fingerprint = taskFingerprint(agent, task);
|
|
4525
|
+
if (turnDispatchFingerprints.has(fingerprint)) {
|
|
4526
|
+
turnReport.refusals++;
|
|
4527
|
+
sessionTotals.refusals++;
|
|
4528
|
+
return {
|
|
4529
|
+
content: [{ type: "text", text: `⚠ Duplicate dispatch refused: you already dispatched ${agent} with this task (or a trivial rewording of it) THIS turn. Use the earlier result — re-read its digest/returnPath — or change the task materially (new instructions, corrected inputs) before re-dispatching.` }],
|
|
4530
|
+
details: { agent, task, status: "duplicate_refused", elapsed: 0, exitCode: 1, fullOutput: "" },
|
|
4531
|
+
};
|
|
4532
|
+
}
|
|
4533
|
+
turnDispatchCount++;
|
|
4534
|
+
sessionTotals.dispatches++;
|
|
4535
|
+
updateModeStatus();
|
|
4243
4536
|
let writableTracked = false;
|
|
4244
4537
|
let scopeSnapshot: any = null;
|
|
4245
4538
|
let scopeOverlapBaseline = writableOverlapCounter;
|
|
@@ -4269,7 +4562,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
4269
4562
|
scopeSnapshot = snapshotWorktree(ctx.cwd || process.cwd());
|
|
4270
4563
|
}
|
|
4271
4564
|
|
|
4272
|
-
let result = await dispatchAgent(agent, task, ctx, inputArtifacts, scopeGlobs);
|
|
4565
|
+
let result = await dispatchAgent(agent, task, ctx, inputArtifacts, scopeGlobs, watchdog);
|
|
4566
|
+
let dispatchBilled = result.billed ?? 0;
|
|
4567
|
+
let dispatchOut = result.out ?? 0;
|
|
4273
4568
|
|
|
4274
4569
|
// Auto-research pipe: when the specialist pauses with NEEDS_RESEARCH
|
|
4275
4570
|
// lines, the hub (in code, not the dispatcher LLM) fans out read-only
|
|
@@ -4311,7 +4606,9 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
4311
4606
|
const resumePrompt = "Research findings for your NEEDS_RESEARCH questions are ready. " +
|
|
4312
4607
|
"Read each file with your read tool, then continue from where you paused:\n" +
|
|
4313
4608
|
answered.map((a, i) => `${i + 1}. ${a.question}\n → ${a.file}`).join("\n");
|
|
4314
|
-
result = await dispatchAgent(agent, resumePrompt, ctx, inputArtifacts, scopeGlobs);
|
|
4609
|
+
result = await dispatchAgent(agent, resumePrompt, ctx, inputArtifacts, scopeGlobs, watchdog);
|
|
4610
|
+
dispatchBilled += result.billed ?? 0;
|
|
4611
|
+
dispatchOut += result.out ?? 0;
|
|
4315
4612
|
}
|
|
4316
4613
|
|
|
4317
4614
|
let scopeViolations: any = null;
|
|
@@ -4343,6 +4640,15 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
4343
4640
|
const questions = extractAskUserQuestions(result.output);
|
|
4344
4641
|
|
|
4345
4642
|
const status = result.exitCode === 0 ? "done" : "error";
|
|
4643
|
+
// Record the fingerprint only for completed or watchdog/deadline-stopped
|
|
4644
|
+
// runs — those must not be repeated unchanged. A failed spawn or plain
|
|
4645
|
+
// error stays retryable (the failure may be transient).
|
|
4646
|
+
if (result.exitCode === 0 || result.exitCode === 124 || result.exitCode === 125) {
|
|
4647
|
+
turnDispatchFingerprints.add(fingerprint);
|
|
4648
|
+
}
|
|
4649
|
+
turnReport.dispatches.push({ agent, status, elapsed: result.elapsed, billed: dispatchBilled, out: dispatchOut });
|
|
4650
|
+
sessionTotals.billed += dispatchBilled;
|
|
4651
|
+
sessionTotals.out += dispatchOut;
|
|
4346
4652
|
const summary = `[${agent}] ${status} in ${Math.round(result.elapsed / 1000)}s`;
|
|
4347
4653
|
const questionsNotice = questions.length > 0
|
|
4348
4654
|
? `\n\n⚠ ${questions.length} ASK_USER question(s) raised by ${agent}. ` +
|
|
@@ -4470,6 +4776,28 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
4470
4776
|
async execute(_toolCallId, params, _signal, onUpdate, ctx) {
|
|
4471
4777
|
const { task, persona, model, artifacts } = params as { task: string; persona?: string; model?: string; artifacts?: string[] };
|
|
4472
4778
|
|
|
4779
|
+
// Turn-budget gate (dispatcher-initiated research only — the auto-research
|
|
4780
|
+
// pipe and the /research command are exempt).
|
|
4781
|
+
const budgetRefusal = checkTurnBudget(
|
|
4782
|
+
"research",
|
|
4783
|
+
{ dispatches: turnDispatchCount, research: turnResearchCount },
|
|
4784
|
+
currentBudget(),
|
|
4785
|
+
Date.now() - (currentTurnStartedAt || Date.now()),
|
|
4786
|
+
hubMode,
|
|
4787
|
+
);
|
|
4788
|
+
if (budgetRefusal) {
|
|
4789
|
+
turnReport.refusals++;
|
|
4790
|
+
sessionTotals.refusals++;
|
|
4791
|
+
return {
|
|
4792
|
+
content: [{ type: "text", text: budgetRefusal.message }],
|
|
4793
|
+
details: { status: "budget_refused", reason: budgetRefusal.reason },
|
|
4794
|
+
};
|
|
4795
|
+
}
|
|
4796
|
+
turnResearchCount++;
|
|
4797
|
+
turnReport.research++;
|
|
4798
|
+
sessionTotals.research++;
|
|
4799
|
+
updateModeStatus();
|
|
4800
|
+
|
|
4473
4801
|
let def: AgentDef;
|
|
4474
4802
|
let isPersona = false;
|
|
4475
4803
|
if (persona) {
|
|
@@ -4500,11 +4828,13 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
4500
4828
|
}
|
|
4501
4829
|
|
|
4502
4830
|
try {
|
|
4503
|
-
const result = await spawnResearch(state, task, ctx, inputArtifacts);
|
|
4831
|
+
const result = await spawnResearch(state, task, ctx, inputArtifacts, _signal);
|
|
4504
4832
|
const truncated = result.output.length > 8000
|
|
4505
4833
|
? result.output.slice(0, 8000) + "\n\n... [truncated]"
|
|
4506
4834
|
: result.output;
|
|
4507
|
-
const status = result.
|
|
4835
|
+
const status = result.termination
|
|
4836
|
+
? result.termination.reason
|
|
4837
|
+
: result.exitCode === 0 ? "done" : "error";
|
|
4508
4838
|
const label = isPersona ? displayName(def.name) : "ad-hoc";
|
|
4509
4839
|
const summary = `[research r${state.id} · ${label} · read-only] ${status} in ${Math.round(result.elapsed / 1000)}s`;
|
|
4510
4840
|
return {
|
|
@@ -4517,6 +4847,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
4517
4847
|
elapsed: result.elapsed,
|
|
4518
4848
|
exitCode: result.exitCode,
|
|
4519
4849
|
fullOutput: result.output,
|
|
4850
|
+
termination: result.termination,
|
|
4520
4851
|
artifacts: inputArtifacts.map(a => ({ path: a.path, displayPath: a.displayPath, preview: a.preview })),
|
|
4521
4852
|
},
|
|
4522
4853
|
};
|
|
@@ -4569,6 +4900,102 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
4569
4900
|
},
|
|
4570
4901
|
});
|
|
4571
4902
|
|
|
4903
|
+
// ── set_task_tier Tool (complexity triage) ──
|
|
4904
|
+
// The dispatcher classifies each user turn BEFORE its first dispatch; the
|
|
4905
|
+
// declared tier lowers the dispatch/research caps to min(mode, tier) in code.
|
|
4906
|
+
// Skipping it makes the first dispatch assume the default tier (run-budget.js).
|
|
4907
|
+
|
|
4908
|
+
pi.registerTool({
|
|
4909
|
+
name: "set_task_tier",
|
|
4910
|
+
label: "Set Task Tier",
|
|
4911
|
+
description:
|
|
4912
|
+
"Classify THIS user turn's ask before your first dispatch: trivial (one obvious, low-risk change — 1 dispatch), small (a contained change, no planning pipeline — 2 dispatches), feature (a normal multi-step feature — 6 dispatches), project (a large effort — mode budget applies). The hub enforces the resulting caps; re-call it if the ask turns out bigger than classified (raising the tier mid-turn is allowed and cheap — say why).",
|
|
4913
|
+
parameters: Type.Object({
|
|
4914
|
+
tier: Type.String({ description: "One of: trivial | small | feature | project" }),
|
|
4915
|
+
reason: Type.Optional(Type.String({ description: "One line on why this tier fits the ask." })),
|
|
4916
|
+
}),
|
|
4917
|
+
async execute(_callId, params, _signal, _onUpdate, _ctx) {
|
|
4918
|
+
const { tier, reason } = params as { tier: string; reason?: string };
|
|
4919
|
+
const normalized = normalizeTaskTier(tier);
|
|
4920
|
+
if (!normalized) {
|
|
4921
|
+
return {
|
|
4922
|
+
content: [{ type: "text" as const, text: `Unknown tier "${tier}" — expected one of: ${TASK_TIERS.join(", ")}. Tier unchanged (${turnTaskTier ?? "unset"}).` }],
|
|
4923
|
+
details: { status: "error", tier: turnTaskTier },
|
|
4924
|
+
};
|
|
4925
|
+
}
|
|
4926
|
+
turnTaskTier = normalized;
|
|
4927
|
+
turnReport.tier = normalized;
|
|
4928
|
+
updateModeStatus();
|
|
4929
|
+
const b = currentBudget();
|
|
4930
|
+
const cap = (n: number | null) => (n == null ? "unlimited" : String(n));
|
|
4931
|
+
return {
|
|
4932
|
+
content: [{ type: "text" as const, text: `Task tier: ${normalized}${reason ? ` (${reason})` : ""}. Effective caps this turn: ${cap(b.maxDispatches)} dispatches, ${cap(b.maxResearch)} research. Size the apparatus accordingly — do not spend a cap just because it exists.` }],
|
|
4933
|
+
details: { status: "ok", tier: normalized },
|
|
4934
|
+
};
|
|
4935
|
+
},
|
|
4936
|
+
renderCall(args, theme) {
|
|
4937
|
+
return new Text(
|
|
4938
|
+
theme.fg("toolTitle", theme.bold("set_task_tier ")) +
|
|
4939
|
+
theme.fg("accent", String((args as any).tier || "?")) +
|
|
4940
|
+
theme.fg("dim", (args as any).reason ? ` — ${String((args as any).reason).slice(0, 60)}` : ""),
|
|
4941
|
+
0, 0,
|
|
4942
|
+
);
|
|
4943
|
+
},
|
|
4944
|
+
});
|
|
4945
|
+
|
|
4946
|
+
// ── team_adjust Tool (dispatcher-driven roster changes, gated) ──
|
|
4947
|
+
// The dispatcher may restructure its own team mid-session — but never in fast
|
|
4948
|
+
// mode, never past the roster cap, and the human is notified of every change.
|
|
4949
|
+
const TEAM_ADJUST_ROSTER_CAP = 8;
|
|
4950
|
+
|
|
4951
|
+
pi.registerTool({
|
|
4952
|
+
name: "team_adjust",
|
|
4953
|
+
label: "Team Adjust",
|
|
4954
|
+
description:
|
|
4955
|
+
"Add or drop a specialist persona in the ACTIVE team (the roster you can dispatch to). Use sparingly, when the current roster genuinely cannot serve the task (e.g. add security-auditor for a security-sensitive change, drop an unused specialist). Not available in fast mode. The human sees every change and can revert with /agents-add //agents-drop.",
|
|
4956
|
+
parameters: Type.Object({
|
|
4957
|
+
action: Type.String({ description: "add | drop" }),
|
|
4958
|
+
agent: Type.String({ description: "Persona name (case-insensitive), e.g. security-auditor" }),
|
|
4959
|
+
reason: Type.String({ description: "One line on why the roster must change for this task." }),
|
|
4960
|
+
}),
|
|
4961
|
+
async execute(_callId, params, _signal, _onUpdate, ctx) {
|
|
4962
|
+
const { action, agent, reason } = params as { action: string; agent: string; reason: string };
|
|
4963
|
+
const act = String(action || "").trim().toLowerCase();
|
|
4964
|
+
if (hubMode === "fast") {
|
|
4965
|
+
return {
|
|
4966
|
+
content: [{ type: "text" as const, text: "team_adjust is disabled in fast mode — a single-specialist path never needs roster changes. Ask the user to /hub-mode standard if the task outgrew fast mode." }],
|
|
4967
|
+
details: { status: "refused" },
|
|
4968
|
+
};
|
|
4969
|
+
}
|
|
4970
|
+
if (act !== "add" && act !== "drop") {
|
|
4971
|
+
return { content: [{ type: "text" as const, text: `Unknown action "${action}" — expected add or drop.` }], details: { status: "error" } };
|
|
4972
|
+
}
|
|
4973
|
+
if (act === "add" && agentStates.size >= TEAM_ADJUST_ROSTER_CAP) {
|
|
4974
|
+
return {
|
|
4975
|
+
content: [{ type: "text" as const, text: `Roster cap reached (${TEAM_ADJUST_ROSTER_CAP}) — drop an unused member first, or ask the user to /agents-add manually.` }],
|
|
4976
|
+
details: { status: "refused" },
|
|
4977
|
+
};
|
|
4978
|
+
}
|
|
4979
|
+
const result = act === "add" ? rosterAdd(agent) : rosterDrop(agent);
|
|
4980
|
+
if (result.ok) {
|
|
4981
|
+
ctx.ui.notify(`team_adjust (${act}): ${result.message} — dispatcher's reason: ${reason || "(none given)"}`, "info");
|
|
4982
|
+
}
|
|
4983
|
+
const roster = Array.from(agentStates.values()).map(s => s.def.name).join(", ");
|
|
4984
|
+
return {
|
|
4985
|
+
content: [{ type: "text" as const, text: `${result.message}. Active team: ${roster}.` }],
|
|
4986
|
+
details: { status: result.ok ? "ok" : "refused", roster },
|
|
4987
|
+
};
|
|
4988
|
+
},
|
|
4989
|
+
renderCall(args, theme) {
|
|
4990
|
+
return new Text(
|
|
4991
|
+
theme.fg("toolTitle", theme.bold("team_adjust ")) +
|
|
4992
|
+
theme.fg("accent", `${String((args as any).action || "?")} ${String((args as any).agent || "?")}`) +
|
|
4993
|
+
theme.fg("dim", (args as any).reason ? ` — ${String((args as any).reason).slice(0, 50)}` : ""),
|
|
4994
|
+
0, 0,
|
|
4995
|
+
);
|
|
4996
|
+
},
|
|
4997
|
+
});
|
|
4998
|
+
|
|
4572
4999
|
// ── Verification Contract tools (assertion ledger) ──
|
|
4573
5000
|
// set_assertions builds/rebuilds the ledger before dispatching; update_assertion
|
|
4574
5001
|
// records a gate outcome. Both persist to disk and refresh the one-line status;
|
|
@@ -5360,6 +5787,178 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
5360
5787
|
},
|
|
5361
5788
|
});
|
|
5362
5789
|
|
|
5790
|
+
// ── /hub-mode: execution mode (fast|standard|strict) ──
|
|
5791
|
+
// Session-lifetime switch over the overrides-file default. Budgets bind on
|
|
5792
|
+
// the NEXT tool call (counters are per user turn and keep running); the
|
|
5793
|
+
// dispatcher prompt rebuilds with the new mode on the next turn.
|
|
5794
|
+
pi.registerCommand("hub-mode", {
|
|
5795
|
+
description: "Show or set the execution mode: fast (single specialist) | standard (batched, default) | strict (full Verification Contract)",
|
|
5796
|
+
handler: async (args, ctx) => {
|
|
5797
|
+
widgetCtx = ctx;
|
|
5798
|
+
const requested = (args || "").trim();
|
|
5799
|
+
if (!requested) {
|
|
5800
|
+
const b = currentBudget();
|
|
5801
|
+
const cap = (n: number | null) => (n == null ? "∞" : String(n));
|
|
5802
|
+
ctx.ui.notify(
|
|
5803
|
+
`Execution mode: ${hubMode}\nThis turn: ${turnDispatchCount}/${cap(b.maxDispatches)} dispatches, ` +
|
|
5804
|
+
`${turnResearchCount}/${cap(b.maxResearch)} research\nSwitch with /hub-mode ${HUB_MODES.join("|")}`,
|
|
5805
|
+
"info",
|
|
5806
|
+
);
|
|
5807
|
+
return;
|
|
5808
|
+
}
|
|
5809
|
+
const mode = normalizeHubMode(requested);
|
|
5810
|
+
if (!mode) {
|
|
5811
|
+
ctx.ui.notify(`Unknown mode "${requested}" — expected one of: ${HUB_MODES.join(", ")}`, "error");
|
|
5812
|
+
return;
|
|
5813
|
+
}
|
|
5814
|
+
hubMode = mode;
|
|
5815
|
+
updateModeStatus();
|
|
5816
|
+
ctx.ui.notify(`Execution mode → ${mode} (budgets apply from the next dispatch; prompt updates next turn)`, "success");
|
|
5817
|
+
},
|
|
5818
|
+
});
|
|
5819
|
+
|
|
5820
|
+
pi.registerCommand("watchdog", {
|
|
5821
|
+
description: "Drift watchdog: /watchdog [on|off|auto] hub-wide, /watchdog <agent> [on|off|clear] per agent, no args to show",
|
|
5822
|
+
handler: async (args, ctx) => {
|
|
5823
|
+
widgetCtx = ctx;
|
|
5824
|
+
const parts = (args || "").trim().split(/\s+/).filter(Boolean);
|
|
5825
|
+
if (parts.length === 0) {
|
|
5826
|
+
const perAgent = watchdogAgentOverrides.size > 0
|
|
5827
|
+
? Array.from(watchdogAgentOverrides.entries()).map(([k, v]) => `${k}: ${v}`).join(", ")
|
|
5828
|
+
: "(none)";
|
|
5829
|
+
ctx.ui.notify(
|
|
5830
|
+
`Drift watchdog: ${watchdogSetting} (hub-wide)\nPer-agent overrides: ${perAgent}\n` +
|
|
5831
|
+
`Judge model: ${watchdogJudgeModel || "(researcher persona's, else dispatcher's)"}\n` +
|
|
5832
|
+
`Usage: /watchdog on|off|auto — or /watchdog <agent> on|off|clear`,
|
|
5833
|
+
"info",
|
|
5834
|
+
);
|
|
5835
|
+
return;
|
|
5836
|
+
}
|
|
5837
|
+
if (parts.length === 1) {
|
|
5838
|
+
const setting = normalizeWatchdogSetting(parts[0]);
|
|
5839
|
+
if (!setting) {
|
|
5840
|
+
ctx.ui.notify(`Unknown setting "${parts[0]}" — expected one of: ${WATCHDOG_SETTINGS.join(", ")} (or /watchdog <agent> on|off|clear)`, "error");
|
|
5841
|
+
return;
|
|
5842
|
+
}
|
|
5843
|
+
watchdogSetting = setting;
|
|
5844
|
+
ctx.ui.notify(`Drift watchdog → ${setting} (applies from the next dispatch)`, "success");
|
|
5845
|
+
return;
|
|
5846
|
+
}
|
|
5847
|
+
const agentKey = normalizeAgentInput(parts[0]);
|
|
5848
|
+
const value = parts[1].toLowerCase();
|
|
5849
|
+
if (!agentStates.has(agentKey)) {
|
|
5850
|
+
ctx.ui.notify(`"${parts[0]}" is not in the active team (${Array.from(agentStates.values()).map(s => s.def.name).join(", ")})`, "error");
|
|
5851
|
+
return;
|
|
5852
|
+
}
|
|
5853
|
+
if (value === "clear") {
|
|
5854
|
+
watchdogAgentOverrides.delete(agentKey);
|
|
5855
|
+
ctx.ui.notify(`Drift watchdog override cleared for ${agentKey} (hub-wide setting "${watchdogSetting}" applies)`, "success");
|
|
5856
|
+
return;
|
|
5857
|
+
}
|
|
5858
|
+
if (value !== "on" && value !== "off") {
|
|
5859
|
+
ctx.ui.notify(`Per-agent watchdog must be on, off, or clear — got "${parts[1]}"`, "error");
|
|
5860
|
+
return;
|
|
5861
|
+
}
|
|
5862
|
+
watchdogAgentOverrides.set(agentKey, value);
|
|
5863
|
+
ctx.ui.notify(`Drift watchdog for ${agentKey} → ${value} (overrides the hub-wide "${watchdogSetting}")`, "success");
|
|
5864
|
+
},
|
|
5865
|
+
});
|
|
5866
|
+
|
|
5867
|
+
pi.registerCommand("agents-add", {
|
|
5868
|
+
description: "Add persona(s) to the active team without switching teams: /agents-add <name> [<name>…]",
|
|
5869
|
+
handler: async (args, ctx) => {
|
|
5870
|
+
widgetCtx = ctx;
|
|
5871
|
+
const names = (args || "").trim().split(/\s+/).filter(Boolean);
|
|
5872
|
+
if (names.length === 0) {
|
|
5873
|
+
const available = allAgentDefs
|
|
5874
|
+
.filter(d => !agentStates.has(d.name.toLowerCase()))
|
|
5875
|
+
.map(d => d.name).sort().join(", ") || "(all personas are already in the team)";
|
|
5876
|
+
ctx.ui.notify(`Usage: /agents-add <persona> [<persona>…]\nNot in the team yet: ${available}`, "info");
|
|
5877
|
+
return;
|
|
5878
|
+
}
|
|
5879
|
+
const results = names.map(n => rosterAdd(n));
|
|
5880
|
+
const level = results.some(r => r.ok) ? "success" : "error";
|
|
5881
|
+
ctx.ui.notify(results.map(r => r.message).join("\n"), level as any);
|
|
5882
|
+
ctx.ui.setStatus("agent-team", `Team: ${activeTeamName}* (${agentStates.size})`);
|
|
5883
|
+
},
|
|
5884
|
+
});
|
|
5885
|
+
|
|
5886
|
+
pi.registerCommand("agents-drop", {
|
|
5887
|
+
description: "Drop persona(s) from the active team: /agents-drop <name> [<name>…]",
|
|
5888
|
+
handler: async (args, ctx) => {
|
|
5889
|
+
widgetCtx = ctx;
|
|
5890
|
+
const names = (args || "").trim().split(/\s+/).filter(Boolean);
|
|
5891
|
+
if (names.length === 0) {
|
|
5892
|
+
ctx.ui.notify(`Usage: /agents-drop <persona> [<persona>…]\nActive team: ${Array.from(agentStates.values()).map(s => s.def.name).join(", ")}`, "info");
|
|
5893
|
+
return;
|
|
5894
|
+
}
|
|
5895
|
+
const results = names.map(n => rosterDrop(n));
|
|
5896
|
+
const level = results.some(r => r.ok) ? "success" : "error";
|
|
5897
|
+
ctx.ui.notify(results.map(r => r.message).join("\n"), level as any);
|
|
5898
|
+
ctx.ui.setStatus("agent-team", `Team: ${activeTeamName}* (${agentStates.size})`);
|
|
5899
|
+
},
|
|
5900
|
+
});
|
|
5901
|
+
|
|
5902
|
+
pi.registerCommand("agents-save", {
|
|
5903
|
+
description: "Persist the CURRENT roster as a named team in .pi/agents/teams.yaml: /agents-save <team-name>",
|
|
5904
|
+
handler: async (args, ctx) => {
|
|
5905
|
+
widgetCtx = ctx;
|
|
5906
|
+
const name = (args || "").trim();
|
|
5907
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(name)) {
|
|
5908
|
+
ctx.ui.notify("Usage: /agents-save <team-name> (letters, digits, hyphens, underscores)", "error");
|
|
5909
|
+
return;
|
|
5910
|
+
}
|
|
5911
|
+
const members = Array.from(agentStates.values()).map(s => s.def.name);
|
|
5912
|
+
if (members.length === 0) {
|
|
5913
|
+
ctx.ui.notify("The active team is empty — nothing to save.", "error");
|
|
5914
|
+
return;
|
|
5915
|
+
}
|
|
5916
|
+
const teamsPath = join(ctx.cwd || process.cwd(), ".pi", "agents", "teams.yaml");
|
|
5917
|
+
let raw = "";
|
|
5918
|
+
try { raw = existsSync(teamsPath) ? readFileSync(teamsPath, "utf-8") : ""; } catch {}
|
|
5919
|
+
try {
|
|
5920
|
+
mkdirSync(join(ctx.cwd || process.cwd(), ".pi", "agents"), { recursive: true });
|
|
5921
|
+
writeFileSync(teamsPath, upsertTeamInYaml(raw, name, members), "utf-8");
|
|
5922
|
+
} catch (err) {
|
|
5923
|
+
ctx.ui.notify(`Could not write ${teamsPath}: ${err instanceof Error ? err.message : String(err)}`, "error");
|
|
5924
|
+
return;
|
|
5925
|
+
}
|
|
5926
|
+
teams[name] = members;
|
|
5927
|
+
activeTeamName = name;
|
|
5928
|
+
ctx.ui.setStatus("agent-team", `Team: ${name} (${agentStates.size})`);
|
|
5929
|
+
ctx.ui.notify(`Team "${name}" saved to .pi/agents/teams.yaml — ${members.join(", ")}`, "success");
|
|
5930
|
+
},
|
|
5931
|
+
});
|
|
5932
|
+
|
|
5933
|
+
pi.registerCommand("hub-report", {
|
|
5934
|
+
description: "Per-turn cost report: dispatches, research, tokens, recycles, drift stops (last turn + session totals)",
|
|
5935
|
+
handler: async (_args, ctx) => {
|
|
5936
|
+
widgetCtx = ctx;
|
|
5937
|
+
const fmtTok = (n: number) => n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);
|
|
5938
|
+
const renderReport = (label: string, r: TurnReport): string => {
|
|
5939
|
+
const billed = r.dispatches.reduce((n, d) => n + d.billed, 0);
|
|
5940
|
+
const out = r.dispatches.reduce((n, d) => n + d.out, 0);
|
|
5941
|
+
const rows = r.dispatches.map(d => ` ${d.agent}: ${d.status} in ${Math.round(d.elapsed / 1000)}s · ${fmtTok(d.billed)} billed / ${fmtTok(d.out)} out`);
|
|
5942
|
+
return [
|
|
5943
|
+
`${label} — tier ${r.tier ?? "(unset)"} · ${r.dispatches.length} dispatch(es) · ${r.research} research · ` +
|
|
5944
|
+
`${fmtTok(billed)} billed / ${fmtTok(out)} out · ${r.recycles} recycle(s) · ${r.driftStops} drift stop(s) · ${r.refusals} refusal(s)`,
|
|
5945
|
+
...rows,
|
|
5946
|
+
].join("\n");
|
|
5947
|
+
};
|
|
5948
|
+
const lines: string[] = [];
|
|
5949
|
+
if (turnReport.dispatches.length > 0 || turnReport.research > 0 || turnReport.refusals > 0) {
|
|
5950
|
+
lines.push(renderReport("Current turn", turnReport));
|
|
5951
|
+
}
|
|
5952
|
+
if (lastTurnReport) lines.push(renderReport("Last turn", lastTurnReport));
|
|
5953
|
+
lines.push(
|
|
5954
|
+
`Session — ${sessionTotals.turns} dispatching turn(s) · ${sessionTotals.dispatches} dispatch(es) · ${sessionTotals.research} research · ` +
|
|
5955
|
+
`${fmtTok(sessionTotals.billed)} billed / ${fmtTok(sessionTotals.out)} out · ${sessionTotals.recycles} recycle(s) · ` +
|
|
5956
|
+
`${sessionTotals.driftStops} drift stop(s) · ${sessionTotals.refusals} refusal(s)`,
|
|
5957
|
+
);
|
|
5958
|
+
ctx.ui.notify(lines.join("\n\n"), "info");
|
|
5959
|
+
},
|
|
5960
|
+
});
|
|
5961
|
+
|
|
5363
5962
|
// Alt+A toggles the agent view between the full dashboard grid (above the
|
|
5364
5963
|
// editor) and the compact running-agents list (below the editor). alt+a has no
|
|
5365
5964
|
// default pi binding — every useful ctrl+letter is already taken (ctrl+r is
|
|
@@ -6193,7 +6792,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
6193
6792
|
// Coms-backed run: no local process to SIGTERM — only the wait can be
|
|
6194
6793
|
// released; the standing peer keeps running its turn in its own pane.
|
|
6195
6794
|
if (!state.proc) {
|
|
6196
|
-
state.comsAbort
|
|
6795
|
+
void cancelLocalWaitOnly({ abort: state.comsAbort, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.runCount), event: { kind: "wait_only_cancelled" } });
|
|
6197
6796
|
ctx.ui.notify(`Abandoning ${displayName(state.def.name)}'s coms dispatch (the peer pane keeps running)...`, "info");
|
|
6198
6797
|
return;
|
|
6199
6798
|
}
|
|
@@ -6201,7 +6800,7 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
6201
6800
|
// delegate children die with it. The close handler resolves the awaited
|
|
6202
6801
|
// dispatch with a "do not auto-retry" message, unblocking the dispatcher.
|
|
6203
6802
|
state.killedByOperator = true;
|
|
6204
|
-
|
|
6803
|
+
cancelLocalOwnedProcess({ process: state.proc, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.runCount), treeKill: killPiTree });
|
|
6205
6804
|
ctx.ui.notify(`Killing ${displayName(state.def.name)}...`, "info");
|
|
6206
6805
|
},
|
|
6207
6806
|
});
|
|
@@ -6257,16 +6856,17 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
6257
6856
|
// re-dispatching (dispatchAgent rejects a re-entry while status is running).
|
|
6258
6857
|
// A coms-backed run has no process — abandoning the wait is the "kill".
|
|
6259
6858
|
if (state.status === "running" && (state.proc || state.comsAbort)) {
|
|
6260
|
-
|
|
6261
|
-
|
|
6262
|
-
|
|
6263
|
-
|
|
6264
|
-
|
|
6265
|
-
|
|
6266
|
-
|
|
6267
|
-
|
|
6268
|
-
}
|
|
6269
|
-
}
|
|
6859
|
+
let resolveTermination!: () => void;
|
|
6860
|
+
const terminated = new Promise<void>(res => { resolveTermination = res; });
|
|
6861
|
+
state.onTerminate = resolveTermination;
|
|
6862
|
+
if (state.proc) {
|
|
6863
|
+
state.killedByOperator = true;
|
|
6864
|
+
state.restarting = true;
|
|
6865
|
+
killPiTree(state.proc);
|
|
6866
|
+
} else {
|
|
6867
|
+
await cancelLocalWaitOnly({ abort: state.comsAbort, monitorBridge, monitorKey: monitorKeyForAgent(state.def.name, state.runCount), event: { kind: "restart" } });
|
|
6868
|
+
}
|
|
6869
|
+
await terminated;
|
|
6270
6870
|
}
|
|
6271
6871
|
// Re-run fresh: a frozen session file may be inconsistent, so drop it (no -c).
|
|
6272
6872
|
state.sessionFile = null;
|
|
@@ -6488,6 +7088,20 @@ Finish with the artifact-relative path plus a digest of no more than 10 lines. I
|
|
|
6488
7088
|
currentOrchestratorEntry = null;
|
|
6489
7089
|
askUserStarts.clear();
|
|
6490
7090
|
turnAskUserIntervals.length = 0;
|
|
7091
|
+
// Fresh turn → fresh budget window (mode itself persists across turns).
|
|
7092
|
+
// The tier and the duplicate guard are turn-scoped too: a new user message
|
|
7093
|
+
// is a new ask, so it re-triages and may legitimately repeat a task.
|
|
7094
|
+
turnDispatchCount = 0;
|
|
7095
|
+
turnResearchCount = 0;
|
|
7096
|
+
turnTaskTier = null;
|
|
7097
|
+
turnDispatchFingerprints.clear();
|
|
7098
|
+
// Snapshot the previous turn's cost report before opening a fresh one.
|
|
7099
|
+
if (turnReport.dispatches.length > 0 || turnReport.research > 0 || turnReport.refusals > 0) {
|
|
7100
|
+
lastTurnReport = turnReport;
|
|
7101
|
+
sessionTotals.turns++;
|
|
7102
|
+
}
|
|
7103
|
+
turnReport = freshTurnReport();
|
|
7104
|
+
updateModeStatus();
|
|
6491
7105
|
|
|
6492
7106
|
// Build dynamic agent catalog from active team only
|
|
6493
7107
|
const agentCatalog = Array.from(agentStates.values())
|
|
@@ -6537,8 +7151,8 @@ ask the human. You MUST instead:
|
|
|
6537
7151
|
the user in ${userLanguage} and wait for their reply in the next turn.`;
|
|
6538
7152
|
|
|
6539
7153
|
const toolList = askUserAvailable
|
|
6540
|
-
? "these tools: `dispatch_agent` (delegate work to a specialist), `spawn_research` (run a read-only research helper), `set_assertions` / `update_assertion` / `get_assertions` (own and read back the acceptance-assertion ledger), and `ask_user` (talk to the human)"
|
|
6541
|
-
: "these tools: `dispatch_agent` (delegate work to a specialist), `spawn_research` (run a read-only research helper), and `set_assertions` / `update_assertion` / `get_assertions` (own and read back the acceptance-assertion ledger). `ask_user` is NOT available — see the section below";
|
|
7154
|
+
? "these tools: `dispatch_agent` (delegate work to a specialist), `spawn_research` (run a read-only research helper), `set_task_tier` (classify the ask before the first dispatch), `team_adjust` (add/drop a team persona, sparingly), `set_assertions` / `update_assertion` / `get_assertions` (own and read back the acceptance-assertion ledger), and `ask_user` (talk to the human)"
|
|
7155
|
+
: "these tools: `dispatch_agent` (delegate work to a specialist), `spawn_research` (run a read-only research helper), `set_task_tier` (classify the ask before the first dispatch), `team_adjust` (add/drop a team persona, sparingly), and `set_assertions` / `update_assertion` / `get_assertions` (own and read back the acceptance-assertion ledger). `ask_user` is NOT available — see the section below";
|
|
6542
7156
|
|
|
6543
7157
|
const dispatchSection = askUserAvailable
|
|
6544
7158
|
? `- BEFORE dispatching: if anything is ambiguous, missing, or could go several valid
|
|
@@ -6580,6 +7194,105 @@ ask the human. You MUST instead:
|
|
|
6580
7194
|
- When a specialist emits an \`ASK_USER:\` line in English, translate it to
|
|
6581
7195
|
${userLanguage} before relaying to the user.${userLanguage.toLowerCase() === "english" ? " (If user-language is English this is a no-op.)" : ""}`;
|
|
6582
7196
|
|
|
7197
|
+
// ── Execution mode section + mode-conditional Verification Contract ──
|
|
7198
|
+
// The mode is the dispatcher's operating envelope: the hub ENFORCES the
|
|
7199
|
+
// budgets in code (dispatch_agent/spawn_research refuse past them); the
|
|
7200
|
+
// prompt teaches the dispatcher to plan within them instead of hitting them.
|
|
7201
|
+
const budget = currentBudget();
|
|
7202
|
+
const cap = (n: number | null) => (n == null ? "unlimited" : String(n));
|
|
7203
|
+
const capMin = (ms: number | null) => (ms == null ? "unlimited" : `${Math.round(ms / 60_000)} min`);
|
|
7204
|
+
const modeSection = `## Task triage (FIRST, before any dispatch)
|
|
7205
|
+
Call \`set_task_tier\` to classify THIS turn's ask — the hub lowers the enforced caps
|
|
7206
|
+
to min(mode, tier), so an honest tier is how you avoid burning budget on ceremony:
|
|
7207
|
+
- trivial — one obvious, low-risk change (1 dispatch, 1 research). No ledger, no review pipeline.
|
|
7208
|
+
- small — a contained change in familiar code (2 dispatches, 2 research). At most 3 narrow assertions.
|
|
7209
|
+
- feature — a normal multi-step feature (6 dispatches, 4 research). Ledger + one review gate.
|
|
7210
|
+
- project — a large, multi-phase effort (mode budget applies). Full rigor per the mode.
|
|
7211
|
+
If you skip the call, the hub assumes "feature". Re-call it (say why) if the ask turns
|
|
7212
|
+
out bigger — raising the tier mid-turn is allowed. Tie the tier to the USER'S ask, not
|
|
7213
|
+
to how interesting the work is.
|
|
7214
|
+
- A provided plan is a SPEC: when the user hands you an existing plan/task list (a PLAN
|
|
7215
|
+
file, a numbered breakdown), do NOT re-plan or re-spec it. Skip planner and
|
|
7216
|
+
plan-reviewer; batch the plan's tasks straight to the builder and use the plan's own
|
|
7217
|
+
acceptance criteria as the assertions.
|
|
7218
|
+
- Using every persona is a smell, not a virtue: each dispatch must change the outcome.
|
|
7219
|
+
If a dispatch's absence would change nothing, don't make it.
|
|
7220
|
+
|
|
7221
|
+
## Execution mode: ${hubMode}${turnTaskTier ? ` · tier: ${turnTaskTier}` : ""}
|
|
7222
|
+
Budgets for THIS user turn (enforced by the hub — exhausted budgets make dispatch_agent/
|
|
7223
|
+
spawn_research refuse; a new user message opens a fresh window; /hub-mode switches mode):
|
|
7224
|
+
- dispatch_agent calls: ${cap(budget.maxDispatches)} · spawn_research calls: ${cap(budget.maxResearch)}
|
|
7225
|
+
- turn wall clock: ${capMin(budget.wallMs)} · per-run deadline: ${capMin(budget.agentTurnMs)}
|
|
7226
|
+
Plan within the budget: batch related work into ONE dispatch (a coherent slice of 4–6
|
|
7227
|
+
plan tasks, not one dispatch per micro-task), and when a budget refusal comes back, STOP —
|
|
7228
|
+
summarize progress and ask the user; never retry the refused call in the same turn.
|
|
7229
|
+
Repeating an identical task to the same agent in one turn is refused in code
|
|
7230
|
+
(duplicate guard) — use the earlier result or change the task materially.
|
|
7231
|
+
Every task you dispatch states four things: the objective, the expected output format,
|
|
7232
|
+
the files in scope (also pass them as \`scope\` globs — they arm the live drift watchdog),
|
|
7233
|
+
and the boundaries (what NOT to touch). Vague tasks produce duplicated or drifting work.
|
|
7234
|
+
${hubMode === "fast"
|
|
7235
|
+
? `FAST mode rules: this is a single-specialist path for small, low-risk asks.
|
|
7236
|
+
- Use at most ONE specialist dispatch (plus one research call only if truly needed).
|
|
7237
|
+
- Skip the assertion ledger and the plan/review pipeline; rely on the specialist's own
|
|
7238
|
+
verification and report back.
|
|
7239
|
+
- Nested delegation is disabled; do not commission inventories or parity audits.
|
|
7240
|
+
- If the task turns out to be larger than fast mode fits, say so and ask the user to
|
|
7241
|
+
switch modes (/hub-mode standard) instead of burning the budget.`
|
|
7242
|
+
: hubMode === "standard"
|
|
7243
|
+
? `STANDARD mode rules: rigor where it pays, batching everywhere else.
|
|
7244
|
+
- At most ONE reconnaissance pass before building (skip it for familiar code); prefer the
|
|
7245
|
+
specialist's own recon over a separate research run.
|
|
7246
|
+
- Execute plans in a FEW large batches (4–6 tasks per builder dispatch), each followed by
|
|
7247
|
+
ONE verification gate; do not re-audit everything after every small fix — re-verify only
|
|
7248
|
+
the assertions the fix touched.
|
|
7249
|
+
- One review gate at the end (code review; security only when the change is
|
|
7250
|
+
security-sensitive) — not one per micro-slice.
|
|
7251
|
+
- Reserve deep-researcher for genuinely cross-cutting questions (max 1–2 per task).`
|
|
7252
|
+
: `STRICT mode rules: the full Verification Contract below applies — use for production
|
|
7253
|
+
migrations, security-sensitive work, or when the user explicitly asks for it. The wide
|
|
7254
|
+
budgets are a checkpoint, not a target: when one is hit, stop and check in with the user.`}
|
|
7255
|
+
`;
|
|
7256
|
+
|
|
7257
|
+
const fullVerificationContract = `## Verification Contract (assertion ledger)
|
|
7258
|
+
A clearly stated requirement must never be silently dropped. You OWN a ledger of checkable
|
|
7259
|
+
acceptance assertions; build it before you dispatch, and refuse "done" until each is proven.
|
|
7260
|
+
- BEFORE dispatching a builder for any non-trivial task, convert the request into numbered
|
|
7261
|
+
assertions and record them with \`set_assertions\` — one pass condition each, tagged
|
|
7262
|
+
test | runtime-ui | code-grep | manual (see skills/orchestration-verification/SKILL.md).
|
|
7263
|
+
Pass the relevant assertions VERBATIM into each dispatch.
|
|
7264
|
+
- Keep assertions NARROW: one subsystem / one behavior each. Never bundle several
|
|
7265
|
+
subsystems into one giant assertion — a compound assertion forces a full re-audit after
|
|
7266
|
+
every small fix. After a fix, re-verify the touched assertions only.
|
|
7267
|
+
- After each verification gate, call \`update_assertion\` with proven (and name the evidence),
|
|
7268
|
+
unproven, or failed. Advance ONLY on proven; unproven and failed both mean not done.
|
|
7269
|
+
- A runtime-ui assertion (visibility, placement, "appears in the table") is proven only by an
|
|
7270
|
+
actual runtime observation — dispatch a browser-capable specialist; a static review never
|
|
7271
|
+
closes it.
|
|
7272
|
+
- For "make X behave like existing Y" requests, FIRST spawn_research a deep-researcher parity
|
|
7273
|
+
inventory of every site where the exemplar is special-cased, and turn each site into an
|
|
7274
|
+
assertion — otherwise the exemplar ships and its siblings are missed.
|
|
7275
|
+
- On a "wrong again" correction, call \`set_assertions\` again to rebuild the ledger from the
|
|
7276
|
+
LATEST correction before re-dispatching (a regression reset — old summaries are now suspect).
|
|
7277
|
+
- After a context compaction your status line shows only counts (e.g. "2✓ 3○"), not the
|
|
7278
|
+
assertion text. Call \`get_assertions\` to read the full ledger back — ids, tags, pass
|
|
7279
|
+
conditions, and the named evidence on each proven/failed assertion — before you re-dispatch
|
|
7280
|
+
or report done. This is your bounded read-only window onto recorded ground truth; you do not
|
|
7281
|
+
author code.
|
|
7282
|
+
- Specialist returns land pre-parsed in \`details.structuredReturn\` with the raw return at
|
|
7283
|
+
\`details.returnPath\` — read the digest/path directly; NEVER spawn a research helper just to
|
|
7284
|
+
read a return artifact you already hold.
|
|
7285
|
+
The ledger is persisted and its status is shown to the human; it is advisory — it informs your
|
|
7286
|
+
gating, it does not auto-block a dispatch.`;
|
|
7287
|
+
|
|
7288
|
+
const verificationSection = hubMode === "fast"
|
|
7289
|
+
? `## Verification (fast mode)
|
|
7290
|
+
The assertion ledger is OPTIONAL in fast mode. State what was asked, dispatch the one
|
|
7291
|
+
specialist, and verify from its returned evidence (command output, file:line). If the
|
|
7292
|
+
request carries real acceptance criteria or turns risky, ask the user to switch to
|
|
7293
|
+
standard/strict instead of improvising rigor here.`
|
|
7294
|
+
: fullVerificationContract;
|
|
7295
|
+
|
|
6583
7296
|
// Peer section only when coms initialised. Decision G4: the coms_* tools are
|
|
6584
7297
|
// already in the active tool surface when ready; here we just teach the
|
|
6585
7298
|
// dispatcher how and when to reach for them.
|
|
@@ -6615,7 +7328,10 @@ ${languageLines}
|
|
|
6615
7328
|
## Active Team: ${activeTeamName}
|
|
6616
7329
|
Members: ${teamMembers}
|
|
6617
7330
|
You can ONLY dispatch to agents listed below. Do not attempt to dispatch to agents
|
|
6618
|
-
outside this team.
|
|
7331
|
+
outside this team. The roster CAN change mid-session: the human via /agents-add,
|
|
7332
|
+
/agents-drop, /agents-team — or you via \`team_adjust\` (add/drop with a reason)
|
|
7333
|
+
when the current roster genuinely cannot serve the task. Use it sparingly; more
|
|
7334
|
+
personas is usually the wrong answer.
|
|
6619
7335
|
|
|
6620
7336
|
## How to Work
|
|
6621
7337
|
- Analyze the user's request and break it into clear sub-tasks.
|
|
@@ -6627,30 +7343,8 @@ ${dispatchSection}
|
|
|
6627
7343
|
|
|
6628
7344
|
${askUserBlock}
|
|
6629
7345
|
|
|
6630
|
-
|
|
6631
|
-
|
|
6632
|
-
acceptance assertions; build it before you dispatch, and refuse "done" until each is proven.
|
|
6633
|
-
- BEFORE dispatching a builder for any non-trivial task, convert the request into numbered
|
|
6634
|
-
assertions and record them with \`set_assertions\` — one pass condition each, tagged
|
|
6635
|
-
test | runtime-ui | code-grep | manual (see skills/orchestration-verification/SKILL.md).
|
|
6636
|
-
Pass the relevant assertions VERBATIM into each dispatch.
|
|
6637
|
-
- After each verification gate, call \`update_assertion\` with proven (and name the evidence),
|
|
6638
|
-
unproven, or failed. Advance ONLY on proven; unproven and failed both mean not done.
|
|
6639
|
-
- A runtime-ui assertion (visibility, placement, "appears in the table") is proven only by an
|
|
6640
|
-
actual runtime observation — dispatch a browser-capable specialist; a static review never
|
|
6641
|
-
closes it.
|
|
6642
|
-
- For "make X behave like existing Y" requests, FIRST spawn_research a deep-researcher parity
|
|
6643
|
-
inventory of every site where the exemplar is special-cased, and turn each site into an
|
|
6644
|
-
assertion — otherwise the exemplar ships and its siblings are missed.
|
|
6645
|
-
- On a "wrong again" correction, call \`set_assertions\` again to rebuild the ledger from the
|
|
6646
|
-
LATEST correction before re-dispatching (a regression reset — old summaries are now suspect).
|
|
6647
|
-
- After a context compaction your status line shows only counts (e.g. "2✓ 3○"), not the
|
|
6648
|
-
assertion text. Call \`get_assertions\` to read the full ledger back — ids, tags, pass
|
|
6649
|
-
conditions, and the named evidence on each proven/failed assertion — before you re-dispatch
|
|
6650
|
-
or report done. This is your bounded read-only window onto recorded ground truth; you do not
|
|
6651
|
-
author code.
|
|
6652
|
-
The ledger is persisted and its status is shown to the human; it is advisory — it informs your
|
|
6653
|
-
gating, it does not auto-block a dispatch.
|
|
7346
|
+
${modeSection}
|
|
7347
|
+
${verificationSection}
|
|
6654
7348
|
|
|
6655
7349
|
## Research helpers (read-only)
|
|
6656
7350
|
- \`spawn_research\` runs a READ-ONLY helper (read/grep/find/ls — no bash, no writes)
|
|
@@ -6717,6 +7411,8 @@ ${researchCatalog}`;
|
|
|
6717
7411
|
// ── Session Start ────────────────────────────
|
|
6718
7412
|
|
|
6719
7413
|
pi.on("session_start", async (_event, _ctx) => {
|
|
7414
|
+
registerVersionStatus(_ctx);
|
|
7415
|
+
accessApprovalRouter.reset();
|
|
6720
7416
|
// Clear widgets + any research helpers from a previous session
|
|
6721
7417
|
for (const [, st] of Array.from(researchStates.entries())) {
|
|
6722
7418
|
if (st.proc && st.status === "running") { st.killedByOperator = true; st.proc.kill("SIGTERM"); }
|
|
@@ -6741,16 +7437,95 @@ ${researchCatalog}`;
|
|
|
6741
7437
|
delegatedTokens = 0;
|
|
6742
7438
|
widgetCtx = _ctx;
|
|
6743
7439
|
contextWindow = _ctx.model?.contextWindow || 0;
|
|
6744
|
-
|
|
6745
|
-
|
|
6746
|
-
if (!damageControlExtPath) {
|
|
7440
|
+
safetyHarnessPath = resolveSafetyHarness(_ctx.cwd);
|
|
7441
|
+
if (!safetyHarnessPath) {
|
|
6747
7442
|
_ctx.ui.notify(
|
|
6748
|
-
"damage-control harness not found —
|
|
6749
|
-
"
|
|
7443
|
+
"damage-control-continue harness not found — native child dispatches will be refused. Install .pi/harnesses/damage-control-continue/.",
|
|
7444
|
+
"error",
|
|
6750
7445
|
);
|
|
6751
7446
|
}
|
|
6752
7447
|
delegateExtPath = resolveDelegateExtension(_ctx.cwd);
|
|
6753
7448
|
|
|
7449
|
+
const monitorConfig = monitorLifecycleConfig(process.env);
|
|
7450
|
+
if (monitorBridge || monitorLifecycle) { try { await monitorBridge?.cancelAllWaitOnly(); await monitorLifecycle?.stop(); } finally { monitorBridge=null; monitorLifecycle=null; } }
|
|
7451
|
+
if (monitorConfig) {
|
|
7452
|
+
try {
|
|
7453
|
+
fs.mkdirSync(monitorConfig.profilePath, { recursive: true, mode: 0o700 });
|
|
7454
|
+
const stableHubId = stableMonitorHubId({ profileId: monitorConfig.profileId, checkout: _ctx.cwd || process.cwd(), workspaceId: process.env.HERDR_WORKSPACE_ID, paneId: process.env.HERDR_PANE_ID });
|
|
7455
|
+
monitorHubId = stableHubId;
|
|
7456
|
+
const store = new MonitorStore();
|
|
7457
|
+
const monitorRegistry = new MonitorRegistry({ runtimeDir: monitorConfig.runtimeDir });
|
|
7458
|
+
monitorLifecycle = createMonitorLifecycle({
|
|
7459
|
+
registry: monitorRegistry,
|
|
7460
|
+
treeKill: killPiTree,
|
|
7461
|
+
wait: (proc: ChildProcess) => new Promise<boolean>((resolve) => proc.once("close", () => resolve(true))),
|
|
7462
|
+
getRecoveryEvidence: async (task: any) => {
|
|
7463
|
+
if (task?.ownerSessionId) {
|
|
7464
|
+
const evidence = monitorRegistry.evidenceForOwner(task.ownerSessionId, task.hubInstanceId ?? stableHubId);
|
|
7465
|
+
if (evidence.transient) return { transient: true };
|
|
7466
|
+
const herdr = await monitorReconcileEvidence({
|
|
7467
|
+
hubId: task.hubInstanceId ?? stableHubId,
|
|
7468
|
+
currentHubId: stableHubId,
|
|
7469
|
+
paneId: process.env.HERDR_PANE_ID,
|
|
7470
|
+
workspaceId: process.env.HERDR_WORKSPACE_ID,
|
|
7471
|
+
herdr: {
|
|
7472
|
+
pane: { get: async (id: string) => (await herdrApi.paneGet(id)).pane },
|
|
7473
|
+
workspace: { get: async (id: string) => {
|
|
7474
|
+
const panes = await herdrApi.paneList({ workspace_id: id });
|
|
7475
|
+
return panes.panes.length ? { id } : null;
|
|
7476
|
+
} },
|
|
7477
|
+
},
|
|
7478
|
+
});
|
|
7479
|
+
return {
|
|
7480
|
+
oldOwner: evidence.owner,
|
|
7481
|
+
oldSocket: evidence.socket,
|
|
7482
|
+
oldSession: evidence.session,
|
|
7483
|
+
oldHerdr: herdr.herdr,
|
|
7484
|
+
transient: herdr.transient,
|
|
7485
|
+
};
|
|
7486
|
+
}
|
|
7487
|
+
return monitorReconcileEvidence({
|
|
7488
|
+
owner: monitorLifecycle?.isAlive(),
|
|
7489
|
+
socket: monitorLifecycle?.isAlive(),
|
|
7490
|
+
session: true,
|
|
7491
|
+
hubId: stableHubId,
|
|
7492
|
+
currentHubId: stableHubId,
|
|
7493
|
+
paneId: process.env.HERDR_PANE_ID,
|
|
7494
|
+
workspaceId: process.env.HERDR_WORKSPACE_ID,
|
|
7495
|
+
herdr: {
|
|
7496
|
+
pane: { get: async (id: string) => (await herdrApi.paneGet(id)).pane },
|
|
7497
|
+
workspace: { get: async (id: string) => {
|
|
7498
|
+
const panes = await herdrApi.paneList({ workspace_id: id });
|
|
7499
|
+
return panes.panes.length ? { id } : null;
|
|
7500
|
+
} },
|
|
7501
|
+
},
|
|
7502
|
+
});
|
|
7503
|
+
},
|
|
7504
|
+
});
|
|
7505
|
+
monitorBridge = createMonitorSessionBridge({
|
|
7506
|
+
runtime: new MonitorRuntime({
|
|
7507
|
+
runtimeDir: monitorConfig.runtimeDir,
|
|
7508
|
+
profileId: monitorConfig.profileId,
|
|
7509
|
+
hubInstanceId: stableHubId,
|
|
7510
|
+
}),
|
|
7511
|
+
registerOwnedProcess: (_key: string, process: ChildProcess, task: any) => monitorLifecycle?.registerOwnedGeneration({
|
|
7512
|
+
taskId: task.id,
|
|
7513
|
+
generation: task.generation,
|
|
7514
|
+
process,
|
|
7515
|
+
}),
|
|
7516
|
+
cancelOwnedProcess: (request: any) => monitorLifecycle?.lowLevelCancelOwnedGeneration(request) ?? {
|
|
7517
|
+
cancelled: false,
|
|
7518
|
+
reason: "unsupported",
|
|
7519
|
+
},
|
|
7520
|
+
});
|
|
7521
|
+
if (!monitorBridge.snapshot().tasks.some((task: any) => task.kind === "parent")) monitorBridge.startParent({ id: `hub-turn-${stableHubId}`, hubInstanceId: stableHubId, checkoutId: _ctx.cwd || process.cwd() });
|
|
7522
|
+
await monitorLifecycle.startBridge(monitorBridge, { profilePath: monitorConfig.profilePath, profileId: monitorConfig.profileId, hubInstanceId: stableHubId });
|
|
7523
|
+
} catch (error) {
|
|
7524
|
+
monitorLifecycle = null;
|
|
7525
|
+
_ctx.ui.notify(`Agent Fleet monitor disabled: ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
7526
|
+
}
|
|
7527
|
+
}
|
|
7528
|
+
|
|
6754
7529
|
// ── Embedded coms init ──
|
|
6755
7530
|
// Always refresh the ctx the coms handlers use. Bind the endpoint + register
|
|
6756
7531
|
// in the pool exactly once per process (guard on comsReady), so a /new session
|
|
@@ -6901,6 +7676,16 @@ ${researchCatalog}`;
|
|
|
6901
7676
|
const overrides = parseAgentTeamOverrides(_ctx.cwd);
|
|
6902
7677
|
userLanguage = overrides.language;
|
|
6903
7678
|
researchKeep = overrides.researchKeep;
|
|
7679
|
+
reconSearchTimeoutMs = overrides.reconSearchTimeoutMs;
|
|
7680
|
+
hubMode = overrides.hubMode;
|
|
7681
|
+
budgetOverrides = overrides.budgetOverrides;
|
|
7682
|
+
watchdogSetting = overrides.watchdogSetting;
|
|
7683
|
+
watchdogJudgeModel = overrides.watchdogJudgeModel;
|
|
7684
|
+
turnDispatchCount = 0;
|
|
7685
|
+
turnResearchCount = 0;
|
|
7686
|
+
turnTaskTier = null;
|
|
7687
|
+
turnDispatchFingerprints.clear();
|
|
7688
|
+
updateModeStatus();
|
|
6904
7689
|
if (overrides.warnings.length > 0) {
|
|
6905
7690
|
_ctx.ui.notify(`agent-fleet-overrides warnings:\n${overrides.warnings.join("\n")}`, "warning");
|
|
6906
7691
|
}
|
|
@@ -7002,7 +7787,7 @@ ${researchCatalog}`;
|
|
|
7002
7787
|
// The coms_* tools when the peer layer bound successfully; ask_user only when
|
|
7003
7788
|
// pi-ask-user is installed. Per decision G4 the dispatcher persona NEVER narrows
|
|
7004
7789
|
// this surface.
|
|
7005
|
-
const dispatcherTools = ["dispatch_agent", "spawn_research", "set_assertions", "update_assertion", "get_assertions"];
|
|
7790
|
+
const dispatcherTools = ["dispatch_agent", "spawn_research", "set_task_tier", "team_adjust", "set_assertions", "update_assertion", "get_assertions"];
|
|
7006
7791
|
if (comsReady) dispatcherTools.push("coms_list", "coms_send", "coms_get", "coms_await");
|
|
7007
7792
|
if (askUserAvailable) dispatcherTools.push("ask_user");
|
|
7008
7793
|
// Fleet tools only inside a herdr pane with a live server (graceful
|
|
@@ -7091,9 +7876,7 @@ ${researchCatalog}`;
|
|
|
7091
7876
|
const filled = Math.round(pct / 10);
|
|
7092
7877
|
const bar = "#".repeat(filled) + "-".repeat(10 - filled);
|
|
7093
7878
|
|
|
7094
|
-
const left = theme
|
|
7095
|
-
theme.fg("muted", " · ") +
|
|
7096
|
-
theme.fg("accent", activeTeamName);
|
|
7879
|
+
const left = renderHubFooterLeft(theme, HARNESS_VERSION, model, think, activeTeamName);
|
|
7097
7880
|
const hint = theme.fg("muted", "Alt+A ") + theme.fg("dim", `view:${viewMode}`);
|
|
7098
7881
|
// The btw extension flips this global the first time a /btw command or
|
|
7099
7882
|
// Alt+' is used; surface its reopen shortcut right next to the Alt+A hint.
|
|
@@ -7223,6 +8006,14 @@ ${researchCatalog}`;
|
|
|
7223
8006
|
try { server.close(); } catch { /* ignore */ }
|
|
7224
8007
|
server = null;
|
|
7225
8008
|
}
|
|
8009
|
+
if (monitorBridge) { try { await monitorBridge.cancelAllWaitOnly(); } catch { /* ignore */ } }
|
|
8010
|
+
if (monitorLifecycle) {
|
|
8011
|
+
try { await monitorLifecycle.stop(); } catch { /* ignore */ }
|
|
8012
|
+
monitorLifecycle = null;
|
|
8013
|
+
}
|
|
8014
|
+
monitorBridge?.reset();
|
|
8015
|
+
monitorBridge?.stop();
|
|
8016
|
+
monitorBridge = null;
|
|
7226
8017
|
if (identity) {
|
|
7227
8018
|
if (process.platform !== "win32") {
|
|
7228
8019
|
try { fs.unlinkSync(identity.endpoint); } catch { /* ignore */ }
|