Files
archie/internal/infrastructure/kit/launch.go
T

316 lines
9.8 KiB
Go

package kit
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"path"
"regexp"
"slices"
"strings"
"time"
"github.com/docker/sandbox-kit-spec/v3/spec"
"github.com/samcharles93/archie-core/internal/domain/agentrun"
"github.com/samcharles93/archie-core/internal/infrastructure/egress"
)
const (
// DefaultHarnessUser is the Kit agent user: the harness runs as it when
// the image names no user, or names root.
DefaultHarnessUser = "1000"
// WorkspaceDir is where a Kit container mounts the task worktree. Its
// parent holds the agent-context profile: beside the worktree, not in
// it, and below the filesystem root, which some CLIs stop short of when
// they look upward for instruction files.
WorkspaceDir = "/archie/workspace"
installHookUser = "0"
)
// hookBaseline is the platform baseline a hook sees besides its declared
// variables, taken from the image's environment, never the host's.
var hookBaseline = []string{"PATH", "HOME", "HOSTNAME", "TERM"}
var unsafeVolumeChars = regexp.MustCompile(`[^a-zA-Z0-9_.-]`)
// ImageConfig is the workload image's runtime contract.
type ImageConfig struct {
Entrypoint []string
Cmd []string
Env []string
User string
}
// OAuthFacts is the non-secret part of a bound OAuth credential's stored
// token set that a credential file renders: the scopes the provider granted
// and when the access token expires. The tokens themselves never cross into
// kit, so a real token cannot be written to the file.
type OAuthFacts struct {
Scopes []string
ExpiresAt time.Time
}
// LaunchParams are the run-specific inputs to a Kit container.
type LaunchParams struct {
// Instance prefixes the Kit's volume names, so instances sharing a
// Docker host never mount each other's volumes.
Instance string
// Execution keys the Kit's volumes, so they survive retries of one
// WorkflowExecution and are never shared with another.
Execution string
ProxyToken string
CAPath string
// Bound maps each credential service the run carries to its kind. Values
// never leave the host.
Bound map[string]egress.CredentialKind
// OAuth is the non-secret facts of each bound OAuth credential's stored
// token set, keyed by service, that a Kit's credentialFile renders: the
// granted scopes and the expiry. The tokens themselves never cross into
// kit, so a real token cannot be written.
OAuth map[string]OAuthFacts
}
// Hook is one lifecycle hook, ready to exec in the container.
type Hook struct {
Argv []string
User string
Env []string
Background bool
}
// Volume is one volume@1 path backed by a named volume.
type Volume struct {
Name string
Path string
}
// Launch is everything archie needs to run a composed Kit for one run.
type Launch struct {
Harness agentrun.HarnessSpec
Install []Hook
Startup []Hook
Files []spec.File
InstallFiles []spec.File
// Context is the agent-context profile and the inline bodies it points
// at, written as root so a run can read but not change them.
Context []spec.File
Skills []Skill
Volumes []Volume
}
// Skill exposes an image-bundled directory at an agent's discovery path.
type Skill struct {
Source string
Target string
}
// Assemble derives a Kit container's launch from its admitted plan and the
// workload image's config. The harness never runs as root, and no hook sees
// a variable it did not declare beyond the image-derived baseline and the
// egress settings every sandbox process needs.
func Assemble(p *Plan, img ImageConfig, params LaunchParams) (Launch, error) {
installCreds, err := spec.CredentialsOfPhase(p.Capabilities, "install")
if err != nil {
return Launch{}, err
}
runtimeCreds, err := spec.CredentialsOfPhase(p.Capabilities, "runtime")
if err != nil {
return Launch{}, err
}
lifecycle, err := spec.LifecycleOf(p.Capabilities)
if err != nil {
return Launch{}, err
}
volumes, err := spec.VolumesOf(p.Capabilities)
if err != nil {
return Launch{}, err
}
proxyEnv := egress.ProxyEnv(params.ProxyToken, params.CAPath)
installVars := credentialVars(installCreds, params.Bound)
runtimeVars := credentialVars(runtimeCreds, params.Bound)
l := Launch{Harness: agentrun.HarnessSpec{
User: harnessUser(img.User),
Launch: slices.Concat(img.Entrypoint, img.Cmd),
Env: slices.Concat(img.Env, []string{"WORKSPACE_DIR=" + WorkspaceDir}, proxyEnv, egress.SentinelEnv(runtimeCreds)),
}}
if s := p.Sessions; s != nil {
l.Harness.Prompt, l.Harness.Resume, l.Harness.Continue = s.Prompt, s.Resume, s.Continue
}
baseline := slices.Concat(pick(img.Env, hookBaseline), proxyEnv)
if lifecycle != nil {
for _, h := range lifecycle.Install {
l.Install = append(l.Install, Hook{
Argv: slices.Clone(h.Command), User: orDefault(h.User, installHookUser),
Env: slices.Concat(baseline, declared(h.Env, installVars)),
})
}
for _, h := range lifecycle.Startup {
l.Startup = append(l.Startup, Hook{
Argv: slices.Clone(h.Command), User: orDefault(h.User, DefaultHarnessUser),
Env: slices.Concat(baseline, declared(h.Env, runtimeVars)), Background: h.Background,
})
}
l.Files = lifecycle.Files
}
l.InstallFiles, err = credentialFiles(installCreds, params.Bound, params.OAuth)
if err != nil {
return Launch{}, err
}
credential, err := credentialFiles(runtimeCreds, params.Bound, params.OAuth)
if err != nil {
return Launch{}, err
}
l.Files = append(l.Files, credential...)
for _, v := range volumes {
l.Volumes = append(l.Volumes, Volume{Name: volumeName(params.Instance, params.Execution, v.Path), Path: v.Path})
}
if l.Context, err = contextFiles(p); err != nil {
return Launch{}, err
}
l.Skills, err = bundledSkills(p.Capabilities)
if err != nil {
return Launch{}, err
}
return l, nil
}
func bundledSkills(capabilities []spec.Capability) ([]Skill, error) {
bundles, err := spec.AgentSkillRequestsOf(capabilities)
if err != nil {
return nil, err
}
discovery, err := spec.AgentSkillsOf(capabilities)
if err != nil {
return nil, err
}
var skills []Skill
for _, destination := range discovery {
for _, bundle := range bundles {
skills = append(skills, Skill{Source: bundle.Path, Target: path.Join(destination.Path, spec.AgentSkillName(bundle.AgentSkill))})
}
}
return skills, nil
}
func credentialVars(creds []spec.CredentialCapability, bound map[string]egress.CredentialKind) map[string]string {
vars := map[string]string{"WORKSPACE_DIR": WorkspaceDir}
for _, c := range creds {
vars[credentialModeVar(c.Service)] = credentialMode(bound[c.Service])
}
for _, entry := range egress.SentinelEnv(creds) {
name, value, _ := strings.Cut(entry, "=")
vars[name] = value
}
return vars
}
// credentialFiles renders the credential file for each OAuth-bound
// credential that declares one.
func credentialFiles(creds []spec.CredentialCapability, bound map[string]egress.CredentialKind, oauth map[string]OAuthFacts) ([]spec.File, error) {
var files []spec.File
for _, c := range creds {
if c.OAuth == nil || c.OAuth.CredentialFile == nil || bound[c.Service] != egress.CredentialOAuth {
continue
}
content, err := renderCredentialFile(c, oauth[c.Service])
if err != nil {
return nil, err
}
files = append(files, spec.File{Path: c.OAuth.CredentialFile.Path, Content: content, Mode: credentialFileMode})
}
return files, nil
}
// contextFiles writes agent-context@1: a profile file beside the workspace
// indexing each Kit's body.
func contextFiles(p *Plan) ([]spec.File, error) {
ac, err := spec.AgentContextOf(p.Capabilities)
if err != nil || ac == nil || ac.Filename == "" {
return nil, err
}
root := ac.Directory
if root == "" {
root = path.Dir(WorkspaceDir)
}
var files []spec.File
var index strings.Builder
index.WriteString("# Archie\n\nArchie runs this environment. Each task's rules are in its prompt.\n")
for i, src := range p.ContextSources {
if i == 0 {
index.WriteString("\n## Kits\n\nRead a Kit's guidance when its tools are relevant.\n\n")
}
at := src.Path
if at == "" {
at = path.Join(root, "archie-kit-context", fmt.Sprintf("%d.md", i+1))
files = append(files, spec.File{Path: at, Content: src.Content, Mode: "0644"})
}
fmt.Fprintf(&index, "- `%s`: %s\n", src.Reference, at)
}
return append(files, spec.File{Path: path.Join(root, path.Base(ac.Filename)), Content: index.String(), Mode: "0644"}), nil
}
func harnessUser(imageUser string) string {
name, _, _ := strings.Cut(imageUser, ":")
if name == "" || name == "root" || name == "0" {
return DefaultHarnessUser
}
return imageUser
}
func credentialModeVar(service string) string {
return "SBX_CRED_" + strings.ToUpper(strings.ReplaceAll(service, "-", "_")) + "_MODE"
}
// credentialModeNone is the mode variable's value for a service this run does
// not carry at all.
const credentialModeNone = "none"
// credentialMode is one service's SBX_CRED_*_MODE value: how this run carries
// the credential, or none when it carries none at all.
func credentialMode(kind egress.CredentialKind) string {
if kind == "" {
return credentialModeNone
}
return string(kind)
}
// declared resolves a hook's declared variable names against the runtime
// variables archie provides; a name archie does not provide stays unset.
func declared(names []string, vars map[string]string) []string {
var env []string
for _, name := range names {
if v, ok := vars[name]; ok {
env = append(env, name+"="+v)
}
}
return env
}
// pick returns the entries of env whose names are listed.
func pick(env, names []string) []string {
var out []string
for _, e := range env {
if name, _, _ := strings.Cut(e, "="); slices.Contains(names, name) {
out = append(out, e)
}
}
return out
}
func orDefault(v, fallback string) string {
if v == "" {
return fallback
}
return v
}
func volumeName(instance, execution, path string) string {
sum := sha256.Sum256([]byte(path))
return instance + "-kit-" + unsafeVolumeChars.ReplaceAllString(execution, "_") + "-" + hex.EncodeToString(sum[:6])
}