1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Client for streaming queries and multi-turn conversations
//!
//! This module provides the core streaming client implementation for the Open Agent SDK.
//! It handles communication with OpenAI-compatible and Anthropic messages endpoints,
//! selected per endpoint with [`ApiProtocol`](crate::ApiProtocol), manages conversation
//! history, and provides two modes of operation: manual and automatic tool execution.
//!
//! # Architecture Overview
//!
//! The SDK implements a **streaming-first architecture** where all responses from the model
//! are received as a stream of content blocks. This design enables:
//!
//! - **Progressive rendering**: Display text as it arrives without waiting for completion
//! - **Real-time tool execution**: Execute tools as they're requested by the model
//! - **Interruption support**: Cancel operations mid-stream without corrupting state
//! - **Memory efficiency**: Process large responses without buffering everything in memory
//!
//! ## Two Operating Modes
//!
//! ### 1. Manual Tool Execution Mode (default)
//!
//! In manual mode, the client streams content blocks directly to the caller. When the model
//! requests a tool, the caller receives a `ToolUseBlock`, executes the tool, adds the result
//! using `add_tool_result()`, and continues the conversation with another `send()` call.
//!
//! **Use cases**: Custom tool execution logic, interactive debugging, fine-grained control
//!
//! ### 2. Automatic Tool Execution Mode
//!
//! When `auto_execute_tools` is enabled, the client automatically executes tools and continues
//! the conversation until receiving a text-only response. The caller only receives the final
//! text blocks after all tool iterations complete.
//!
//! **Use cases**: Simple agentic workflows, automated task completion, batch processing
//!
//! ## Request Flow
//!
//! ```text
//! User sends prompt
//! │
//! ├─> UserPromptSubmit hook executes (can modify/block prompt)
//! │
//! ├─> Prompt added to history
//! │
//! ├─> HTTP request to the configured endpoint (OpenAI chat or Anthropic messages)
//! │
//! ├─> Response streamed as Server-Sent Events (SSE)
//! │
//! ├─> SSE chunks aggregated into ContentBlocks
//! │
//! └─> Blocks emitted to caller (or buffered for auto-execution)
//! ```
//!
//! ## Tool Execution Flow
//!
//! ### Manual Mode:
//! ```text
//! receive() → ToolUseBlock
//! │
//! ├─> Caller executes tool
//! │
//! ├─> Caller calls add_tool_result()
//! │
//! ├─> Caller calls send("") to continue
//! │
//! └─> receive() → TextBlock (model's response)
//! ```
//!
//! ### Auto Mode:
//! ```text
//! receive() triggers auto-execution loop
//! │
//! ├─> Collect all blocks from stream
//! │
//! ├─> For each ToolUseBlock:
//! │ ├─> PreToolUse hook executes (can modify/block)
//! │ ├─> Tool executed via Tool.execute()
//! │ ├─> PostToolUse hook executes (can modify result)
//! │ └─> Result added to history
//! │
//! ├─> Continue conversation with send("")
//! │
//! ├─> Repeat until text-only response or max iterations
//! │
//! └─> Return text blocks one-by-one via receive()
//! ```
//!
//! ## State Management
//!
//! The client maintains several pieces of state:
//!
//! - **history**: Full conversation history (`Vec<Message>`)
//! - **current_stream**: Active SSE stream being consumed (`Option<EventStream>`)
//! - **interrupted**: Atomic flag for cancellation (`Arc<AtomicBool>`)
//! - **auto_exec_buffer**: Buffered blocks for auto-execution mode (`Vec<ContentBlock>`)
//! - **auto_exec_index**: Current position in buffer (usize)
//!
//! ## Interruption Mechanism
//!
//! The interrupt system uses `Arc<AtomicBool>` to enable safe, thread-safe cancellation:
//!
//! ```rust,no_run
//! # use open_agent::{Client, AgentOptions};
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut client = Client::new(AgentOptions::default())?;
//! let handle = client.interrupt_handle(); // Clone Arc for use in other threads
//!
//! // In another thread or async task:
//! tokio::spawn(async move {
//! tokio::time::sleep(std::time::Duration::from_secs(5)).await;
//! handle.store(true, std::sync::atomic::Ordering::SeqCst);
//! });
//!
//! client.send("Long request").await?;
//! while let Some(block) = client.receive().await? {
//! // Will stop when interrupted
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Hook Integration
//!
//! Hooks provide extension points throughout the request lifecycle:
//!
//! - **UserPromptSubmit**: Called before sending user prompt (can modify or block)
//! - **PreToolUse**: Called before executing each tool (can modify input or block execution)
//! - **PostToolUse**: Called after tool execution (can modify result)
//!
//! Hooks are only invoked in specific scenarios and have access to conversation history.
//!
//! ## Error Handling
//!
//! Errors are propagated immediately and leave the client in a valid state:
//!
//! - **HTTP errors**: Network failures, timeouts, connection issues
//! - **API errors**: Invalid model, authentication failures, rate limits
//! - **Parse errors**: Malformed SSE responses, invalid JSON
//! - **Tool errors**: Tool execution failures (converted to JSON error responses)
//! - **Hook errors**: Hook execution failures or blocked operations
//!
//! After an error, the client remains usable for new requests.
//!
//! # Examples
//!
//! ## Simple Single-Turn Query
//!
//! ```rust,no_run
//! use open_agent::{query, AgentOptions, ContentBlock};
//! use futures::StreamExt;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let options = AgentOptions::builder()
//! .model("gpt-4")
//! .api_key("sk-...")
//! .build()?;
//!
//! let mut stream = query("What is Rust?", &options).await?;
//!
//! while let Some(event) = stream.next().await {
//! if let Some(ContentBlock::Text(text)) = event?.into_block() {
//! print!("{}", text.text);
//! }
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! ## Multi-Turn Conversation
//!
//! ```rust,no_run
//! use open_agent::{Client, AgentOptions, ContentBlock};
//! use futures::StreamExt;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut client = Client::new(AgentOptions::builder()
//! .model("gpt-4")
//! .api_key("sk-...")
//! .build()?)?;
//!
//! // First question
//! client.send("What's the capital of France?").await?;
//! while let Some(block) = client.receive().await? {
//! if let ContentBlock::Text(text) = block {
//! println!("{}", text.text);
//! }
//! }
//!
//! // Follow-up question (history is maintained)
//! client.send("What's its population?").await?;
//! while let Some(block) = client.receive().await? {
//! if let ContentBlock::Text(text) = block {
//! println!("{}", text.text);
//! }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Manual Tool Execution
//!
//! ```rust,no_run
//! use open_agent::{Client, AgentOptions, ContentBlock, Tool};
//! use serde_json::json;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let calculator = Tool::new(
//! "calculator",
//! "Performs arithmetic operations",
//! json!({"type": "object", "properties": {"operation": {"type": "string"}}}),
//! |input| Box::pin(async move {
//! // Custom execution logic
//! Ok(json!({"result": 42}))
//! })
//! );
//!
//! let mut client = Client::new(AgentOptions::builder()
//! .model("gpt-4")
//! .api_key("sk-...")
//! .tools(vec![calculator])
//! .build()?)?;
//!
//! client.send("Calculate 2+2").await?;
//!
//! while let Some(block) = client.receive().await? {
//! match block {
//! ContentBlock::ToolUse(tool_use) => {
//! println!("Model wants to use: {}", tool_use.name());
//!
//! // Execute tool manually
//! let tool = client.get_tool(tool_use.name()).unwrap();
//! let result = tool.execute(tool_use.input().clone()).await?;
//!
//! // Add result and continue
//! client.add_tool_result(tool_use.id(), result)?;
//! client.send("").await?;
//! }
//! ContentBlock::Text(text) => {
//! println!("Response: {}", text.text);
//! }
//! ContentBlock::ToolResult(_) | ContentBlock::Image(_) => {}
//! }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Automatic Tool Execution
//!
//! ```rust,no_run
//! use open_agent::{Client, AgentOptions, ContentBlock, Tool};
//! use serde_json::json;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let calculator = Tool::new(
//! "calculator",
//! "Performs arithmetic operations",
//! json!({"type": "object"}),
//! |input| Box::pin(async move { Ok(json!({"result": 42})) })
//! );
//!
//! let mut client = Client::new(AgentOptions::builder()
//! .model("gpt-4")
//! .api_key("sk-...")
//! .tools(vec![calculator])
//! .auto_execute_tools(true) // Enable auto-execution
//! .max_tool_iterations(5) // Max 5 tool rounds
//! .build()?)?;
//!
//! client.send("Calculate 2+2 and then multiply by 3").await?;
//!
//! // Tools are executed automatically - you only get final text response
//! while let Some(block) = client.receive().await? {
//! if let ContentBlock::Text(text) = block {
//! println!("{}", text.text);
//! }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## With Hooks
//!
//! ```ignore
//! use open_agent::{Client, AgentOptions, Hooks, HookDecision};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let hooks = Hooks::new()
//! .add_user_prompt_submit(|event| async move {
//! // Block prompts containing certain words
//! if event.prompt.contains("forbidden") {
//! return Some(HookDecision::block("Forbidden word detected"));
//! }
//! Some(HookDecision::continue_())
//! })
//! .add_pre_tool_use(|event| async move {
//! // Log all tool uses
//! println!("Executing tool: {}", event.tool_name);
//! Some(HookDecision::continue_())
//! });
//!
//! let mut client = Client::new(AgentOptions::builder()
//! .model("gpt-4")
//! .base_url("http://localhost:1234/v1")
//! .hooks(hooks)
//! .build()?)?;
//!
//! // Hooks will be executed automatically
//! client.send("Hello!").await?;
//! # Ok(())
//! # }
//! ```
use crate;
use crate;
use crate::;
use ;
use Pin;
use Arc;
use ;
use Duration;
/// The API version header every Anthropic messages request must carry.
///
/// A dated constant rather than a configurable field: it names the request/response schema
/// this SDK was written against, so it changes when the code does.
const ANTHROPIC_VERSION: &str = "2023-06-01";
/// Sends the request over whichever protocol `options` selects and returns its event stream.
///
/// The one place the two protocols differ. Both call sites build the same protocol-neutral
/// [`OpenAIRequest`]; the translation, the auth header and the streaming vocabulary are all
/// resolved here, so neither caller has to know which endpoint it is talking to.
async
include!;
include!;
include!;
include!;
include!;
include!;
include!;
include!;