Files
hzhang 78b1ec5181 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)
2026-06-03 11:28:05 +01:00

122 lines
4.1 KiB
Go

// 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
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
)
// Bridge is constructed once per scheduler and reused across heartbeats.
type Bridge struct {
BaseURL string
ClawIdentifier string
HTTP *http.Client
}
// New constructs a bridge with a 20s default timeout.
func New(baseURL, clawIdentifier string) *Bridge {
return &Bridge{
BaseURL: strings.TrimRight(baseURL, "/"),
ClawIdentifier: clawIdentifier,
HTTP: &http.Client{Timeout: 20 * time.Second},
}
}
// 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
}
var out HeartbeatResponse
if len(raw) > 0 {
if err := json.Unmarshal(raw, &out); err != nil {
return HeartbeatResponse{}, fmt.Errorf("decode heartbeat: %w (body=%q)", err, truncate(raw, 200))
}
}
return out, nil
}
// 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
}
// 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
}
// 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 %s: %w", method, path, err)
}
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")
req.Header.Set("X-Agent-ID", agentID)
req.Header.Set("X-Claw-Identifier", b.ClawIdentifier)
res, err := b.HTTP.Do(req)
if err != nil {
return nil, fmt.Errorf("%s %s: %w", method, path, err)
}
defer res.Body.Close()
out, _ := io.ReadAll(res.Body)
if res.StatusCode < 200 || res.StatusCode >= 300 {
return nil, fmt.Errorf("%s %s → %d: %s",
method, path, res.StatusCode, truncate(out, 300))
}
return out, nil
}
func truncate(b []byte, n int) string {
if len(b) <= n {
return string(b)
}
return string(b[:n]) + "…"
}