Skip to content

Commit ab0bca1

Browse files
authored
feat: add lease heartbeat command (#1356)
* feat: add lease heartbeat command * docs: sync heartbeat skill example
1 parent ba91f28 commit ab0bca1

12 files changed

Lines changed: 633 additions & 2 deletions

File tree

‎.agents/skills/crabbox/SKILL.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,7 @@ crabbox sync-plan
425425
crabbox warmup --class beast
426426
crabbox prewarm
427427
crabbox status --id <lease> --wait
428+
crabbox heartbeat --id <lease> --idle-timeout 90m
428429
crabbox inspect --id <lease> --json
429430
crabbox run --id <lease> --preflight --timing-json -- pnpm test
430431
crabbox job list

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## Unreleased
4+
5+
### Added
6+
7+
- Added `crabbox heartbeat` so external SSH drivers can refresh owned lease idle deadlines and optionally update the idle timeout.
8+
39
## 0.43.0 - 2026-08-15
410

511
### Added

‎docs/cli.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ crabbox run --timing-record=default -- <cmd> append timing to the local benchmar
4646
crabbox watch -- <command...> re-run on a warm lease when local files change
4747
crabbox bench run --providers a,b -- <cmd> run a workload and record benchmark timings
4848
crabbox status --id <id> show lease state (--wait to block)
49+
crabbox heartbeat --id <id> refresh the lease idle deadline
4950
crabbox inspect --id <id> print lease/provider details
5051
crabbox list list machines (alias: crabbox pool list)
5152
crabbox share --id <id> [--user|--org] grant access to a lease
@@ -59,7 +60,7 @@ crabbox pool ready [key] list hydrated broker ready-pool le
5960

6061
See [warmup](commands/warmup.md), [prewarm](commands/prewarm.md),
6162
[run](commands/run.md), [watch](commands/watch.md),
62-
[status](commands/status.md), [inspect](commands/inspect.md),
63+
[status](commands/status.md), [heartbeat](commands/heartbeat.md), [inspect](commands/inspect.md),
6364
[list](commands/list.md), [share](commands/share.md),
6465
[unshare](commands/unshare.md), [stop](commands/stop.md),
6566
[pause](commands/pause.md), [resume](commands/resume.md),

‎docs/commands/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ same order as the CLI help.
3333
- [verify](verify.md)
3434
- [cache](cache.md)
3535
- [status](status.md)
36+
- [heartbeat](heartbeat.md)
3637
- [list](list.md)
3738
- [share](share.md)
3839
- [unshare](unshare.md)

‎docs/commands/heartbeat.md‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# heartbeat
2+
3+
`crabbox heartbeat` refreshes the idle deadline for one owned lease and prints
4+
the resulting lease state. It is intended for external drivers that keep a
5+
lease busy over SSH without running commands through `crabbox run`.
6+
7+
```sh
8+
crabbox heartbeat --id swift-crab
9+
crabbox heartbeat --id swift-crab --idle-timeout 90m
10+
crabbox heartbeat --id cbx_abcdef123456 --provider aws --json
11+
```
12+
13+
## Identifying the lease
14+
15+
`--id` accepts a canonical `cbx_...` lease ID or an active slug. When
16+
`--provider` is omitted, Crabbox uses the same local-claim routing as `status`
17+
and `inspect`; an explicit provider still wins.
18+
19+
## Coordinator and direct-provider behavior
20+
21+
For managed coordinator leases, the command sends exactly one request through
22+
the existing lease heartbeat endpoint. The configured owner credentials and
23+
provider binding are unchanged, so unknown, unowned, expired, released, or
24+
otherwise terminal leases retain the coordinator's normal failure response.
25+
26+
`broker.mode: registered` has both coordinator and direct-provider expiry
27+
state. The command therefore requires the exact direct claim, sends one
28+
coordinator heartbeat, and calls the provider's existing `Touch` capability
29+
with the same idle timeout before reporting success.
30+
31+
Without a coordinator, Crabbox resolves the direct SSH lease and calls the
32+
provider's existing `Touch` capability. This fallback requires an exact local
33+
claim that matches the provider scope and live resource identity, and it
34+
rejects terminal leases before touching them. Providers without lease-touch
35+
support fail with `provider=<name> does not support lease heartbeat`.
36+
37+
## Idle timeout
38+
39+
`--idle-timeout <duration>` optionally replaces the lease's idle window while
40+
refreshing it. The value must be positive. Omitting the flag preserves the
41+
current direct-provider timeout when it is available in lease metadata and
42+
omits the coordinator heartbeat override.
43+
44+
## Output
45+
46+
Human output is one line with the lease ID, slug, provider, state, idle timeout,
47+
last-touch timestamp, and expiry. `--json` emits the same fields as a JSON
48+
object.
49+
50+
## Flags
51+
52+
```text
53+
--id <lease-id-or-slug>
54+
--provider <provider>
55+
--idle-timeout <duration>
56+
--json
57+
```
58+
59+
## See also
60+
61+
- [`status`](status.md) — read the current lease state without touching it.
62+
- [`inspect`](inspect.md) — inspect full lease and provider details.
63+
- [`run`](run.md) — run a command with automatic background heartbeats.

‎internal/cli/app.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,8 @@ func (a App) directCommandHelp(ctx context.Context, args []string) (error, bool)
107107
return a.verify(ctx, helpArgs), true
108108
case "status":
109109
return a.status(ctx, helpArgs), true
110+
case "heartbeat":
111+
return a.heartbeat(ctx, helpArgs), true
110112
case "list":
111113
return a.list(ctx, helpArgs), true
112114
case "usage":
@@ -207,6 +209,7 @@ Commands:
207209
verify Verify a signed run receipt
208210
cache Inspect, purge, warm, or list remote cache volumes
209211
status Show lease state; add --wait to block until ready
212+
heartbeat Refresh a lease idle deadline and print its state
210213
list List Crabbox machines
211214
share Share a lease with users or the owning org
212215
unshare Remove lease sharing
@@ -244,6 +247,7 @@ Common Flows:
244247
crabbox job run openclaw-wsl2
245248
crabbox warmup
246249
crabbox status --id blue-lobster --wait
250+
crabbox heartbeat --id blue-lobster --idle-timeout 90m
247251
crabbox run --id blue-lobster --shell 'pnpm install --frozen-lockfile && pnpm test'
248252
crabbox run --timing-record=default -- pnpm test
249253
crabbox bench run --providers aws,hetzner --repeats 3 -- pnpm test

‎internal/cli/cli_kong.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ type crabboxKongCLI struct {
3737
Verify verifyKongCmd `cmd:"" passthrough:"" help:"Verify a signed run receipt."`
3838
Cache cacheKongCmd `cmd:"" help:"Inspect, purge, or warm remote caches."`
3939
Status statusKongCmd `cmd:"" passthrough:"" help:"Show lease state; add --wait to block until ready."`
40+
Heartbeat heartbeatKongCmd `cmd:"" passthrough:"" help:"Refresh a lease idle deadline and print its state."`
4041
List listKongCmd `cmd:"" passthrough:"" help:"List Crabbox machines."`
4142
Ports portsKongCmd `cmd:"" passthrough:"" help:"Publish, list, or unpublish provider-native ports."`
4243
Cp cpKongCmd `cmd:"" name:"cp" passthrough:"" help:"Copy files between the host and a lease."`
@@ -229,6 +230,9 @@ type tunnelKongCmd struct {
229230
type statusKongCmd struct {
230231
Args []string `arg:"" optional:""`
231232
}
233+
type heartbeatKongCmd struct {
234+
Args []string `arg:"" optional:""`
235+
}
232236
type listKongCmd struct {
233237
Args []string `arg:"" optional:""`
234238
}
@@ -651,6 +655,7 @@ func (c *portsKongCmd) Run(ctx context.Context, app App) error { return app.
651655
func (c *cpKongCmd) Run(ctx context.Context, app App) error { return app.copyCommand(ctx, c.Args) }
652656
func (c *tunnelKongCmd) Run(ctx context.Context, app App) error { return app.tunnel(ctx, c.Args) }
653657
func (c *statusKongCmd) Run(ctx context.Context, app App) error { return app.status(ctx, c.Args) }
658+
func (c *heartbeatKongCmd) Run(ctx context.Context, app App) error { return app.heartbeat(ctx, c.Args) }
654659
func (c *listKongCmd) Run(ctx context.Context, app App) error { return app.list(ctx, c.Args) }
655660
func (c *shareKongCmd) Run(ctx context.Context, app App) error { return app.share(ctx, c.Args) }
656661
func (c *unshareKongCmd) Run(ctx context.Context, app App) error { return app.unshare(ctx, c.Args) }

‎internal/cli/heartbeat.go‎

Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
package cli
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"fmt"
7+
"io"
8+
"time"
9+
)
10+
11+
type leaseHeartbeatView struct {
12+
ID string `json:"id"`
13+
Slug string `json:"slug,omitempty"`
14+
Provider string `json:"provider"`
15+
State string `json:"state"`
16+
LastTouchedAt string `json:"lastTouchedAt,omitempty"`
17+
IdleTimeout string `json:"idleTimeout,omitempty"`
18+
ExpiresAt string `json:"expiresAt,omitempty"`
19+
}
20+
21+
func (a App) heartbeat(ctx context.Context, args []string) error {
22+
defaults := defaultConfig()
23+
fs := newFlagSet("heartbeat", a.Stderr)
24+
provider := registerProviderSelectionFlag(fs, defaults, providerHelpSSH())
25+
id := fs.String("id", "", "lease id or slug")
26+
idleTimeout := fs.Duration("idle-timeout", 0, "replace the lease idle timeout while heartbeating")
27+
jsonOut := fs.Bool("json", false, "print JSON")
28+
if err := parseFlags(fs, args); err != nil {
29+
return err
30+
}
31+
setIDFromFirstArg(fs, id)
32+
if fs.NArg() > 1 {
33+
return exit(2, "usage: crabbox heartbeat --id <lease-id-or-slug> [--provider <provider>] [--idle-timeout <duration>] [--json]")
34+
}
35+
idleTimeoutSet := flagWasSet(fs, "idle-timeout")
36+
if idleTimeoutSet && *idleTimeout <= 0 {
37+
return exit(2, "idle timeout must be positive")
38+
}
39+
40+
cfg, err := loadLeaseTargetConfig(fs, *provider, targetFlagValues{}, networkModeFlagValues{}, leaseTargetConfigOptions{LeaseID: *id})
41+
if err != nil {
42+
return err
43+
}
44+
if err := requireLeaseID(*id, "crabbox heartbeat --id <lease-id-or-slug>", cfg); err != nil {
45+
return err
46+
}
47+
if idleTimeoutSet {
48+
cfg.IdleTimeout = *idleTimeout
49+
}
50+
51+
backend, err := loadBackend(cfg, runtimeForApp(a))
52+
if err != nil {
53+
return err
54+
}
55+
if coordinator, ok := backend.(*coordinatorLeaseBackend); ok {
56+
var override *time.Duration
57+
if idleTimeoutSet {
58+
override = idleTimeout
59+
}
60+
lease, err := coordinator.HeartbeatLease(ctx, *id, override)
61+
if err != nil {
62+
return err
63+
}
64+
return writeLeaseHeartbeatView(a.Stdout, heartbeatViewFromCoordinatorLease(lease), *jsonOut)
65+
}
66+
var registeredCoord *CoordinatorClient
67+
if shouldRegisterCoordinatorLease(cfg) {
68+
coord, configured, err := newCoordinatorClient(cfg)
69+
if err != nil {
70+
return err
71+
}
72+
if !configured {
73+
return exit(2, "provider=%s does not support lease heartbeat", backend.Spec().Name)
74+
}
75+
registeredCoord = coord
76+
}
77+
78+
sshBackend, ok := backend.(SSHLeaseBackend)
79+
if !ok {
80+
return exit(2, "provider=%s does not support lease heartbeat", backend.Spec().Name)
81+
}
82+
lease, err := sshBackend.Resolve(ctx, ResolveRequest{
83+
Options: leaseOptionsFromConfig(cfg),
84+
ID: *id,
85+
StatusOnly: true,
86+
NoLocalStateMutations: true,
87+
})
88+
if err != nil {
89+
return err
90+
}
91+
state := blank(lease.Server.Labels["state"], lease.Server.Status)
92+
if statusTerminalState(state) {
93+
return exit(5, "lease %s is in terminal state %s", *id, state)
94+
}
95+
claimed, err := statusLeaseHasExactClaim(backend, lease, backend.Spec().Name, leaseOptionsFromConfig(cfg).ProviderScope)
96+
if err != nil {
97+
return err
98+
}
99+
if !claimed {
100+
return exit(4, "lease %s is not claimed for provider=%s; refusing heartbeat", *id, backend.Spec().Name)
101+
}
102+
103+
if !idleTimeoutSet {
104+
if current, ok := directLeaseIdleTimeout(lease.Server.Labels); ok {
105+
cfg.IdleTimeout = current
106+
backend, err = loadBackend(cfg, runtimeForApp(a))
107+
if err != nil {
108+
return err
109+
}
110+
var supportsTouch bool
111+
sshBackend, supportsTouch = backend.(SSHLeaseBackend)
112+
if !supportsTouch {
113+
return exit(2, "provider=%s does not support lease heartbeat", backend.Spec().Name)
114+
}
115+
}
116+
}
117+
var registeredLease *CoordinatorLease
118+
if registeredCoord != nil {
119+
var override *time.Duration
120+
if idleTimeoutSet {
121+
override = idleTimeout
122+
}
123+
canonicalLeaseID := lease.LeaseID
124+
coordinatorLease, err := heartbeatCoordinatorLease(ctx, registeredCoord, canonicalLeaseID, cfg.Provider, override)
125+
if err != nil {
126+
return err
127+
}
128+
if err := validateCoordinatorProviderIdentity(cfg.Provider, coordinatorLease.ID, coordinatorLease.Provider, true); err != nil {
129+
return err
130+
}
131+
if coordinatorLease.ID != canonicalLeaseID {
132+
return exit(4, "coordinator returned mismatched lease id: expected %s, found %s", canonicalLeaseID, blank(coordinatorLease.ID, "<empty>"))
133+
}
134+
registeredLease = &coordinatorLease
135+
}
136+
touched, err := sshBackend.Touch(ctx, TouchRequest{
137+
Lease: lease,
138+
State: state,
139+
IdleTimeout: cfg.IdleTimeout,
140+
})
141+
if err != nil {
142+
return err
143+
}
144+
if registeredLease != nil {
145+
return writeLeaseHeartbeatView(a.Stdout, heartbeatViewFromCoordinatorLease(*registeredLease), *jsonOut)
146+
}
147+
return writeLeaseHeartbeatView(a.Stdout, heartbeatViewFromServer(lease.LeaseID, touched), *jsonOut)
148+
}
149+
150+
func directLeaseIdleTimeout(labels map[string]string) (time.Duration, bool) {
151+
if duration, ok := parseDurationSecondsLabel(labels["idle_timeout_secs"]); ok {
152+
return duration, true
153+
}
154+
return parseDurationSecondsLabel(labels["idle_timeout"])
155+
}
156+
157+
func heartbeatViewFromCoordinatorLease(lease CoordinatorLease) leaseHeartbeatView {
158+
return leaseHeartbeatView{
159+
ID: lease.ID,
160+
Slug: lease.Slug,
161+
Provider: lease.Provider,
162+
State: lease.State,
163+
LastTouchedAt: lease.LastTouchedAt,
164+
IdleTimeout: formatSecondsDuration(lease.IdleTimeoutSeconds),
165+
ExpiresAt: lease.ExpiresAt,
166+
}
167+
}
168+
169+
func heartbeatViewFromServer(leaseID string, server Server) leaseHeartbeatView {
170+
return leaseHeartbeatView{
171+
ID: leaseID,
172+
Slug: serverSlug(server),
173+
Provider: server.Provider,
174+
State: blank(server.Labels["state"], server.Status),
175+
LastTouchedAt: blank(leaseLabelTimeDisplay(server.Labels["last_touched_at"]), server.Labels["last_touched_at"]),
176+
IdleTimeout: leaseLabelDurationDisplay(server.Labels["idle_timeout_secs"], server.Labels["idle_timeout"]),
177+
ExpiresAt: blank(leaseLabelTimeDisplay(server.Labels["expires_at"]), server.Labels["expires_at"]),
178+
}
179+
}
180+
181+
func writeLeaseHeartbeatView(stdout io.Writer, view leaseHeartbeatView, jsonOut bool) error {
182+
if jsonOut {
183+
return json.NewEncoder(stdout).Encode(view)
184+
}
185+
_, err := fmt.Fprintf(stdout, "heartbeat lease=%s slug=%s provider=%s state=%s idle_timeout=%s last_touched=%s expires=%s\n",
186+
view.ID,
187+
blank(view.Slug, "-"),
188+
view.Provider,
189+
view.State,
190+
blank(view.IdleTimeout, "-"),
191+
blank(view.LastTouchedAt, "-"),
192+
blank(view.ExpiresAt, "-"),
193+
)
194+
return err
195+
}

0 commit comments

Comments
 (0)