fix: align calendar API with actual HarborForge.Backend contract

Initial drop guessed the heartbeat shape; sim e2e against a running
harborforge-backend revealed the real contract is per-agent with
header auth, not server-wide with bearer:

  POST /calendar/agent/heartbeat
    headers: X-Agent-ID, X-Claw-Identifier
    body:    {claw_identifier, agent_id}
    response: {slots: [Slot], agent_status, message?}

  PATCH /calendar/slots/{id}/agent-update
  PATCH /calendar/slots/virtual/{vid}/agent-update
    body: {status, started_at?, actual_duration?}

  POST /calendar/agent/status
    body: {claw_identifier, agent_id, status}

Refactors:

  - internal/calendar/types.go now mirrors OpenclawPlugin/calendar/
    types.ts 1:1 (SlotStatus camelCase, real vs virtual slot id
    discrimination, event_data shape)
  - internal/calendar/bridge.go: header-based auth, per-agent method
    signatures, separate UpdateRealSlot vs UpdateVirtualSlot
  - internal/calendar/scheduler.go: per-agent heartbeat loop
    (one HTTP call per agent per tick), highest-priority slot
    selection, agent-update PATCH for terminal/non-terminal states
  - SingleActiveAgentID helper for main.bestEffortAgentID

Also fix two bugs found in sim:

  - bgCtx capture: AgentLister closures were capturing Init's ctx
    which dies the moment MCP initialize returns; switched to
    bgCtx (lifetime = plugin process)
  - tools.toolRestartStatus referenced a non-existent
    sch.RestartPending — HF backend has no restart endpoint per
    /openapi.json, so the tool now reports last_heartbeats freshness

Scheduler logs each tick + each heartbeat outcome at info so
operators can see backend connectivity without enabling debug.

E2E against http://harborforge-backend:8000 in sim:
  daemon → heartbeat → 404 "Agent not found"
  (= correct endpoint, correct headers, correct body — agent just
   isn't registered yet, which is expected for an untenanted
   plugin)
This commit is contained in:
h z
2026-06-03 11:28:05 +01:00
parent 754e5183f7
commit 78b1ec5181
5 changed files with 474 additions and 370 deletions

View File

