Files
archie/internal/infrastructure/harnesssession/harnesssession.go
T
sam d201257382 feat(harness): serve a daemon-side setup session to the dashboard
The dashboard's setup terminal was a 503: it had a WebSocket route, an
authorizer and an xterm.js surface, but nothing owned a container. The
daemon owns containers, so the session contract lands there and the
dashboard consumes it over a new gRPC contract.

One session concept, two targets. A setup session is addressed by Kit
profile and is ephemeral; a run session (archie-core-qi91) is addressed by
task and attempt and is bounded by the task. This slice serves setup and
answers Unimplemented for run.

The contract, the authorisation, the lifetime and the egress phase are
settled in docs/prds/external-agent-harness.md, "Session contract". The
short version: the daemon serves harness.v1.HarnessService; the dashboard
authorizes the operator as an update on the secret and then dials the
daemon with the harness service token, required even on loopback because a
session is a shell holding an org's credential; the setup container runs
no worker, mounts no worktree, holds a keepalive, and carries an empty
container environment. Install hooks run at the install phase and the
session enters runtime before the shell, so a runtime-phase credential's
token endpoint is the one the proxy intercepts.

Capture is gated by the egress proxy on a granted service, and a setup
session has no task, so the daemon registers a session grant: the
session's proxy token resolves to the org's bindings for the Kit's
declared services. The real token never enters the container: the token
endpoint response is sentinelized and stored as the org's harness secret.

Every teardown path releases the pool slot, revokes the egress session and
the grant, removes the sandbox network, and removes the session's volumes.
The listener requires HARNESS_TOKEN and stops with a 10s grace before
Stop, so an open session cannot hold shutdown to the watchdog leash.
2026-10-09 01:38:41 +11:00

119 lines
3.8 KiB
Go

// Package harnesssession runs the daemon side of a harness session: it builds
// an ephemeral Kit-profile container, opens a PTY into it as the Kit's harness
// user, and tears the container down when the session closes. It owns no
// transport; internal/app/archied serves the gRPC contract over it.
package harnesssession
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"sync"
"time"
"github.com/moby/moby/client"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/container"
"github.com/samcharles93/archie-core/internal/infrastructure/kitrun"
)
// The address errors a caller distinguishes: an unknown profile is the
// caller's mistake, not a daemon that cannot run containers.
var (
ErrProfileUnknown = errors.New("agent profile is not configured")
ErrProfileNotKit = errors.New("agent profile is not a Kit profile")
)
// Launcher starts and ends a setup session's container. *kitrun.Launcher
// satisfies it.
type Launcher interface {
LaunchSetup(ctx context.Context, req kitrun.SetupRequest) (*kitrun.Run, error)
Release(ctx context.Context, run *kitrun.Run) error
}
// Manager opens setup sessions.
type Manager struct {
Launcher Launcher
// Client is the container pool's Docker client, used for the PTY exec.
Client *client.Client
// Profile resolves an agent profile by name from the running config.
Profile func(name string) (config.AgentProfile, error)
// TTL bounds a session's life. Zero means the container pool's max-uptime
// reaper is the only bound.
TTL time.Duration
}
// Open starts a setup session and returns its duplex PTY.
func (m *Manager) Open(ctx context.Context, org, profile string) (*Session, error) {
p, err := m.Profile(profile)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrProfileUnknown, profile)
}
if !p.IsKit() {
return nil, fmt.Errorf("%w: %s", ErrProfileNotKit, profile)
}
id, err := sessionID()
if err != nil {
return nil, err
}
run, err := m.Launcher.LaunchSetup(ctx, kitrun.SetupRequest{Session: id, Kit: p.Kit, Org: org})
if err != nil {
return nil, err
}
pty, err := container.ExecPTY(ctx, m.Client, run.Container.ID, run.Harness.User, run.Harness.Env, []string{"sh", "-l"}, 24, 80)
if err != nil {
_ = m.Launcher.Release(context.WithoutCancel(ctx), run)
return nil, err
}
s := &Session{pty: pty, run: run, release: m.Launcher.Release}
if m.TTL > 0 {
//nolint:contextcheck // teardown must outlive the stream context that opened the session
s.timer = time.AfterFunc(m.TTL, func() { _ = s.Close() })
}
return s, nil
}
// Session is one open setup session. Close is idempotent.
type Session struct {
pty *container.PTY
run *kitrun.Run
release func(context.Context, *kitrun.Run) error
timer *time.Timer
once sync.Once
}
func (s *Session) Read(p []byte) (int, error) { return s.pty.Read(p) }
func (s *Session) Write(p []byte) (int, error) { return s.pty.Write(p) }
// ExitCode reports the shell's exit status once its output has ended.
func (s *Session) ExitCode(ctx context.Context) (int, error) { return s.pty.ExitCode(ctx) }
// Close ends the PTY and tears the session down: the container, its volumes,
// its network and its egress session. Teardown uses its own context because
// the session's is usually already cancelled.
func (s *Session) Close() error {
var err error
s.once.Do(func() {
if s.timer != nil {
s.timer.Stop()
}
_ = s.pty.Close()
err = s.release(context.Background(), s.run)
})
return err
}
// sessionID is the per-session key for the container, network and volumes. It
// is random so two sessions for one profile never collide on a container name.
func sessionID() (string, error) {
var b [8]byte
if _, err := rand.Read(b[:]); err != nil {
return "", fmt.Errorf("mint session id: %w", err)
}
return "setup-" + hex.EncodeToString(b[:]), nil
}