A Kit's credential@1 oauth.credentialFile was never rendered: Assemble set
SBX_CRED_<SVC>_MODE=oauth but no file was written, so the harness CLI started
logged out and never reached the token endpoint the egress proxy intercepts.
Render it at launch, for each bound OAuth-managed service that declares one:
the Kit's structure with its access/refresh sentinels, and the stored token
set's expiry for {{.ExpiresAt}}. The renderer's only input about a token set
is that expiry -- the tokens never cross into kit, so a real token cannot be
written (docs/prds/external-agent-harness.md, Verification).
Expiry renders as epoch milliseconds, the unit both in-spec OAuth credential
files use (Claude Code's expiresAt, OpenCode's expires). A placeholder archie
does not render, or a token placeholder with no declared sentinel, refuses the
launch rather than leaving a literal or an empty value in the file.
kitrun reads the store only for a service the run credential carries, and
fails closed when a rendered credential file has no captured token set.
255 lines
8.0 KiB
Go
255 lines
8.0 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
|
|
}
|
|
|
|
// 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
|
|
// OAuthExpiries is the stored token set's expiry for each bound OAuth
|
|
// credential whose Kit renders a credentialFile, keyed by service. It is
|
|
// the only fact about a token set the renderer receives: the tokens
|
|
// themselves never cross into kit, so a real token cannot be written.
|
|
OAuthExpiries map[string]time.Time
|
|
}
|
|
|
|
// 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.OAuthExpiries)
|
|
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 expiry. A service the run credential does not carry
|
|
// produces no file.
|
|
func credentialFiles(creds []spec.CredentialCapability, bound []string, expiries map[string]time.Time) ([]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, expiries[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])
|
|
}
|