Skip to content

API Reference

agentshim

BaseAgentSession

Bases: ABC

Abstract base class for stateful coding-agent sessions.

generate(prompt, cwd=None, timeout=None, silent=None, on_process_started=None) abstractmethod

Send prompt within an existing chat session.

BaseCodingAgent

Bases: ABC

Abstract base class for coding agents.

backend_class_name property

Concrete backend class name.

readable_name property

Human-readable name for logs and UI.

generate(prompt, cwd=None, timeout=300, silent=False) abstractmethod

One-shot prompt → reply. Equivalent to a fresh start_session followed by a single session.generate(prompt); no conversation state is retained. Use start_session for multi-turn flows.

Parameters:

Name Type Description Default
prompt str

The prompt to send to the agent.

required
cwd str | None

Optional working directory context.

None
timeout int

Timeout in seconds.

300
silent bool

If True, suppress stdout printing of the agent's output.

False

Returns:

Type Description
str

Generated text.

start_session(cwd=None, timeout=300, silent=False)

Open a stateful session if supported by the backend.

CallbackCommandStreamSink dataclass

Command stream sink backed by callables.

This is a convenience adapter for callers that already have simple callback functions. Exceptions raised by on_started are ignored to preserve the historical best-effort process-start callback behavior.

ClaudeCodeCodingAgent

Bases: CLICodingAgent

Coding agent implementation using the Claude Code CLI tool.

claude_path property

Return path to claude binary (for backward compatibility).

__init__(model=None, event_handler=None, event_handlers=None, mcp_servers=None, sandbox=False, executor=None)

Initialize the Claude Code coding agent.

Parameters:

Name Type Description Default
model str | None

Optional model name to use with Claude Code. If None, uses default.

None
event_handler AgentEventHandler | None

Optional event handler for UI updates.

None
mcp_servers Sequence[McpServerConfig] | None

Optional list of MCP server configurations.

None
sandbox bool | SandboxConfig

If True (or a SandboxConfig), enable Claude Code's native sandbox (bubblewrap on Linux / Seatbelt on macOS) by injecting a sandbox settings block via --settings. Only bash subprocess commands are sandboxed; the Claude process itself is not wrapped. Defaults to False (no sandbox).

False
executor CommandExecutor | None

Optional command executor for binary lookup and process execution.

None

CodexCodingAgent

Bases: CLICodingAgent

Coding agent implementation using the Codex CLI tool.

codex_path property

Return path to codex binary (for backward compatibility).

__init__(model=None, event_handler=None, event_handlers=None, mcp_servers=None, sandbox=False, executor=None)

Initialize the Codex coding agent.

Parameters:

Name Type Description Default
model str | None

Optional model name to use with codex. If None, uses default.

None
event_handler AgentEventHandler | None

Optional event handler for UI updates.

None
mcp_servers Sequence[McpServerConfig] | None

Optional list of MCP server configurations.

None
sandbox bool | SandboxConfig

Not supported for Codex; must be False.

False
executor CommandExecutor | None

Optional command executor for binary lookup and process execution.

None

CodingAgent

Bases: BaseCodingAgent

Concrete provider-routing coding agent.

Construct with a provider name and shared options, and this facade will instantiate the appropriate registered backend internally.

backend property

Return the concrete backend instance.

CommandExecutor

Bases: Protocol

Controls binary lookup, validation, and streaming command execution.

Implement this protocol to run provider CLIs somewhere other than the local host process, such as inside an existing container or over a remote shell. agentshim still owns provider-specific command construction, stdout/stderr parsing, session state, usage accounting, and event handling.

check_binary(binary_path, env, *, timeout)

Validate the executable before the first command run.

Raise RuntimeError if the executable is unavailable or broken. Executors that cannot cheaply validate the target runtime may make this a no-op.

find_binary(binary_name, env)

Return the executable path/name to put in provider commands.

The returned value becomes CommandRequest.argv[0]. Host executors usually resolve an absolute path; container or remote executors may return the original binary name if lookup happens in the target runtime.

run(request, sink)

Run request and stream stdout/stderr into sink.

Implementations should:

  • call sink.started(handle) once the command is running
  • write request.stdin to the command's stdin and close it
  • call sink.stdout(line) and sink.stderr(line) for each line
  • honor request.cwd, request.env, and request.timeout
  • return a CommandResult after the command exits

CommandHandle

Bases: Protocol

Executor-neutral handle for a started command.

Executors pass a handle to :meth:CommandStreamSink.started immediately after the command has been launched. Callers can keep this handle to stop the command from outside the normal timeout path.

kill()

Forcefully stop the running command.

terminate()

Ask the running command to terminate.

CommandRequest dataclass

Inputs needed to run a provider CLI command.

Attributes:

Name Type Description
argv list[str]

Complete command argument vector. argv[0] is the provider binary path returned by :meth:CommandExecutor.find_binary.

stdin str

Prompt text to write to the command's standard input.

cwd str | None

Working directory for the command, or None to inherit the executor's default.

env dict[str, str]

Environment variables to use for the command.

timeout float | None

Maximum command runtime in seconds, or None for no timeout. Executors should raise subprocess.TimeoutExpired or an equivalent timeout error when this limit is exceeded.

