oaustegard avatar

environment-and-config

Environment setup, credential management, container building, and workflow orchestration.

version
2.0.0
GitHub stars
404

Install

/plugin install environment-and-config@oaustegard-claude-skills

Run it inside Claude Code after adding the marketplace with /plugin marketplace add oaustegard/claude-skills.

Contents

Discovered from source

Skills 5

API Credentials Management

🚨 DEPRECATED: This skill is no longer needed for hosted skills environments.

New approach: Skills now read credentials directly from project knowledge files:

  • ANTHROPIC_API_KEY.txt, GOOGLE_API_KEY.txt, GITHUB_API_KEY.txt (recommended)
  • Or API_CREDENTIALS.json (combined file)

See updated skill documentation:

Legacy use only: This skill may still be useful for local development environments or backward compatibility.


⚠️ WARNING: This is a PERSONAL skill - DO NOT share or commit with actual credentials!

This skill provides secure storage and retrieval of API credentials for multiple providers. It serves as a dependency for other skills that need to invoke external APIs programmatically.

Supported Providers

  • Anthropic (Claude API)
  • Google (Gemini API, Vertex AI, etc.)
  • GitHub (GitHub API, Personal Access Tokens)
  • Extensible for additional providers

Purpose

  • Centralized credential storage for multiple API providers
  • Secure retrieval methods for dependent skills
  • Clear error messages when credentials are missing
  • Support for multiple credential sources (config file, environment variables)

Usage by Other Skills

Skills that need to invoke APIs should reference this skill:

Anthropic Claude API

import sys
sys.path.append('/home/user/claude-skills/api-credentials/scripts')
from credentials import get_anthropic_api_key

try:
    api_key = get_anthropic_api_key()
    # Use api_key for Claude API calls
except ValueError as e:
    print(f"Error: {e}")

Google Gemini API

import sys
sys.path.append('/home/user/claude-skills/api-credentials/scripts')
from credentials import get_google_api_key

try:
    api_key = get_google_api_key()
    # Use api_key for Gemini API calls
except ValueError as e:
    print(f"Error: {e}")

GitHub API

import sys
sys.path.append('/home/user/claude-skills/api-credentials/scripts')
from credentials import get_github_api_key

try:
    api_key = get_github_api_key()
    # Use api_key for GitHub API calls
except ValueError as e:
    print(f"Error: {e}")

Setup Instructions

Option 1: Configuration File (Recommended)

  1. Copy the example config:
cp /home/user/claude-skills/api-credentials/assets/config.json.example \
   /home/user/claude-skills/api-credentials/config.json
  1. Edit config.json and add your API keys:
{
  "anthropic_api_key": "sk-ant-api03-...",
  "google_api_key": "AIzaSy...",
  "github_api_key": "ghp_..."
}
  1. Ensure the config file is in .gitignore (already configured)

Option 2: Environment Variables

Set environment variables for the providers you need:

# Anthropic Claude
export ANTHROPIC_API_KEY="sk-ant-api03-..."

# Google Gemini
export GOOGLE_API_KEY="AIzaSy..."

# GitHub
export GITHUB_TOKEN="ghp_..."
# or
export GITHUB_API_KEY="ghp_..."

Add to your shell profile (~/.bashrc, ~/.zshrc) to persist.

Priority

Credential retrieval follows this priority for each provider:

  1. config.json in the skill directory (highest priority)
  2. Environment variable (ANTHROPIC_API_KEY or GOOGLE_API_KEY)
  3. ValueError raised if neither is available

Security Notes

  • Never commit config.json with real credentials
  • The config.json file should be in .gitignore
  • Only config.json.example should be version controlled
  • Consider using environment variables in shared/production environments
  • Rotate API keys regularly
  • Skills should never log or display full API keys

File Structure

api-credentials/
β”œβ”€β”€ SKILL.md              # This file
β”œβ”€β”€ config.json           # YOUR credentials (gitignored)
β”œβ”€β”€ scripts/
β”‚   └── credentials.py    # Credential retrieval module
└── assets/
    └── config.json.example  # Template for users

Error Handling

