@chankov/agent-fleet 0.0.2 → 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/doctor-agent-fleet.md +1 -1
- package/.claude/commands/setup-agent-fleet.md +5 -5
- package/.opencode/commands/af-doctor-agent-fleet.md +2 -0
- package/.opencode/commands/af-setup-agent-fleet.md +1 -1
- package/.pi/agents/peers.yaml +4 -0
- package/.pi/agents/teams.yaml +2 -2
- package/.pi/harnesses/agent-hub/README.md +254 -18
- 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 +1269 -322
- 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-retention.js +34 -0
- 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/ask-user-remote/README.md +2 -0
- package/.pi/harnesses/coms/README.md +21 -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/doctor-agent-fleet.md +1 -1
- package/.pi/prompts/setup-agent-fleet.md +5 -5
- 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 +103 -541
- package/agents/architect.md +1 -1
- 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/planner.md +1 -1
- package/agents/security-auditor.md +1 -1
- package/agents/test-engineer.md +11 -4
- package/bin/lib/validate-overrides.js +19 -0
- package/bin/snapshot-version.js +17 -1
- package/bin/sync-harness-versions.js +94 -0
- package/codex/CONDUCTOR.md +148 -0
- package/docs/ARCHITECTURE.md +210 -0
- package/docs/agent-fleet-setup.md +11 -0
- package/docs/claude-code-coms-bridge.md +10 -0
- package/docs/codex-remote-conductor.md +170 -0
- package/docs/coms-hermes-bridge.md +121 -0
- package/docs/getting-started.md +14 -0
- package/docs/npm-install.md +2 -0
- package/docs/pi-extensions.md +49 -14
- package/docs/pi-setup.md +12 -4
- package/hermes/README.md +228 -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/hermes/skills/hub-conductor/SKILL.md +84 -0
- package/hermes/skills/hub-liaison/SKILL.md +84 -0
- package/justfile +106 -23
- package/package.json +17 -5
- package/scripts/codex-conductor.ts +41 -0
- package/scripts/codex-remote-control.ts +167 -0
- package/scripts/coms-cli.ts +311 -199
- package/scripts/coms-hermes-bridge.ts +2 -2
- package/scripts/lib/codex-conductor.ts +88 -0
- package/scripts/lib/codex-remote-control.ts +480 -0
- package/scripts/lib/coms-envelope.ts +51 -6
- package/scripts/lib/fake-herdr-server.ts +88 -0
- package/scripts/lib/herdr-layout.ts +18 -3
- package/scripts/lib/hermes-bridge-core.ts +4 -4
- 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/scripts/lib/team-project.ts +85 -1
- package/scripts/team-up.ts +77 -18
- 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 +131 -102
- package/skills/guided-workspace-setup/companion-manifest.json +33 -0
- package/skills/peer-coms/SKILL.md +9 -0
- package/systemd/user/agent-fleet-codex-remote-control.service.in +23 -0
- package/.pi/harnesses/damage-control/README.md +0 -65
- package/.pi/harnesses/damage-control/index.ts +0 -250
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
// scripts/coms-hermes-bridge.ts
|
|
2
|
+
//
|
|
3
|
+
// Hermes/Telegram user-remote bridge daemon. Registers a coms peer, turns
|
|
4
|
+
// prompt envelopes into `hermes send` messages, watches the private answer-file
|
|
5
|
+
// wire, and replies to the sender with the mapped answer/error envelope.
|
|
6
|
+
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import * as fs from "node:fs";
|
|
9
|
+
import * as path from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
|
|
12
|
+
import {
|
|
13
|
+
bindEndpoint,
|
|
14
|
+
ensureComsDirs,
|
|
15
|
+
isCancelEnvelope,
|
|
16
|
+
isPromptEnvelope,
|
|
17
|
+
makeConnHandler,
|
|
18
|
+
makeEndpoint,
|
|
19
|
+
makeResponseEnvelope,
|
|
20
|
+
nowIso,
|
|
21
|
+
removeRegistryEntry,
|
|
22
|
+
resolveUniqueName,
|
|
23
|
+
sendEnvelope,
|
|
24
|
+
ulid,
|
|
25
|
+
writeAck,
|
|
26
|
+
writeNack,
|
|
27
|
+
writeRegistryAtomic,
|
|
28
|
+
type AgentCard,
|
|
29
|
+
type PromptEnvelope,
|
|
30
|
+
type RegistryEntry,
|
|
31
|
+
type SenderIdentity,
|
|
32
|
+
} from "./lib/coms-envelope.ts";
|
|
33
|
+
import {
|
|
34
|
+
formatTelegramQuestion,
|
|
35
|
+
isValidQid,
|
|
36
|
+
logPath as defaultLogPath,
|
|
37
|
+
makeLogRecord,
|
|
38
|
+
mapAnswerToAskResponse,
|
|
39
|
+
qidFromPromptEnvelope,
|
|
40
|
+
questionsDir as defaultQuestionsDir,
|
|
41
|
+
renderLogRecord,
|
|
42
|
+
timeoutMsFromEnv,
|
|
43
|
+
timeoutOutcome,
|
|
44
|
+
validateAnswerFile,
|
|
45
|
+
type BridgeEventName,
|
|
46
|
+
type QuestionOption,
|
|
47
|
+
type QuestionState,
|
|
48
|
+
} from "./lib/hermes-bridge-core.ts";
|
|
49
|
+
|
|
50
|
+
const KEEPALIVE_MS = 30_000;
|
|
51
|
+
const DEFAULT_POLL_MS = 1_000;
|
|
52
|
+
const COLOR = "#38BDF8";
|
|
53
|
+
const DEFAULT_NAME = "user-remote";
|
|
54
|
+
const DEFAULT_PURPOSE = "Remote human via Hermes/Telegram";
|
|
55
|
+
|
|
56
|
+
interface PendingQuestion {
|
|
57
|
+
env: PromptEnvelope;
|
|
58
|
+
state: QuestionState;
|
|
59
|
+
options: QuestionOption[];
|
|
60
|
+
timer: NodeJS.Timeout;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface ParsedPrompt {
|
|
64
|
+
question: string;
|
|
65
|
+
context?: string;
|
|
66
|
+
options: QuestionOption[];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function flagValue(argv: string[], flag: string): string | null {
|
|
70
|
+
const i = argv.indexOf(flag);
|
|
71
|
+
return i >= 0 && i + 1 < argv.length ? argv[i + 1] : null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function die(msg: string): never {
|
|
75
|
+
console.error(`coms-hermes-bridge: ${msg}`);
|
|
76
|
+
process.exit(1);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function parsePrompt(env: PromptEnvelope): ParsedPrompt {
|
|
80
|
+
try {
|
|
81
|
+
const parsed = JSON.parse(env.prompt) as { question?: unknown; context?: unknown; options?: unknown };
|
|
82
|
+
if (parsed && typeof parsed === "object" && typeof parsed.question === "string") {
|
|
83
|
+
const rawOptions = Array.isArray(parsed.options) ? parsed.options : [];
|
|
84
|
+
const options = rawOptions
|
|
85
|
+
.map((option): QuestionOption | null => {
|
|
86
|
+
if (typeof option === "string") return { title: option };
|
|
87
|
+
if (option && typeof option === "object" && typeof (option as { title?: unknown }).title === "string") {
|
|
88
|
+
const desc = (option as { description?: unknown }).description;
|
|
89
|
+
return typeof desc === "string"
|
|
90
|
+
? { title: (option as { title: string }).title, description: desc }
|
|
91
|
+
: { title: (option as { title: string }).title };
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
})
|
|
95
|
+
.filter((option): option is QuestionOption => option !== null);
|
|
96
|
+
const context = typeof parsed.context === "string" && parsed.context.trim() ? parsed.context : undefined;
|
|
97
|
+
return { question: parsed.question, context, options };
|
|
98
|
+
}
|
|
99
|
+
} catch {
|
|
100
|
+
// Plain coms-cli prompts are expected; fall through.
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
question: env.prompt,
|
|
104
|
+
context: `From ${env.sender_name} @ ${env.sender_cwd}`,
|
|
105
|
+
options: [],
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function appendLogFile(logFile: string, qid: string, event: BridgeEventName, detail?: unknown): void {
|
|
110
|
+
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
|
111
|
+
fs.appendFileSync(logFile, renderLogRecord(makeLogRecord(qid, event, detail)));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function appendAnswerRejectLog(logFile: string, qid: string, detail: unknown): void {
|
|
115
|
+
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
|
116
|
+
fs.appendFileSync(logFile, JSON.stringify({ at: nowIso(), qid, event: "answer_rejected", detail }) + "\n");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function hermesSend(to: string, text: string): Promise<void> {
|
|
120
|
+
return new Promise((resolve, reject) => {
|
|
121
|
+
const child = spawn("hermes", ["send", "--to", to, text], { stdio: ["ignore", "pipe", "pipe"] });
|
|
122
|
+
let stderr = "";
|
|
123
|
+
let stdout = "";
|
|
124
|
+
child.stdout?.on("data", (chunk) => { stdout += chunk.toString("utf-8"); });
|
|
125
|
+
child.stderr?.on("data", (chunk) => { stderr += chunk.toString("utf-8"); });
|
|
126
|
+
child.once("error", (err) => reject(err));
|
|
127
|
+
child.once("close", (code) => {
|
|
128
|
+
if (code === 0) {
|
|
129
|
+
resolve();
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const detail = (stderr || stdout).trim();
|
|
133
|
+
reject(new Error(`hermes send failed${code === null ? "" : ` (${code})`}${detail ? `: ${detail}` : ""}`));
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function main(): Promise<void> {
|
|
139
|
+
const argv = process.argv.slice(2);
|
|
140
|
+
const requestedName = flagValue(argv, "--name") ?? DEFAULT_NAME;
|
|
141
|
+
const project = flagValue(argv, "--project") ?? "default";
|
|
142
|
+
const to = flagValue(argv, "--to") ?? "telegram";
|
|
143
|
+
const timeoutMs = Number(flagValue(argv, "--timeout") ?? timeoutMsFromEnv());
|
|
144
|
+
const pollMs = Number(flagValue(argv, "--poll-ms") ?? DEFAULT_POLL_MS);
|
|
145
|
+
const qDir = flagValue(argv, "--questions-dir") ?? defaultQuestionsDir();
|
|
146
|
+
const logFile = path.join(path.dirname(qDir), path.basename(defaultLogPath()));
|
|
147
|
+
|
|
148
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) die("--timeout must be a positive number");
|
|
149
|
+
if (!Number.isFinite(pollMs) || pollMs <= 0) die("--poll-ms must be a positive number");
|
|
150
|
+
|
|
151
|
+
ensureComsDirs(project);
|
|
152
|
+
fs.mkdirSync(qDir, { recursive: true });
|
|
153
|
+
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
|
154
|
+
|
|
155
|
+
const sessionId = ulid();
|
|
156
|
+
const uniqueName = resolveUniqueName(project, requestedName);
|
|
157
|
+
const id: SenderIdentity = {
|
|
158
|
+
session_id: sessionId,
|
|
159
|
+
name: uniqueName,
|
|
160
|
+
endpoint: makeEndpoint(sessionId),
|
|
161
|
+
cwd: process.cwd(),
|
|
162
|
+
};
|
|
163
|
+
const pending = new Map<string, PendingQuestion>();
|
|
164
|
+
const closed = new Map<string, QuestionState>();
|
|
165
|
+
// Answer files the liaison may still be mid-write: an invalid_json file is
|
|
166
|
+
// kept for a short grace window (first-seen timestamps below) instead of
|
|
167
|
+
// being eaten while the write is still in flight.
|
|
168
|
+
const invalidJsonSeen = new Map<string, number>();
|
|
169
|
+
const invalidJsonGraceMs = Math.max(2 * pollMs, 1_000);
|
|
170
|
+
const CLOSED_CAP = 1_000;
|
|
171
|
+
|
|
172
|
+
function markClosed(qid: string, state: QuestionState): void {
|
|
173
|
+
closed.set(qid, state);
|
|
174
|
+
if (closed.size > CLOSED_CAP) {
|
|
175
|
+
const oldest = closed.keys().next().value;
|
|
176
|
+
if (oldest !== undefined) closed.delete(oldest);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function queueDepth(): number {
|
|
181
|
+
return pending.size;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function registryEntry(): RegistryEntry {
|
|
185
|
+
return {
|
|
186
|
+
session_id: sessionId,
|
|
187
|
+
name: uniqueName,
|
|
188
|
+
purpose: DEFAULT_PURPOSE,
|
|
189
|
+
model: "hermes-bridge",
|
|
190
|
+
color: COLOR,
|
|
191
|
+
pid: process.pid,
|
|
192
|
+
endpoint: id.endpoint,
|
|
193
|
+
cwd: id.cwd,
|
|
194
|
+
started_at: nowIso(),
|
|
195
|
+
explicit: false,
|
|
196
|
+
version: 1,
|
|
197
|
+
context_used_pct: 0,
|
|
198
|
+
queue_depth: queueDepth(),
|
|
199
|
+
heartbeat_at: nowIso(),
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function sendResponse(env: PromptEnvelope, response: unknown, error: string | null = null): Promise<void> {
|
|
204
|
+
await sendEnvelope(env.sender_endpoint, makeResponseEnvelope(id, env.msg_id, response, error));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function handleTimeout(qid: string): Promise<void> {
|
|
208
|
+
const item = pending.get(qid);
|
|
209
|
+
if (!item) return;
|
|
210
|
+
pending.delete(qid);
|
|
211
|
+
markClosed(qid, "timeout");
|
|
212
|
+
appendLogFile(logFile, qid, "timeout", { timeout_ms: timeoutMs });
|
|
213
|
+
const outcome = timeoutOutcome(qid, timeoutMs);
|
|
214
|
+
await hermesSend(to, outcome.telegramNote).catch((err) => {
|
|
215
|
+
appendLogFile(logFile, qid, "delivery_error", { phase: "timeout_note", error: err instanceof Error ? err.message : String(err) });
|
|
216
|
+
});
|
|
217
|
+
await sendResponse(item.env, outcome.response, outcome.error).catch((err) => {
|
|
218
|
+
console.error(`coms-hermes-bridge: could not deliver timeout for ${qid}: ${err instanceof Error ? err.message : String(err)}`);
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async function handlePrompt(env: PromptEnvelope): Promise<void> {
|
|
223
|
+
let qid: string;
|
|
224
|
+
try {
|
|
225
|
+
qid = qidFromPromptEnvelope(env);
|
|
226
|
+
} catch (err) {
|
|
227
|
+
await sendResponse(env, null, err instanceof Error ? err.message : String(err)).catch(() => {});
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const parsed = parsePrompt(env);
|
|
232
|
+
const duplicate = pending.get(qid);
|
|
233
|
+
if (duplicate) clearTimeout(duplicate.timer);
|
|
234
|
+
appendLogFile(logFile, qid, "question_received", { from: env.sender_name });
|
|
235
|
+
const timer = setTimeout(() => { void handleTimeout(qid); }, timeoutMs);
|
|
236
|
+
timer.unref?.();
|
|
237
|
+
pending.set(qid, { env, state: "pending", options: parsed.options, timer });
|
|
238
|
+
|
|
239
|
+
try {
|
|
240
|
+
await hermesSend(to, formatTelegramQuestion({
|
|
241
|
+
qid,
|
|
242
|
+
question: parsed.question,
|
|
243
|
+
context: parsed.context,
|
|
244
|
+
options: parsed.options,
|
|
245
|
+
}));
|
|
246
|
+
const item = pending.get(qid);
|
|
247
|
+
if (!item) return;
|
|
248
|
+
item.state = "delivered";
|
|
249
|
+
appendLogFile(logFile, qid, "delivered", { to });
|
|
250
|
+
} catch (err) {
|
|
251
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
252
|
+
const item = pending.get(qid);
|
|
253
|
+
if (item) {
|
|
254
|
+
clearTimeout(item.timer);
|
|
255
|
+
pending.delete(qid);
|
|
256
|
+
}
|
|
257
|
+
appendLogFile(logFile, qid, "delivery_error", { error: message });
|
|
258
|
+
await sendResponse(env, null, message).catch((sendErr) => {
|
|
259
|
+
console.error(`coms-hermes-bridge: could not deliver error for ${qid}: ${sendErr instanceof Error ? sendErr.message : String(sendErr)}`);
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function handleCancel(refMsgId: string): Promise<void> {
|
|
265
|
+
if (!isValidQid(refMsgId)) return;
|
|
266
|
+
const item = pending.get(refMsgId);
|
|
267
|
+
if (!item) return;
|
|
268
|
+
clearTimeout(item.timer);
|
|
269
|
+
pending.delete(refMsgId);
|
|
270
|
+
markClosed(refMsgId, "cancelled");
|
|
271
|
+
appendLogFile(logFile, refMsgId, "cancelled", { reason: "cancel envelope" });
|
|
272
|
+
await hermesSend(to, `✖ [HUB-Q:${refMsgId}] The question was cancelled — it was answered from the console.`).catch((err) => {
|
|
273
|
+
appendLogFile(logFile, refMsgId, "delivery_error", { phase: "cancel_note", error: err instanceof Error ? err.message : String(err) });
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function handleLateAnswer(qid: string): Promise<void> {
|
|
278
|
+
appendLogFile(logFile, qid, "late_answer", { state: closed.get(qid) ?? "unknown" });
|
|
279
|
+
await hermesSend(to, `ℹ [HUB-Q:${qid}] This question is already closed; the late answer was ignored.`).catch((err) => {
|
|
280
|
+
appendLogFile(logFile, qid, "delivery_error", { phase: "late_note", error: err instanceof Error ? err.message : String(err) });
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async function consumeAnswerFile(file: string): Promise<void> {
|
|
285
|
+
const full = path.join(qDir, file);
|
|
286
|
+
let raw: string;
|
|
287
|
+
try {
|
|
288
|
+
raw = fs.readFileSync(full, "utf-8");
|
|
289
|
+
} catch {
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const qidFromName = file.endsWith(".answer.json") ? file.slice(0, -".answer.json".length) : file;
|
|
294
|
+
if (isValidQid(qidFromName) && closed.has(qidFromName)) {
|
|
295
|
+
invalidJsonSeen.delete(file);
|
|
296
|
+
try { fs.unlinkSync(full); } catch { /* ignore */ }
|
|
297
|
+
await handleLateAnswer(qidFromName);
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const validation = validateAnswerFile(raw, full, pending.keys());
|
|
302
|
+
if (!validation.ok) {
|
|
303
|
+
if (validation.reason === "invalid_json") {
|
|
304
|
+
// Possibly a partial write from the liaison; retry until the grace expires.
|
|
305
|
+
const firstSeen = invalidJsonSeen.get(file);
|
|
306
|
+
if (firstSeen === undefined) {
|
|
307
|
+
invalidJsonSeen.set(file, Date.now());
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (Date.now() - firstSeen < invalidJsonGraceMs) return;
|
|
311
|
+
}
|
|
312
|
+
invalidJsonSeen.delete(file);
|
|
313
|
+
const logQid = validation.qid && isValidQid(validation.qid) ? validation.qid : (isValidQid(qidFromName) ? qidFromName : "00000000000000000000000000");
|
|
314
|
+
appendAnswerRejectLog(logFile, logQid, { reason: validation.reason, file });
|
|
315
|
+
try { fs.unlinkSync(full); } catch { /* ignore */ }
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
invalidJsonSeen.delete(file);
|
|
320
|
+
const item = pending.get(validation.qid);
|
|
321
|
+
if (!item) return;
|
|
322
|
+
clearTimeout(item.timer);
|
|
323
|
+
pending.delete(validation.qid);
|
|
324
|
+
markClosed(validation.qid, "answered");
|
|
325
|
+
try { fs.unlinkSync(full); } catch { /* ignore */ }
|
|
326
|
+
appendLogFile(logFile, validation.qid, "answered", { answered_by: validation.answer.answered_by });
|
|
327
|
+
const response = mapAnswerToAskResponse(validation.answer.answer, item.options);
|
|
328
|
+
await sendResponse(item.env, response).catch((err) => {
|
|
329
|
+
console.error(`coms-hermes-bridge: could not deliver answer for ${validation.qid}: ${err instanceof Error ? err.message : String(err)}`);
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async function scanAnswers(): Promise<void> {
|
|
334
|
+
let files: string[];
|
|
335
|
+
try {
|
|
336
|
+
files = fs.readdirSync(qDir);
|
|
337
|
+
} catch {
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
for (const file of files) {
|
|
341
|
+
await consumeAnswerFile(file);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const server = await bindEndpoint(
|
|
346
|
+
id.endpoint,
|
|
347
|
+
makeConnHandler((env, socket) => {
|
|
348
|
+
if (isPromptEnvelope(env)) {
|
|
349
|
+
writeAck(socket, env.msg_id);
|
|
350
|
+
void handlePrompt(env);
|
|
351
|
+
} else if (isCancelEnvelope(env)) {
|
|
352
|
+
writeAck(socket, env.msg_id);
|
|
353
|
+
void handleCancel(env.ref_msg_id);
|
|
354
|
+
} else if ((env as { type?: string }).type === "ping") {
|
|
355
|
+
const card: AgentCard = {
|
|
356
|
+
name: uniqueName,
|
|
357
|
+
purpose: DEFAULT_PURPOSE,
|
|
358
|
+
model: "hermes-bridge",
|
|
359
|
+
color: COLOR,
|
|
360
|
+
context_used_pct: 0,
|
|
361
|
+
queue_depth: queueDepth(),
|
|
362
|
+
};
|
|
363
|
+
try {
|
|
364
|
+
socket.write(JSON.stringify({ type: "pong", msg_id: (env as { msg_id?: string }).msg_id ?? "", agent_card: card }) + "\n");
|
|
365
|
+
} catch { /* ignore */ }
|
|
366
|
+
try { socket.end(); } catch { /* ignore */ }
|
|
367
|
+
} else {
|
|
368
|
+
writeNack(socket, (env as { msg_id?: string }).msg_id ?? "", "bridge accepts prompts, cancels, and pings");
|
|
369
|
+
}
|
|
370
|
+
}),
|
|
371
|
+
);
|
|
372
|
+
|
|
373
|
+
const keepalive = setInterval(() => {
|
|
374
|
+
try { writeRegistryAtomic(registryEntry(), project); } catch { /* best-effort */ }
|
|
375
|
+
}, KEEPALIVE_MS);
|
|
376
|
+
keepalive.unref?.();
|
|
377
|
+
const watcher = setInterval(() => { void scanAnswers(); }, pollMs);
|
|
378
|
+
watcher.unref?.();
|
|
379
|
+
|
|
380
|
+
let shuttingDown = false;
|
|
381
|
+
function shutdown(): void {
|
|
382
|
+
if (shuttingDown) return;
|
|
383
|
+
shuttingDown = true;
|
|
384
|
+
clearInterval(keepalive);
|
|
385
|
+
clearInterval(watcher);
|
|
386
|
+
for (const item of pending.values()) clearTimeout(item.timer);
|
|
387
|
+
try { server.close(); } catch { /* ignore */ }
|
|
388
|
+
try { fs.unlinkSync(id.endpoint); } catch { /* ignore */ }
|
|
389
|
+
removeRegistryEntry(project, uniqueName);
|
|
390
|
+
process.exit(0);
|
|
391
|
+
}
|
|
392
|
+
process.on("SIGTERM", shutdown);
|
|
393
|
+
process.on("SIGINT", shutdown);
|
|
394
|
+
|
|
395
|
+
// Publish readiness only after shutdown handlers are installed. A caller may
|
|
396
|
+
// terminate the bridge as soon as its registry entry appears; publishing
|
|
397
|
+
// earlier can bypass cleanup and leave both the entry and socket behind.
|
|
398
|
+
writeRegistryAtomic(registryEntry(), project);
|
|
399
|
+
console.error(`coms-hermes-bridge: ${uniqueName}@${project} listening (${to})`);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const isEntry = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
403
|
+
if (isEntry) void main();
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import * as fs from 'node:fs';import * as path from 'node:path';import * as crypto from 'node:crypto';import {fileURLToPath} from 'node:url';import {spawn as realSpawn} from 'node:child_process';
|
|
2
|
+
export function parseRunnerArgs(argv:string[]){if(argv[0]!=='verify')throw Error('unsupported command');const out:any={};for(let i=1;i<argv.length;i+=2){const k=argv[i],v=argv[i+1];if(!['--root','--artifact'].includes(k)||!v||out[k])throw Error('invalid arguments');out[k]=v;}if(!out['--root']||!out['--artifact'])throw Error('missing arguments');return{root:out['--root'],artifact:out['--artifact']};}
|
|
3
|
+
export function verifyGateArtifact(root:string,artifactPath:string){root=validateOwnedRoot(root);const st=fs.lstatSync(artifactPath);if(st.isSymbolicLink()||!st.isFile())throw Error('unsafe gate artifact');const a=JSON.parse(fs.readFileSync(artifactPath,'utf8'));const bad=()=>{throw Error('gate artifact failed closed')};if(a.schema!=='agent-fleet.hermes-gate-c-capabilities'||a.schemaVersion!==1||a.gate!=='C'||a.status!=='passed'||a.runtimeVerified!==true)bad();const argv=a.argv??{};for(const k of ['pluginEnableArgv','backendStartArgv','backendStopArgv','desktopStartArgv','desktopStopArgv'])if(!Array.isArray(argv[k])||!argv[k].length||argv[k].some((x:any)=>typeof x!=='string'||!x))bad();if(!a.capabilities?.desktopDebugAttachment?.url||!a.capabilities?.desktopDebugAttachment?.probeExpression)bad();const proof=a.pluginLoadProof;if(proof?.backendPluginId!=='agent-fleet-monitor'||proof?.desktopPluginId!=='agent-fleet-monitor')bad();if(a.validation?.status!=='passed'||a.gateDecision?.status!=='pass'||a.gateDecision?.implementationMayProceed!==true)bad();const raw=JSON.stringify(a);if(/(api[_-]?key|token|password|\/home\/|\.pi\/agent)/i.test(raw))bad();return{sha256:crypto.createHash('sha256').update(raw).digest('hex'),argv:{enable:argv.pluginEnableArgv,backend:argv.backendStartArgv,desktop:argv.desktopStartArgv},debug:a.capabilities.desktopDebugAttachment,proof};}
|
|
4
|
+
export type Owned={root:string;pid?:number;argv:string[];executable:string;start?:string;reservation:string};
|
|
5
|
+
export function ownedIndexPath(root:string,file:string){root=validateOwnedRoot(root);const target=path.resolve(root,file);if(path.dirname(target)!==root||path.basename(target)!==file)throw Error('owned index must be direct child');return target;}
|
|
6
|
+
export function writeOwnedIndex(root:string,file:string,value:any){const target=ownedIndexPath(root,file);if(!value||value.schema!==1||value.root!==validateOwnedRoot(root)||typeof value.owner!=='string'||typeof value.artifactSha256!=='string'||typeof value.components!=='object')throw Error('invalid owned index');for(const [component,item] of Object.entries(value.components)){componentName(component);const x:any=item;if(!x||x.registry!==`registry-${component}.json`||typeof x.owner!=='string')throw Error('invalid owned index component');}const tmp=path.join(root,`.${path.basename(file)}.${process.pid}.tmp`);fs.writeFileSync(tmp,JSON.stringify(value),{mode:0o600});fs.renameSync(tmp,target);return value;}
|
|
7
|
+
export function readOwnedIndex(root:string,file:string){const target=ownedIndexPath(root,file),st=fs.lstatSync(target);if(st.isSymbolicLink()||!st.isFile()||(st.mode&0o777)!==0o600)throw Error('unsafe owned index');return JSON.parse(fs.readFileSync(target,'utf8'));}
|
|
8
|
+
const SENTINEL='.agent-fleet-hermes-monitor-smoke',REGISTRY='owned-registry.json';const componentName=(v:string)=>{if(!/^[A-Za-z0-9._-]+$/.test(v)||v.includes('..'))throw Error('invalid component');return v};
|
|
9
|
+
export async function terminateExactChild(child:any,deps:any={}){if(!child||typeof child.kill!=='function')throw Error('child handle required');if(child.exitCode!==null&&child.exitCode!==undefined)return{exited:true};const set=deps.setTimeout??setTimeout,clear=deps.clearTimeout??clearTimeout,waitMs=deps.waitMs??5000;let resolve:any;const exited=new Promise(r=>resolve=r);child.once?.('exit',()=>resolve(true));const wait=()=>new Promise(r=>{timer=set(r,waitMs)});try{child.kill('SIGTERM')}catch(e:any){if(e?.code==='ESRCH')return{exited:true};throw e}let timer:any;try{const first=await Promise.race([exited,wait()]);if(first)return{exited:true};try{child.kill('SIGKILL')}catch(e:any){if(e?.code==='ESRCH')return{exited:true};throw e}const second=await Promise.race([exited,wait()]);return{exited:!!second};}finally{if(timer!==undefined)clear(timer);}}
|
|
10
|
+
const finalizedLaunchErrors=new Set<string>();export async function finalizeDurableLaunchError(root:string,component:string,owner:string,reservation:string,child:any,deps:any={}){const key=`${root}:${component}:${owner}`;if(finalizedLaunchErrors.has(key))return;finalizedLaunchErrors.add(key);try{if(child?.exitCode===null||child?.exitCode===undefined)await terminateExactChild(child,deps);}catch{}try{const record=readOwnedRegistry(root,component);if(record.owner!==owner||record.state==='exited')return;writeOwnedRegistry(root,{...record,state:'failed'},component);const value=JSON.parse(fs.readFileSync(reservation,'utf8'));if(value.owner===owner)fs.unlinkSync(reservation);}catch{}}
|
|
11
|
+
export function safeRoot(root:string){const r=path.resolve(root);if(r===path.parse(r).root)throw Error('owned root required');return r;}
|
|
12
|
+
export function validateOwnedRoot(root:string){root=safeRoot(root);const st=fs.lstatSync(root);if(st.isSymbolicLink()||!st.isDirectory()||(st.mode&0o777)!==0o700)throw Error('unsafe owned root');const sentinel=path.join(root,SENTINEL),ss=fs.lstatSync(sentinel);if(ss.isSymbolicLink()||!ss.isFile()||(ss.mode&0o777)!==0o600)throw Error('unsafe owned sentinel');const value=JSON.parse(fs.readFileSync(sentinel,'utf8'));if(value?.schema!==1||value?.owner!=='agent-fleet'||value?.root!==fs.realpathSync(root))throw Error('invalid owned sentinel');return fs.realpathSync(root);}
|
|
13
|
+
export function buildOwnedEnv(root:string,env:any={}){root=validateOwnedRoot(root);const child=(n:string)=>path.join(root,n);for(const n of ['home','config','state','runtime','cache','hermes','sockets']){const p=child(n);fs.mkdirSync(p,{recursive:true,mode:0o700});const st=fs.lstatSync(p);if(st.isSymbolicLink()||!st.isDirectory()||(st.mode&0o777)!==0o700)throw Error('unsafe owned env path');}return{...env,HOME:child('home'),XDG_CONFIG_HOME:child('config'),XDG_STATE_HOME:child('state'),XDG_RUNTIME_DIR:child('runtime'),XDG_CACHE_HOME:child('cache'),HERMES_HOME:child('hermes'),HERDR_SOCKET_PATH:path.join(child('sockets'),'herdr.sock')};}
|
|
14
|
+
export function writeOwnedRegistry(root:string,value:any,component?:string){root=validateOwnedRoot(root);if(component)componentName(component);if(!Array.isArray(value.argv)||!value.argv.length||value.argv.some((x:any)=>typeof x!=='string'||!x))throw Error('invalid owned argv');const clean={schema:1,root,component:(typeof value.component==='string'&&/^[A-Za-z0-9._-]+$/.test(value.component)?value.component:(()=>{throw Error('invalid component')})()),executable:fs.realpathSync(value.executable),argv:[...(value.argv??[])].map(String),pid:Number(value.pid),start:String(value.start),state:String(value.state??'running'),owner:typeof value.owner==='string'?value.owner:undefined,createdAt:value.createdAt??new Date().toISOString(),updatedAt:new Date().toISOString()};const name=component?`registry-${component}.json`:REGISTRY,file=path.join(root,name),tmp=path.join(root,`.${name}.${process.pid}.tmp`);fs.writeFileSync(tmp,JSON.stringify(clean),{mode:0o600});fs.renameSync(tmp,file);return clean;}
|
|
15
|
+
export function readOwnedRegistry(root:string,component?:string){root=validateOwnedRoot(root);if(component)componentName(component);const file=path.join(root,component?`registry-${component}.json`:REGISTRY),st=fs.lstatSync(file);if(st.isSymbolicLink()||!st.isFile()||(st.mode&0o777)!==0o600)throw Error('unsafe owned registry');const v=JSON.parse(fs.readFileSync(file,'utf8'));if(v?.schema!==1||v.root!==root||!Array.isArray(v.argv)||!v.argv.length||v.argv.some((x:any)=>typeof x!=='string'||!x)||typeof v.component!=='string'||typeof v.pid!=='number'||v.pid<=0||typeof v.start!=='string'||!v.start||typeof v.owner!=='string'||!v.owner||!['starting','running','stopping','exited','failed'].includes(v.state))throw Error('invalid owned registry');return v;}
|
|
16
|
+
export async function launchOwnedDurable(root:string,component:string,argv:string[],deps:any={}){root=validateOwnedRoot(root);if(!/^[A-Za-z0-9._-]+$/.test(component)||!Array.isArray(argv)||!argv.length||argv.some(x=>typeof x!=='string'||!x))throw Error('invalid durable launch');const f=deps.fs??fs,spawn=deps.spawn??realSpawn,owner=deps.uuid?.()??crypto.randomUUID(),reservation=path.join(root,`.reservation-${component}`);try{f.writeFileSync(reservation,JSON.stringify({owner,component}),{flag:'wx',mode:0o600});}catch{throw Error('component reservation exists')}let child:any=null;const fail=(state:string)=>{try{writeOwnedRegistry(root,{component,executable:argv[0],argv,pid:0,start:'',state,owner},component)}catch{}try{const value=JSON.parse(f.readFileSync(reservation,'utf8'));if(value.owner===owner)f.unlinkSync(reservation)}catch{}};try{writeOwnedRegistry(root,{component,executable:argv[0],argv,pid:0,start:'pending',state:'starting',owner},component);child=spawn(argv[0],argv.slice(1),{cwd:root,env:buildOwnedEnv(root),shell:false,stdio:'ignore'});child.once?.('error',()=>{void finalizeDurableLaunchError(root,component,owner,reservation,child,deps).catch(()=>{})});const start=(deps.startOf??startOf)(child.pid);const record=writeOwnedRegistry(root,{component,executable:argv[0],argv,pid:child.pid,start,state:'running',owner},component);child.once?.('exit',()=>{try{const current=readOwnedRegistry(root,component);if(current.component===component&¤t.pid===child.pid&¤t.start===start)writeOwnedRegistry(root,{...current,state:'exited'},component);}catch{}});return{child,record,reservation};}catch(error){if(child){await finalizeDurableLaunchError(root,component,owner,reservation,child,deps);fail('failed')}else fail('failed');throw error;}}
|
|
17
|
+
export async function waitOwnedFromRegistry(root:string,component:string,deps:any={}){const now=deps.now??Date.now,sleep=deps.sleep??((ms:number)=>new Promise(r=>setTimeout(r,ms))),start=deps.startOf??startOf,timeout=deps.timeout??10_000;const record=readOwnedRegistry(root,component);if(record.component!==component||!['running','stopping'].includes(record.state))return record;if(start(record.pid)!==record.start)throw Error('owned process identity changed');const began=now();while(now()-began<timeout){try{if(start(record.pid)!==record.start){const exited=writeOwnedRegistry(root,{...record,state:'exited'},component);return exited;}}catch{return writeOwnedRegistry(root,{...record,state:'exited'},component)}await sleep(10);}throw Error('owned wait timeout');}
|
|
18
|
+
export async function stopOwnedFromRegistry(root:string,component:string,deps:any={}){const signal=deps.signal??((pid:number,s:string)=>process.kill(pid,s)),start=deps.startOf??startOf,sleep=deps.sleep??((ms:number)=>new Promise(r=>setTimeout(r,ms)));let record=readOwnedRegistry(root,component);if(record.component!==component||record.state!=='running')throw Error('component not running');const markExited=()=>{const exited=writeOwnedRegistry(root,{...record,state:'exited'},component);try{const p=path.join(root,`.reservation-${component}`),v=JSON.parse(fs.readFileSync(p,'utf8'));if(v.owner===record.owner)fs.unlinkSync(p)}catch{}return exited};const same=()=>{try{const value=start(record.pid);if(value===undefined||value===null)return null;return value===record.start}catch(e:any){if(e?.code==='ESRCH')return null;throw e}};const initial=same();if(initial===null)return markExited();if(!initial)throw Error('owned process identity changed');record=writeOwnedRegistry(root,{...record,state:'stopping'},component);try{signal(record.pid,'SIGTERM')}catch(e:any){if(e?.code==='ESRCH'){const exited=writeOwnedRegistry(root,{...record,state:'exited'},component);try{const p=path.join(root,`.reservation-${component}`),v=JSON.parse(fs.readFileSync(p,'utf8'));if(v.owner===record.owner)fs.unlinkSync(p)}catch{}return exited;}throw e}try{await waitOwnedFromRegistry(root,component,{...deps,timeout:5000});}catch{const beforeKill=same();if(beforeKill===null)return markExited();if(!beforeKill)throw Error('owned process identity changed');try{signal(record.pid,'SIGKILL')}catch(e:any){if(e?.code==='ESRCH')return writeOwnedRegistry(root,{...record,state:'exited'},component);throw e}try{await waitOwnedFromRegistry(root,component,{...deps,timeout:5000});}catch{writeOwnedRegistry(root,{...record,state:'failed'},component);throw Error('owned stop timeout');}}const final=readOwnedRegistry(root,component);try{const p=path.join(validateOwnedRoot(root),`.reservation-${component}`),v=JSON.parse(fs.readFileSync(p,'utf8'));if(v.owner===final.owner)fs.unlinkSync(p)}catch{}return final;}
|
|
19
|
+
export async function launchOwnedIndexed(root:string,component:string,argv:string[],ownedFile:string,artifactSha:string,deps:any={}){root=validateOwnedRoot(root);const lock=path.join(root,'.owned-index.lock');let fd,acquired=false;let launched:any,index:any,prior:any;try{fd=fs.openSync(lock,'wx',0o600);acquired=true;try{index=readOwnedIndex(root,ownedFile)}catch{index={schema:1,root,owner:crypto.randomUUID(),artifactSha256:artifactSha,components:{}}}if(index.artifactSha256!==artifactSha)throw Error('artifact mismatch');prior=index.components[component];launched=await launchOwnedDurable(root,component,argv,deps);const record=readOwnedRegistry(root,component);index.components[component]={registry:`registry-${component}.json`,owner:record.owner};writeOwnedIndex(root,ownedFile,index);return launched;}catch(error){if(launched){try{const record=readOwnedRegistry(root,component);if(record.owner===launched.record.owner&&record.pid===launched.record.pid&&record.start===launched.record.start)await stopOwnedFromRegistry(root,component,deps);}catch{}try{if(index){if(prior)index.components[component]=prior;else delete index.components[component];writeOwnedIndex(root,ownedFile,index);}}catch{}}throw error;}finally{if(acquired){try{fs.closeSync(fd)}catch{};try{fs.unlinkSync(lock)}catch{}}}}
|
|
20
|
+
export async function waitOwnedIndexed(root:string,component:string,ownedFile:string,artifactSha:string,deps:any={}){const index=readOwnedIndex(root,ownedFile),entry=index.components?.[component],record=readOwnedRegistry(root,component);if(index.artifactSha256!==artifactSha||!entry||entry.registry!==`registry-${component}.json`||entry.owner!==record.owner)throw Error('owned index mismatch');return waitOwnedFromRegistry(root,component,deps);}
|
|
21
|
+
export async function stopOwnedIndexed(root:string,component:string,ownedFile:string,artifactSha:string,deps:any={}){const index=readOwnedIndex(root,ownedFile),record=readOwnedRegistry(root,component),entry=index.components?.[component];if(!entry||entry.owner!==record.owner||index.artifactSha256!==artifactSha)throw Error('owned index mismatch');const result=await stopOwnedFromRegistry(root,component,deps);if(['exited','failed'].includes(result.state)&&index.components[component]?.owner===record.owner){delete index.components[component];writeOwnedIndex(root,ownedFile,index);}return result;}
|
|
22
|
+
if(process.argv[1]===fileURLToPath(import.meta.url)){try{const a=parseRunnerArgs(process.argv.slice(2)),v=verifyGateArtifact(a.root,a.artifact);process.stdout.write(JSON.stringify({ok:true,sha256:v.sha256})+'\n');}catch{process.stdout.write(JSON.stringify({ok:false,error:'verification_failed'})+'\n');process.exitCode=2;}}
|
|
23
|
+
export function writeGateArtifact(root:string,value:unknown){root=validateOwnedRoot(root);fs.mkdirSync(root,{recursive:true,mode:0o700});const file=path.join(root,'gate-c.json'),tmp=`${file}.${process.pid}.${Math.random()}.tmp`;fs.writeFileSync(tmp,JSON.stringify(value),{mode:0o600});fs.renameSync(tmp,file);return file;}
|
|
24
|
+
const startOf=(pid:number,read=(p:string)=>fs.readFileSync(p,'utf8'))=>{const stat=read(`/proc/${pid}/stat`),tail=stat.slice(stat.lastIndexOf(')')+2).split(' ');return tail[19];};
|
|
25
|
+
export async function runOwned(argv:string[],root:string,deps:any={}){if(!Array.isArray(argv)||!argv.length||argv.some(x=>typeof x!=='string'))throw Error('argv required');root=validateOwnedRoot(root);const f=deps.fs??fs,spawn=deps.spawn??realSpawn,set=deps.setTimeout??setTimeout,clear=deps.clearTimeout??clearTimeout,signals=deps.signals??process;f.mkdirSync(root,{recursive:true,mode:0o700});const reservation=path.join(root,'.reservation');let fd;try{fd=f.openSync(reservation,'wx',0o600);}catch{throw Error('owned reservation exists')}const owned:Owned={root,argv:[...argv],executable:argv[0],reservation};let child:any,exitResolve:any;const exited=new Promise(r=>exitResolve=r);let released=false,timer:any;const release=()=>{if(released)return;released=true;try{f.unlinkSync(reservation)}catch{};try{f.unlinkSync(path.join(root,'gate-c.json'))}catch{}};try{writeGateArtifact(root,{root,argv,executable:argv[0]});child=spawn(argv[0],argv.slice(1),{cwd:root,env:{...process.env,HOME:path.join(root,'home')},shell:false,stdio:'ignore'});owned.pid=child.pid;owned.start=(deps.startOf??startOf)(child.pid);child.once('exit',(code:any)=>{if(timer!==undefined)clear(timer);exitResolve(code);release();});}catch(e){release();throw e}const valid=()=>!!owned.pid&&(deps.startOf??startOf)(owned.pid)===owned.start;const stop=async()=>{if(released)return;if(!valid())throw Error('owned process identity changed');child.kill('SIGTERM');timer=set(()=>{if(valid())child.kill('SIGKILL')},5000);await exited;};const wait=()=>exited;const onSignal=()=>void stop();signals.once('SIGINT',onSignal);signals.once('SIGTERM',onSignal);return{child,owned,wait,stop,dispose:()=>{signals.removeListener('SIGINT',onSignal);signals.removeListener('SIGTERM',onSignal);release()}};}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import * as fs from 'node:fs';import * as path from 'node:path';import * as net from 'node:net';import {MonitorRegistry} from './lib/hermes-monitor-registry.ts';import {MonitorSocketServer} from './lib/hermes-monitor-socket.ts';import {FakeHerdrServer} from './lib/fake-herdr-server.ts';import {watchHubMonitor} from './lib/hermes-monitor-herdr.ts';import {createViewerGatedMonitor} from '../.pi/harnesses/agent-hub/monitor-publisher.ts';
|
|
2
|
+
import {createMonitorSessionBridge} from '../.pi/harnesses/agent-hub/monitor-session-bridge.ts';import {MonitorRuntime} from '../.pi/harnesses/agent-hub/monitor-runtime.ts';
|
|
3
|
+
export type Scenario={root:string;tasks:Map<string,any>;visible:boolean;counters:{polls:number;outputs:number};bridge?:any;registration?:any;server?:any;herdr?:any;hybrid?:any;viewer?:any;statuses:any[];outputs:any[];clock:any;disposables:Set<()=>any>};
|
|
4
|
+
export function createScenario(root:string,options:any={}):Scenario{root=path.resolve(root);if(root===path.parse(root).root)throw Error('owned scenario root required');fs.mkdirSync(root,{recursive:true,mode:0o700});return{root,tasks:new Map(),visible:false,counters:{polls:0,outputs:0},statuses:[],outputs:[],clock:options.clock??{setInterval,clearInterval,setTimeout,clearTimeout,now:Date.now},disposables:new Set()};}
|
|
5
|
+
export function registerDisposable(s:Scenario,dispose:()=>any){let done=false;s.disposables.add(async()=>{if(done)return;done=true;await dispose();});}
|
|
6
|
+
const uds=(socketPath:string,frame:any)=>new Promise<any>((resolve,reject)=>{let text='';const c=net.createConnection(socketPath);c.setTimeout(1000,()=>c.destroy(Error('scenario timeout')));c.on('connect',()=>c.end(JSON.stringify(frame)+'\n'));c.on('data',d=>text+=d);c.on('close',()=>resolve(JSON.parse(text)));c.on('error',reject)});
|
|
7
|
+
export async function execute(s:Scenario,argv:string[]){const [command,...args]=argv;if(!command)throw Error('scenario command required');if(command==='serve'){if(s.server)return{socketPath:s.registration.socketPath};const profile=path.join(s.root,'profile');fs.mkdirSync(profile,{recursive:true,mode:0o700});const bridge=createMonitorSessionBridge({now:()=>new Date(s.clock.now()),runtime:new MonitorRuntime({runtimeDir:s.root,profileId:'scenario',hubInstanceId:'hub'})});const registration:any=new MonitorRegistry({runtimeDir:s.root}).register({profilePath:profile,profileId:'scenario',hubInstanceId:'hub',snapshot:()=>bridge.snapshot()});registration.output=(r:any)=>{s.counters.outputs++;return bridge.readOutput(r)};const server=new MonitorSocketServer(registration);await server.listen();s.bridge=bridge;s.registration=registration;s.server=server;s.herdr=await FakeHerdrServer.start({paneId:'pane',workspaceId:'workspace',resyncOutput:{sequence:1,text:'resync'}});const env:any={HERDR_ENV:'1',HERDR_PANE_ID:'pane',HERDR_SOCKET_PATH:s.herdr.socketPath};s.hybrid=watchHubMonitor({env,reconnectDelayMs:1,onStatus:(v:any)=>s.statuses.push(v),onOutput:(v:any)=>s.outputs.push(v)});s.viewer=createViewerGatedMonitor({pollMetadata:async()=>{s.counters.polls++;return[]},fetchOutput:async()=>({sequence:0}),intervalMs:1});registerDisposable(s,()=>s.hybrid?.close());registerDisposable(s,()=>s.viewer?.stop());registerDisposable(s,()=>s.herdr?.close());registerDisposable(s,async()=>{await server.close();registration.cleanup()});return{socketPath:registration.socketPath,token:registration.token};}if(command==='apply'){if(args[0]==='status'){s.herdr.emitStatus();return true;}if(args[0]==='disconnect'){s.herdr.disconnectSubscribers();return true;}if(args[0]==='reconnect'){s.herdr.setWorkspaceId(args[1]??'workspace');s.herdr.emitStatus();return true;}if(!s.bridge)throw Error('serve first');const [action,id,value]=args;if(action==='owner'){s.bridge.setCurrentOwner({ownerSessionId:id,ownerLeaseExpiresAt:value,updateActive:true});return true;}if(action==='parent')return s.bridge.startParent({id,hubInstanceId:'hub',checkoutId:'scenario'});if(action==='child')return s.bridge.startChild({key:id,id,generation:1,parentId:value,parentGeneration:1,specialist:'fake'},{});if(action==='output')return s.bridge.appendOutput(id,value??'');if(action==='wait-only')return s.bridge.registerWaitOnly(id,async()=>{});if(action==='cancel-wait')return s.bridge.cancelWaitOnly(id,{kind:'scenario_cancel'});if(action==='late')return s.bridge.appendOutput(id,value??'');if(action==='evidence-loss')return s.bridge.reconcile({owner:false,socket:false,session:false,herdr:false});if(action==='transition')return s.bridge.finishChild(id,value);throw Error('unsupported apply');}if(command==='get'){if(!s.registration)throw Error('serve first');const [kind='snapshot',id,generation='1',after='0']=args;s.counters.polls++;return kind==='output'?uds(s.registration.socketPath,{type:'output',token:s.registration.token,taskId:id,generation:Number(generation),afterSequence:Number(after)}):uds(s.registration.socketPath,{type:'snapshot',token:s.registration.token});}if(command==='visibility'){s.visible=args[0]==='show';s.viewer?.setViewers(s.visible?1:0);return{visible:s.visible};}if(command==='counters')return{...s.counters,statuses:s.statuses.length,outputs:s.outputs.length,subscriptions:s.herdr?.subscriptionCount()??0};if(command==='wait'){return s.bridge?.snapshot()??[];}if(command==='assert'){if(args[0]!=='visible'||String(s.visible)!==args[1])throw Error('assertion failed');return true;}if(command==='stop-owned'){for(const dispose of [...s.disposables])await dispose();s.disposables.clear();s.server=null;return true;}if(command==='wait-owned'){if(s.disposables.size)throw Error('owned handles remain');return{live:false,handles:0};}throw Error('unsupported scenario command');}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// scripts/lib/claude-bridge-core.ts
|
|
2
|
+
//
|
|
3
|
+
// Pure logic for the Claude Code coms bridge (scripts/coms-claude-bridge.ts):
|
|
4
|
+
// prompt formatting, completion sentinels, hook-record parsing, reply
|
|
5
|
+
// extraction from pane text, and the serial prompt queue. No sockets, no fs,
|
|
6
|
+
// no herdr — everything here runs under node --test.
|
|
7
|
+
|
|
8
|
+
export const SENTINEL_PREFIX = "<<COMS_DONE:";
|
|
9
|
+
|
|
10
|
+
export function completionSentinel(msgId: string): string {
|
|
11
|
+
return `${SENTINEL_PREFIX}${msgId}>>`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// The prompt as typed into the Claude Code pane. Mirrors the pi side's
|
|
15
|
+
// "[from name @ cwd]" framing so Claude knows who is asking; in sentinel mode
|
|
16
|
+
// (no Stop hook seen yet) it also asks for the completion marker.
|
|
17
|
+
export function formatPanePrompt(
|
|
18
|
+
env: { prompt: string; sender_name: string; sender_cwd: string; msg_id: string },
|
|
19
|
+
sentinelMode: boolean,
|
|
20
|
+
): string {
|
|
21
|
+
const header = `[coms message from ${env.sender_name} @ ${env.sender_cwd}] `;
|
|
22
|
+
const sentinelNote = sentinelMode
|
|
23
|
+
? `\n\nEnd your reply with this exact line so the bridge can capture it: ${completionSentinel(env.msg_id)}`
|
|
24
|
+
: "";
|
|
25
|
+
return `${header}${env.prompt}${sentinelNote}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Stop-hook record: the hook writes {text, session_id?, written_at} as JSON.
|
|
29
|
+
export interface HookRecord {
|
|
30
|
+
text: string;
|
|
31
|
+
written_at?: string;
|
|
32
|
+
[key: string]: unknown;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function parseHookRecord(raw: string): HookRecord | null {
|
|
36
|
+
try {
|
|
37
|
+
const rec = JSON.parse(raw);
|
|
38
|
+
if (rec && typeof rec.text === "string") return rec as HookRecord;
|
|
39
|
+
return null;
|
|
40
|
+
} catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Sentinel-mode fallback: pull the reply out of raw pane text. Takes
|
|
46
|
+
// everything between the last prompt echo (identified by the msg_id-bearing
|
|
47
|
+
// sentinel instruction OR the header line) and the sentinel line, stripped of
|
|
48
|
+
// obvious TUI furniture. Returns null when the sentinel has not appeared.
|
|
49
|
+
export function extractSentinelReply(paneText: string, msgId: string): string | null {
|
|
50
|
+
const sentinel = completionSentinel(msgId);
|
|
51
|
+
const at = paneText.lastIndexOf(sentinel);
|
|
52
|
+
if (at === -1) return null;
|
|
53
|
+
const before = paneText.slice(0, at);
|
|
54
|
+
// Cut at the end of the prompt echo: the sentinel instruction line
|
|
55
|
+
// contains the sentinel too, so use the LAST occurrence before the final
|
|
56
|
+
// one — that's the echo; the reply follows it.
|
|
57
|
+
const echoAt = before.lastIndexOf(sentinel);
|
|
58
|
+
const replyRegion = echoAt !== -1 ? before.slice(echoAt + sentinel.length) : before;
|
|
59
|
+
const lines = replyRegion
|
|
60
|
+
.split("\n")
|
|
61
|
+
.map((l) => l.replace(/^[●❯>\s]+/, "").trimEnd())
|
|
62
|
+
.filter((l) => l.trim() !== "" && !/^[─━┏┗┃│]+/.test(l));
|
|
63
|
+
return lines.join("\n").trim() || null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ━━ Serial prompt queue ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
67
|
+
//
|
|
68
|
+
// One prompt at a time per pane; queue depth is reported in the agent card.
|
|
69
|
+
|
|
70
|
+
export interface QueuedPrompt<T> {
|
|
71
|
+
envelope: T;
|
|
72
|
+
enqueued_at: string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export class PromptQueue<T> {
|
|
76
|
+
private items: Array<QueuedPrompt<T>> = [];
|
|
77
|
+
private active = false;
|
|
78
|
+
|
|
79
|
+
get depth(): number {
|
|
80
|
+
return this.items.length + (this.active ? 1 : 0);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
push(envelope: T, now: () => string = () => new Date().toISOString()): void {
|
|
84
|
+
this.items.push({ envelope, enqueued_at: now() });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Take the next prompt if none is being processed. Callers MUST call
|
|
88
|
+
// done() when processing finishes (success or failure).
|
|
89
|
+
take(): QueuedPrompt<T> | null {
|
|
90
|
+
if (this.active) return null;
|
|
91
|
+
const next = this.items.shift();
|
|
92
|
+
if (!next) return null;
|
|
93
|
+
this.active = true;
|
|
94
|
+
return next;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
done(): void {
|
|
98
|
+
this.active = false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Fail-closed command construction for the experimental external Codex conductor.
|
|
2
|
+
// It deliberately exposes only the two contract-approved coms operations.
|
|
3
|
+
|
|
4
|
+
import * as fs from "node:fs";
|
|
5
|
+
import * as path from "node:path";
|
|
6
|
+
|
|
7
|
+
import { validateComsName, validateComsProject } from "./coms-envelope.ts";
|
|
8
|
+
import { conductorWorkspacePath, loadOwnedConfig } from "./codex-remote-control.ts";
|
|
9
|
+
|
|
10
|
+
export interface ConductorContext {
|
|
11
|
+
repoRoot: string;
|
|
12
|
+
project: string;
|
|
13
|
+
name: string;
|
|
14
|
+
timeoutMs: number;
|
|
15
|
+
conductorCwd: string;
|
|
16
|
+
comsDir: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type ConductorOperation =
|
|
20
|
+
| { operation: "list" }
|
|
21
|
+
| { operation: "send"; peer: string; prompt: string };
|
|
22
|
+
|
|
23
|
+
function realDirectory(value: string, label: string): string {
|
|
24
|
+
try {
|
|
25
|
+
const resolved = fs.realpathSync(value);
|
|
26
|
+
if (!fs.statSync(resolved).isDirectory()) throw new Error("not a directory");
|
|
27
|
+
return resolved;
|
|
28
|
+
} catch {
|
|
29
|
+
throw new Error(`${label} must resolve to an existing directory`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Parse before any config/filesystem/process access. No scope overrides exist. */
|
|
34
|
+
export function parseConductorArgs(argv: string[]): ConductorOperation {
|
|
35
|
+
const flags = new Set<string>();
|
|
36
|
+
for (const arg of argv) {
|
|
37
|
+
if (!arg.startsWith("--")) continue;
|
|
38
|
+
if (flags.has(arg)) throw new Error(`${arg} may only be provided once`);
|
|
39
|
+
flags.add(arg);
|
|
40
|
+
}
|
|
41
|
+
if (flags.size > 0) throw new Error("flags and scope overrides are not allowed; the owned configuration is authoritative");
|
|
42
|
+
if (argv[0] === "list" && argv.length === 1) return { operation: "list" };
|
|
43
|
+
if (argv[0] === "send") {
|
|
44
|
+
if (argv.length !== 3) throw new Error("send requires exactly a peer and prompt");
|
|
45
|
+
return { operation: "send", peer: argv[1], prompt: argv[2] };
|
|
46
|
+
}
|
|
47
|
+
throw new Error("usage: codex-conductor <list|send <listed-peer> <bounded-prompt>>");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function loadConductorContext(input: { configPath: string; cwd: string; checkoutRoot: string }): ConductorContext {
|
|
51
|
+
const config = loadOwnedConfig(input.configPath);
|
|
52
|
+
const checkoutRoot = realDirectory(input.checkoutRoot, "checkout root");
|
|
53
|
+
if (config.repoRoot !== checkoutRoot) {
|
|
54
|
+
throw new Error("configured repository does not match this checkout");
|
|
55
|
+
}
|
|
56
|
+
const conductorCwd = conductorWorkspacePath(config.runtimeDir!);
|
|
57
|
+
if (realDirectory(input.cwd, "working directory") !== conductorCwd) {
|
|
58
|
+
throw new Error(`working directory must be ${conductorCwd}`);
|
|
59
|
+
}
|
|
60
|
+
validateComsProject(config.project);
|
|
61
|
+
validateComsName(config.name);
|
|
62
|
+
return {
|
|
63
|
+
repoRoot: config.repoRoot,
|
|
64
|
+
project: config.project,
|
|
65
|
+
name: config.name,
|
|
66
|
+
timeoutMs: config.timeoutMs,
|
|
67
|
+
conductorCwd,
|
|
68
|
+
comsDir: realDirectory(config.comsDir, "coms directory"),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function conductorProcessEnv(
|
|
73
|
+
context: ConductorContext,
|
|
74
|
+
base: NodeJS.ProcessEnv = process.env,
|
|
75
|
+
): NodeJS.ProcessEnv {
|
|
76
|
+
return { ...base, PI_COMS_DIR: context.comsDir };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function buildConductorCommand(context: ConductorContext, operation: ConductorOperation): string[] {
|
|
80
|
+
if (operation.operation === "list") {
|
|
81
|
+
return ["list", "--project", context.project, "--name", context.name];
|
|
82
|
+
}
|
|
83
|
+
return [
|
|
84
|
+
"send", operation.peer, operation.prompt,
|
|
85
|
+
"--project", context.project, "--name", context.name,
|
|
86
|
+
"--await", "--timeout", String(context.timeoutMs), "--conductor", "codex",
|
|
87
|
+
];
|
|
88
|
+
}
|