CommandResult dataclass

Completed CLI command output.

stdout and stderr should contain the same text that was streamed through :class:CommandStreamSink. returncode follows subprocess.Popen.returncode conventions.

CommandStreamSink

Bases: Protocol

Receives command lifecycle and line-oriented output events.

Provider parsers consume these callbacks incrementally, so executors should call stdout and stderr as output becomes available. Lines should include their trailing newline when the underlying stream provided one, matching TextIO.readline behavior.

started(handle)

Called once, immediately after the command has started.

stderr(line)

Called for each stderr line.

stdout(line)

Called for each stdout line.

CompositeEventHandler

Dispatch every event to a sequence of handlers in order.

ConsoleEventHandler

Default terminal renderer for agent events.

Console output is intentionally implemented as an event handler so callers can replace it or explicitly compose it with their own handlers.

bind_context(*, logger, log_prefix)

Bind session defaults when the caller did not configure them.

CopilotCodingAgent

Bases: CLICodingAgent

Coding agent implementation using the GitHub Copilot CLI tool.

copilot_path property

Return path to copilot binary (for backward compatibility).

GeminiCodingAgent

Bases: CLICodingAgent

Coding agent implementation using the Gemini CLI tool.

gemini_path property

Return path to gemini binary (for backward compatibility).

__init__(model=None, event_handler=None, event_handlers=None, mcp_servers=None, sandbox=False, executor=None)

Initialize the Gemini coding agent.

Parameters:

Name Type Description Default
model str | None

Optional model name to use.

None
event_handler AgentEventHandler | None

Optional event handler for UI updates.

None
mcp_servers Sequence[object] | None

Optional list of MCP server configurations.

None
sandbox bool | SandboxConfig

Not supported for Gemini; must be False.

False
executor CommandExecutor | None

Optional command executor for binary lookup and process execution.

None

Raises:

Type Description
ValueError

If mcp_servers is non-empty (not supported).

NotImplementedError

If sandbox is truthy.

HostCommandExecutor

Default executor that runs commands on the host via subprocess.

The host executor uses line-buffered text pipes, streams stdout and stderr from separate reader threads, starts commands in a new process group, and kills the process group when a timeout or forced cleanup occurs.

HttpMcpServer

Bases: BaseModel

MCP server accessed over HTTP/SSE.

NullEventHandler

Event handler that intentionally ignores every event.

OpencodeCodingAgent

Bases: CLICodingAgent

Coding agent implementation using the Opencode CLI tool.

__init__(model=None, event_handler=None, event_handlers=None, mcp_servers=None, sandbox=False, executor=None)

Initialize the Opencode coding agent.

Parameters:

Name Type Description Default
model str | None

Optional model name to use.

None
event_handler AgentEventHandler | None

Optional event handler for UI updates.

None
mcp_servers Sequence[object] | None

Optional list of MCP server configurations.

None
sandbox bool | SandboxConfig

Not supported for Opencode; must be False.

False
executor CommandExecutor | None

Optional command executor for binary lookup and process execution.

None

Raises:

Type Description
ValueError

If mcp_servers is non-empty (not supported).

NotImplementedError

If sandbox is truthy.

SandboxConfig dataclass

Claude Code sandbox configuration.

Fields mirror a subset of the sandbox key in Claude Code's settings.json. Only the knobs we actually need are exposed; pass additional keys through extra_settings if you need something not modeled here.

Attributes:

Name Type Description
fail_if_unavailable bool

If True, Claude exits with an error when the sandbox can't start (missing bwrap, unsupported platform) instead of silently falling back to unsandboxed execution. Recommended to keep True so sandbox behavior is a hard gate.

auto_allow_bash bool

If True, sandboxed bash commands are auto-approved without permission prompts (they're already constrained by the sandbox).

allow_unsandboxed_commands bool

If False, disables the dangerouslyDisableSandbox escape hatch entirely.

excluded_commands list[str]

Commands that should run outside the sandbox (e.g. ["docker *"]).

allow_write list[str]

Extra paths where sandboxed commands may write (cwd is always writable by default).

deny_write list[str]

Paths sandboxed commands must not write to.

allow_read list[str]

Paths to re-allow inside deny_read regions.

deny_read list[str]

Paths sandboxed commands must not read.

allowed_domains list[str]

Outbound network domains allowed for bash subprocesses (e.g. ["github.com", "*.npmjs.org"]). Does not affect Claude's own API calls.

extra_settings dict[str, Any]

Raw dict merged into the sandbox settings block, for fields not covered above.

StdioMcpServer

Bases: BaseModel

MCP server launched as a subprocess (stdio transport).

get_provider_class(name)

Resolve name to a registered provider class.

list_providers()

Return the sorted canonical provider names.

register_provider(canonical_name, *extra_names, aliases=(), overwrite=False)

Decorator to register a coding agent provider.

Registration is import-driven: the decorated class becomes available only after its defining module has been imported in the current process.

Parameters:

Name Type Description Default
canonical_name str

Stable provider id exposed by list_providers().

required
*extra_names str

Backward-compatible positional aliases.

()
aliases tuple[str, ...]

Additional aliases for the same provider.

()
overwrite bool

Whether to replace an existing registration for any name.

False