Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions cmd/outpost-host/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions docs/contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down
7 changes: 6 additions & 1 deletion internal/e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
28 changes: 27 additions & 1 deletion internal/e2e/mcp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down
3 changes: 3 additions & 0 deletions internal/host/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
52 changes: 49 additions & 3 deletions internal/host/conn/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()) }

Expand Down Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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
}
Expand Down
4 changes: 4 additions & 0 deletions internal/host/harness/claudecode/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
14 changes: 13 additions & 1 deletion internal/host/harness/claudecode/runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"}
Expand Down Expand Up @@ -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)
}
Expand Down
7 changes: 6 additions & 1 deletion internal/host/harness/codex/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
Expand Down Expand Up @@ -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()
Expand Down
1 change: 1 addition & 0 deletions internal/host/peer/grants.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions internal/host/peer/scopes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions internal/host/session/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ type Runtime interface {
}

type TurnInput struct {
Scheduled bool
MessageID string
Text string
Images []string // paths on this machine
Expand Down
1 change: 1 addition & 0 deletions internal/host/session/rpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading