Files
cp1-agents/docs/source-material/agent-shapes/agent-pattern/run-local.sh
Jonathan Boniface 416c66ced4
All checks were successful
check agents / check (push) Successful in 10s
Add CP1 Discovery agents in both patterns
ALZ-F01 Discovery as a sub-agent orchestrator (sub-agents/) and as eight
individual declarative agents (individual-agents/), with their KAB workflow
exports. Shared check, render and import scripts, the alz-discovery-sample
MCP server, the crucible-kab-dev deploy profile, deployment docs, platform
issue reports and the source material. Agent steps time out at 20 minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:25:57 +00:00

225 lines
10 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# Run this agent locally with the SAME configuration it will get in production.
#
# In Kubernetes, deployment.yaml does `envFrom: configMapRef`, which injects
# every key in kubernetes/configmap.yaml into the container as an environment
# variable. Nothing reads that file locally, so a plain `podman run` drifts from
# the deployed configuration the moment either one changes — and the drift is
# silent, which is the worst kind.
#
# This script closes that gap: it reads kubernetes/configmap.yaml and passes
# each key through as -e, exactly as Kubernetes would. Change a setting in the
# ConfigMap and it takes effect both here and on deploy — one source of truth.
#
# Secrets are NOT in the ConfigMap (in production they arrive from Secrets; see
# kubernetes/secretnames.yaml), so they are passed separately below, read from
# your shell or from .env.
#
# Usage:
# ./run-local.sh # build if needed, run on port 8080
# PORT_HOST=8081 ./run-local.sh # different host port
# DEV_RELOAD=true ./run-local.sh # restart the server on source edits
# RUNTIME_REGISTRY=localhost ./run-local.sh # a runtime built from source
#
# Works with podman or docker; set CONTAINER_CLI to choose.
set -euo pipefail
cd "$(dirname "$0")"
# The directory name is the agent name — no template variable needed, and it
# stays correct if the project is renamed.
AGENT="$(basename "$(pwd)")"
IMAGE="localhost/${AGENT}:local"
PORT_HOST="${PORT_HOST:-8080}"
CONFIGMAP="kubernetes/configmap.yaml"
CLI="${CONTAINER_CLI:-podman}"
# --- configuration, straight from the ConfigMap --------------------------
# Mirrors `envFrom: configMapRef`. Keys whose values are placeholders for the
# CI/CD pipeline are skipped, since they are meaningless locally.
#
# Read into an array with a while-loop rather than `mapfile`, which needs
# bash 4 — macOS still ships bash 3.2, so this script would not run there.
ENV_ARGS=()
while IFS= read -r line; do
ENV_ARGS+=("$line")
done < <(
python3 - "$CONFIGMAP" <<'PY'
import sys, yaml
data = yaml.safe_load(open(sys.argv[1])) or {}
for key, value in (data.get("data") or {}).items():
text = str(value)
if "<placeholder" in text:
continue
print("-e")
print(f"{key}={text}")
PY
)
# --- .env: secrets, and anything you are changing locally ----------------
#
# Passed AFTER the ConfigMap args, and the last -e wins, so .env overrides the
# ConfigMap for this run. That is the point: kubernetes/ is generated and you
# should never need to open it. A different model, a different agent name, MCP
# off, Langfuse on — all of it goes in .env.
#
# Every key .env defines is forwarded, not only the secrets. Forwarding just
# some of them was the old behaviour and it was quietly confusing: you could set
# LITELLM_MODEL in .env, restart, and watch the ConfigMap's value win with
# nothing to indicate why.
#
# The override is local by construction. In production the ConfigMap is listed
# after the .env-derived Secret in envFrom, so the ConfigMap wins there and
# nothing you set here follows the agent to a cluster.
[ -f .env ] && set -a && . ./.env && set +a
: "${LITELLM_PROXY_BASE:?set LITELLM_PROXY_BASE (see .env.example)}"
: "${LITELLM_MASTER_KEY:?set LITELLM_MASTER_KEY (see .env.example)}"
DOTENV_ARGS=()
if [ -f .env ]; then
# Names only; values come from the shell, which sourcing .env above has
# already populated with quoting resolved.
while IFS= read -r dotenv_key; do
[ -n "$dotenv_key" ] || continue
# Indirect expansion via eval, so this works on the bash 3.2 macOS ships.
eval "dotenv_value=\${$dotenv_key:-}"
DOTENV_ARGS+=(-e "${dotenv_key}=${dotenv_value}")
done < <(
grep -E '^[[:space:]]*(export[[:space:]]+)?[A-Za-z_][A-Za-z0-9_]*[[:space:]]*=' .env \
| sed -E 's/^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)[[:space:]]*=.*/\2/'
)
fi
PYTHONPATH_VALUE="/agent:/agent/vendor"
SECRET_ARGS=()
# Bind-mount the project over /agent so edits are visible inside the container.
# Production uses only what the Dockerfile COPYed; nothing is mounted there.
# /agent/vendor gets a volume of its own, filled from the image: the extra
# packages from requirements.txt live there, and the project mount would
# otherwise hide them. (It leaves an empty vendor/ in the project, ignored.)
MOUNTS=(-v "$(pwd):/agent:rw" -v /agent/vendor -w /agent)
# The shared execution storage, mounted at the same path production uses.
#
# An activity that hands on a large payload does not inline it -- it writes the
# bytes under EXECUTION_STORAGE_ROOT and sends a reference. An agent that
# receives one has to open that path, so the path has to mean the same thing on
# both sides. In Kubernetes that is the execution-storage-pvc this template's
# deployment.yaml already mounts at /data/executions; locally it is the volume
# the dev kit creates for the workers.
#
# Without it an agent works for small inputs and fails on large ones, which is
# the worst way to find out: the workflow is correct, the payload size decided
# the outcome, and the error reads as a missing file.
EXECUTION_STORAGE_VOLUME="${EXECUTION_STORAGE_VOLUME:-agent-builder-local-dev-kit_execution_data}"
if podman volume exists "$EXECUTION_STORAGE_VOLUME" 2>/dev/null; then
MOUNTS+=(-v "${EXECUTION_STORAGE_VOLUME}:/data/executions:rw")
SECRET_ARGS_STORAGE=(-e "EXECUTION_STORAGE_ROOT=/data/executions")
else
echo "note: volume '$EXECUTION_STORAGE_VOLUME' not found; the agent will not be"
echo " able to read large payloads passed by reference. Start the dev kit"
echo " first, or set EXECUTION_STORAGE_VOLUME to the right name."
SECRET_ARGS_STORAGE=()
fi
# The image's own entry point serves the agent, exactly as in production.
CMD=()
# Hot reload is local-only. DEV_RELOAD is read case-insensitively, and 1/yes
# count too, so DEV_RELOAD=TRUE is not quietly ignored.
#
# tr rather than ${VAR,,} because macOS still ships bash 3.2.
DEV_RELOAD_NORMALISED="$(printf '%s' "${DEV_RELOAD:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')"
case "$DEV_RELOAD_NORMALISED" in
1|true|yes) DEV_RELOAD_ON=1 ;;
*) DEV_RELOAD_ON=0 ;;
esac
if [[ "$DEV_RELOAD_ON" == "1" ]]; then
# WATCHFILES_FORCE_POLLING is required because the file-change events a
# bind mount would normally deliver do not cross the podman-machine VM
# boundary on macOS or Windows — without it the watcher simply never fires.
#
# The runtime's own server, under uvicorn's reloader: it restarts on any
# change under /agent -- code, prompt.md, agent.yaml, schemas, skills --
# which needs watchfiles, installed here for this container only.
SECRET_ARGS+=(-e "WATCHFILES_FORCE_POLLING=true")
CMD=(sh -c "pip install --quiet --user watchfiles && exec python -m uvicorn \
kyndryl_agent_runtime.a2a.server:create_a2a_server --factory --host 0.0.0.0 --port 8080 \
--reload --reload-dir /agent --reload-include '*.md' --reload-include '*.json' --reload-include '*.yaml'")
fi
# Optional: run against a checkout of the runtime SDK instead of the runtime
# in the image. Only useful if you are changing the SDK itself.
if [[ -n "${SDK_SRC:-}" ]]; then
SDK_PACKAGE="${SDK_SRC%/}/src/kyndryl_agent_runtime"
if [[ ! -f "${SDK_PACKAGE}/__init__.py" ]]; then
echo "error: SDK_SRC must point to the kyndryl-agent-runtime checkout root" >&2
exit 1
fi
MOUNTS+=(-v "${SDK_PACKAGE}:/sdk-override/kyndryl_agent_runtime:ro")
PYTHONPATH_VALUE="/sdk-override:${PYTHONPATH_VALUE}"
echo "note: using SDK source from ${SDK_PACKAGE}"
fi
SECRET_ARGS+=(-e "PYTHONPATH=${PYTHONPATH_VALUE}")
# Seeded with the flags that are always present, because `set -u` on bash 3.2 —
# still what macOS ships — treats expanding an empty array as an unbound
# variable and aborts. Appending to a non-empty array sidesteps that.
RUN_ARGS=(-d --name "$AGENT" -p "${PORT_HOST}:8080")
# Optional: join a shared network so the platform can reach this agent.
#
# --network-alias is not optional here. `--name` alone registers only the
# container ID with podman's DNS, so other containers cannot resolve the agent
# by name and the platform's registration URL never connects. The alias is what
# makes http://<agent>:8080 work from the API and the Temporal worker.
if [[ -n "${CONTAINER_NETWORK:-}" ]]; then
RUN_ARGS+=(--network "${CONTAINER_NETWORK}" --network-alias "$AGENT")
fi
# The runtime image the agent is built FROM. The Dockerfile names the one the
# agent pipeline builds on; locally the same image (name and version) comes
# from RUNTIME_REGISTRY: the dev kit's GHCR by default, where an FDE pulls it,
# or localhost for a runtime built from source. RUNTIME_IMAGE, in .env or the
# shell, names one outright.
PIPELINE_RUNTIME="$(sed -n 's/^ARG RUNTIME_IMAGE=//p' Dockerfile | head -1)"
RUNTIME_IMAGE="${RUNTIME_IMAGE:-${RUNTIME_REGISTRY:-ghcr.io/kyndryl-agentic-ai}/${PIPELINE_RUNTIME##*/}}"
# Rebuild only when what the image is made of changed -- the Dockerfile, the
# runtime image, requirements.txt -- and not on every run: the agent's code is
# mounted, so edits to it need no rebuild. (It used to build only when the
# image was missing, so a new runtime version in the Dockerfile was ignored
# until the image was removed by hand.)
BUILD_KEY="$( { cat Dockerfile requirements.txt 2>/dev/null; echo "$RUNTIME_IMAGE"; } | cksum | cut -d' ' -f1)"
CURRENT_KEY="$("$CLI" image inspect "$IMAGE" 2>/dev/null | python3 -c '
import json, sys
try:
image = json.load(sys.stdin)[0]
except Exception:
sys.exit(0)
labels = image.get("Labels") or (image.get("Config") or {}).get("Labels") or {}
print(labels.get("agent.build-key", ""))' || true)"
if [[ "$CURRENT_KEY" != "$BUILD_KEY" ]]; then
echo "building ${IMAGE} on ${RUNTIME_IMAGE}"
"$CLI" build --build-arg RUNTIME_IMAGE="$RUNTIME_IMAGE" --label agent.build-key="$BUILD_KEY" \
-t "$IMAGE" -f Dockerfile .
fi
"$CLI" rm -f "$AGENT" >/dev/null 2>&1 || true
"$CLI" run "${RUN_ARGS[@]}" \
"${ENV_ARGS[@]}" \
${DOTENV_ARGS[@]+"${DOTENV_ARGS[@]}"} \
${SECRET_ARGS[@]+"${SECRET_ARGS[@]}"} \
${SECRET_ARGS_STORAGE[@]+"${SECRET_ARGS_STORAGE[@]}"} \
"${MOUNTS[@]}" "$IMAGE" ${CMD[@]+"${CMD[@]}"} >/dev/null
echo "${AGENT} on http://localhost:${PORT_HOST} (config from ${CONFIGMAP})"
echo " card: curl -s localhost:${PORT_HOST}/.well-known/agent-card.json"
echo " chat: python tests/test_chatbot.py --url http://localhost:${PORT_HOST}"
echo " logs: ${CLI} logs -f ${AGENT}"