diff --git a/cmd/outpost-host/main.go b/cmd/outpost-host/main.go
index 43eabd9..eae8b98 100644
--- a/cmd/outpost-host/main.go
+++ b/cmd/outpost-host/main.go
@@ -343,7 +343,11 @@ func cmdRun(args []string) error {
if err != nil {
return err
}
- a := agent.New(agent.Options{DeviceID: dev.DeviceID, Version: version, Env: login.Env, DetectTools: true, StateDir: dir, StablePromptURL: promptURL,
+ mcpURL := os.Getenv("OUTPOST_MCP_URL")
+ if mcpURL == "" && promptURL == config.DefaultControlPlane+"/api/v1/agents/stable-prompt" {
+ mcpURL = "https://outpost-mcp.andrewmorgan.ai/mcp"
+ }
+ a := agent.New(agent.Options{MCPURL: mcpURL, DeviceID: dev.DeviceID, Version: version, Env: login.Env, DetectTools: true, StateDir: dir, StablePromptURL: promptURL,
TerminalIdle: idle, OpenURLDir: openURLDir, Binary: bin})
status := config.Status{PID: os.Getpid(), URL: target, Version: version}
// The agent's methods are served to paired clients over their encrypted channels. The
@@ -374,7 +378,15 @@ func cmdRun(args []string) error {
// Dev mode has no identity provider: the dev server's single account owns everything.
peers.Owner, peers.Verifier = "dev", peer.DevVerifier{}
}
- client := conn.New(conn.Config{
+ var wake func(context.Context, string) error
+ if a.Sessions2 != nil {
+ wake = a.Sessions2.DeliverWake
+ a.Sessions2.CanWake = func(id string) bool {
+ rec := store.Lookup(id)
+ return rec != nil && rec.Has(peer.ScopeSteer) && rec.Active(time.Now())
+ }
+ }
+ client := conn.New(conn.Config{Wake: wake,
URL: target, DeviceID: dev.DeviceID, Tokens: tokens, Peers: peers, Hello: a.SafeHello, UserAgent: userAgent(),
// The machine's public key, so browsers can open a channel to it. They pin it on first
// use; the control plane could lie about it once, and never unnoticed after that.
@@ -396,6 +408,9 @@ func cmdRun(args []string) error {
_ = config.SaveStatus(dir, status)
},
})
+ if a.Sessions2 != nil {
+ a.Sessions2.ChangeWake = client.ChangeWake
+ }
// Login links carry sign-in URLs, so they go to paired clients, never to the control plane.
a.SetNotifier(func(method string, params any) error { return peers.Notify(peer.ScopeSteer, method, params) })
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
diff --git a/docs/contract.md b/docs/contract.md
index fc22912..0f09c6a 100644
--- a/docs/contract.md
+++ b/docs/contract.md
@@ -78,6 +78,8 @@ The harness receives the usual Outpost client notes, agent name and job, and the
document when opening or resuming the conversation. Edits take effect when the next turn can
safely resume the harness. A running turn, pending approval or background task keeps its process.
+The encrypted host method `agents.setWake { sessionId, at }` requires steer access and a named session. Pass `cancel: true` in place of `at` to cancel. The device registers an opaque timer ID and deadline with the server, then stores its conversation and scheduling key locally. PostgreSQL retains timers while machines are offline. The server delivers due IDs on reconnect and heartbeat. The device checks the deadline and current grant, then consumes its local timer and records a scheduled turn in one SQLite transaction. A repeated or cancelled delivery cannot create a turn. Chat content stays on the encrypted channel.
+
### Session
```ts
diff --git a/docs/mcp.md b/docs/mcp.md
index 1d228dd..54c4d2c 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -2,7 +2,7 @@
`cmd/outpost-mcp` lets claude.ai (or any MCP client) reach your machines. Tools so far:
`whoami`, `machines_list`, `sessions_list`, `folders_list` and `session_read` read; `session_start`,
-`agent_create`, `session_answer`, `session_send` and `session_stop` act, and need a grant with `steer`.
+`agent_create`, `agent_wake`, `session_answer`, `session_send` and `session_stop` act, and need a grant with `steer`.
`folders_list` is where sessions have worked on each machine, newest first. A grant cannot browse
a machine's files, so this is how a client finds a folder; any full path can still be given.
@@ -28,9 +28,14 @@ A machine grant with `steer` enables these tools.
| `session_answer { machine, session, request, decision, answers, note }` | Answers what the session is waiting on (`request.answer`). `request` is `waitingOn.id`, so an answer never lands on a later request; the machine refuses a decision the request does not offer, and the first answer wins. |
| `session_send { machine, session, text }` | Sends a message (`turn.send`). |
| `session_stop { machine, session }` | Stops the turn under way (`turn.interrupt`). |
+| `agent_wake { machine, session, at?, cancel? }` | Set the next wake for a named agent at an RFC3339 timestamp, or pass `cancel: true` to remove it. Returns the accepted time. |
| `agent_create { machine, name, job, harness, prompt, iconUrl?, requestKey? }` | Creates a named agent with an idle permanent chat. The result includes its machine ID, session ID and chat URL. |
| `session_start { machine, agent, folder, prompt, name, permissions, plan, branch, from, model, effort }` | Starts a session (`session.start`). `permissions` is `ask` unless said otherwise: nobody is watching a session started from here. With `branch` the machine makes the session a worktree of its own on a new branch. |
+A named agent receives the Outpost MCP endpoint and its own machine and session IDs when its harness opens. The hosted service uses `https://outpost-mcp.andrewmorgan.ai/mcp`. A self-hosted machine can set `OUTPOST_MCP_URL` to its Outpost MCP endpoint. Each harness uses its normal OAuth sign-in and Outpost's machine grant.
+
+To wake again, call `agent_wake` with the home machine ID, permanent session ID and an absolute time, then end the turn. This replaces any previous wake for that agent. For periodic work, register the next occurrence at each check. A connected home machine receives due wakes on its roughly 15-second heartbeat. An offline machine receives overdue wakes when it reconnects. A wake queues behind an active turn. The machine checks the scheduling key's steer grant again at delivery.
+
For `agent_create`, the harness is `claude` or `codex`. The standing prompt goes through the MCP service and over its encrypted connection to the home machine. The device builds the same AGENT.md as the web editor and starts the chat in Ask mode. Use `session_send` to give the agent its first assignment.
Each creation key belongs to one connection on one home machine and defaults to the agent's name. Repeating the same request returns the same chat. A different profile under that key returns a conflict. Supply a distinct `requestKey` to create a second agent with the same display name. Owners can edit profiles in the Agents menu.
diff --git a/internal/e2e/e2e_test.go b/internal/e2e/e2e_test.go
index c8ac8b0..198b086 100644
--- a/internal/e2e/e2e_test.go
+++ b/internal/e2e/e2e_test.go
@@ -74,11 +74,16 @@ func start(t *testing.T) *rig {
Owner: "alice", Verifier: fakeIssuer{}}
ws := "ws" + strings.TrimPrefix(hs.URL, "http")
// The production wiring: no Router for the control plane, clients through Peers.
- c := conn.New(conn.Config{URL: ws + "/api/v1/hosts/connect", DeviceID: "host-e2e", Peers: table, Hello: a.SafeHello,
+ c := conn.New(conn.Config{Wake: a.Sessions2.DeliverWake, PingEvery: 200 * time.Millisecond, URL: ws + "/api/v1/hosts/connect", DeviceID: "host-e2e", Peers: table, Hello: a.SafeHello,
Backoff: []time.Duration{50 * time.Millisecond}, Logf: t.Logf,
Announce: func(notify func(string, any) error) {
_ = notify(peer.MethodHostKey, map[string]string{"publicKey": hex.EncodeToString(static.Public)})
}})
+ a.Sessions2.ChangeWake = c.ChangeWake
+ a.Sessions2.CanWake = func(id string) bool {
+ rec := store.Lookup(id)
+ return rec != nil && rec.Has(peer.ScopeSteer) && rec.Active(time.Now())
+ }
done := make(chan error, 1)
go func() { done <- c.Run(ctx) }()
t.Cleanup(func() {
diff --git a/internal/e2e/mcp_test.go b/internal/e2e/mcp_test.go
index 66ed129..dbc5455 100644
--- a/internal/e2e/mcp_test.go
+++ b/internal/e2e/mcp_test.go
@@ -33,7 +33,8 @@ func callTool[T any](t *testing.T, ctx context.Context, s *mcp.ClientSession, na
res, err := s.CallTool(ctx, &mcp.CallToolParams{Name: name, Arguments: args})
must(t, err)
if res.IsError {
- t.Fatalf("%s: %+v", name, res.Content)
+ detail, _ := json.Marshal(res.Content)
+ t.Fatalf("%s: %s", name, detail)
}
var out T
raw, _ := json.Marshal(res.StructuredContent)
@@ -104,8 +105,13 @@ func TestTheMCPServiceNeedsABrowsersGrant(t *testing.T) {
}
input := mcpserver.AgentCreateInput{Machine: r.hostID, Name: "Navi", Job: "Release coordinator", Harness: "codex", Prompt: " " + canary + "\n"}
+ wakeInput := mcpserver.AgentWakeInput{Machine: r.hostID, Session: "not-created-yet", At: time.Now().Add(time.Hour).Format(time.RFC3339Nano)}
needsGrant := func() {
t.Helper()
+ wake := callTool[mcpserver.AgentWakeResult](t, r.ctx, cs, "agent_wake", wakeInput)
+ if wake.Access != mcpserver.AccessNeedsApproval || wake.ApproveURL != who.ApproveURL {
+ t.Fatalf("scheduling without steer: %+v", wake)
+ }
out := callTool[mcpserver.AgentCreated](t, r.ctx, cs, "agent_create", input)
if out.Access != mcpserver.AccessNeedsApproval || out.ApproveURL != who.ApproveURL || out.SessionID != "" {
t.Fatalf("creating an agent without steer: %+v", out)
@@ -155,6 +161,26 @@ func TestTheMCPServiceNeedsABrowsersGrant(t *testing.T) {
if state.Session.Title != "Navi" || state.Session.Status != "idle" || len(state.Entries) != 0 {
t.Fatalf("permanent chat: %+v", state)
}
+ // A real MCP registration goes over the encrypted channel. The server delivers
+ // only the timer ID; the attributed turn and its fixed prompt originate on the device.
+ wakeInput.Session = created.SessionID
+ at := time.Now().UTC().Add(time.Second)
+ wakeInput.At = at.Format(time.RFC3339Nano)
+ wake := callTool[mcpserver.AgentWakeResult](t, r.ctx, cs, "agent_wake", wakeInput)
+ if wake.At == nil || !wake.At.Equal(at) {
+ t.Fatalf("unconfirmed wake: %+v", wake)
+ }
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ got := callTool[mcpserver.SessionRead](t, r.ctx, cs, "session_read", map[string]string{"machine": r.hostID, "session": created.SessionID})
+ if len(got.Entries) > 0 && strings.Contains(got.Entries[0].Text, "Scheduled wake from Outpost") {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("scheduled turn did not arrive: %+v", got)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
doc, err := os.ReadFile(filepath.Join(r.home, ".config", "outpost-host", "agents", created.SessionID, "AGENT.md"))
must(t, err)
if !strings.HasPrefix(string(doc), "You are a named agent in Outpost.") || !strings.HasSuffix(string(doc), "## Standing prompt\n\n "+canary+"\n") || r.srv.Stats.CanaryHits.Load() != 0 {
diff --git a/internal/host/agent/agent.go b/internal/host/agent/agent.go
index ff6aee1..ed6752a 100644
--- a/internal/host/agent/agent.go
+++ b/internal/host/agent/agent.go
@@ -50,6 +50,7 @@ type Options struct {
StateDir string
// StablePromptURL is the control plane's shared prompt for named agents.
StablePromptURL string
+ MCPURL string
// TerminalIdle closes a terminal with no input or output for this long (0: the default 24 h,
// negative: never).
TerminalIdle time.Duration
@@ -212,6 +213,8 @@ func (a *Agent) startSessions(opts Options) {
}); err != nil {
log.Printf("named agents: restoring definitions: %v", err)
}
+ svc.HomeMachine = opts.DeviceID
+ svc.MCPURL = opts.MCPURL
registerDefinitions(a.Router, dir, opts.StablePromptURL, opts.Home, svc)
if a.git != nil {
svc.Worktree = a.git.NewWorktree
diff --git a/internal/host/conn/conn.go b/internal/host/conn/conn.go
index 5239f1e..60d71ac 100644
--- a/internal/host/conn/conn.go
+++ b/internal/host/conn/conn.go
@@ -75,6 +75,8 @@ type Config struct {
// Hello builds host.hello for each connection.
Hello func() wire.HostHelloParams
// Announce, when set, sends further notifications right after host.hello.
+ // Wake delivers only an opaque ID. The device verifies its own scheduled intent.
+ Wake func(context.Context, string) error
Announce func(notify func(method string, params any) error)
UserAgent string
@@ -141,6 +143,22 @@ func New(cfg Config) *Client {
return &Client{cfg: cfg}
}
+// ChangeWake stores or removes one opaque timer on this device's control socket.
+func (c *Client) ChangeWake(ctx context.Context, id string, at *time.Time) error {
+ s := c.current.Load()
+ if s == nil {
+ return ErrNotConnected
+ }
+ ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ method := "host.wake.set"
+ if at == nil {
+ method = "host.wake.clear"
+ }
+ _, err := s.call(ctx, method, map[string]any{"id": id, "at": at})
+ return err
+}
+
// Connects is how many connections succeeded so far.
func (c *Client) Connects() int { return int(c.connects.Load()) }
@@ -277,6 +295,11 @@ func (c *Client) once(ctx context.Context) (connected bool, err error) {
if c.cfg.Announce != nil {
c.cfg.Announce(s.Notify)
}
+ if c.cfg.Wake != nil {
+ if err := s.Notify("host.wake.ready", struct{}{}); err != nil {
+ return true, err
+ }
+ }
go s.ep.Run()
go s.pingLoop()
if c.cfg.Tokens != nil {
@@ -303,9 +326,10 @@ type session struct {
cancel context.CancelFunc
ep *rpc.Endpoint
- wmu sync.Mutex
- lastRecv atomic.Int64
- fatal atomic.Pointer[error]
+ wmu sync.Mutex
+ processingWakes atomic.Bool
+ lastRecv atomic.Int64
+ fatal atomic.Pointer[error]
}
func (s *session) write(msg *wire.Message) error {
@@ -376,6 +400,28 @@ func (s *session) readLoop() error {
// local answers the control plane's host.ping; everything else goes to the router.
func (s *session) local(msg *wire.Message) bool {
+ if msg.Method == "host.wake.due" && !msg.IsRequest() && s.c.cfg.Wake != nil {
+ var p struct {
+ IDs []string `json:"ids"`
+ }
+ if json.Unmarshal(msg.Params, &p) == nil && len(p.IDs) <= 32 && s.processingWakes.CompareAndSwap(false, true) {
+ go func() {
+ defer s.processingWakes.Store(false)
+ for _, id := range p.IDs {
+ if s.ctx.Err() != nil {
+ return
+ }
+ if err := s.c.cfg.Wake(s.ctx, id); err != nil {
+ continue
+ }
+ ctx, cancel := context.WithTimeout(s.ctx, 10*time.Second)
+ _, _ = s.call(ctx, "host.wake.clear", map[string]string{"id": id})
+ cancel()
+ }
+ }()
+ }
+ return true
+ }
if msg.Method != wire.MethodHostPing {
return false
}
diff --git a/internal/host/harness/claudecode/runtime.go b/internal/host/harness/claudecode/runtime.go
index c8056ed..6f8e419 100644
--- a/internal/host/harness/claudecode/runtime.go
+++ b/internal/host/harness/claudecode/runtime.go
@@ -171,6 +171,10 @@ func Argv(binary string, s session.Session, nativeID string, resume, fork bool)
"--include-partial-messages", "--replay-user-messages",
"--permission-prompt-tool", "stdio", "--permission-mode", CLIMode(s.Mode, s.Plan), "--allow-dangerously-skip-permissions",
"--setting-sources", "project"}
+ if s.MCPURL != "" {
+ cfg, _ := json.Marshal(map[string]any{"mcpServers": map[string]any{"outpost": map[string]string{"type": "http", "url": s.MCPURL}}})
+ argv = append(argv, "--mcp-config", string(cfg))
+ }
if s.Instructions == "" {
argv = append(argv, "--append-system-prompt", session.ClientNotes)
}
diff --git a/internal/host/harness/claudecode/runtime_test.go b/internal/host/harness/claudecode/runtime_test.go
index 786acc1..6ca915a 100644
--- a/internal/host/harness/claudecode/runtime_test.go
+++ b/internal/host/harness/claudecode/runtime_test.go
@@ -467,6 +467,8 @@ func TestNamedAgentLoadsLargePromptAndResumesAfterEdit(t *testing.T) {
r := newCLIRig(t)
defer r.svc.Close()
const id = "navi"
+ r.svc.HomeMachine = "agent-test-machine"
+ r.svc.MCPURL = "https://outpost.example/mcp"
dir := filepath.Dir(r.log)
doc := strings.Repeat("Long standing instruction.\n", 6000)
settings := session.AgentSettings{Name: "Navi", Job: "Release coordinator", Harness: "claude"}
@@ -495,7 +497,17 @@ func TestNamedAgentLoadsLargePromptAndResumesAfterEdit(t *testing.T) {
t.Fatalf("got %d launches", len(launches))
}
for i, document := range []string{doc, doc + "Updated."} {
- instructions := session.ClientNotes + "\n\nAgent name: Navi\nJob: Release coordinator\n\n" + document
+ instructions := session.ClientNotes + "\n\nOutpost home machine ID: \"agent-test-machine\"\nPermanent session ID: \"navi\"\nAgent name: Navi\nJob: Release coordinator\n\n" + document
+ args := toStrings(launches[i]["argv"])
+ configured := false
+ for j := 0; j+1 < len(args); j++ {
+ if args[j] == "--mcp-config" && strings.Contains(args[j+1], `"outpost":{"type":"http","url":"https://outpost.example/mcp"}`) {
+ configured = true
+ }
+ }
+ if !configured {
+ t.Fatal("named Claude launch is missing the Outpost MCP endpoint")
+ }
if launches[i]["promptHash"] != fmt.Sprintf("%x", sha256.Sum256([]byte(instructions))) {
t.Fatalf("Claude did not read the intended prompt on launch %d", i)
}
diff --git a/internal/host/harness/codex/runtime.go b/internal/host/harness/codex/runtime.go
index b9b606e..1ccf64e 100644
--- a/internal/host/harness/codex/runtime.go
+++ b/internal/host/harness/codex/runtime.go
@@ -11,6 +11,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "strconv"
"strings"
"sync"
"syscall"
@@ -110,7 +111,11 @@ func (a *Adapter) start(dir string, s session.Session) (*runtime, error) {
}
}
}
- cmd := exec.Command(binary, "app-server")
+ args := []string{"app-server"}
+ if s.MCPURL != "" {
+ args = append(args, "-c", "mcp_servers.outpost.url="+strconv.Quote(s.MCPURL), "-c", `mcp_servers.outpost.scopes=["mcp:outpost"]`)
+ }
+ cmd := exec.Command(binary, args...)
cmd.Dir, cmd.Env = dir, env
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
stdin, err := cmd.StdinPipe()
diff --git a/internal/host/peer/grants.go b/internal/host/peer/grants.go
index 8c016b6..9332154 100644
--- a/internal/host/peer/grants.go
+++ b/internal/host/peer/grants.go
@@ -36,6 +36,7 @@ var GrantableScopes = []string{ScopeView, ScopeSteer}
// both tell only what they were written to tell, and neither a login link.
var GrantMethods = map[string]bool{
"agents.create": true, // create an idle permanent chat with Ask permissions
+ "agents.setWake": true, // schedule a future turn for a named chat
"sessions.watch": true,
"session.recent": true,
"session.read": true, // steer only, by its scope
diff --git a/internal/host/peer/scopes.go b/internal/host/peer/scopes.go
index bc6f2a7..d0a0d84 100644
--- a/internal/host/peer/scopes.go
+++ b/internal/host/peer/scopes.go
@@ -33,6 +33,7 @@ var methodScope = map[string]string{
// tools.update installs a new version of a CLI: it changes the machine's software, which
// is the owner's call alone.
"tools.update": ScopeAdmin,
+ "agents.setWake": ScopeSteer,
"agents.create": ScopeSteer,
"agents.saveProfile": ScopeAdmin,
"agents.saveDefinition": ScopeAdmin,
diff --git a/internal/host/session/adapter.go b/internal/host/session/adapter.go
index 7faa495..9cf8813 100644
--- a/internal/host/session/adapter.go
+++ b/internal/host/session/adapter.go
@@ -51,6 +51,7 @@ type Runtime interface {
}
type TurnInput struct {
+ Scheduled bool
MessageID string
Text string
Images []string // paths on this machine
diff --git a/internal/host/session/rpc.go b/internal/host/session/rpc.go
index 01cd75f..8c99894 100644
--- a/internal/host/session/rpc.go
+++ b/internal/host/session/rpc.go
@@ -46,6 +46,7 @@ type subscription struct {
// Register adds the client API to a router.
func (s *Service) Register(r *rpc.Router) {
+ s.registerWake(r)
subs := &subscriptions{subs: map[string]subscription{}}
if s.Prepare != nil {
r.Handle("session.worktreeDraft", rpc.Typed(func(c *rpc.Call, p *struct {
diff --git a/internal/host/session/service.go b/internal/host/session/service.go
index d4da244..a004e6e 100644
--- a/internal/host/session/service.go
+++ b/internal/host/session/service.go
@@ -29,10 +29,15 @@ func errf(code, format string, args ...any) *Error {
// Service owns sessions: it decides commands, records them, drives the harness adapters and
// turns what they report into events.
type Service struct {
- store *Store
- hub *Hub
- adapters map[string]Adapter
- Logf func(format string, args ...any)
+ HomeMachine string
+ MCPURL string
+ wakeMu sync.Mutex
+ ChangeWake func(context.Context, string, *time.Time) error
+ CanWake func(string) bool
+ store *Store
+ hub *Hub
+ adapters map[string]Adapter
+ Logf func(format string, args ...any)
// Worktree makes a worktree on a new branch in the repository folder is in, branched off
// from, and returns the repository's main folder and the worktree's. Nil where the machine
// cannot: starting a session on a branch of its own is then refused.
@@ -605,6 +610,10 @@ func (s *Service) planSend(ctx context.Context, l *live, sess *Session, w *Write
return nil, errf("conflict", "that message id is already in use")
}
sess.ArchivedAt = nil
+ trigger := "user"
+ if in.Scheduled {
+ trigger = "scheduled"
+ }
message := func(turnID, intent string) *Item {
l.itemOrd++
return &Item{ID: in.MessageID, SessionID: sess.ID, TurnID: turnID, Ordinal: l.itemOrd, Type: "user_message", Status: ItemCompleted,
@@ -619,7 +628,7 @@ func (s *Service) planSend(ctx context.Context, l *live, sess *Session, w *Write
}
// Behind the running turn: started when that one ends.
l.turnOrd++
- turn := &Turn{ID: newID("trn"), SessionID: sess.ID, Ordinal: l.turnOrd, Status: TurnQueued, Trigger: "user", StartedAt: now}
+ turn := &Turn{ID: newID("trn"), SessionID: sess.ID, Ordinal: l.turnOrd, Status: TurnQueued, Trigger: trigger, StartedAt: now}
w.Changes = append(w.Changes, turn, message(turn.ID, "queued"), touch(sess))
return nil, nil
}
@@ -634,13 +643,13 @@ func (s *Service) planSend(ctx context.Context, l *live, sess *Session, w *Write
}
if next != nil {
l.turnOrd++
- turn := &Turn{ID: newID("trn"), SessionID: sess.ID, Ordinal: l.turnOrd, Status: TurnQueued, Trigger: "user", StartedAt: now}
+ turn := &Turn{ID: newID("trn"), SessionID: sess.ID, Ordinal: l.turnOrd, Status: TurnQueued, Trigger: trigger, StartedAt: now}
w.Changes = append(w.Changes, turn, message(turn.ID, "queued"), touch(sess))
return []func(){next}, nil
}
}
l.turnOrd++
- turn := &Turn{ID: newID("trn"), SessionID: sess.ID, Ordinal: l.turnOrd, Status: TurnStarting, Trigger: "user", StartedAt: now}
+ turn := &Turn{ID: newID("trn"), SessionID: sess.ID, Ordinal: l.turnOrd, Status: TurnStarting, Trigger: trigger, StartedAt: now}
sess.Status, sess.ActiveTurnID, sess.LastError = StatusStarting, &turn.ID, nil
w.Changes = append(w.Changes, turn, message(turn.ID, "start"), touch(sess))
return []func(){s.startTurn(w, sess.ID, turn.ID, in)}, nil
@@ -926,7 +935,8 @@ func (s *Service) runtime(ctx context.Context, l *live, sessionID, forTurn strin
if err != nil {
return nil, err
}
- sess.Instructions = fmt.Sprintf("%s\n\nAgent name: %s\nJob: %s\n\n%s", ClientNotes, *sess.Title, sess.Agent.Job, doc)
+ sess.MCPURL = s.MCPURL
+ sess.Instructions = fmt.Sprintf("%s\n\nOutpost home machine ID: %q\nPermanent session ID: %q\nAgent name: %s\nJob: %s\n\n%s", ClientNotes, s.HomeMachine, sess.ID, *sess.Title, sess.Agent.Job, doc)
}
rt, err := adapter.Open(ctx, *sess)
if err != nil {
diff --git a/internal/host/session/store.go b/internal/host/session/store.go
index 9fd6e44..acda5f2 100644
--- a/internal/host/session/store.go
+++ b/internal/host/session/store.go
@@ -18,6 +18,7 @@ type Store struct{ db *sql.DB }
const schemaSQL = `
CREATE TABLE IF NOT EXISTS worktree_drafts (session_id TEXT PRIMARY KEY, payload TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, harness TEXT NOT NULL, status TEXT NOT NULL, payload TEXT NOT NULL);
+CREATE TABLE IF NOT EXISTS agent_wakes (session_id TEXT PRIMARY KEY, token TEXT UNIQUE NOT NULL, due_at TEXT NOT NULL, caller TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS agent_documents (session_id TEXT PRIMARY KEY, document TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS turns (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, ordinal INTEGER NOT NULL, status TEXT NOT NULL, payload TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS turns_session ON turns (session_id, ordinal);
@@ -94,6 +95,7 @@ type Finished struct {
// and requests written without an event each: history copied into a session nobody is following
// yet, which a client reads as a snapshot.
type Write struct {
+ ConsumeWake string
Draft *worktreeDraft
ClearDraft string
Receipt *Receipt
@@ -163,6 +165,11 @@ func (s *Store) Commit(ctx context.Context, w Write) ([]Event, error) {
return nil, err
}
}
+ if w.ConsumeWake != "" {
+ if _, err := tx.ExecContext(ctx, "DELETE FROM agent_wakes WHERE token=?", w.ConsumeWake); err != nil {
+ return nil, err
+ }
+ }
if doc := w.AgentDocument; doc != nil {
if _, err := tx.ExecContext(ctx, `INSERT INTO agent_documents (session_id, document) VALUES (?,?) ON CONFLICT(session_id) DO UPDATE SET document=excluded.document`, doc.ID, doc.Document); err != nil {
return nil, err
diff --git a/internal/host/session/types.go b/internal/host/session/types.go
index 59cf001..36ea9d0 100644
--- a/internal/host/session/types.go
+++ b/internal/host/session/types.go
@@ -129,6 +129,7 @@ type Session struct {
ID string `json:"id"`
Agent *AgentProfile `json:"agent,omitempty"`
// Instructions are populated only when opening a named agent runtime.
+ MCPURL string `json:"-"` // filled only when opening a named agent
Instructions string `json:"-"`
Harness string `json:"harness"`
NativeID *string `json:"nativeId"`
diff --git a/internal/host/session/wake.go b/internal/host/session/wake.go
new file mode 100644
index 0000000..cbed35d
--- /dev/null
+++ b/internal/host/session/wake.go
@@ -0,0 +1,137 @@
+package session
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "time"
+
+ "github.com/andyjmorgan/outpost/internal/host/rpc"
+ "github.com/andyjmorgan/outpost/internal/host/wire"
+)
+
+const wakeMessage = "Scheduled wake from Outpost. Check the latest assignment and any newer instructions in this chat. Continue only if there is work remaining."
+
+// SetWake replaces the named chat's next wake. The cloud gets an independent
+// opaque timer first. If the local write fails, the old timer remains usable
+// and the machine discards the unrecognised delivery of the new one.
+func (s *Service) SetWake(ctx context.Context, id string, at *time.Time, caller string) error {
+ s.wakeMu.Lock()
+ defer s.wakeMu.Unlock()
+ if s.ChangeWake == nil {
+ return errf("unavailable", "this machine has no wake scheduler")
+ }
+ sess, err := s.store.Session(ctx, id)
+ if err != nil {
+ return err
+ }
+ if sess == nil || sess.Agent == nil {
+ return errf("not_found", "choose a named agent's permanent session")
+ }
+ var previous, stamp, grant string
+ err = s.store.db.QueryRowContext(ctx, "SELECT token,due_at,caller FROM agent_wakes WHERE session_id=?", id).Scan(&previous, &stamp, &grant)
+ if err != nil && !errors.Is(err, sql.ErrNoRows) {
+ return err
+ }
+ if at == nil {
+ if previous == "" {
+ return nil
+ }
+ if _, err := s.store.db.ExecContext(ctx, "DELETE FROM agent_wakes WHERE token=?", previous); err != nil {
+ return err
+ }
+ } else {
+ if caller == grant && stamp == ts(*at) {
+ return nil
+ }
+ if !at.After(time.Now()) {
+ return errf("invalid", "choose a wake time in the future")
+ }
+ token := wire.NewUUID()
+ if err := s.ChangeWake(ctx, token, at); err != nil {
+ return err
+ }
+ _, err = s.store.db.ExecContext(ctx, `INSERT INTO agent_wakes(session_id,token,due_at,caller) VALUES(?,?,?,?)
+ ON CONFLICT(session_id) DO UPDATE SET token=excluded.token,due_at=excluded.due_at,caller=excluded.caller`, id, token, ts(*at), caller)
+ if err != nil {
+ return err
+ }
+ }
+ if previous != "" {
+ _ = s.ChangeWake(ctx, previous, nil)
+ }
+ return nil
+}
+
+// DeliverWake consumes the device's permit in the same commit as the queued
+// turn. A replay, cancelled timer, or an arbitrary ID from the relay does nothing.
+func (s *Service) DeliverWake(ctx context.Context, token string) error {
+ s.wakeMu.Lock()
+ defer s.wakeMu.Unlock()
+ var id, stamp, caller string
+ err := s.store.db.QueryRowContext(ctx, "SELECT session_id,due_at,caller FROM agent_wakes WHERE token=?", token).Scan(&id, &stamp, &caller)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ at, err := time.Parse(time.RFC3339Nano, stamp)
+ if err != nil {
+ return err
+ }
+ if time.Now().Before(at) {
+ return errors.New("wake is not due")
+ }
+ if caller != "" && (s.CanWake == nil || !s.CanWake(caller)) {
+ _, err = s.store.db.ExecContext(ctx, "DELETE FROM agent_wakes WHERE token=?", token)
+ return err
+ }
+ l := s.session(id)
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ sess, err := s.store.Session(ctx, id)
+ if err != nil {
+ return err
+ }
+ if sess == nil || sess.Agent == nil {
+ return errf("not_found", "named session missing")
+ }
+ if err := l.load(ctx, s.store, id); err != nil {
+ return err
+ }
+ w := Write{ConsumeWake: token}
+ after, err := s.planSend(ctx, l, sess, &w, TurnInput{Text: wakeMessage, Scheduled: true}, "queue")
+ if err == nil {
+ _, err = s.commit(ctx, w)
+ }
+ if err != nil {
+ l.loaded = false
+ return err
+ }
+ for _, f := range after {
+ l.effects.push(f)
+ }
+ return nil
+}
+
+func (s *Service) registerWake(r *rpc.Router) {
+ r.Handle("agents.setWake", rpc.Typed(func(c *rpc.Call, p *struct {
+ SessionID string `json:"sessionId"`
+ At *time.Time `json:"at"`
+ Cancel bool `json:"cancel"`
+ }) (any, error) {
+ if (p.At == nil) != p.Cancel {
+ return nil, wire.Errorf(wire.CodeBadParams, "pass a wake time or cancel")
+ }
+ caller := ""
+ if c.Caller.Delegated {
+ caller = c.Caller.ClientID
+ if caller == "" {
+ return nil, wire.Errorf(403, "a wake needs the scheduling grant's key")
+ }
+ }
+ err := s.SetWake(c.Ctx, p.SessionID, p.At, caller)
+ return map[string]any{"at": p.At}, WireError(err)
+ }), false)
+}
diff --git a/internal/host/session/wake_test.go b/internal/host/session/wake_test.go
new file mode 100644
index 0000000..792bba0
--- /dev/null
+++ b/internal/host/session/wake_test.go
@@ -0,0 +1,103 @@
+package session
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestWakeNeedsItsLocalPermitAndOnlyQueuesOnce(t *testing.T) {
+ r := newRig(t, true)
+ const id = "navi"
+ _, err := r.svc.SaveAgent(r.ctx, id, "/work", AgentSettings{Name: "Navi", Job: "Check changes", Harness: "fake"}, "instructions")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var last string
+ var fail bool
+ cloud := func(_ context.Context, token string, at *time.Time) error {
+ if fail {
+ return errors.New("cloud unavailable")
+ }
+ if at != nil {
+ last = token
+ }
+ return nil
+ }
+ r.svc.ChangeWake = cloud
+ r.svc.CanWake = func(key string) bool { return key == "granted" }
+ later := time.Now().Add(time.Hour)
+ if err := r.svc.SetWake(r.ctx, id, &later, "granted"); err != nil {
+ t.Fatal(err)
+ }
+ first := last
+ if err := r.svc.DeliverWake(r.ctx, first); err == nil {
+ t.Fatal("the cloud could deliver an early wake")
+ }
+ at := later.Add(time.Hour)
+ fail = true
+ if err := r.svc.SetWake(r.ctx, id, &at, "granted"); err == nil {
+ t.Fatal("reported success before the cloud accepted")
+ }
+ fail = false
+ var token string
+ if err := r.store.db.QueryRow("SELECT token FROM agent_wakes WHERE session_id=?", id).Scan(&token); err != nil || token != first {
+ t.Fatal("failed replacement lost its previous wake", err)
+ }
+ if err := r.svc.SetWake(r.ctx, id, &at, "granted"); err != nil {
+ t.Fatal(err)
+ }
+ second := last
+ for _, key := range []string{"made-up", first} {
+ if err := r.svc.DeliverWake(r.ctx, key); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := r.svc.SetWake(r.ctx, id, nil, "granted"); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.svc.DeliverWake(r.ctx, second); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.svc.SetWake(r.ctx, id, &at, "granted"); err != nil {
+ t.Fatal(err)
+ }
+ // Simulate disconnection, a host restart and delivery after the requested time.
+ r.restart()
+ r.svc.ChangeWake = cloud
+ r.svc.CanWake = func(key string) bool { return key == "granted" }
+ r.must(r.cmd(id, "turn.send", map[string]string{"text": "An in-flight assignment"}))
+ r.untilCalls(1)
+ if _, err := r.store.db.Exec("UPDATE agent_wakes SET due_at=? WHERE token=?", ts(time.Now().Add(-time.Minute)), last); err != nil {
+ t.Fatal(err)
+ }
+ for range 2 {
+ if err := r.svc.DeliverWake(r.ctx, last); err != nil {
+ t.Fatal(err)
+ }
+ }
+ turns, err := r.store.Turns(r.ctx, id)
+ if err != nil || len(turns) != 2 || turns[1].Trigger != "scheduled" || turns[1].Status != TurnQueued {
+ t.Fatalf("expected one queued wake: %+v, %v", turns, err)
+ }
+ r.svc.CanWake = func(string) bool { return false }
+ at = later
+ if err := r.svc.SetWake(r.ctx, id, &at, "revoked"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := r.store.db.Exec("UPDATE agent_wakes SET due_at=? WHERE token=?", ts(time.Now().Add(-time.Minute)), last); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.svc.DeliverWake(r.ctx, last); err != nil {
+ t.Fatal(err)
+ }
+ turns, err = r.store.Turns(r.ctx, id)
+ if err != nil || len(turns) != 2 {
+ t.Fatal("delivered a revoked grant", err)
+ }
+ if err := r.svc.SetWake(r.ctx, r.start(""), &later, "granted"); err == nil || !strings.Contains(err.Error(), "named") {
+ t.Fatal("registered a wake on an ordinary session", err)
+ }
+}
diff --git a/internal/mcpserver/icons.go b/internal/mcpserver/icons.go
index 5151701..61547f1 100644
--- a/internal/mcpserver/icons.go
+++ b/internal/mcpserver/icons.go
@@ -21,6 +21,7 @@ var toolGlyphs = map[string]string{
"sessions_list": ``,
"session_read": ``,
"folders_list": ``,
+ "agent_wake": ``,
"agent_create": ``,
"session_start": ``,
"session_answer": ``,
diff --git a/internal/mcpserver/server.go b/internal/mcpserver/server.go
index 2069e4c..b0270a1 100644
--- a/internal/mcpserver/server.go
+++ b/internal/mcpserver/server.go
@@ -362,6 +362,8 @@ func (s *Server) mcp() *mcp.Server {
mcp.AddTool(srv, withIcons(&mcp.Tool{Name: "folders_list", Title: "List folders", Annotations: readOnly(),
Description: "The folders the user's sessions have worked in on each machine, most recent first: where a new session is most likely wanted. " +
"A folder not listed can still be used with session_start by its full path."}), s.foldersList)
+ mcp.AddTool(srv, withIcons(&mcp.Tool{Name: "agent_wake", Title: "Schedule a named agent wake", Annotations: acts(false),
+ Description: "Register or cancel the next wake for a named agent on an approved machine, then end the current turn. Outpost resumes its permanent conversation when due, including after downtime. The latest registration replaces the previous one. Needs steer access."}), s.agentWake)
mcp.AddTool(srv, withIcons(&mcp.Tool{Name: "agent_create", Title: "Create a named agent", Annotations: acts(false),
Description: "Create a named agent on an approved home machine with a permanent chat and standing instructions. Needs steer access. The chat starts idle in Ask mode. Use the returned chat URL to open it, or use session_send with its machine and session IDs to assign work."}), s.agentCreate)
mcp.AddTool(srv, withIcons(&mcp.Tool{Name: "session_start", Title: "Start a session", Annotations: acts(false),
diff --git a/internal/mcpserver/wake.go b/internal/mcpserver/wake.go
new file mode 100644
index 0000000..e9e303d
--- /dev/null
+++ b/internal/mcpserver/wake.go
@@ -0,0 +1,80 @@
+package mcpserver
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/andyjmorgan/outpost/internal/host/peer"
+ "github.com/andyjmorgan/outpost/internal/host/wire"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+)
+
+// AgentWakeInput changes one pending wake for a permanent conversation.
+type AgentWakeInput struct {
+ Machine string `json:"machine" jsonschema:"home machine ID or name"`
+ Session string `json:"session" jsonschema:"permanent named-agent session ID"`
+ At string `json:"at,omitempty" jsonschema:"when to resume in RFC3339 with time zone; replaces the previous wake"`
+ Cancel bool `json:"cancel,omitempty" jsonschema:"clear the next wake instead of setting a time"`
+}
+
+type AgentWakeResult struct {
+ At *time.Time `json:"at,omitempty"`
+ Cancelled bool `json:"cancelled,omitempty"`
+ Access string `json:"access,omitempty"`
+ ApproveURL string `json:"approveUrl,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+func (s *Server) agentWake(ctx context.Context, req *mcp.CallToolRequest, in AgentWakeInput) (*mcp.CallToolResult, AgentWakeResult, error) {
+ var result AgentWakeResult
+ u, err := userOf(req)
+ if err != nil {
+ return nil, result, err
+ }
+ if in.Machine == "" || in.Session == "" || (in.At == "") != in.Cancel {
+ return nil, result, errors.New("pass the machine, permanent session and either at or cancel")
+ }
+ var at *time.Time
+ if !in.Cancel {
+ due, err := time.Parse(time.RFC3339Nano, in.At)
+ if err != nil {
+ return nil, result, errors.New("at must be RFC3339 with a time zone")
+ }
+ at = &due
+ }
+ ctx, cancel := context.WithTimeout(ctx, perHost+15*time.Second)
+ defer cancel()
+ c, h, ask, early, err := s.reach(ctx, req, u, in.Machine)
+ if c == nil {
+ if early != nil {
+ result.Access, result.ApproveURL, result.Error = early.Access, early.ApproveURL, early.Error
+ }
+ return ask, result, err
+ }
+ defer c.Close()
+ err = c.Call(ctx, "agents.setWake", map[string]any{"sessionId": in.Session, "at": at, "cancel": in.Cancel}, &result)
+ if err != nil {
+ var rpcErr *wire.Error
+ if errors.As(err, &rpcErr) && rpcErr.Code == peer.CodeForbidden && strings.Contains(rpcErr.Message, `"steer" scope`) {
+ if ask, err := s.approval(u, req); ask != nil || err != nil {
+ return ask, result, err
+ }
+ key, err := s.key(u)
+ if err != nil {
+ return nil, result, err
+ }
+ result.Access, result.ApproveURL = AccessNeedsApproval, s.approveURL(u, key)
+ result.Error = "Choose View and steer sessions for this machine to schedule a wake."
+ return nil, result, nil
+ }
+ if errors.As(err, &rpcErr) && (rpcErr.Code == wire.CodeMethodNotFound || (rpcErr.Code == peer.CodeForbidden && (strings.Contains(rpcErr.Message, `"admin" scope`) || strings.Contains(rpcErr.Message, "may only reach sessions")))) {
+ return nil, result, fmt.Errorf("update Outpost on %s to schedule named-agent wakes", h.Name)
+ }
+ return nil, result, err
+ }
+ result.Cancelled = in.Cancel
+ return nil, result, nil
+}
diff --git a/internal/server/agent_prompt.go b/internal/server/agent_prompt.go
index 8ab1a1d..59e9397 100644
--- a/internal/server/agent_prompt.go
+++ b/internal/server/agent_prompt.go
@@ -6,7 +6,7 @@ import "net/http"
// the agent's own standing prompt only travels over the browser-to-device channel.
const stableAgentPrompt = `You are a named agent in Outpost. This conversation is your permanent chat.
Use the Outpost tools available to you to inspect or steer sessions within the user's grants.
-For an assignment that needs another check, record the work and its completion condition in this chat. If a wake tool is available, register the next check and confirm the time it returns.
+For an assignment that needs another check, record the work and its completion condition in this chat. Call the Outpost agent_wake tool with your home machine ID, permanent session ID and next check time. Once the tool confirms the wake, finish this turn. For recurring work register your following wake at each check. If Outpost asks for a grant, give the user its approval link.
When woken, read the latest assignment and any newer user instructions, then check the current state before acting. When the assignment is finished, report the outcome in this chat.`
func agentStablePrompt(w http.ResponseWriter, _ *http.Request) {
diff --git a/internal/server/server.go b/internal/server/server.go
index b01022d..125f4a2 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -78,12 +78,13 @@ type ticket struct {
const ticketTTL = 30 * time.Second
type hostConn struct {
- id, owner string
- ws *websocket.Conn
- wmu sync.Mutex
- hello atomic.Pointer[safeHello]
- key atomic.Pointer[string] // the machine's Noise public key (hex), as it announced it
- connectedAt time.Time
+ wakesEnabled bool // only read and written in the socket control loop
+ id, owner string
+ ws *websocket.Conn
+ wmu sync.Mutex
+ hello atomic.Pointer[safeHello]
+ key atomic.Pointer[string] // the machine's Noise public key (hex), as it announced it
+ connectedAt time.Time
mu sync.Mutex
clients map[uint32]*clientConn
@@ -320,10 +321,16 @@ func (s *Server) hostControl(h *hostConn, data []byte) bool {
if json.Unmarshal(msg.Params, &p) == nil && len(p.PublicKey) == 64 {
h.key.Store(&p.PublicKey)
}
+ case "host.wake.ready":
+ h.wakesEnabled = true
+ s.deliverWakes(h)
+ case "host.wake.set", "host.wake.clear":
+ s.changeWake(h, &msg)
case wire.MethodHostPing:
if msg.IsRequest() {
res, _ := wire.NewResult(msg.ID, wire.HostPingResult{At: time.Now().UTC().Format(time.RFC3339Nano)})
h.reply(res)
+ s.deliverWakes(h)
}
case wire.MethodHostAuth:
var p wire.HostAuthParams
diff --git a/internal/server/store.go b/internal/server/store.go
index c839052..77912ab 100644
--- a/internal/server/store.go
+++ b/internal/server/store.go
@@ -25,6 +25,7 @@ var ErrOtherOwner = errors.New("this device is enrolled to another account")
// DeviceStore keeps enrolments.
type DeviceStore interface {
+ wakeStore
// Enrol records the device for owner (again is fine; another owner is ErrOtherOwner).
Enrol(ctx context.Context, d Device) error
// Get returns the device, or nil when it is not enrolled.
@@ -38,6 +39,7 @@ type DeviceStore interface {
type MemoryStore struct {
mu sync.Mutex
devices map[string]Device
+ wakes map[string]map[string]time.Time
prefs map[string]json.RawMessage
shapes map[string]map[string]ReportedShape
}
@@ -88,5 +90,6 @@ func (m *MemoryStore) Remove(_ context.Context, owner, id string) (bool, error)
return false, nil
}
delete(m.devices, id)
+ delete(m.wakes, id)
return true, nil
}
diff --git a/internal/server/store_pg.go b/internal/server/store_pg.go
index 6cfc954..cba7f77 100644
--- a/internal/server/store_pg.go
+++ b/internal/server/store_pg.go
@@ -21,6 +21,14 @@ CREATE TABLE IF NOT EXISTS devices (
agent_version text NOT NULL DEFAULT '',
enrolled_at timestamptz NOT NULL DEFAULT now()
);
+CREATE TABLE IF NOT EXISTS agent_wakes (
+ device_id text NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
+ owner text NOT NULL,
+ id text NOT NULL,
+ due_at timestamptz NOT NULL,
+ PRIMARY KEY (device_id,owner,id)
+);
+CREATE INDEX IF NOT EXISTS agent_wakes_due ON agent_wakes(device_id,owner,due_at);
CREATE INDEX IF NOT EXISTS devices_owner ON devices (owner);
ALTER TABLE devices ADD COLUMN IF NOT EXISTS name text NOT NULL DEFAULT '';
CREATE TABLE IF NOT EXISTS preferences (
diff --git a/internal/server/wakes.go b/internal/server/wakes.go
new file mode 100644
index 0000000..79b1d46
--- /dev/null
+++ b/internal/server/wakes.go
@@ -0,0 +1,137 @@
+package server
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "regexp"
+ "time"
+
+ "github.com/andyjmorgan/outpost/internal/host/wire"
+ "github.com/jackc/pgx/v5"
+)
+
+// A device mints a fresh opaque ID for each wake. Only the device knows the
+// permanent conversation it belongs to or the grant which authorised it.
+type wake struct {
+ ID string `json:"id"`
+ At time.Time `json:"at"`
+}
+
+type wakeStore interface {
+ putWake(context.Context, string, string, wake) error
+ clearWake(context.Context, string, string, string) error
+ dueWakes(context.Context, string, string, time.Time) ([]string, error)
+}
+
+var wakeID = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
+
+func (s *Server) changeWake(h *hostConn, msg *wire.Message) {
+ var w wake
+ if !msg.IsRequest() {
+ return
+ }
+ if json.Unmarshal(msg.Params, &w) != nil || !wakeID.MatchString(w.ID) || (msg.Method == "host.wake.set" && w.At.IsZero()) {
+ h.reply(wire.NewError(msg.ID, wire.Errorf(wire.CodeBadParams, "invalid wake")))
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ store := s.Devices
+ var err error
+ if msg.Method == "host.wake.set" {
+ err = store.putWake(ctx, h.owner, h.id, w)
+ } else {
+ err = store.clearWake(ctx, h.owner, h.id, w.ID)
+ }
+ if err != nil {
+ h.reply(wire.NewError(msg.ID, wire.Errorf(wire.CodeAgentError, "could not save the wake")))
+ return
+ }
+ res, _ := wire.NewResult(msg.ID, struct{}{})
+ h.reply(res)
+}
+
+// Send due controls on the live heartbeat. A missed control is sent again until
+// the machine acknowledges it, including on the first heartbeat after reconnect.
+func (s *Server) deliverWakes(h *hostConn) {
+ if !h.wakesEnabled {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer cancel()
+ ids, err := s.Devices.dueWakes(ctx, h.owner, h.id, time.Now().UTC())
+ if err != nil {
+ s.logf("reading due wakes for %s: %v", h.id, err)
+ return
+ }
+ if len(ids) > 0 {
+ msg, _ := wire.NewNotification("host.wake.due", map[string]any{"ids": ids})
+ h.reply(msg)
+ }
+}
+
+func (p *PostgresStore) putWake(ctx context.Context, owner, device string, w wake) error {
+ tag, err := p.pool.Exec(ctx, `INSERT INTO agent_wakes(device_id,owner,id,due_at)
+ SELECT id,owner,$3,$4 FROM devices WHERE id=$1 AND owner=$2
+ ON CONFLICT (device_id,owner,id) DO UPDATE SET due_at=EXCLUDED.due_at`, device, owner, w.ID, w.At)
+ if err == nil && tag.RowsAffected() != 1 {
+ return errors.New("device is no longer enrolled")
+ }
+ return err
+}
+
+func (p *PostgresStore) clearWake(ctx context.Context, owner, device, id string) error {
+ _, err := p.pool.Exec(ctx, `DELETE FROM agent_wakes WHERE device_id=$1 AND owner=$2 AND id=$3`, device, owner, id)
+ return err
+}
+
+func (p *PostgresStore) dueWakes(ctx context.Context, owner, device string, now time.Time) ([]string, error) {
+ rows, err := p.pool.Query(ctx, `SELECT id FROM agent_wakes WHERE device_id=$1 AND owner=$2 AND due_at <= $3 ORDER BY due_at,id LIMIT 32`, device, owner, now)
+ if err != nil {
+ return nil, err
+ }
+ return pgx.CollectRows(rows, pgx.RowTo[string])
+}
+
+func (m *MemoryStore) putWake(_ context.Context, owner, device string, w wake) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if d, ok := m.devices[device]; !ok || d.Owner != owner {
+ return errors.New("device is no longer enrolled")
+ }
+ if m.wakes == nil {
+ m.wakes = map[string]map[string]time.Time{}
+ }
+ if m.wakes[device] == nil {
+ m.wakes[device] = map[string]time.Time{}
+ }
+ m.wakes[device][w.ID] = w.At
+ return nil
+}
+
+func (m *MemoryStore) clearWake(_ context.Context, owner, device, id string) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if d, ok := m.devices[device]; ok && d.Owner == owner {
+ delete(m.wakes[device], id)
+ }
+ return nil
+}
+
+func (m *MemoryStore) dueWakes(_ context.Context, owner, device string, now time.Time) ([]string, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ var ids []string
+ if d, ok := m.devices[device]; ok && d.Owner == owner {
+ for id, at := range m.wakes[device] {
+ if !at.After(now) {
+ ids = append(ids, id)
+ }
+ if len(ids) == 32 {
+ break
+ }
+ }
+ }
+ return ids, nil
+}