When credentials are not found, the module raises ValueError with clear guidance:

  • Where to place config.json
  • How to set environment variables
  • Links to provider consoles for key generation

Skills should catch ValueError exceptions and handle appropriately.

Available Functions

get_anthropic_api_key() β†’ str

  • Returns Anthropic API key
  • Raises ValueError if not configured

get_google_api_key() β†’ str

  • Returns Google API key
  • Raises ValueError if not configured

get_github_api_key() β†’ str

  • Returns GitHub API token (Personal Access Token)
  • Raises ValueError if not configured

get_api_key_masked(api_key) β†’ str

  • Returns masked version for safe logging
  • Example: "sk-ant-...xyz"

verify_credential(provider) β†’ bool

  • Checks if provider is configured
  • Returns True/False without raising exceptions
  • Providers: 'anthropic', 'google', 'github'

Adding New Providers

To support additional providers:

  1. Add field to assets/config.json.example
  2. Add getter function to scripts/credentials.py:
    def get_provider_api_key() -> str:
        # Follow existing pattern with config file + env var
        pass
    
  3. Add to verify_credential() mapping
  4. Update this documentation

Token Efficiency

This skill uses ~300 tokens when loaded but saves repeated credential management code across multiple skills that invoke external APIs. It provides a single, consistent pattern for all credential handling.

Configuring

Unified configuration management across AI coding environments. Load environment variables, secrets, and other opinionated configuration setups from any AI coding platform.

Quick Start

import sys
sys.path.insert(0, '/path/to/claude-skills')  # or wherever skills are installed
from configuring import get_env, detect_environment

# Get a variable (searches all sources automatically)
token = get_env("TURSO_TOKEN", required=True)

# With default
port = get_env("PORT", default="8080")

# What environment are we in?
env = detect_environment()  # "claude.ai", "claude-code-desktop", "codex", "jules", etc.

Supported Environments

