claudestream 0.7.7 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +251 -0
- package/package.json +1 -1
package/README.md
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
<!-- Auto-generated by selfdoc from docs/_README.md — do not edit -->
|
|
2
|
+
|
|
3
|
+
# claudestream
|
|
4
|
+
|
|
5
|
+
A Python library and CLI for streaming Claude Code's JSON protocol
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
uv pip install claudestream
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick start
|
|
14
|
+
|
|
15
|
+
### One-shot ask
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from claudestream import SessionConfig, SyncSession
|
|
19
|
+
|
|
20
|
+
config = SessionConfig(model="sonnet", profile="default")
|
|
21
|
+
with SyncSession(config) as session:
|
|
22
|
+
result = session.ask("What is 2 + 2?")
|
|
23
|
+
print(result.text)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
### Streaming events
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from claudestream import SessionConfig, SyncSession, AssistantText, ToolUse, Result
|
|
30
|
+
|
|
31
|
+
config = SessionConfig(model="sonnet", profile="default")
|
|
32
|
+
with SyncSession(config) as session:
|
|
33
|
+
for event in session.send("List the files in the current directory"):
|
|
34
|
+
if isinstance(event, AssistantText):
|
|
35
|
+
print(event.text, end="")
|
|
36
|
+
elif isinstance(event, ToolUse):
|
|
37
|
+
print(f"\n[tool: {event.name}]")
|
|
38
|
+
elif isinstance(event, Result):
|
|
39
|
+
print(f"\n(cost: ${event.total_cost_usd:.4f})")
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### Async session
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import asyncio
|
|
46
|
+
from claudestream import SessionConfig, AsyncSession, AssistantText
|
|
47
|
+
|
|
48
|
+
async def main():
|
|
49
|
+
config = SessionConfig(model="sonnet", profile="default")
|
|
50
|
+
async with AsyncSession(config) as session:
|
|
51
|
+
async for event in session.send("Hello!"):
|
|
52
|
+
if isinstance(event, AssistantText):
|
|
53
|
+
print(event.text, end="")
|
|
54
|
+
|
|
55
|
+
asyncio.run(main())
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Multi-turn conversation
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from claudestream import SessionConfig, SyncSession, AssistantText
|
|
62
|
+
|
|
63
|
+
config = SessionConfig(model="sonnet", profile="default")
|
|
64
|
+
with SyncSession(config) as session:
|
|
65
|
+
for event in session.send("Remember that my name is Alice."):
|
|
66
|
+
if isinstance(event, AssistantText):
|
|
67
|
+
print(event.text, end="")
|
|
68
|
+
print()
|
|
69
|
+
for event in session.send("What is my name?"):
|
|
70
|
+
if isinstance(event, AssistantText):
|
|
71
|
+
print(event.text, end="")
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Custom tools
|
|
75
|
+
|
|
76
|
+
Define tools with the `@tool` decorator. claudestream auto-generates JSON Schema from type hints and serves them via MCP.
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from claudestream import tool, collect_tools, SessionConfig, SyncSession, AssistantText
|
|
80
|
+
|
|
81
|
+
@tool("my_server")
|
|
82
|
+
def lookup_weather(city: str, units: str = "celsius") -> str:
|
|
83
|
+
"""Look up current weather for a city.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
city: City name to look up.
|
|
87
|
+
units: Temperature units, celsius or fahrenheit.
|
|
88
|
+
"""
|
|
89
|
+
return f"22 degrees {units} in {city}"
|
|
90
|
+
|
|
91
|
+
config = SessionConfig(
|
|
92
|
+
model="sonnet",
|
|
93
|
+
profile="default",
|
|
94
|
+
tools=[lookup_weather._tool],
|
|
95
|
+
)
|
|
96
|
+
with SyncSession(config) as session:
|
|
97
|
+
for event in session.send("What's the weather in Paris?"):
|
|
98
|
+
if isinstance(event, AssistantText):
|
|
99
|
+
print(event.text, end="")
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Agents
|
|
103
|
+
|
|
104
|
+
Agents are JSON-defined configurations with prompt templates, tool schemas, sandbox policies, and budget limits.
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from claudestream import (
|
|
108
|
+
load_agent, invoke_agent_sync, SessionConfig, AssistantText,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
agent = load_agent("code_reviewer") # loads .claudestream/agents/code_reviewer.agent.json
|
|
112
|
+
config = SessionConfig(model="sonnet", profile="default")
|
|
113
|
+
|
|
114
|
+
with invoke_agent_sync(agent, config, variables={"file": "main.py"}) as session:
|
|
115
|
+
for event in session.send("Review this file"):
|
|
116
|
+
if isinstance(event, AssistantText):
|
|
117
|
+
print(event.text, end="")
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
## Sandbox policies
|
|
121
|
+
|
|
122
|
+
Restrict which tools Claude can use and which paths it can write to.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from claudestream import create_sandbox, SessionConfig, SyncSession
|
|
126
|
+
|
|
127
|
+
sandbox = create_sandbox(
|
|
128
|
+
tools=["Read", "Bash"],
|
|
129
|
+
write_paths=["/home/user/project"],
|
|
130
|
+
)
|
|
131
|
+
config = SessionConfig(model="sonnet", profile="default", sandbox=sandbox)
|
|
132
|
+
|
|
133
|
+
with SyncSession(config) as session:
|
|
134
|
+
result = session.ask("Read the README and summarize it")
|
|
135
|
+
print(result.text)
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
## CLI
|
|
139
|
+
|
|
140
|
+
| Command | Description |
|
|
141
|
+
| --- | --- |
|
|
142
|
+
| `send` | Send a prompt and display the response |
|
|
143
|
+
| `stream` | Stream a prompt with real-time token output |
|
|
144
|
+
| `events` | Debug: show all raw protocol events |
|
|
145
|
+
| `repl` | Interactive multi-turn REPL |
|
|
146
|
+
| `ask` | Send a prompt and print the response text |
|
|
147
|
+
| `doctor` | Check claudestream environment health |
|
|
148
|
+
| `config` | Show resolved configuration |
|
|
149
|
+
| **agent** | Manage and run agents defined in .agent.json files. Agent definitions declare a model, prompt template, allowed tools with input schemas, sandbox permissions, and budget limits (cost, turns, tokens). Use subcommands to validate configurations, run agents against prompts, and inspect metadata. |
|
|
150
|
+
| `agent run` | Load an agent definition and run it with the given prompt. Accepts a path to a .agent.json file or a bare agent name (resolved from .claudestream/agents/). The definition specifies the model, a prompt template with {variable} placeholders, tool schemas, sandbox policy, and budget constraints. Use --var key=value to substitute template variables. Use --model to override the model declared in the definition. |
|
|
151
|
+
| `agent list` | List available agents from .claudestream/agents/. Scans the agents directory in the working directory (or the directory specified by --cwd) and prints a table with each agent's name, schema version, and description. Use this to discover which agents are configured before running one with 'agent run'. |
|
|
152
|
+
| `agent info` | Display agent definition details for a given agent name or path. Loads the .agent.json file, parses it, and prints every configured field: name, version, description, model, budget limits, sandbox policy, tool schemas, MCP server config, and stream options. Use this to inspect an agent's full configuration before invoking it. |
|
|
153
|
+
| `agent validate` | Validate an agent definition by loading and checking its .agent.json file for structural and semantic correctness. Verifies that budget values are non-negative, the prompt template is non-empty, tool schemas are well-formed, and required fields are present. Reports specific errors on failure or prints a success confirmation. |
|
|
154
|
+
|
|
155
|
+
## Configuration
|
|
156
|
+
|
|
157
|
+
| Field | Type | Default | Description |
|
|
158
|
+
| --- | --- | --- | --- |
|
|
159
|
+
| `model` | `str` | | Claude model identifier (e.g. "claude-sonnet-4-20250514") |
|
|
160
|
+
| `profile` | `str` | | Claude Code profile name (e.g. "work", "personal") |
|
|
161
|
+
| `cwd` | `str | None` | `None` | Working directory for the Claude Code process; None uses current dir |
|
|
162
|
+
| `binary` | `str | None` | `None` | Path to the Claude CLI binary; None uses PATH lookup |
|
|
163
|
+
| `sandbox` | `Sandbox | None` | `None` | Tool/filesystem sandbox policy; None means no restrictions |
|
|
164
|
+
| `system_prompt` | `str | None` | `None` | Custom system prompt to prepend to the session |
|
|
165
|
+
| `tools` | `list[Tool] | None` | `None` | User-defined tools served via MCP to Claude Code |
|
|
166
|
+
| `extra_args` | `list[str] | None` | `None` | Additional raw CLI arguments passed to the process |
|
|
167
|
+
| `env` | `dict[str, str] | None` | `None` | Extra environment variables for the subprocess |
|
|
168
|
+
| `resume_session_id` | `str | None` | `None` | Session ID to resume; None starts a new session |
|
|
169
|
+
| `session_resolution` | `SessionResolution | None` | `None` | Session lookup/resume/fork strategy |
|
|
170
|
+
| `debug` | `DebugOptions | None` | `None` | Debug output configuration |
|
|
171
|
+
| `mcp` | `McpOptions | None` | `None` | External MCP server configuration |
|
|
172
|
+
| `plugins` | `PluginOptions | None` | `None` | Plugin loading paths and URLs |
|
|
173
|
+
| `stream` | `StreamOptions | None` | `None` | Controls which events appear in the output stream |
|
|
174
|
+
| `process_limits` | `ProcessLimits | None` | `None` | Subprocess buffer/timeout tuning |
|
|
175
|
+
| `budget` | `Budget | None` | `None` | Cost, turn, and token limits for the session |
|
|
176
|
+
| `poll_timeout` | `float` | `1.0` | Seconds between event queue polls in SyncSession |
|
|
177
|
+
| `join_timeout` | `float` | `5.0` | Seconds to wait for the background thread on SyncSession close |
|
|
178
|
+
| `effort` | `str | None` | `None` | Model reasoning effort level (e.g. "low", "medium", "high") |
|
|
179
|
+
| `json_schema` | `dict | None` | `None` | JSON Schema to constrain model output format |
|
|
180
|
+
| `fallback_model` | `str | None` | `None` | Model to fall back to if the primary model is unavailable |
|
|
181
|
+
| `betas` | `list[str] | None` | `None` | Beta feature flags to enable in the session |
|
|
182
|
+
| `add_dirs` | `list[str] | None` | `None` | Additional directories to include in the session context |
|
|
183
|
+
| `builtin_tools` | `list[str] | None` | `None` | Built-in tool names to enable (e.g. "computer") |
|
|
184
|
+
| `brief` | `bool` | `False` | Produce shorter, more concise model responses |
|
|
185
|
+
| `settings` | `str | None` | `None` | Path to a custom settings file |
|
|
186
|
+
| `setting_sources` | `str | None` | `None` | Comma-separated setting source override |
|
|
187
|
+
| `file_specs` | `list[str] | None` | `None` | Files to attach to the session context |
|
|
188
|
+
| `agent_name` | `str | None` | `None` | Built-in agent name to activate in Claude Code |
|
|
189
|
+
| `agents_json` | `str | None` | `None` | Path to a custom agents JSON configuration file |
|
|
190
|
+
| `hooks` | `dict | None` | `None` | Hook definitions for lifecycle events (e.g. pre-tool-use) |
|
|
191
|
+
| `no_persistence` | `bool` | `False` | Disable session persistence so nothing is saved to disk |
|
|
192
|
+
| `from_pr` | `str | None` | `None` | GitHub PR identifier to load as session context |
|
|
193
|
+
| `tool_context` | `Any` | `None` | Object injected into tool handlers via the inject mechanism |
|
|
194
|
+
|
|
195
|
+
## Sandbox fields
|
|
196
|
+
|
|
197
|
+
| Field | Type | Default | Description |
|
|
198
|
+
| --- | --- | --- | --- |
|
|
199
|
+
| `tools` | `list[str] | None` | `None` | Tool allow-list; None means all tools allowed |
|
|
200
|
+
| `bare` | `bool` | `False` | Suppress CLAUDE.md loading (passes --bare) |
|
|
201
|
+
| `write_paths` | `list[str] | None` | `None` | Allowed paths for Write/Edit/MultiEdit; None means unrestricted |
|
|
202
|
+
| `log_violations` | `bool` | `False` | Log denied tool calls at WARNING level |
|
|
203
|
+
| `skip_permissions` | `bool` | `False` | Bypass all permission prompts (passes --dangerously-skip-permissions) |
|
|
204
|
+
|
|
205
|
+
## Dependencies
|
|
206
|
+
|
|
207
|
+
| Package | Version Constraint |
|
|
208
|
+
| --- | --- |
|
|
209
|
+
| `strictcli` | * |
|
|
210
|
+
| `msgspec` | * |
|
|
211
|
+
| `selfdoc` | * |
|
|
212
|
+
| `claudewheel` | * |
|
|
213
|
+
|
|
214
|
+
## Modules
|
|
215
|
+
|
|
216
|
+
- **claudestream** (`claudestream/__init__.py`): A Python library and CLI for streaming Claude Code's JSON protocol, providing typed events, async/sync sessions, and tool registration.
|
|
217
|
+
- **claudestream._agent** (`claudestream/_agent.py`): Agent definition loader and budget enforcement for Claude Code sessions, with sync and async context managers for invoking agents.
|
|
218
|
+
- **claudestream._async_session** (`claudestream/_async_session.py`): Async session manager for the Claude Code stream-json protocol, handling process lifecycle, event parsing, and permission callbacks.
|
|
219
|
+
- **claudestream._cli** (`claudestream/_cli.py`): Command-line interface entry point for claudestream, providing send, listen, and agent commands for interacting with Claude Code.
|
|
220
|
+
- **claudestream._color** (`claudestream/_color.py`): ANSI color output support with automatic TTY detection, NO_COLOR environment variable compliance, and a reusable Colorizer class.
|
|
221
|
+
- **claudestream._options** (`claudestream/_options.py`): Option structs for configuring claudestream sessions, covering session resolution, debug, MCP, plugins, stream output, process limits, budget, tool sche...
|
|
222
|
+
- **claudestream._process** (`claudestream/_process.py`): Subprocess management for launching and monitoring the Claude Code CLI process, including graceful shutdown and atexit cleanup.
|
|
223
|
+
- **claudestream._protocol** (`claudestream/_protocol.py`): NDJSON protocol layer that reads raw Claude Code stream-json output lines and decodes them into typed Event objects for consumption.
|
|
224
|
+
- **claudestream._sync_session** (`claudestream/_sync_session.py`): Synchronous session wrapper that bridges the async Claude Code stream-json protocol to a blocking iterator-based interface.
|
|
225
|
+
- **claudestream._tools** (`claudestream/_tools.py`): Tool registration API providing the Tool struct and a decorator for defining user tools that are served via MCP to Claude Code.
|
|
226
|
+
- **claudestream.events** (`claudestream/events.py`): Typed event dataclasses for every Claude Code stream output event, including assistant messages, tool use, permissions, and results.
|
|
227
|
+
- **claudestream.messages** (`claudestream/messages.py`): Typed message structs for all Claude Code stream input messages, including user prompts, tool results, and permission responses.
|
|
228
|
+
- **claudestream.policy** (`claudestream/policy.py`): Sandbox and permission policy types for Claude Code sessions, defining allow, deny, and approval rules for tool execution requests.
|
|
229
|
+
|
|
230
|
+
## Project layout
|
|
231
|
+
|
|
232
|
+
```
|
|
233
|
+
claudestream/
|
|
234
|
+
├── __init__.py
|
|
235
|
+
├── _agent.py
|
|
236
|
+
├── _async_session.py
|
|
237
|
+
├── _cli.py
|
|
238
|
+
├── _color.py
|
|
239
|
+
├── _options.py
|
|
240
|
+
├── _process.py
|
|
241
|
+
├── _protocol.py
|
|
242
|
+
├── _sync_session.py
|
|
243
|
+
├── _tools.py
|
|
244
|
+
├── events.py
|
|
245
|
+
├── messages.py
|
|
246
|
+
└── policy.py
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
## License
|
|
250
|
+
|
|
251
|
+
MIT
|