AgentStack
SKILL verified MIT Self-run

Cli Codex

skill-michelkerkmeester-opencode-skilled-agent-loops-with-spec-kit-memory-cli-codex · by MichelKerkmeester

Codex CLI executor for OpenAI-backed coding, repo analysis, PR review, web research, and cross-model validation.

No reviews yet
0 installs
19 views
0.0% view→install

Install

$ agentstack add skill-michelkerkmeester-opencode-skilled-agent-loops-with-spec-kit-memory-cli-codex

✓ scanned · ✓ verified — works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access No
  • Filesystem access Used
  • Shell / process execution Used
  • Environment & secrets Used
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

Are you the author of Cli Codex? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

Codex CLI Orchestrator - Cross-AI Task Delegation

> CRITICAL — SELF-INVOCATION PROHIBITED > > This skill dispatches to the OpenAI CLI binary (codex). If the agent currently reading this skill is itself running inside Codex (detection signals listed in §2), the skill MUST refuse to load and return the documented error message instead of generating any codex invocation. > > A running CLI skill never dispatches itself. The cli-X skills are for cross-AI delegation only — never self-invocation.

Orchestrate OpenAI's Codex CLI for tasks that benefit from a second AI perspective, real-time web search, deep codebase analysis, built-in code review workflows, or parallel code generation.

Core Principle: Use Codex for what it does best. Delegate, validate, integrate. The calling AI stays the conductor.


1. WHEN TO USE

