diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..a7c7a93a9 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,73 @@ +# archie-agent fat image: multi-ecosystem development environment for +# generic agent workloads. Pre-installs system-level tools that agents +# can't easily install themselves (no apt, no sudo). Language-specific +# packages are installed by the agent at runtime via UV/npm/go. +# +# Build: docker build -t archie-agent:latest . +# Run: docker run -e NATS_URL=nats://host:4222 archie-agent:latest + +# ── builder ─────────────────────────────────────────────────────────── +FROM golang:1.26-bookworm AS builder +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +RUN CGO_ENABLED=0 go build -o /usr/local/bin/archie-agent ./cmd/archie-agent/ + +# ── runtime ─────────────────────────────────────────────────────────── +FROM ubuntu:24.04 + +# Avoid interactive prompts during package installs. +ENV DEBIAN_FRONTEND=noninteractive + +# ── system packages ─────────────────────────────────────────────────── +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates \ + curl \ + git \ + gh \ + jq \ + unzip \ + xz-utils \ + build-essential \ + openssh-client \ + && rm -rf /var/lib/apt/lists/* + +# ── Go ──────────────────────────────────────────────────────────────── +# Latest stable Go for agent-driven Go tasks (build, test, lint). +ARG GO_VERSION=1.26.2 +RUN curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" \ + | tar -C /usr/local -xz +ENV PATH="/usr/local/go/bin:${PATH}" +ENV GOPATH="/go" + +# Pre-install common Go tools that need a Go toolchain. +RUN go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest && \ + go install mvdan.cc/gofumpt@latest && \ + rm -rf /go/pkg/mod/cache + +# ── Node.js 22 LTS ──────────────────────────────────────────────────── +RUN curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && \ + apt-get install -y --no-install-recommends nodejs && \ + rm -rf /var/lib/apt/lists/* +RUN npm install -g pnpm typescript tsx esbuild && \ + npm cache clean --force + +# ── Python + UV ─────────────────────────────────────────────────────── +# Python 3.12 and 3.13 (3.13 is latest; 3.12 is one below). +RUN apt-get update && apt-get install -y --no-install-recommends \ + software-properties-common && \ + add-apt-repository -y ppa:deadsnakes/ppa && \ + apt-get install -y --no-install-recommends \ + python3.12 python3.12-dev python3.12-venv \ + python3.13 python3.13-dev python3.13-venv \ + && rm -rf /var/lib/apt/lists/* +RUN curl -fsSL https://astral.sh/uv/install.sh | sh +ENV PATH="/root/.local/bin:${PATH}" + +# ── archie-agent ────────────────────────────────────────────────────── +COPY --from=builder /usr/local/bin/archie-agent /usr/local/bin/archie-agent + +# ── entrypoint ──────────────────────────────────────────────────────── +# The daemon passes -nats-url and other flags at container start. +ENTRYPOINT ["archie-agent"] diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 562d8b861..870efa754 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -16,6 +16,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/container" "github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forge" @@ -119,6 +120,22 @@ func run() int { log.Info("nats connected", "url", cfg.NATS.URL) } + // Container pool (optional — no containers when [containers] is absent). + var containerPool *container.Pool + if cfg.Containers.Enabled { + containerPool, err = container.NewPool(ctx, container.Config{ + Image: cfg.Containers.Image, + MaxConcurrency: cfg.Containers.MaxConcurrency, + MaxUptime: cfg.Containers.MaxUptime.Std(), + PullPolicy: cfg.Containers.PullPolicy, + }, cfg.NATS.URL, log) + if err != nil { + log.Error("container pool failed", "err", err) + return 1 + } + defer containerPool.Close() + } + providers := executionProviders(cfg) llm := agentexec.NewRuntime(providers) var agentRunner agentexec.Runner @@ -167,9 +184,10 @@ func run() int { "feasibility": workflow.Feasibility(), "default": workflow.Implement(), }, - Log: log, - CustomStages: wfeval.Discover, - Nats: natsClient, + Log: log, + CustomStages: wfeval.Discover, + Nats: natsClient, + ContainerPool: containerPool, } if err := d.Startup(ctx); err != nil { diff --git a/config.example.toml b/config.example.toml index f98adfbbb..f1025c67f 100644 --- a/config.example.toml +++ b/config.example.toml @@ -61,6 +61,14 @@ gate_max_failures = 5 # url = "nats://localhost:4222" # token_env = "NATS_TOKEN" +# Docker sandbox execution of archie-agent. Requires [nats] and agent.mode = "nats". +# [containers] +# enabled = true +# image = "archie-agent:latest" # Docker image to run +# max_concurrency = 4 # max simultaneous containers +# max_uptime = "60m" # container lifetime cap +# pull_policy = "missing" # "missing" or "always" + [[repos]] owner = "samcharles93" name = "todo" diff --git a/go.mod b/go.mod index 4c53ed27f..a248cb1cf 100644 --- a/go.mod +++ b/go.mod @@ -9,20 +9,37 @@ require ( ) require ( + github.com/Microsoft/go-winio v0.6.2 // indirect github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op // indirect + github.com/containerd/errdefs v1.0.0 // indirect + github.com/containerd/errdefs/pkg v0.3.0 // indirect + github.com/distribution/reference v0.6.0 // indirect + github.com/docker/go-connections v0.7.0 // indirect + github.com/docker/go-units v0.5.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect + github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/go-logr/logr v1.4.2 // indirect + github.com/go-logr/stdr v1.2.2 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/google/go-tpm v0.9.8 // indirect github.com/google/uuid v1.6.0 // indirect github.com/klauspost/compress v1.18.6 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/minio/highwayhash v1.0.4 // indirect + github.com/moby/docker-image-spec v1.3.1 // indirect github.com/nats-io/jwt/v2 v2.8.2 // indirect github.com/nats-io/nkeys v0.4.16 // indirect github.com/nats-io/nuid v1.0.1 // indirect github.com/ncruces/go-strftime v1.0.0 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.1.1 // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 // indirect + go.opentelemetry.io/otel v1.35.0 // indirect + go.opentelemetry.io/otel/metric v1.35.0 // indirect + go.opentelemetry.io/otel/trace v1.35.0 // indirect golang.org/x/crypto v0.53.0 // indirect golang.org/x/sys v0.46.0 // indirect golang.org/x/time v0.15.0 // indirect @@ -32,6 +49,8 @@ require ( ) require ( + github.com/moby/moby/api v1.55.0 + github.com/moby/moby/client v0.5.0 github.com/nats-io/nats-server/v2 v2.14.3 github.com/nats-io/nats.go v1.52.0 github.com/samcharles93/ai-sdk v0.1.17 diff --git a/go.sum b/go.sum index 3f7bdffce..9f06912ea 100644 --- a/go.sum +++ b/go.sum @@ -1,9 +1,30 @@ github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= +github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op h1:Z/MZK75wC/NSrkgqeNIa7jexam9uWzhLmFTSCPI/kn0= github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI= +github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= +github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= +github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= +github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c= +github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= @@ -21,10 +42,20 @@ github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao= github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4= github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ= +github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= +github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= +github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc= +github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs= +github.com/moby/moby/client v0.5.0 h1:5XhyPk2fuOWf6RlSFa3MkIIgDZkF25xToXW8Q/BH7cc= +github.com/moby/moby/client v0.5.0/go.mod h1:rcVpF8ncl9vo5gaIBdol6CnbEtSj1uxMvEV/UrykF/s= github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc= github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc= github.com/nats-io/nats-server/v2 v2.14.3 h1:+xjydPt7rkit67G+04TN0mcO2n+8nveZE7tK/PPV53A= @@ -37,12 +68,36 @@ github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= +github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E= github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY= +go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= +go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 h1:sbiXRNDSWJOTobXh5HyQKjq6wUC5tNybqjIqDpAY4CU= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0/go.mod h1:69uWxva0WgAA/4bu2Yy70SLDBwZXuQ6PbBpbsa5iZrQ= +go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= +go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= +go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M= +go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE= +go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY= +go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg= +go.opentelemetry.io/otel/sdk/metric v1.35.0 h1:1RriWBmCKgkeHEhM7a2uMjMUfP7MsOF5JpUCaEqEI9o= +go.opentelemetry.io/otel/sdk/metric v1.35.0/go.mod h1:is6XYCUMpcKi+ZsOvfluY5YstFnhW0BidkR+gL+qN+w= +go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= +go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= @@ -59,10 +114,13 @@ golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= +gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= modernc.org/cc/v4 v4.29.0 h1:CXgwL8cvxmyzBQZzbSl/6xFtMCryb6u8IOqDci39cgc= modernc.org/cc/v4 v4.29.0/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU= @@ -91,3 +149,5 @@ modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= +pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk= +pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= diff --git a/internal/config/config.go b/internal/config/config.go index 0a9266551..5e11b45c7 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -225,10 +225,11 @@ type Config struct { Agent Agent `toml:"agent"` Budgets Budgets `toml:"budgets"` - Web Web `toml:"web"` - Notify Notify `toml:"notify"` - NATS NATSConfig `toml:"nats"` - Repos []Repo `toml:"repos"` + Web Web `toml:"web"` + Notify Notify `toml:"notify"` + NATS NATSConfig `toml:"nats"` + Containers ContainerConfig `toml:"containers"` + Repos []Repo `toml:"repos"` } // NATSConfig configures NATS JetStream for task distribution. When URL is @@ -242,6 +243,20 @@ type NATSConfig struct { TokenEnv string `toml:"token_env"` } +// ContainerConfig configures Docker sandbox execution of archie-agent. +type ContainerConfig struct { + // Enabled activates container execution. Requires agent.mode = "nats". + Enabled bool `toml:"enabled"` + // Image is the Docker image to run (e.g. "ghcr.io/sam/archie-agent:latest"). + Image string `toml:"image"` + // MaxConcurrency limits simultaneous containers. 0 = no limit. + MaxConcurrency int `toml:"max_concurrency"` + // MaxUptime caps a container's lifetime before recycling. + MaxUptime Duration `toml:"max_uptime"` + // PullPolicy controls image pulling: "missing" (default) or "always". + PullPolicy string `toml:"pull_policy"` +} + // Notify configures outbound notifications (n8n webhook → email etc.). type Notify struct { // Webhook receives JSON POSTs for events that need a human (e.g. @@ -363,6 +378,23 @@ func Load(path string) (Config, error) { } } } + if cfg.Containers.Enabled { + if cfg.Containers.Image == "" { + return cfg, errors.New("config: containers.image is required when containers.enabled is true") + } + if cfg.Agent.Mode != "nats" { + return cfg, errors.New("config: agent.mode must be \"nats\" when containers.enabled is true") + } + if cfg.NATS.URL == "" { + return cfg, errors.New("config: [nats] url is required when containers.enabled is true") + } + if cfg.Containers.MaxUptime == 0 { + cfg.Containers.MaxUptime = Duration(60 * time.Minute) + } + if cfg.Containers.PullPolicy == "" { + cfg.Containers.PullPolicy = "missing" + } + } return cfg, nil } diff --git a/internal/container/pool.go b/internal/container/pool.go new file mode 100644 index 000000000..d7000d417 --- /dev/null +++ b/internal/container/pool.go @@ -0,0 +1,210 @@ +// Package container manages Docker containers running archie-agent. +// A Pool acquires and releases containers per task, handling image pull, +// creation, startup, health check, and teardown. The daemon's existing +// NATSRunner handles agent communication unchanged. +package container + +import ( + "context" + "fmt" + "io" + "log/slog" + "sync" + "time" + + "github.com/moby/moby/api/types/container" + "github.com/moby/moby/api/types/mount" + "github.com/moby/moby/client" +) + +// Container wraps a running Docker container. +type Container struct { + ID string +} + +// Pool manages a set of Docker containers running archie-agent. +type Pool struct { + cli *client.Client + cfg Config + log *slog.Logger + natsURL string + + mu sync.Mutex + active int +} + +// Config is the subset of daemon container configuration the pool needs. +type Config struct { + Image string + MaxConcurrency int + MaxUptime time.Duration + PullPolicy string +} + +// NewPool connects to the Docker daemon, optionally pulls the image, +// and cleans up orphaned containers from a previous daemon crash. +func NewPool(ctx context.Context, cfg Config, natsURL string, log *slog.Logger) (*Pool, error) { + cli, err := client.New(client.FromEnv) + if err != nil { + return nil, fmt.Errorf("docker client: %w", err) + } + + p := &Pool{ + cli: cli, + cfg: cfg, + log: log, + natsURL: natsURL, + } + + // Pull image if needed. + if cfg.PullPolicy == "always" || cfg.PullPolicy == "missing" { + if err := p.pullImage(ctx); err != nil { + cli.Close() + return nil, err + } + } + + // Recover orphaned containers from a previous daemon crash. + p.recoverOrphans(ctx) + + return p, nil +} + +// Acquire creates and starts a container, mounting workspace at /workspace, +// passing provider API keys and NATS URL as environment variables. +func (p *Pool) Acquire(ctx context.Context, workspace string, env []string) (*Container, error) { + p.mu.Lock() + if p.cfg.MaxConcurrency > 0 && p.active >= p.cfg.MaxConcurrency { + p.mu.Unlock() + return nil, fmt.Errorf("max concurrency %d reached", p.cfg.MaxConcurrency) + } + p.active++ + p.mu.Unlock() + + name := fmt.Sprintf("archie-agent-%d", time.Now().UnixNano()) + + resp, err := p.cli.ContainerCreate(ctx, client.ContainerCreateOptions{ + Name: name, + Config: &container.Config{ + Image: p.cfg.Image, + Env: env, + Labels: map[string]string{ + "archie-daemon": "true", + }, + }, + HostConfig: &container.HostConfig{ + Mounts: []mount.Mount{ + { + Type: mount.TypeBind, + Source: workspace, + Target: "/workspace", + }, + }, + AutoRemove: true, + }, + }) + if err != nil { + p.mu.Lock() + p.active-- + p.mu.Unlock() + return nil, fmt.Errorf("container create: %w", err) + } + + if _, err := p.cli.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil { + // Best-effort cleanup. + p.cli.ContainerRemove(context.Background(), resp.ID, client.ContainerRemoveOptions{Force: true}) + p.mu.Lock() + p.active-- + p.mu.Unlock() + return nil, fmt.Errorf("container start: %w", err) + } + + p.log.Info("container started", "id", resp.ID[:12], "name", name, "workspace", workspace) + return &Container{ID: resp.ID}, nil +} + +// Release stops and removes a container after a task completes. +func (p *Pool) Release(c *Container) { + if c == nil { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + if _, err := p.cli.ContainerStop(ctx, c.ID, client.ContainerStopOptions{}); err != nil { + p.log.Warn("container stop failed", "id", c.ID[:12], "err", err) + } + // AutoRemove is set, but force-remove as a safety net. + p.cli.ContainerRemove(context.Background(), c.ID, client.ContainerRemoveOptions{Force: true}) + + p.mu.Lock() + p.active-- + p.mu.Unlock() + p.log.Info("container released", "id", c.ID[:12]) +} + +// Close stops and removes all active containers, then closes the client. +func (p *Pool) Close() error { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + list, err := p.cli.ContainerList(ctx, client.ContainerListOptions{ + All: true, + Filters: client.Filters{}.Add("label", "archie-daemon=true"), + }) + if err != nil { + p.log.Warn("container list failed during close", "err", err) + } else { + for _, c := range list.Items { + p.log.Info("cleaning up container", "id", c.ID[:12]) + p.cli.ContainerStop(ctx, c.ID, client.ContainerStopOptions{}) + p.cli.ContainerRemove(ctx, c.ID, client.ContainerRemoveOptions{Force: true}) + } + } + return p.cli.Close() +} + +// ── helpers ────────────────────────────────────────────────────────── + +// pullImage pulls the configured image. On "missing" policy, skips if +// the image already exists locally. +func (p *Pool) pullImage(ctx context.Context) error { + ref := p.cfg.Image + + if p.cfg.PullPolicy == "missing" { + _, err := p.cli.ImageInspect(ctx, ref) + if err == nil { + p.log.Info("image already present", "image", ref) + return nil + } + } + + p.log.Info("pulling image", "image", ref) + rc, err := p.cli.ImagePull(ctx, ref, client.ImagePullOptions{}) + if err != nil { + return fmt.Errorf("pull %s: %w", ref, err) + } + defer rc.Close() + io.Copy(io.Discard, rc) + p.log.Info("image pulled", "image", ref) + return nil +} + +// recoverOrphans stops and removes containers left by a previous daemon. +func (p *Pool) recoverOrphans(ctx context.Context) { + list, err := p.cli.ContainerList(ctx, client.ContainerListOptions{ + All: true, + Filters: client.Filters{}.Add("label", "archie-daemon=true"), + }) + if err != nil { + return + } + for _, c := range list.Items { + p.log.Info("recovering orphaned container", "id", c.ID[:12]) + p.cli.ContainerStop(ctx, c.ID, client.ContainerStopOptions{}) + p.cli.ContainerRemove(ctx, c.ID, client.ContainerRemoveOptions{Force: true}) + } + if len(list.Items) > 0 { + p.log.Info("orphan recovery complete", "count", len(list.Items)) + } +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 22ca5c818..81ed9ba21 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -8,6 +8,7 @@ import ( "context" "fmt" "log/slog" + "os" "slices" "strings" "time" @@ -19,6 +20,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/container" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forge" arnats "github.com/samcharles93/archie-core/internal/nats" @@ -40,6 +42,9 @@ type Daemon struct { // Nats is the optional NATS client for task distribution. Nil means // NATS is not configured; the existing SQLite ClaimNext flow is used. Nats *arnats.Client + // ContainerPool manages Docker container lifecycle. Nil when [containers] + // is not configured. When non-nil, every task gets a fresh container. + ContainerPool *container.Pool // CustomStages discovers a repo's per-repo Yaegi custom stages // (.archie/stages/*.go) from its prepared worktree. Set by the // composition root (cmd/archied) to wfeval.Discover; nil disables @@ -478,6 +483,19 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { wf := workflow.Route(task, d.Workflows) d.Log.Info("processing task", "repo", repo.FullName(), "issue", task.IssueNumber, "workflow", wf.Name, "attempt", task.Attempt) d.Forge.SetStateLabel(ctx, task.Owner, task.Repo, task.IssueNumber, d.Cfg.Dispatch.StateLabel("working"), d.Cfg.Dispatch.LabelValues()) + + // Acquire a container for the task when Docker sandboxing is enabled. + if d.ContainerPool != nil { + workDir := d.Trees.Dir(task.Owner, task.Repo, task.IssueNumber) + ctr, err := d.ContainerPool.Acquire(ctx, workDir, d.containerEnv()) + if err != nil { + d.Log.Error("container acquire failed", "err", err) + _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "container acquire failed: "+err.Error()) + return + } + defer d.ContainerPool.Release(ctr) + } + workflow.Run(ctx, wf, &workflow.TaskContext{ Task: task, Repo: repo, @@ -492,6 +510,20 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { }) } +// containerEnv returns the environment variables passed to agent containers. +func (d *Daemon) containerEnv() []string { + var env []string + env = append(env, "NATS_URL="+d.Cfg.NATS.URL) + for _, p := range d.Cfg.Providers { + if p.APIKeyEnv != "" { + if v := os.Getenv(p.APIKeyEnv); v != "" { + env = append(env, p.APIKeyEnv+"="+v) + } + } + } + return env +} + func (d *Daemon) repoFor(t *store.Task) (config.Repo, bool) { for _, r := range d.Cfg.Repos { if r.Owner == t.Owner && r.Name == t.Repo {