agentspan
Skill4 starsChanged 8 months agoMITView on GitHub
Build, run, monitor, and manage durable AI agents with AgentSpan. Use when the user wants to create agents, define tools, orchestrate multi-agent teams, handle human-in-the-loop approvals, stream events, or manage credentials. Uses the `agentspan` CLI or Python SDK. Requires AGENTSPAN_SERVER_URL.
- Pipes a download into a shell
- Reads credentials
- Installs packages
In this repositoryOne other file it gives its agents.
- CLAUDE.mdCLAUDE.md
The file
We split this skill into the rules it gives an agent
12 rules. About 0 are common, 6 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 13
Always install and use the
agentspanCLI proactively: If missing, run npm install -g @agentspan-ai/agentspan. - Very specific: line 14
Never hardcode credentials in code: Always use agentspan credentials set --name KEY and reference via credentials=["KEY"] in Agent …
- Very specific: line 17
Always check
result.is_success: before using result.output — especially in autonomous agent flows. - Distinctive: line 37
Follow every step in order.
- Very specific: line 51
If npm is missing, install Node.js first (see https://nodejs.org).
- Distinctive: line 64
Fallback: Only if CLI and npm are both unavailable, install the Python SDK directly:
- Distinctive: line 98
If 401/403, ask user for credentials:
- Distinctive: line 423
When the agent calls this tool, execution pauses.
- Distinctive: line 656
Never echo credentials or secrets in output.
- Very specific: line 661
Connection refused: Verify AGENTSPAN_SERVER_URL is correct and server is running.
- Very specific: line 662
401 Unauthorized: Run agentspan configure with correct credentials.
- Distinctive: line 664
Tool schema errors: Ensure tool functions have type hints and docstrings.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AgentSpan — Build Durable AI Agents
AI agents that don't die when your process dies. Agents compile to server-side workflows, survive crashes, scale across machines, and pause for human approval.
Rules
- Always install and use the
agentspanCLI proactively. If missing, runnpm install -g @agentspan-ai/agentspan. Verify withagentspan --versionandagentspan doctor. Do not just tell the user to install it — do it yourself. - Never hardcode credentials in code. Always use
agentspan credentials set --name KEYand reference viacredentials=["KEY"]in Agent definitions. - Never use
python3 -cfor any purpose. Write Python to files using the Write tool, then run them. - Server resolution:
AGENTSPAN_SERVER_URLenv var oragentspan configuresettings. Default local server:http://localhost:6767. - Always check
result.is_successbefore usingresult.output— especially in autonomous agent flows. - Agent names must be unique — alphanumeric + underscore/hyphen, start with letter or underscore.
- Tools need type hints and docstrings — schema is auto-generated from them.
- Use
result.output["result"]for text output, notresult.outputdirectly (it's a dict). - Deploy is idempotent — safe to call on every startup.
- Serve blocks forever — triggering comes from outside (CLI, API, another process).
Updating this skill
curl -sSL https://raw.githubusercontent.com/agentspan-ai/agentspan-skills/main/install.sh | bash -s -- --all --upgradeOn Windows:
irm https://raw.githubusercontent.com/agentspan-ai/agentspan-skills/main/install.ps1 -OutFile install.ps1; .\install.ps1 -All -UpgradeFirst-time setup
Follow every step in order. Do not skip steps.
Step 1 — Install the CLI
agentspan --versionIf not installed:
npm --versionIf npm is missing, install Node.js first (see https://nodejs.org). Then:
npm install -g @agentspan-ai/agentspanVerify:
agentspan --version
agentspan doctorFallback: Only if CLI and npm are both unavailable, install the Python SDK directly:
pip install agentspanStep 2 — Choose a server
Ask the user whether they want:
- Option A — Start a local server (development/testing)
- Option B — Connect to an existing remote server
Option A — Local server:
agentspan server startVerify: agentspan doctor
Option B — Remote server:
agentspan configure --url https://your-server.example.com --auth-key YOUR_KEYStep 3 — Test connectivity
agentspan doctor
agentspan agent listIf 401/403, ask user for credentials:
agentspan configure --url URL --auth-key KEY --auth-secret SECRETStep 4 — Install Python SDK
pip install agentspanSetup is complete.
1) Creating agents
Basic agent
from agentspan.agents import Agent, AgentRuntime
agent = Agent(
name="helper",
model="openai/gpt-4o",
instructions="You are a helpful assistant.",
)
with AgentRuntime() as rt:
result = rt.run(agent, "What is quantum computing?")
print(result.output["result"])Agent with all options
Agent(
name="my_agent",
model="openai/gpt-4o", # "provider/model" format
instructions="You are a ...", # System prompt (str, callable, or PromptTemplate)
tools=[my_tool], # List of @tool functions
max_turns=25, # Max LLM iterations
timeout_seconds=0, # 0 = no timeout
max_tokens=None, # Max output tokens per LLM call
temperature=None, # LLM temperature
output_type=MyPydanticModel, # Structured output (Pydantic model)
planner=False, # Enable planning-first behavior
thinking_budget_tokens=None, # Extended reasoning token budget
credentials=["API_KEY"], # Credentials resolved from server
metadata={"team": "backend"}, # Custom metadata
)@agent decorator
from agentspan.agents import agent
@agent(model="openai/gpt-4o", tools=[search])
def researcher():
"""You are a research assistant. Find and summarize information."""
# Use: rt.run(researcher, "Find info about quantum computing")Model formats
"openai/gpt-4o", "anthropic/claude-sonnet-4-6", "google_gemini/gemini-2.5-flash", "claude-code/opus", "aws_bedrock/anthropic.claude-v2", "azure_openai/gpt-4o", "groq/llama-3-70b", "ollama/llama3", "deepseek/deepseek-chat", "mistral/mistral-large", "grok/grok-3"
2) Tools
@tool decorator
from agentspan.agents import tool
@tool
def search(query: str) -> str:
"""Search the web for information."""
return f"Results for: {query}"
@tool(approval_required=True, credentials=["API_KEY"])
def delete_file(path: str) -> str:
"""Delete a file. Requires human approval."""
os.remove(path)
return f"Deleted {path}"Tool functions must have type hints and a docstring. Schema is auto-generated.
ToolContext (dependency injection)
from agentspan.agents import tool, ToolContext
@tool
def lookup(query: str, context: ToolContext) -> str:
"""Search with context."""
exec_id = context.execution_id
state = context.state # Mutable dict shared across tool calls
deps = context.dependencies # From Agent(dependencies={...})
return f"Found in execution {exec_id}"Server-side tools (no local worker needed)
from agentspan.agents import http_tool, mcp_tool, search_tool
weather = http_tool(
name="get_weather",
description="Get weather for a city",
url="https://api.weather.com/v1/current?city=${city}",
credentials=["WEATHER_API_KEY"],
)
github = mcp_tool(
server_url="https://mcp.github.com",
tool_names=["create_issue", "list_repos"],
credentials=["GITHUB_TOKEN"],
)
# Built-in tools: search_tool, index_toolAgent as tool
from agentspan.agents import agent_tool
specialist = Agent(name="math_expert", model="openai/gpt-4o", instructions="Solve math problems.")
orchestrator = Agent(
name="orchestrator",
model="openai/gpt-4o",
tools=[agent_tool(specialist, description="Call the math expert")],
)3) Running agents
Ephemeral (one-shot)
with AgentRuntime() as rt:
result = rt.run(agent, "prompt") # Sync
result = await rt.run_async(agent, "prompt") # Async
result = rt.run(agent, "prompt",
session_id="conv-123", # Multi-turn
media=["https://example.com/image.png"], # Multimodal
timeout=60000, # Timeout ms
credentials=["MY_API_KEY"], # Runtime credentials
)Streaming
stream = rt.stream(agent, "prompt")
for event in stream:
print(event.type, event.content)
result = stream.get_result()Non-blocking
handle = rt.start(agent, "prompt")
status = rt.get_status(handle.execution_id)
handle.pause()
handle.resume()
handle.cancel("no longer needed")Production (deploy + serve)
rt.deploy(agent) # Push definition to server (idempotent)
rt.serve(agent) # Start workers, poll for tasks (blocks forever)Trigger from outside:
agentspan agent run --name helper "What is quantum computing?"CLI execution
# Run by name (agent must be deployed)
agentspan agent run --name helper "What is quantum computing?"
# Run from config file
agentspan agent run --config agent.yaml "prompt"
# Check status
agentspan agent status <execution-id>
# Stream events
agentspan agent stream <execution-id>4) Multi-agent orchestration
Sequential pipeline (>>)
researcher = Agent(name="researcher", model="openai/gpt-4o", instructions="Research the topic.")
writer = Agent(name="writer", model="openai/gpt-4o", instructions="Write a summary.")
pipeline = researcher >> writer
result = rt.run(pipeline, "Quantum computing breakthroughs")Parallel
Agent(
name="analysis",
model="openai/gpt-4o",
agents=[pros_agent, cons_agent],
strategy="parallel",
)Router
Agent(
name="team",
model="openai/gpt-4o",
agents=[billing, technical],
strategy="router",
router=router_agent,
)Swarm (peer-to-peer handoff)
from agentspan.agents.handoff import OnTextMention
coder = Agent(name="coder", model="openai/gpt-4o", instructions="Code. Say HANDOFF_TO_QA when done.")
qa = Agent(name="qa", model="openai/gpt-4o", instructions="Test. Say HANDOFF_TO_CODER if bugs found.")
Agent(
name="dev_team",
model="openai/gpt-4o",
agents=[coder, qa],
strategy="swarm",
handoffs=[
OnTextMention(text="HANDOFF_TO_QA", target="qa"),
OnTextMention(text="HANDOFF_TO_CODER", target="coder"),
],
)Scatter-gather (fan-out/fan-in)
from agentspan.agents import scatter_gather
coordinator = scatter_gather(
name="multi_search",
worker=Agent(name="searcher", model="openai/gpt-4o-mini", instructions="Search and summarize."),
timeout_seconds=300,
)Strategies: handoff, sequential, parallel, router, round_robin, random, swarm, manual
5) Monitoring and managing
List agents
agentspan agent listGet agent definition
agentspan agent get <name>Search executions
agentspan agent execution --status FAILED --since 1d
agentspan agent execution --status RUNNING --since 7d
agentspan agent execution --status COMPLETEDExecution details
agentspan agent status <execution-id>Stream events (SSE)
agentspan agent stream <execution-id>Delete agent
agentspan agent delete <name>6) Human-in-the-loop
Mark any tool with approval_required=True — execution pauses durably (days, not minutes):
@tool(approval_required=True)
def deploy_to_prod(service: str) -> str:
"""Deploy service to production. Requires approval."""
return f"Deployed {service}"
agent = Agent(name="deployer", model="openai/gpt-4o", tools=[deploy_to_prod])When the agent calls this tool, execution pauses. Approve or reject from any machine:
# Approve
agentspan agent respond <execution-id> --approve
# Reject with reason
agentspan agent respond <execution-id> --deny --reason "Not ready"Or via Python:
handle = rt.start(agent, "Deploy the auth service")
# ... later ...
handle.approve() # or handle.reject("reason")7) Guardrails
from agentspan.agents import RegexGuardrail, LLMGuardrail, Guardrail, GuardrailResult
# Regex: block emails in output
RegexGuardrail(
name="no_emails",
patterns=[r"[\w.+-]+@[\w-]+\.[\w.-]+"],
message="Remove email addresses.",
on_fail="retry", # retry | raise | fix | human
max_retries=3,
)
# LLM: policy-based check
LLMGuardrail(
name="safety",
model="openai/gpt-4o-mini",
policy="Reject responses with medical advice.",
on_fail="raise",
)
# Custom function
def no_ssn(content: str) -> GuardrailResult:
if re.search(r"\b\d{3}-\d{2}-\d{4}\b", content):
return GuardrailResult(passed=False, message="Redact SSNs.")
return GuardrailResult(passed=True)
Guardrail(no_ssn, position="output", on_fail="retry", max_retries=3)Failure modes: retry (auto-retry), raise (throw exception), fix (LLM auto-fix), human (escalate)
8) Memory and state
Conversation memory (chat history)
from agentspan.agents import ConversationMemory
agent = Agent(
name="chatbot",
model="openai/gpt-4o",
memory=ConversationMemory(max_messages=50),
)Semantic memory (long-term, searchable)
from agentspan.agents import SemanticMemory
memory = SemanticMemory()
memory.add("User prefers Python over JavaScript")
memory.add("User works at Acme Corp")
results = memory.search("What language does the user prefer?")9) Credentials management
Credentials are always resolved from the server. No env var fallback. Missing credentials cause FAILED_WITH_TERMINAL_ERROR.
# Store credentials on server (KEY then VALUE as positional args)
agentspan credentials set GITHUB_TOKEN ghp_xxxxxxxxxxxx
agentspan credentials set OPENAI_API_KEY sk-xxxxxxxxxxxx
# List stored credential keys (values never shown)
agentspan credentials listAgent(
name="github_agent",
model="openai/gpt-4o",
credentials=["GITHUB_TOKEN"],
tools=[my_github_tool],
)10) Advanced features
Structured output
from pydantic import BaseModel
class Analysis(BaseModel):
sentiment: str
confidence: float
summary: str
agent = Agent(name="analyzer", model="openai/gpt-4o", output_type=Analysis)
result = rt.run(agent, "Analyze this text...")
analysis: Analysis = result.output # Fully typedTermination conditions
from agentspan.agents import TextMentionTermination, MaxMessageTermination
Agent(
name="worker",
model="openai/gpt-4o",
instructions="Say DONE when finished.",
termination=TextMentionTermination("DONE"),
# Composable: termination=TextMentionTermination("DONE") | MaxMessageTermination(10),
)Gates (conditional pipelines)
from agentspan.agents.gate import TextGate
checker = Agent(name="checker", model="openai/gpt-4o",
instructions="Output NO_ISSUES if everything is fine.",
gate=TextGate("NO_ISSUES"),
)
fixer = Agent(name="fixer", model="openai/gpt-4o", instructions="Fix the issue.")
pipeline = checker >> fixer # fixer only runs if checker finds issuesCallbacks
from agentspan.agents import CallbackHandler
class MyCallbacks(CallbackHandler):
def on_agent_start(self, **kwargs): pass
def on_agent_end(self, **kwargs): pass
def on_model_start(self, **kwargs): pass
def on_model_end(self, **kwargs): pass
Agent(name="agent", model="openai/gpt-4o", callbacks=[MyCallbacks()])Claude Code agents
from agentspan.agents import Agent, ClaudeCode
reviewer = Agent(
name="reviewer",
model="claude-code/sonnet",
instructions="Review code for quality.",
tools=["Read", "Glob", "Grep"], # Built-in Claude tools (strings only)
max_turns=10,
)
# With config
reviewer = Agent(
name="reviewer",
model=ClaudeCode("opus", permission_mode=ClaudeCode.PermissionMode.ACCEPT_EDITS),
instructions="Review code.",
tools=["Read", "Edit", "Bash"],
)Code execution
Agent(
name="data_scientist",
model="openai/gpt-4o",
instructions="Write and run Python code.",
local_code_execution=True,
allowed_languages=["python"],
)Framework integration
# LangGraph
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI
graph = create_react_agent(ChatOpenAI(model="gpt-4o"), tools=[my_tool])
with AgentRuntime() as rt:
result = rt.run(graph, "What is 15 * 7?")
# OpenAI Agents SDK
from agents import Agent as OpenAIAgent
agent = OpenAIAgent(name="helper", instructions="...", model="gpt-4o")
with AgentRuntime() as rt:
result = rt.run(agent, "Hello")AgentResult reference
result = rt.run(agent, "prompt")
result.output # Dict: {"result": "..."} or structured output
result.output["result"] # The text output (string)
result.status # "COMPLETED", "FAILED", "TERMINATED", "TIMED_OUT"
result.execution_id # Execution ID
result.error # Error message if failed, else None
result.token_usage # {"input_tokens": N, "output_tokens": N}
result.finish_reason # "stop", "length", "error", "cancelled", "timeout", "guardrail"
result.is_success # True if COMPLETED
result.is_failed # True if FAILED/TERMINATED
result.sub_results # List of sub-agent results (multi-agent)
result.print_result() # Pretty-print outputOutput formatting
- Present agent results as structured summaries: execution_id, status, output, token_usage.
- For executions, show a table with execution_id, agent_name, status, start_time.
- On failures, include the error message, failed task, and finish_reason.
- Never echo credentials or secrets in output.
Troubleshooting
- CLI not found: Install via
npm install -g @agentspan-ai/agentspan, or usepip install agentspanfor SDK-only. - Connection refused: Verify
AGENTSPAN_SERVER_URLis correct and server is running. Tryagentspan doctor. - 401 Unauthorized: Run
agentspan configurewith correct credentials. - Missing credentials: Store with
agentspan credentials set KEY value. Agent getsFAILED_WITH_TERMINAL_ERRORif credential is missing. - Tool schema errors: Ensure tool functions have type hints and docstrings.
- Agent name collision: Agent names must be unique. Check with
agentspan agent list. - Docs: https://github.com/agentspan-ai/agentspan
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