Activation Triggers

  • Cross-AI Validation — code review second perspective, security audit alternative analysis, bug detection, /review diff-aware workflow.
  • Web Research — current internet info via --search flag, latest library versions, API changes, community solutions.
  • Codebase Architecture Analysis — onboarding to unfamiliar codebases, cross-file dependency mapping, architecture docs from code.
  • Parallel Task Processing — offloading generation, simultaneous code generations, background docs/test generation.
  • Agent-Delegated Tasks — specialized profile matches (.codex/agents/*.toml), session management (resume, fork), multi-strategy planning.
  • Specialized Generation — explicit Codex requests, test suite generation, code translation, batch docs (JSDoc, README, API), visual input via --image/-i.

When NOT to Use

  • You ARE Codex already. If your runtime is Codex (detection signal: $CODEX_SESSION_ID or any CODEX_* env var set, codex in process ancestry, or ~/.codex/state//lock present), this skill refuses to load. Self-invocation creates a circular dispatch loop and burns tokens for no value. The cli-X family is exclusively for cross-AI delegation.
  • Simple, quick tasks where CLI overhead is not worth it.
  • Tasks requiring immediate response (rate limits may cause delays).
  • Context already loaded and understood by the current agent.
  • Interactive refinement requiring the full-screen TUI (use codex directly instead).
  • Tasks where Codex CLI is not installed.

2. SMART ROUTING

Prerequisite Detection

# Verify Codex CLI is available before routing
command -v codex || echo "Not installed. Run: npm i -g @openai/codex"

Self-Invocation Guard

def detect_self_invocation():
    """Returns a non-None signal when the orchestrator is already running inside Codex."""
    # Layer 1: env var lookup — Codex sets CODEX_SESSION_ID and CODEX_* vars
    for key in os.environ:
        if key == 'CODEX_SESSION_ID' or key.startswith('CODEX_'):
            return ('env', key)
    # Layer 2: process ancestry — codex in parent tree
    try:
        ancestry = subprocess.check_output(['ps', '-o', 'command=', '-p', str(os.getppid())]).decode()
        if '/codex' in ancestry or 'codex ' in ancestry:
            return ('ancestry', 'codex')
    except subprocess.SubprocessError:
        pass
    # Layer 3: state lock-file probe
    state_dir = os.path.expanduser('~/.codex/state')
    if os.path.isdir(state_dir):
        for entry in os.listdir(state_dir):
            if os.path.exists(os.path.join(state_dir, entry, 'lock')):
                return ('lockfile', entry)
    return None

if detect_self_invocation():
    refuse(
        "Self-invocation refused: this agent is already running inside Codex. "
        "Use a sibling cli-* skill or a fresh shell session in a different runtime to dispatch a different model."
    )

Resource Loading Levels

| Level | When to Load | Resources | | ----------- | ----------------------- | ------------------------------ | | ALWAYS | Every skill invocation | references/cli_reference.md, assets/prompt_quality_card.md | | CONDITIONAL | If intent signals match | Intent-mapped reference docs | | ON_DEMAND | Only on explicit request| Extended templates and patterns |

Smart Router

Provider-specific dictionaries (used by the shared helper functions in [system-spec-kit/references/cli/shared_smart_router.md](../system-spec-kit/references/cli/sharedsmartrouter.md)):

INTENT_SIGNALS = {
    "GENERATION":        {"weight": 4, "keywords": ["generate", "create", "build", "write code", "codex create"]},
    "REVIEW":            {"weight": 4, "keywords": ["review", "audit", "security", "bug", "second opinion", "cross-validate", "/review"]},
    "RESEARCH":          {"weight": 4, "keywords": ["search", "latest", "current", "what's new", "web research", "--search", "browse"]},
    "ARCHITECTURE":      {"weight": 3, "keywords": ["architecture", "codebase", "investigate", "dependencies", "analyze project"]},
    "AGENT_DELEGATION":  {"weight": 4, "keywords": ["delegate", "agent", "background", "parallel", "offload", "codex agent"]},
    "TEMPLATES":         {"weight": 3, "keywords": ["template", "prompt", "how to ask", "codex prompt"]},
    "PATTERNS":          {"weight": 3, "keywords": ["pattern", "workflow", "orchestrate", "session", "resume", "fork"]},
    "HOOKS":             {"weight": 4, "keywords": ["hook", "hooks", "advisor brief", "startup context", "userpromptsubmit", "sessionstart", "codex_hooks"]},
}

RESOURCE_MAP = {
    "GENERATION":        ["references/cli_reference.md", "assets/prompt_templates.md"],
    "REVIEW":            ["references/integration_patterns.md", "references/agent_delegation.md"],
    "RESEARCH":          ["references/codex_tools.md", "assets/prompt_templates.md"],
    "ARCHITECTURE":      ["references/codex_tools.md", "references/agent_delegation.md"],
    "AGENT_DELEGATION":  ["references/agent_delegation.md", "references/integration_patterns.md"],
    "TEMPLATES":         ["assets/prompt_templates.md", "references/cli_reference.md"],
    "PATTERNS":          ["references/integration_patterns.md", "references/cli_reference.md"],
    "HOOKS":             ["references/hook_contract.md", "references/cli_reference.md"],
}

LOADING_LEVELS = {
    "ALWAYS": ["references/cli_reference.md", "assets/prompt_quality_card.md"],
    "ON_DEMAND_KEYWORDS": ["full reference", "all templates", "deep dive", "complete guide", "codex agent", "codex prompt", "web research", "review command", "fork session", "hook contract"],
    "ON_DEMAND": ["references/codex_tools.md", "assets/prompt_templates.md"],
}

UNKNOWN_FALLBACK_CHECKLIST = [
    "Is the user asking about Codex CLI specifically?",
    "Does the task benefit from a second AI perspective?",
    "Is real-time web information needed (--search)?",
    "Would codebase-wide analysis or /review workflow help?",
]

Call sequence (using shared helpers from shared_smart_router.md):

  1. discover_markdown_resources() — recursively enumerate current .md files under existing references/ and assets/ folders at routing time.
  2. _guard_in_skill() + load_if_available() — sandbox paths to this skill, reject non-markdown loads, skip missing files, and suppress duplicates.
  3. score_intents(task) and select_intents(scores, ambiguity_delta=1.0) — preserve provider-specific weighted intent scoring and top-2 ambiguity handling.
  4. get_routing_key(task, intents) — derive the provider routing key from task/provider context, then fall back to codex.
  5. ALWAYS-load LOADING_LEVELS["ALWAYS"], then return UNKNOWN_FALLBACK with UNKNOWN_FALLBACK_CHECKLIST when max score is 0.
  6. CONDITIONAL-load RESOURCE_MAP[intent], ON_DEMAND-load keyword matches, and return a notice when no provider-specific knowledge base is available beyond always-load resources.

The route_codex_resources(task) function body lives in [shared_smart_router.md](../system-spec-kit/references/cli/sharedsmartrouter.md) — substitute ` = codex`.


3. HOW IT WORKS

Prerequisites

# Verify installation
command -v codex || echo "Not installed. Run: npm i -g @openai/codex"

# Authentication — API key OR ChatGPT OAuth
export OPENAI_API_KEY=your-key-here
codex login

Authentication options: OPENAI_API_KEY env var (direct API), or ChatGPT OAuth via codex login (uses ChatGPT account credentials).

Provider Auth Pre-Flight (Smart Fallback)

MANDATORY before any first dispatch in a session. The default OpenAI auth (API key OR ChatGPT OAuth) may not be configured on this machine — silently failing with 401 Unauthorized or not authenticated mid-dispatch wastes a round-trip. Run this check once per session, cache the result, and re-run it only if a dispatch fails with an auth error.

# One-shot pre-flight: capture auth status for routing
[ -n "$OPENAI_API_KEY" ] && OPENAI_KEY_OK=1 || OPENAI_KEY_OK=0
CODEX_AUTH=$(codex login status 2>&1)
echo "$CODEX_AUTH" | grep -qi "logged in\|chatgpt-oauth" && CODEX_OAUTH_OK=1 || CODEX_OAUTH_OK=0

Decision tree (apply in order — first match wins):

| State | OPENAIKEYOK | CODEXOAUTHOK | Action | |-------|---------------|----------------|--------| | Default available | 1 | * | Proceed with codex exec --model gpt-5.5 -c model_reasoning_effort="medium" -c service_tier="fast" | | API key missing, OAuth ready | 0 | 1 | ASK user before substituting — never auto-fall-back silently. Surface options A/B/C below. | | Both missing | 0 | 0 | ASK user to configure auth — surface the login commands, do NOT dispatch. |

User prompt template — API key missing, OAuth configured:

`$OPENAI_API_KEY` is not set, but ChatGPT OAuth via `codex login` is configured.
Pick one:
  A) Use the existing ChatGPT OAuth session (works for `codex exec` if your ChatGPT plan covers the model)
  B) Run `export OPENAI_API_KEY=sk-...` first, then retry the original dispatch
  C) Name a different model — paste the `--model ` you want to use

User prompt template — both missing:

No OpenAI auth is configured on this machine. Run one:
  - `export OPENAI_API_KEY=sk-...`  (recommended for direct API calls)
  - `codex login`                    (interactive ChatGPT OAuth flow; requires ChatGPT Plus/Pro/Business)
Which would you like to set up? Confirm when login finishes; the skill will retry the original dispatch.

Error-recovery contract. If a dispatch returns an auth error after pre-flight passed (key revoked or OAuth expired), invalidate the cache, rerun the pre-flight, and apply the same decision tree before retrying. Never substitute a model the user didn't approve.

Default Invocation (Skill Default)

Default model + effort + tier: gpt-5.5 · medium reasoning · fast service tier. Balances speed, cost, and quality for the typical delegation.

codex exec \
  --model gpt-5.5 \
  -c model_reasoning_effort="medium" \
  -c service_tier="fast" \
  -c approval_policy=never \
  --sandbox workspace-write \
  ""

User override (honor explicit user phrasing verbatim):

| User says | Resolve to | |-----------|------------| | (nothing specified) | --model gpt-5.5 -c model_reasoning_effort="medium" -c service_tier="fast" | | "Use gpt 5.5 high fast" | --model gpt-5.5 -c model_reasoning_effort="high" -c service_tier="fast" | | "Use gpt 5.5 low" | --model gpt-5.5 -c model_reasoning_effort="low" -c service_tier="fast" (fast stays unless user drops it) | | "Use gpt 5.5 xhigh" | --model gpt-5.5 -c model_reasoning_effort="xhigh" -c service_tier="fast" |

Only the reasoning-effort dimension changes via override; model stays on gpt-5.5 and service tier stays on fast unless the user explicitly says otherwise.

Core Invocation Pattern

codex exec "prompt" --model gpt-5.5 -c model_reasoning_effort="medium" -c service_tier="fast" 2>&1

> Common flag mistakes: --reasoning, --reasoning-effort and --quiet do NOT exist. Use -c model_reasoning_effort="high" for reasoning effort (or set it in config.toml). There is no quiet flag. Use -o file.txt to capture the last message to a file.

| Flag / Option | Purpose | |---------------|---------| | --model | Model selection — gpt-5.5 (always; skill default) | | -c model_reasoning_effort="" | Reasoning effort — none, minimal, low, medium, high, xhigh | | -c service_tier="fast" | Fast mode — routes through fast tier. Always pass explicitly when delegating from another AI so the call is self-documenting and never silently falls back to a slower tier. | | --sandbox read-only | Safe mode: read files, no writes or shell commands | | --sandbox workspace-write | Allow file writes within the workspace | | --sandbox danger-full-access | Full shell access — requires explicit user approval | | --ask-for-approval untrusted | Prompt before untrusted operations (default) | | --ask-for-approval on-request | Prompt only when Codex requests approval | | --ask-for-approval never | Auto-approve all operations (use with caution) | | --full-auto | Low-friction sandboxed automation: workspace-write sandbox + on-request approval. Default for unattended orchestration. | | --search | Enable live web browsing during task execution | | --image / -i | Attach an image file as visual input |

> Default sandbox behavior: codex exec without an explicit --sandbox flag defaults to read-only with approval: never. File modification tasks will silently fail — the agent reads code and plans changes but cannot write them. Always pass --sandbox workspace-write (or --full-auto) when the task requires file edits.

> Fast mode (REQUIRED for cross-AI delegation): Always pass -c service_tier="fast" explicitly. This routes the call through the fast tier instead of relying on whatever the user's ~/.codex/config.toml sets as default. Explicit means reproducible regardless of who runs it.

Model Selection

The skill dispatches gpt-5.5 for every task. Only the reasoning-effort dimension varies.

| Model | ID | Use Case | Reasoning Effort | |-------|----|----------|-----------------| | GPT-5.5 ★ default | gpt-5.5 | All delegations — code generation, review, implementation, documentation, architecture, research | configurable via -c model_reasoning_effort (default medium; raise to high / xhigh for hard problems, lower to low / minimal for trivial lookups) |

Reasoning Effort Levels: none, minimal, low, medium (skill default), high (user-override tier), xhigh (maximum depth — profile default for all agents).

> Note: There is no --reasoning-effort CLI flag. Set via -c model_reasoning_effort="medium" or in config.toml / profile sections.

Selection Strategy: gpt-5.5 always; tune only reasoning effort: medium for most delegations (default), high/xhigh for architecture/security audits/complex planning, low/minimal for trivial lookups.

Codex Agent Delegation

The calling AI is the conductor; Codex profiles in config.toml [profiles.] shape HOW Codex processes the task (sandbox, reasoning).

| Task Type | Profile | Invocation Pattern | |-----------|---------|-------------------| | Code review / security audit | review | codex exec -p review "Review @./src/auth.ts for security issues" -m gpt-5.5 | | Git diff review | (built-in) | codex exec review "Focus on security" --commit HEAD | | Architecture exploration | context | codex exec -p context "Analyze the architecture of this project" -m gpt-5.5 | | Technical research | research | codex exec -p research "Research latest Express.js security advisories" -m gpt-5.5 --search | | Documentation generation | write | codex exec -p write "Generate README for this project" -m gpt-5.5 | | Fresh-perspective debugging | debug | codex exec -p debug "Debug this error: [error]" -m gpt-5.5 | | Multi-strategy planning | ai-council | `codex e

Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet — be the first.

Versions

  • v0.1.0 Imported from the upstream source.