Files
archie/internal/infrastructure/kit/launch.go
T
sam d64e9a2469 feat(kitrun): render the OAuth scopes and omit an uncaptured primary key
{{.Scopes}} now substitutes the captured set as an ARRAY in the target
encoding, so a one-element set stays a one-element array rather than
collapsing to a bare string. An empty set REFUSES by name with an
actionable "re-run the setup terminal" message: the spec declares an
omission case for {{.PrimaryApiKey}} but none for {{.Scopes}}, and an empty
array would silently change the CLI's capability decisions.

{{.PrimaryApiKey}} now implements the spec's omit case: its enclosing key is
dropped from the structure, never emptied. archie resolves a service key
only to fill the egress grant and the container holds egress.Sentinel, so
there is never a key to render.

The renderer's input becomes OAuthFacts{Scopes, ExpiresAt} -- still the only
thing it receives about a stored token set, so a real access or refresh
token cannot reach the file and an unsourceable placeholder still refuses by
name (docs/prds/external-agent-harness.md, Verification).
2026-09-30 07:59:05 +10:00

264 lines
8.3 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/agentexec"
"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 {
// 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 lists the credential services the run credential carries.
Bound []string
// 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 agentexec.HarnessSpec
Install []Hook
Startup []Hook
Files []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
Volumes []Volume
}
// 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) {
creds, err := spec.CredentialsOf(p.Capabilities)
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)
runtimeVars := map[string]string{"WORKSPACE_DIR": WorkspaceDir}
for _, c := range creds {
runtimeVars[credentialModeVar(c.Service)] = credentialMode(c, slices.Contains(params.Bound, c.Service))
}
l := Launch{Harness: agentexec.HarnessSpec{
User: harnessUser(img.User),
Launch: slices.Concat(img.Entrypoint, img.Cmd),
Env: slices.Concat(img.Env, []string{"WORKSPACE_DIR=" + WorkspaceDir}, proxyEnv, egress.SentinelEnv(creds)),
}}
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, runtimeVars)),
})
}
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
}
credential, err := credentialFiles(creds, 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.Execution, v.Path), Path: v.Path})
}
if l.Context, err = contextFiles(p); err != nil {
return Launch{}, err
}
return l, nil
}
// credentialFiles renders the credential file of every bound OAuth credential
// whose Kit declares one: the path and structure the Kit names, with the
// stored token set's scopes and expiry. A service the run credential does not
// carry produces no file.
func credentialFiles(creds []spec.CredentialCapability, bound []string, oauth map[string]OAuthFacts) ([]spec.File, error) {
var files []spec.File
for _, c := range creds {
if c.OAuth == nil || c.OAuth.CredentialFile == nil || !slices.Contains(bound, c.Service) {
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 materializes agent-context@1: the workload's profile file
// beside the workspace, never in it, carrying an index of each Kit's body.
// A staged body is pointed at where the image holds it; an inline one is
// written to its own file beside the profile. The profile never inlines a
// Kit's text, so stacking Kits does not grow what the agent always loads.
func contextFiles(p *Plan) ([]spec.File, error) {
ac, err := spec.AgentContextOf(p.Capabilities)
if err != nil || ac == nil || ac.Filename == "" {
return nil, err
}
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"
}
func credentialMode(c spec.CredentialCapability, bound bool) string {
switch {
case !bound:
return "none"
case c.APIKey != nil:
return "apikey"
default:
return "oauth"
}
}
// 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(execution, path string) string {
sum := sha256.Sum256([]byte(path))
return "archie-kit-" + unsafeVolumeChars.ReplaceAllString(execution, "_") + "-" + hex.EncodeToString(sum[:6])
}