EnvironmentConfig Sources
Claude.ai Projects/mnt/project/*.env, /mnt/project/*-token.txt
Claude Code~/.claude/settings.json (env block), .claude/settings.json
OpenAI Codex~/.codex/config.toml, setup script β†’ ~/.bashrc, shell_snapshots/*.sh
JulesEnvironment settings UI, .env in repo
Universalos.environ, .env, .env.local

API Reference

# Core
get_env(key, default=None, *, required=False, validator=None) -> str | None
load_env(path) -> dict[str, str]           # Load specific file
load_all(force_reload=False) -> dict       # Load all sources

# Utilities
detect_environment() -> str                 # Current platform
mask_secret(value, show_chars=4) -> str    # Safe logging
debug_info() -> dict                        # Troubleshooting
get_loaded_sources() -> list[str]          # What was checked

Credential File Formats

.env files (KEY=value):

TURSO_TOKEN=eyJhbGciOiJFZERTQSI...
EMBEDDING_API_KEY=sk-svcacct-...

Single-value files (*-token.txt, *-key.txt):

eyJhbGciOiJFZERTQSI...

Filename becomes key: turso-token.txt β†’ TURSO_TOKEN

Claude Code settings.json:

{
  "env": {
    "TURSO_TOKEN": "eyJhbGciOiJFZERTQSI..."
  }
}

Priority Order

Later sources override earlier:

  1. OS environment variables
  2. Platform-specific sources (detected automatically)
  3. .env files in cwd
  4. OS environment variables (again - explicit exports always win)

Debugging

import sys
sys.path.insert(0, '/path/to/claude-skills')
from configuring import debug_info
print(debug_info())
# {'environment': 'claude.ai', 'sources': ['os.environ', 'claude.ai:/mnt/project/'], ...}

CLI:

cd /path/to/claude-skills/configuring
python scripts/getting_env.py                    # Show debug info
python scripts/getting_env.py TURSO_TOKEN        # Get specific key

Migration from api-credentials / getting-env

Replace:

# Old (api-credentials)
from credentials import get_anthropic_api_key
key = get_anthropic_api_key()

# Old (getting-env)
from getting_env import get_env
key = get_env("ANTHROPIC_API_KEY")

# New (configuring)
import sys
sys.path.insert(0, '/path/to/claude-skills')
from configuring import get_env
key = get_env("ANTHROPIC_API_KEY", required=True)

Container Layer

Build a reproducible, cached environment overlay for ephemeral containers using a Dockerfile-like spec.

When NOT to use this skill

This authors and caches a layer spec. It is not a Docker troubleshooting tool.

SituationUse
A build is slow or failingread the build log; this skill will not help
Managing a running containerdocker/podman directly
Session boot sequence and hooksthe workspace's own boot docs

The tell is tense: this skill is for the environment you want next session, not the container you are fighting now.

Concept

The container resets every session, but your environment shouldn't. This skill:

  1. Parses a Containerfile (Dockerfile subset) that declares your environment
  2. Caches the built result as a tarball in GitHub Releases
  3. Restores from cache on subsequent boots (single fetch vs. N installs)
  4. Provides a uv shim that captures ad-hoc installs back into the Containerfile

Supported Containerfile Instructions

# Environment variables
ENV KEY=value

# Shell commands (including package installs)
RUN apt-get install -y foo        # system packages
RUN uv pip install pandas numpy   # Python packages (preferred)
RUN pip install requests          # also works

# Fetch files from URLs or GitHub
FETCH https://example.com/file.tar.gz /dest/path
FETCH github:user/repo /dest/path              # latest tarball
FETCH github:user/repo@ref /dest/path          # specific ref

# Set working directory for subsequent RUN commands
WORKDIR /some/path

# Declare paths to include in the cached layer snapshot
# (auto-detected for FETCH destinations and pip/uv installs)
SNAPSHOT /additional/path/to/capture

# Ignored (Dockerfile compat, no-op here):
# FROM, EXPOSE, CMD, ENTRYPOINT, LABEL, ARG, VOLUME, USER, SHELL

Usage

Single layer β€” build / restore

from scripts.containerfile import ContainerLayer

layer = ContainerLayer(
    containerfile_path="/path/to/Containerfile",
    cache_repo="oaustegard/claude-container-layers",  # GitHub repo for release assets
    gh_token="...",
)

# Try cache first, fall back to full build
layer.restore_or_build()

Or via CLI:

python -m scripts.cli restore /path/to/Containerfile --repo user/cache-repo

Multi-layer composition (v0.2.0+)

Decompose a heavy environment into named layers, each cached independently. Compose them in order on session start so most-changed bits don't invalidate stable bits.

from scripts.containerfile import compose

compose(
    containerfile_paths=[
        "layers/Containerfile",            # name='base'  (always-on)
        "layers/Containerfile.scientific", # name='scientific'
        "layers/Containerfile.mojo",       # name='mojo'
    ],
    cache_repo="user/cache-repo",
)

Each layer gets its own cache release tag layer-<name>-<hash> so retention policies (keep last N) and cache invalidation operate per-name.

Default layer names are derived from the Containerfile path:

  • Containerfile β†’ base
  • Containerfile.scientific β†’ scientific
  • layers/Containerfile.X β†’ X

CLI equivalent:

python -m scripts.cli compose \
    layers/Containerfile \
    layers/Containerfile.scientific \
    layers/Containerfile.mojo \
    --repo user/cache-repo

Per-layer name override

If filename doesn't derive cleanly, pass --name NAME:PATH per layer:

python -m scripts.cli compose \
    --name base:weird-named-file.txt \
    --name mojo:other-file.txt \
    weird-named-file.txt other-file.txt

Single-layer naming (back-compat)

build / restore / hash / inspect accept --name:

python -m scripts.cli restore Containerfile.mojo --name mojo
# Cache tag becomes 'layer-mojo-<hash>' instead of 'layer-<hash>'.
# Omit --name to keep the old back-compat tag for existing callers.

The uv Shim

After building, install the shim to capture future installs:

source /path/to/container-layer/scripts/uv_shim.sh /path/to/Containerfile

Now uv pip install foo both installs the package AND appends RUN uv pip install foo to your Containerfile.

Rebuilding the Cache

After modifying the Containerfile:

layer.build_and_push()  # Execute, snapshot, upload

Architecture

Read scripts/containerfile.py for the parser/executor and scripts/layer_cache.py for the GitHub Releases caching logic. The cache key is a SHA-256 of the Containerfile contents β€” any change triggers a rebuild.

Configuration

The skill expects these environment variables (or pass as constructor args):

  • GH_TOKEN β€” GitHub token with repo scope (for releases)
  • Cache repo can be any repo the token has write access to

Workflow Integration

This skill is designed to be invoked from a boot script. Example Containerfile:

# Skills
FETCH github:oaustegard/claude-skills /mnt/skills/user

# Python environment
RUN uv pip install --system pandas numpy requests

# Path config
RUN echo '/mnt/skills/user/remembering' > /usr/local/lib/python3.12/dist-packages/muninn-remembering.pth

# Custom setup
ENV MY_VAR=hello
WORKDIR /home/claude

NOT SUPERSEDED BY DYNAMIC WORKFLOWS β€” read first

Claude Code's dynamic workflows orchestrate subagents (separate contexts, fan-out to 16-concurrent / 1000-agent). This skill is a different primitive: single-context control flow over YOUR OWN tool calls, with durable side-effects and checkpoint resume. The workflows runtime explicitly cannot touch the filesystem or shell directly β€” its agents do the work and the script only coordinates them. Flowing is the inverse: the script does the work.

Use flowing for an in-context pipeline (3+ steps, branches, retries, validation, detached side-effects). Use a workflow when you need many subagents. They compose; they do not compete. Do not abandon flowing for a workflow β€” you would lose the durable side-effects and the cross-session checkpoint that hub-spoke depends on.

Flowing β€” Control Flow in Code, Not Prose

When a procedure needs 3+ steps with branches, retries, or contracts, encode it as a DAG of Python tasks instead of prose imperatives. Prose like "first X, then Y, then if Z retry 3Γ—" is read and generated past. A @task graph is structural: a step physically cannot run until its inputs are bound, and gates that fire on bad inputs can't be skipped.

The runner owns control flow β€” branching, retrying, validating, propagating failures, parallelizing. You provide judgment at the leaves. Runner: scripts/flowing.py.

Quick Start

from flowing import task, Flow

@task
def fetch_data():
    return {"items": [1, 2, 3]}

@task(depends_on=[fetch_data])
def process(fetch_data):          # param name must match the dep's name
    return sum(fetch_data["items"])

@task(depends_on=[process])
def store(process):
    print(f"Result: {process}")

Flow(store).run()                 # topo-sorts, runs each layer, parallel within a layer

Each task receives its dependencies as kwargs named after them. Independent tasks in the same layer run in parallel.

Control-Flow Primitives

Encode branches and contracts as graph structure, not if statements inside task bodies.

when= β€” conditional gate

Run the task only if the predicate (over gathered dep values) is truthy. Falsy β†’ SKIPPED, and the skip propagates to dependents.

@task(depends_on=[fetch], when=lambda fetch: fetch["needs_processing"])
def process(fetch):
    return transform(fetch["payload"])

validate= β€” edge contract

Check gathered dep values before the body runs. Raise β†’ FAILED with no retry (bad inputs don't fix themselves). Pass β†’ proceed.

def must_have_items(fetch):
    if not fetch.get("items"):
        raise ValueError("fetch returned empty payload")

@task(depends_on=[fetch], validate=must_have_items)
def process(fetch):
    return sum(fetch["items"])

retry_until= β€” predicate-driven loop

Run the body, then call retry_until(value). True β†’ done. False β†’ retry, consuming the retry= budget. Use for self-correcting LLM steps: generate, check, regenerate.

@task(retry=4, retry_until=lambda r: r["valid"])
def generate_until_valid():
    candidate = llm_call(...)
    return {"valid": passes_schema(candidate), "candidate": candidate}

Distinct from retry= alone, which only retries on a raised exception.

undo= β€” rollback on a later failure

When a main task fails, every task that succeeded in this run and declared undo= has undo(value) called with its own return value, in reverse completion order. Undone tasks and everything downstream of them end as ROLLED_BACK, so resume() re-runs them and the journal forgets them. Detached dependents of a rolled-back task skip, so no notification fires for work that was undone.

The common case is edit, test, and restore on red. snapshot(paths) records byte-exact contents (a missing file counts, and is deleted again on restore); restore is its undo:

from flowing import task, Flow, snapshot, restore

@task(undo=restore)
def before():
    return snapshot(["src/tax.py", "src/invoice.py"])

@task(depends_on=[before])
def edit(before):
    rename_everywhere("calculate_tax", "compute_tax")

@task(depends_on=[edit])
def verify(edit):
    r = subprocess.run(["pytest", "-q"], capture_output=True, text=True)
    if r.returncode:
        raise RuntimeError(r.stdout[-3000:])

flow = Flow(verify)
flow.run()   # red tests: both files are back as they were; flow.results["verify"].error holds the output

Put undo= on the step before the risky one. undo only runs for tasks that succeeded, so an edit that fails halfway through its files would never undo itself; the snapshot step that preceded it does.

Limits: an undo that raises is logged, collected in flow.rollback_failures, and leaves its task SUCCEEDED while the rest of the walk continues. Results replayed from the journal are never undone, because their effects belong to an earlier run. Side effects of the failing step itself (a migrated database, a sent message) are only undone if some step's undo covers them. Flow(..., rollback=False) keeps the failed state on disk for inspection. undo= is refused on a detached=True task.

Other capabilities

  • Parallel execution β€” independent tasks in a layer run on a thread pool (max_workers=).
  • detached=True β€” side-effect tasks (memory writes, notifications) that run after the main DAG and never block it on failure.
  • In-process resume β€” flow.run() β†’ fix β†’ flow.resume() re-runs from the failure point, keeping succeeded tasks cached in memory (same process only). flow.override(task, value) injects a corrected result.
  • Durable journal (journal_path=) β€” opt-in content-addressed replay that survives container death. Flow(term, journal_path="/path/run.jsonl").run() appends each succeeded task's result to an append-only JSONL keyed by a step_key = SHA-256 over the task's bytecode + its when/validate/retry_until bodies + its dependencies' keys (chained, so an upstream change propagates downstream). A later run() β€” even in a fresh container β€” replays the unchanged prefix from the journal and only executes tasks whose key is absent; editing a task body busts its key and re-runs it and its dependents, while cosmetic knobs (retry=, timeout_s=, name) do not. This is the cross-session checkpoint hub-spoke work relies on. Caveat: results are pickled, so non-picklable return values simply re-run; closure-captured values are not part of the key (only the task body's own code is).
  • timeout_s=, retry= with exponential backoff, fail_fast=. Under fail_fast, parallel siblings that were already running still have their results recorded, so rollback can undo them.

Read references/reference.md before using anything beyond the quick start and the primitives above β€” it covers every @task parameter, the Flow methods, resume/override, detached auto-discovery, and the validate=/when= signature-matching gotcha.

When to use

  • A procedure has branches that matter β†’ when= makes them structural.
  • Steps have input contracts β†’ validate= makes them enforceable.
  • An LLM step needs to converge β†’ retry_until= puts the check in the loop.
  • A change spans several files and must pass a check, or not land at all β†’ snapshot/restore as undo=.
  • 3+ independent operations that can parallelize.
  • Multi-step pipelines where late failures shouldn't waste early work.
  • Side-effects that shouldn't block the critical path β†’ detached=True.

When NOT to use

  • A single sequential operation β€” just call the function.
  • The next step needs reasoning about the prior result that can't be a predicate β€” use a think loop.
  • Async or distributed workflows β€” this is single-container, thread-pool based.

Authoring discipline

If you find yourself writing prose like "first call X, validate Y, then if Z retry up to 3 times", that is a flowing graph. Refactor before shipping. Prose imperatives don't enforce; @task graphs do.

The same holds for your own tool calls. Search, edit and test as three model turns, each waiting on the last, is one Bash call running one flow. Each turn saved is a full wait for the model plus the tokens to restate the plan. When the next step does not need judgment about the last result, put the steps in a graph instead of in turns.

Uploading Files

Claude Code on the Web has no file-upload widget and no shared mount. Whenever the user needs to get a file (image, PDF, CSV, doc, archive, anything) into the session, route them through a temporary GitHub branch on the working repo's origin remote.

When to use

Trigger this skill when:

  • The user asks to upload, attach, share, or send a file
  • A task clearly needs a file the user has locally that isn't in the repo (e.g. "summarize this PDF", "the spreadsheet I exported", "the screenshot from earlier")
  • You're about to ask the user to paste a long binary or large text blob β€” offer upload instead

Don't trigger when the file is already in the repo, on a public URL you can fetch, or short enough to paste inline.

Workflow

The script lives at /mnt/skills/user/uploading-files/scripts/upload.py once installed. It must be run from inside the working git repo (it uses origin and cwd).

Step 1 β€” Create the upload branch

python3 /mnt/skills/user/uploading-files/scripts/upload.py init

This creates upload-<short-session-id> on origin (from the default branch) and prints a GitHub upload URL. Show that URL to the user on its own line, with no surrounding markdown β€” no **bold**, no [link](...), no backticks. Some chat renderers concatenate trailing punctuation/markup onto the URL when the user clicks it, breaking the branch name. Bare URL only. Then tell them:

Open that link, drag the file(s) into the page, scroll to the bottom and click Commit changes (the default options are fine). Reply here when done.

Then stop and wait for the user. Do not pretend they've uploaded.

Step 2 β€” Fetch files

After the user confirms the upload:

python3 /mnt/skills/user/uploading-files/scripts/upload.py fetch

This downloads everything on the branch (vs default) into ./.uploads/ (filenames are flattened to basenames) and ensures .uploads/ is in .gitignore. Treat the files in .uploads/ like any other local input.

If the script reports "No files on branch yet", the user probably forgot to click commit. Ask them to refresh the upload page and verify they committed, then re-run fetch.

Step 3 β€” Cleanup

When the uploaded files are no longer needed β€” typically after the work is done and anything worth keeping has been moved into the repo proper, and before opening a PR β€” delete the remote branch:

python3 /mnt/skills/user/uploading-files/scripts/upload.py cleanup

Local files in ./.uploads/ are kept (they're gitignored). If the user might want them again, leave them; otherwise rm -rf .uploads after cleanup.

Optional β€” status

python3 /mnt/skills/user/uploading-files/scripts/upload.py status

Prints the repo, branch name, whether the branch exists on origin, and the upload URL. Useful when you've context-switched and want to recover the URL without recreating the branch.

How it works

  • Branch name β€” upload-<short> where <short> is the first hyphen-segment of $CLAUDE_SESSION_ID, or of the most recent transcript filename under ~/.claude/projects/<encoded-cwd>/, or a UTC timestamp tsYYYYMMDD-HHMMSS as fallback. The same session always resolves to the same branch, so re-running init is idempotent.
  • Repo β€” parsed from git remote get-url origin. Must be a github.com remote.
  • Auth β€” uses $GH_TOKEN (then $GITHUB_TOKEN, $GITHUB_PAT, $GH_PAT). Token needs Contents: write on the working repo.
  • Network calls β€” only api.github.com and raw.githubusercontent.com.

Constraints

  • GitHub web upload caps at 25 MB per file. Larger files won't work via this flow.
  • Filenames are flattened to basenames in .uploads/. If the user uploads two files with the same name in different subdirs, the second overwrites the first. Tell them to rename first if it matters.
  • Binary files survive the round-trip fine (raw download, byte-exact).
  • The skill does not read the upload branch's history beyond "what's there now vs default". If the user pushes multiple commits, you get the union of files.

Anti-patterns

  • Don't ask the user to paste binary content (base64, hex dumps). Use this skill.
  • Don't create the branch and immediately try to fetch β€” the user has to upload first.
  • Don't leave the upload branch around after a PR is opened. It clutters the repo's branch list.
  • Don't commit anything in .uploads/ to the working repo. If a file should be persisted, copy it to a proper location first (and git add from there).

Sponsors

Details

Marketplace
oaustegard/claude-skills
Source
plugins/environment-and-config
Category
Environment And Config
License
MIT
Keywords
api-credentials, configuring, container-layer, flowing, uploading-files

More from oaustegard/claude-skills

All 14