From htmlgraph
> **DEPRECATED:** This skill is replaced by the `codex-operator` agent.
npx claudepluginhub shakestzd/htmlgraphThis skill uses the workspace's default tool permissions.
> **DEPRECATED:** This skill is replaced by the `codex-operator` agent.
Provides Ktor server patterns for routing DSL, plugins (auth, CORS, serialization), Koin DI, WebSockets, services, and testApplication testing.
Conducts multi-source web research with firecrawl and exa MCPs: searches, scrapes pages, synthesizes cited reports. For deep dives, competitive analysis, tech evaluations, or due diligence.
Provides demand forecasting, safety stock optimization, replenishment planning, and promotional lift estimation for multi-location retailers managing 300-800 SKUs.
DEPRECATED: This skill is replaced by the
codex-operatoragent. UseAgent(subagent_type="htmlgraph:codex-operator", prompt="...")instead. The codex-operator agent tries Codex CLI first with structured JSON output and hook-based compliance.
name: codex description: CodexSpawner with full event tracking for code generation and implementation when_to_use:
⚠️ IMPORTANT: This skill teaches TWO EXECUTION PATTERNS
Choose based on your needs. See "EXECUTION PATTERNS" below.
| Pattern | Use Case | Tracking | Complexity |
|---|---|---|---|
| Task(general-purpose) | Code generation, implementation, debugging | ✅ Yes (via Task) | Low (1-2 lines) |
| CodexSpawner | Need precise Codex control + full subprocess tracking | ✅ Yes (full parent context) | Medium (setup required) |
CodexSpawner is the HtmlGraph-integrated way to invoke OpenAI Codex CLI with full parent event context and subprocess tracking.
Key distinction: CodexSpawner is invoked directly via Python SDK - NOT wrapped in Task(). Task() is only for Claude subagents (Haiku, Sonnet, Opus).
CodexSpawner:
Use Task(general-purpose) (simple, recommended):
# Delegate to Claude for code generation
Task(subagent_type="general-purpose",
prompt="Implement JWT authentication middleware with tests")
# Task() delegates to Claude - handles everything automatically
Use CodexSpawner (direct Python invocation - advanced):
# Direct Codex CLI invocation with full tracking
spawner = CodexSpawner()
result = spawner.spawn(
prompt="Generate auth middleware",
sandbox="workspace-write",
output_json=True,
track_in_htmlgraph=True,
tracker=tracker,
parent_event_id=parent_event_id
)
# NOT Task(CodexSpawner) - invoke directly!
import os
import sys
from pathlib import Path
from datetime import datetime, timezone
import uuid
# Add plugin agents directory to path
PLUGIN_AGENTS_DIR = Path("/path/to/htmlgraph/packages/claude-plugin/.claude-plugin/agents")
sys.path.insert(0, str(PLUGIN_AGENTS_DIR))
from htmlgraph import SDK
from htmlgraph.orchestration.spawners import CodexSpawner
from htmlgraph.db.schema import HtmlGraphDB
from htmlgraph.config import get_database_path
from spawner_event_tracker import SpawnerEventTracker
# Initialize
sdk = SDK(agent='claude')
db = HtmlGraphDB(str(get_database_path()))
session_id = f"sess-{uuid.uuid4().hex[:8]}"
db._ensure_session_exists(session_id, "claude")
# Create parent event context (like PreToolUse hook does)
user_query_event_id = f"event-query-{uuid.uuid4().hex[:8]}"
parent_event_id = f"event-{uuid.uuid4().hex[:8]}"
start_time = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
# Insert UserQuery event
db.connection.cursor().execute(
"""INSERT INTO agent_events
(event_id, agent_id, event_type, session_id, tool_name, input_summary, status, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
(user_query_event_id, "claude-code", "tool_call", session_id, "UserPromptSubmit",
"Generate spawner usage documentation", "completed", start_time)
)
# Insert Task delegation event
db.connection.cursor().execute(
"""INSERT INTO agent_events
(event_id, agent_id, event_type, session_id, tool_name, input_summary,
context, parent_event_id, subagent_type, status, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(parent_event_id, "claude-code", "task_delegation", session_id, "Task",
"Generate documentation code examples", '{"subagent_type":"general-purpose"}',
user_query_event_id, "general-purpose", "started", start_time)
)
db.connection.commit()
# Export parent context (like PreToolUse hook does)
os.environ["HTMLGRAPH_PARENT_EVENT"] = parent_event_id
os.environ["HTMLGRAPH_PARENT_SESSION"] = session_id
os.environ["HTMLGRAPH_SESSION_ID"] = session_id
# Create tracker with parent context
tracker = SpawnerEventTracker(
delegation_event_id=parent_event_id,
parent_agent="claude",
spawner_type="codex",
session_id=session_id
)
tracker.db = db
# Invoke CodexSpawner with FULL tracking
spawner = CodexSpawner()
result = spawner.spawn(
prompt="Generate Python code example for using CopilotSpawner",
sandbox="workspace-write",
output_json=True,
full_auto=True,
track_in_htmlgraph=True, # Enable SDK activity tracking
tracker=tracker, # Enable subprocess event tracking
parent_event_id=parent_event_id, # Link to parent event
timeout=120
)
# Check results
print(f"Success: {result.success}")
print(f"Response: {result.response}")
if result.tracked_events:
print(f"Tracked {len(result.tracked_events)} events in HtmlGraph")
| Parameter | Type | Required | Description |
|---|---|---|---|
prompt | str | ✅ | Code generation task for Codex |
sandbox | str | ❌ | Sandbox mode: "workspace-write", "workspace-read", etc. |
output_json | bool | ❌ | Return structured JSON output (default: False) |
full_auto | bool | ❌ | Enable full-auto headless mode (default: False) |
track_in_htmlgraph | bool | ❌ | Enable SDK activity tracking (default: True) |
tracker | SpawnerEventTracker | ❌ | Tracker instance for subprocess events |
parent_event_id | str | ❌ | Parent event ID for event hierarchy |
timeout | int | ❌ | Max seconds to wait (default: 120) |
# See above code example + this prompt:
result = spawner.spawn(
prompt="""Generate a Python code example showing how to:
1. Create a CopilotSpawner instance
2. Set up parent event context in database
3. Invoke it with parent event linking
4. Track the execution with SpawnerEventTracker
5. Handle the AIResult
Use real example from HtmlGraph project and show best practices.
""",
sandbox="workspace-write",
output_json=True,
full_auto=True,
track_in_htmlgraph=True,
tracker=tracker,
parent_event_id=parent_event_id,
timeout=120
)
# Result: Full tracking with Codex-generated code examples
# All subprocess invocations recorded in HtmlGraph
CRITICAL: If external spawner fails, delegate to Claude sub-agent (NOT direct execution).
# Try external spawner first
try:
spawner = CodexSpawner()
result = spawner.spawn(
prompt="Your code generation task",
sandbox="workspace-write",
output_json=True,
track_in_htmlgraph=True,
tracker=tracker,
parent_event_id=parent_event_id,
timeout=120
)
if result.success:
return result # Success, use spawner result
else:
# Spawner returned error result
raise Exception(f"Spawner failed: {result.error}")
except Exception as e:
# External spawner failed (CLI not installed, API issues, sandbox restrictions, etc.)
# FALLBACK to Claude sub-agent - do NOT attempt direct execution
print(f"⚠️ CodexSpawner failed: {e}")
print("📌 Falling back to Claude code generation agent...")
return Task(
subagent_type="general-purpose",
prompt="Your code generation task here"
)
# Task(general-purpose) guarantees execution via Claude
Why fallback to Task()?
Pattern Summary:
task_prompt = skill_args if 'skill_args' in dir() else ""
if not task_prompt: print("❌ ERROR: No task prompt provided") print("Usage: Skill(skill='.claude-plugin:codex', args='Generate API endpoint with tests')") sys.exit(1)
cli_check = subprocess.run( ["which", "codex"], capture_output=True, text=True )
if cli_check.returncode != 0: print("⚠️ Codex CLI not found on system") print("Install from: https://github.com/openai/codex") print("\nFallback: Use Task(subagent_type='general-purpose', prompt='...')") print("Claude can generate code directly without the Codex CLI.") sys.exit(1)
print("✅ Codex CLI found, executing spawner...") print(f"\nTask: {task_prompt[:100]}...")
try: spawner = HeadlessSpawner() result = spawner.spawn_codex( prompt=task_prompt, output_json=True, sandbox="workspace-write", full_auto=True, track_in_htmlgraph=True, timeout=120 )
if result.success:
print("\n✅ Codex execution successful")
if result.tokens_used:
print(f"📊 Tokens used: {result.tokens_used}")
print("\n" + "="*60)
print("RESPONSE:")
print("="*60)
print(result.response)
if result.tracked_events:
print(f"\n📈 Tracked {len(result.tracked_events)} events in HtmlGraph")
else:
print(f"\n❌ Codex execution failed: {result.error}")
sys.exit(1)
except Exception as e: print(f"❌ Error executing spawner: {type(e).name}: {e}") sys.exit(1)
Use OpenAI Codex (GPT-4 Turbo) for code generation and implementation in sandboxed environments.
CRITICAL DISTINCTION:
| What | Description |
|---|---|
| This Skill | Documentation teaching HOW to use CodexSpawner |
| CodexSpawner | Direct Codex CLI invocation with full tracking (advanced) |
| Task() Tool | Delegation to Claude subagents ONLY (Haiku, Sonnet, Opus) |
| Bash Tool | Direct CLI invocation without HtmlGraph tracking |
Workflow:
Task(subagent_type="general-purpose") (recommended)⚠️ To actually generate code, use these approaches:
# Use Claude for code generation (native approach)
Task(
subagent_type="general-purpose",
prompt="Generate API endpoint for user authentication with JWT tokens and full tests"
)
# For complex implementations
Task(
subagent_type="general-purpose",
model="sonnet", # or "opus" for complex work
prompt="Refactor authentication system to support multi-tenancy across 15+ files"
)
# If you have codex CLI installed on your system
Bash("codex generate 'Create FastAPI endpoint with authentication'")
# Or use the SDK spawner
uv run python -c "
from htmlgraph.orchestration.headless_spawner import HeadlessSpawner
spawner = HeadlessSpawner()
result = spawner.spawn_codex(
prompt='Generate auth endpoint',
sandbox='workspace-write',
track_in_htmlgraph=True
)
print(result.response)
"
The codex CLI must be installed:
# Install Codex CLI
npm install -g @openai/codex-cli
# Or via pip
pip install openai-codex-cli
# Verify installation
codex --version
PRIMARY: Use Skill() to invoke (tries external CLI first):
# Recommended approach - uses external codex CLI via agent spawner
Skill(skill=".claude-plugin:codex", args="Generate API endpoint for user authentication with full tests")
What happens internally:
codex CLI is installed on your systemcodex generate "API endpoint with tests"Task(subagent_type="general-purpose", prompt="Generate API endpoint")FALLBACK: Direct Task() invocation (when Skill unavailable):
# Manual fallback - uses Claude's general-purpose agent
Task(
subagent_type="general-purpose",
prompt="Generate API endpoint for user authentication with full tests",
model="haiku" # Optional: specify model
)
Note: Direct Codex spawning requires the CLI. If unavailable, Claude can implement the code directly.
Codex provides three security levels:
# Analysis without modifications
Task(
subagent_type="general-purpose",
prompt="Analyze code structure without making changes"
)
# Generate and write code to workspace
Task(
subagent_type="general-purpose",
prompt="Generate new feature implementation with tests"
)
# System-wide operations (dangerous)
Task(
subagent_type="general-purpose",
prompt="System configuration changes (requires full access)"
)
Task(
subagent_type="general-purpose",
prompt="""
Generate FastAPI endpoint for user authentication:
- POST /auth/login
- JWT token generation
- Input validation with Pydantic
- Error handling
- Unit tests with pytest
"""
)
# Generate JSON matching a schema
Task(
subagent_type="general-purpose",
prompt="""
Extract all functions and classes from src/:
Output format:
{
"functions": [{"name": "...", "file": "...", "line": ...}],
"classes": [{"name": "...", "file": "...", "methods": [...]}]
}
"""
)
# Analyze multiple files
Task(
subagent_type="general-purpose",
prompt="Review all Python files in src/ for code quality issues and security vulnerabilities"
)
# Generate comprehensive tests
Task(
subagent_type="general-purpose",
prompt="""
Generate pytest tests for UserService class:
- Test all public methods
- Include edge cases
- Mock external dependencies
- Aim for 90%+ coverage
"""
)
Use Codex when:
Use Claude when:
If you see this error:
ERROR: codex CLI not found
Install from: npm install -g @openai/codex-cli
Options:
Timeout Errors:
Error: Timed out after 120 seconds
Solution: Split into smaller tasks or increase timeout
Approval Failures:
Error: Command requires approval
Solution: Adjust approval settings or sandbox mode
Sandbox Restrictions:
Error: Operation not allowed in sandbox
Solution: Upgrade sandbox level or redesign approach
# Auto-execute generated code
Task(
subagent_type="general-purpose",
prompt="Fix linting errors and run tests automatically"
)
# Include images for context
Task(
subagent_type="general-purpose",
prompt="Convert this UI mockup to React code (see attached image)"
)
Track code generation in features:
from htmlgraph import SDK
sdk = SDK(agent="claude")
# Create feature for implementation
feature = sdk.features.create(
title="User Authentication API",
description="""
Generated via Codex:
- API endpoints
- Input validation
- JWT tokens
- Unit tests
Model: GPT-4 Turbo
Sandbox: workspace-write
"""
).save()
Avoid Codex for:
The skill implements a multi-level fallback strategy:
Skill(skill=".claude-plugin:codex", args="Generate authentication API")
# Attempts to use external codex CLI via agent spawner SDK
# If codex CLI not found, automatically falls back to:
Task(subagent_type="general-purpose", prompt="Generate authentication API")
# Uses Claude for code generation
# If Task() fails:
# - Returns error message to orchestrator
# - Orchestrator can retry with different approach
# - Or escalate to user for guidance
Error Handling:
/gemini - For exploration before implementation/copilot - For GitHub integration after generation/code-quality - For validating generated code/debugging-workflow - For fixing issues in generated code