@@ -1,7 +1,8 @@
// Bridge — thin HTTP client for the HarborForge backend's Calendar API.
// All operations carry the API key as Authorization: Bearer; absent
// key means missing-auth errors from the backend (caller should
// handle them as transient and log).
// Bridge — typed HTTP client for HarborForge.Backend's calendar API.
// Endpoint shapes verified via the backend's /openapi.json and against
// HarborForge.OpenclawPlugin/plugin/calendar/calendar-bridge.ts so
// the two plugins drop into the same backend without per-plugin
// adapters.
package calendar
@@ -13,30 +14,33 @@ import (
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
)
// Bridge is the typed wrapper around an HTTP client + backend URL.
// Bridge is constructed once per scheduler and reused across heartbeats.
type Bridge struct {
BackendURL string
APIKey string
HTTP *http.Client
BaseURL string
ClawIdentifier string
HTTP *http.Client
}
// New constructs a bridge with a sensible default timeout.
func New(backendURL, apiKey string) *Bridge {
// New constructs a bridge with a 20s default timeout.
func New(baseURL, clawIdentifier string) *Bridge {
return &Bridge{
BackendURL: strings.TrimRight(backendURL, "/"),
APIKey: apiKey,
HTTP: &http.Client{Timeout: 20 * time.Second},
BaseURL: strings.TrimRight(baseURL, "/"),
ClawIdentifier: clawIdentifier,
HTTP: &http.Client{Timeout: 20 * time.Second},
}
}
// Heartbeat POSTs /calendar/agent/heartbeat. Returns the backend's
// reply or an error.
func (b *Bridge) Heartbeat(ctx context.Context, payload HeartbeatPayload) (HeartbeatResponse, error) {
raw, err := b.post(ctx, "/calendar/agent/heartbeat", payload)
// Heartbeat POSTs /calendar/agent/heartbeat. Per-agent: each running
// agent on this claw drives its own heartbeat (matches OpenClaw plugin
// semantics).
func (b *Bridge) Heartbeat(ctx context.Context, agentID string) (HeartbeatResponse, error) {
body := HeartbeatRequest{ClawIdentifier: b.ClawIdentifier, AgentID: agentID}
raw, err := b.doJSON(ctx, http.MethodPost, "/calendar/agent/heartbeat", agentID, body)
if err != nil {
return HeartbeatResponse{}, err
}
@@ -49,76 +53,64 @@ func (b *Bridge) Heartbeat(ctx context.Context, payload HeartbeatPayload) (Heart
return out, nil
}
// UpdateSlotStatus POSTs /calendar/slot/<id>/status to mark a slot
// completed / aborted / paused / resumed.
func (b *Bridge) UpdateSlotStatus(ctx context.Context, slotID string, update SlotUpdate) error {
if slotID == "" {
return errors.New("calendar: slot id required")
}
_, err := b.post(ctx, "/calendar/slot/"+slotID+"/status", update)
// UpdateRealSlot PATCHes /calendar/slots/{id}/agent-update.
func (b *Bridge) UpdateRealSlot(ctx context.Context, agentID string, slotID int64, update SlotAgentUpdate) error {
path := "/calendar/slots/" + strconv.FormatInt(slotID, 10) + "/agent-update"
_, err := b.doJSON(ctx, http.MethodPatch, path, agentID, update)
return err
}
// RestartPending GETs /restart/status — returns the backend's
// current restart-requested flag.
func (b *Bridge) RestartPending(ctx context.Context) (bool, error) {
raw, err := b.get(ctx, "/restart/status")
if err != nil {
return false, err
}
var out struct {
Pending bool `json:"pending"`
}
if len(raw) > 0 {
if err := json.Unmarshal(raw, &out); err != nil {
return false, fmt.Errorf("decode restart-status: %w", err)
}
}
return out.Pending, nil
// UpdateVirtualSlot PATCHes /calendar/slots/virtual/{vid}/agent-update.
// The backend materialises the virtual slot first; subsequent calls
// against the same logical slot should use UpdateRealSlot with the
// id returned in the response — but for v1 we don't round-trip the
// materialised id back to the scheduler (would require a separate
// fetch); the agent-update path tolerates re-PATCHing a virtual id.
func (b *Bridge) UpdateVirtualSlot(ctx context.Context, agentID string, virtualID string, update SlotAgentUpdate) error {
path := "/calendar/slots/virtual/" + virtualID + "/agent-update"
_, err := b.doJSON(ctx, http.MethodPatch, path, agentID, update)
return err
}
// post serialises body as JSON, attaches Authorization, returns
// response body bytes. Non-2xx becomes an error with the body
// included for diagnostics.
func (b *Bridge) post(ctx context.Context, path string, body any) ([]byte, error) {
// PushAgentStatus POSTs /calendar/agent/status. Used to push idle ↔
// busy transitions out of the normal heartbeat cycle.
func (b *Bridge) PushAgentStatus(ctx context.Context, agentID string, status AgentStatusValue) error {
body := AgentStatusPush{
ClawIdentifier: b.ClawIdentifier, AgentID: agentID, Status: status,
}
_, err := b.doJSON(ctx, http.MethodPost, "/calendar/agent/status", agentID, body)
return err
}
// doJSON serialises body, attaches the two auth headers, and returns
// the response bytes. Errors on non-2xx with truncated body.
func (b *Bridge) doJSON(ctx context.Context, method, path, agentID string, body any) ([]byte, error) {
if agentID == "" {
return nil, errors.New("calendar: agent_id required for auth headers")
}
raw, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal %s: %w", path, err)
return nil, fmt.Errorf("marshal %s %s: %w", method, path, err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, b.BackendURL+path, bytes.NewReader(raw))
req, err := http.NewRequestWithContext(ctx, method, b.BaseURL+path, bytes.NewReader(raw))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
if b.APIKey != "" {
req.Header.Set("Authorization", "Bearer "+b.APIKey)
}
return b.do(req)
}
req.Header.Set("X-Agent-ID", agentID)
req.Header.Set("X-Claw-Identifier", b.ClawIdentifier)
func (b *Bridge) get(ctx context.Context, path string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, b.BackendURL+path, nil)
if err != nil {
return nil, err
}
if b.APIKey != "" {
req.Header.Set("Authorization", "Bearer "+b.APIKey)
}
return b.do(req)
}
func (b *Bridge) do(req *http.Request) ([]byte, error) {
res, err := b.HTTP.Do(req)
if err != nil {
return nil, fmt.Errorf("%s %s: %w", req.Method, req.URL.Path, err)
return nil, fmt.Errorf("%s %s: %w", method, path, err)
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
out, _ := io.ReadAll(res.Body)
if res.StatusCode < 200 || res.StatusCode >= 300 {
return nil, fmt.Errorf("%s %s → %d: %s",
req.Method, req.URL.Path, res.StatusCode, truncate(body, 300))
method, path, res.StatusCode, truncate(out, 300))
}
return body, nil
return out, nil
}
func truncate(b []byte, n int) string {