1use std::collections::{BTreeMap, VecDeque};
9use std::pin::Pin;
10use std::task::{Context, Poll};
11
12use bytes::Bytes;
13use futures_core::Stream;
14use futures_util::StreamExt;
15use futures_util::stream::{self, BoxStream};
16use reqwest::Method;
17use serde::{Deserialize, Serialize};
18use serde_json::Value;
19
20use crate::{Error, SseDecoder};
21
22mod discovery;
23mod resources;
24mod session;
25pub use discovery::*;
26pub use resources::*;
27pub use session::*;
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ServeDialect {
38 Preview1x,
40 Native2x,
42}
43
44#[derive(Clone)]
46pub struct Client {
47 inner: crate::Client,
48 directory: Option<String>,
49 workspace_id: Option<String>,
50 dialect: std::sync::OnceLock<ServeDialect>,
51}
52
53#[derive(Default)]
54pub struct ClientBuilder {
55 inner: crate::ClientBuilder,
56 directory: Option<String>,
57 workspace_id: Option<String>,
58}
59
60impl Client {
61 pub fn builder() -> ClientBuilder {
62 ClientBuilder::default()
63 }
64
65 pub(crate) fn from_current(client: crate::Client) -> Self {
66 let directory = client.configured_directory().map(str::to_owned);
67 let workspace_id = client.configured_workspace().map(str::to_owned);
68 Self {
69 inner: client,
70 directory,
71 workspace_id,
72 dialect: std::sync::OnceLock::new(),
73 }
74 }
75
76 pub fn session(&self) -> SessionApi<'_> {
77 SessionApi { client: self }
78 }
79
80 pub fn events(&self) -> EventsApi<'_> {
81 EventsApi { client: self }
82 }
83
84 pub async fn serve_dialect(&self) -> Result<ServeDialect, Error> {
91 if let Some(dialect) = self.dialect.get() {
92 return Ok(*dialect);
93 }
94 let response = self
95 .inner
96 .request_base(Method::GET, "api/info")?
97 .send()
98 .await?;
99 let dialect = match response.status().is_success() {
100 true => match response.json::<Value>().await {
101 Ok(info) if info.get("version").is_some() => ServeDialect::Native2x,
102 _ => ServeDialect::Preview1x,
103 },
104 false => ServeDialect::Preview1x,
105 };
106 let _ = self.dialect.set(dialect);
107 Ok(dialect)
108 }
109}
110
111impl From<crate::Client> for Client {
112 fn from(client: crate::Client) -> Self {
113 Self::from_current(client)
114 }
115}
116
117impl ClientBuilder {
118 pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
119 self.inner = self.inner.base_url(base_url);
120 self
121 }
122
123 pub fn http_client(mut self, client: reqwest::Client) -> Self {
124 self.inner = self.inner.http_client(client);
125 self
126 }
127
128 pub fn directory(mut self, directory: impl Into<String>) -> Self {
130 self.directory = Some(directory.into());
131 self
132 }
133
134 pub fn workspace_id(mut self, workspace_id: impl Into<String>) -> Self {
136 self.workspace_id = Some(workspace_id.into());
137 self
138 }
139
140 pub fn basic_auth(mut self, username: impl Into<String>, password: impl Into<String>) -> Self {
141 self.inner = self.inner.basic_auth(username, password);
142 self
143 }
144
145 pub fn password(mut self, password: impl Into<String>) -> Self {
146 self.inner = self.inner.password(password);
147 self
148 }
149
150 pub fn build(self) -> Result<Client, Error> {
151 Ok(Client {
152 inner: self.inner.build()?,
153 directory: self.directory,
154 workspace_id: self.workspace_id,
155 dialect: std::sync::OnceLock::new(),
156 })
157 }
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
161#[serde(rename_all = "camelCase")]
162pub struct LocationRef {
163 pub directory: String,
164 #[serde(
165 default,
166 skip_serializing_if = "Option::is_none",
167 rename = "workspaceID"
168 )]
169 pub workspace_id: Option<String>,
170}
171
172#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
173#[serde(rename_all = "camelCase")]
174pub struct ModelRef {
175 pub id: String,
176 #[serde(rename = "providerID")]
177 pub provider_id: String,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub variant: Option<String>,
180}
181
182#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
183#[serde(rename_all = "camelCase")]
184pub struct Session {
185 pub id: String,
186 #[serde(default, rename = "parentID")]
187 pub parent_id: Option<String>,
188 #[serde(rename = "projectID")]
189 pub project_id: String,
190 #[serde(default)]
191 pub agent: Option<String>,
192 #[serde(default)]
193 pub model: Option<ModelRef>,
194 pub cost: f64,
195 pub tokens: TokenUsage,
196 pub time: SessionTime,
197 #[serde(default)]
199 pub title: Option<String>,
200 pub location: LocationRef,
201 #[serde(default)]
202 pub subpath: Option<String>,
203 #[serde(default)]
204 pub revert: Option<Value>,
205 #[serde(flatten)]
206 pub extra: BTreeMap<String, Value>,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
210pub struct TokenUsage {
211 pub input: u64,
212 pub output: u64,
213 pub reasoning: u64,
214 pub cache: CacheUsage,
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
218pub struct CacheUsage {
219 pub read: u64,
220 pub write: u64,
221}
222
223#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
224pub struct SessionTime {
225 pub created: u64,
226 pub updated: u64,
227 #[serde(default)]
228 pub archived: Option<u64>,
229}
230
231#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
232pub struct Cursor {
233 #[serde(default)]
234 pub previous: Option<String>,
235 #[serde(default)]
236 pub next: Option<String>,
237}
238
239#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
240pub struct SessionPage {
241 pub data: Vec<Session>,
242 pub cursor: Cursor,
243}
244
245#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
246#[serde(rename_all = "lowercase")]
247pub enum Order {
248 Asc,
249 Desc,
250}
251
252#[derive(Debug, Clone, Default, Serialize)]
253pub struct ListSessionsOptions {
254 #[serde(skip_serializing_if = "Option::is_none")]
255 pub workspace: Option<String>,
256 #[serde(skip_serializing_if = "Option::is_none")]
257 pub limit: Option<u32>,
258 #[serde(skip_serializing_if = "Option::is_none")]
259 pub order: Option<Order>,
260 #[serde(skip_serializing_if = "Option::is_none")]
261 pub search: Option<String>,
262 #[serde(skip_serializing_if = "Option::is_none")]
263 pub directory: Option<String>,
264 #[serde(skip_serializing_if = "Option::is_none")]
265 pub project: Option<String>,
266 #[serde(skip_serializing_if = "Option::is_none")]
267 pub subpath: Option<String>,
268 #[serde(skip_serializing_if = "Option::is_none")]
269 pub cursor: Option<String>,
270}
271
272#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
273#[serde(rename_all = "camelCase")]
274pub struct CreateSessionRequest {
275 #[serde(default, skip_serializing_if = "Option::is_none")]
276 pub id: Option<String>,
277 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub agent: Option<String>,
279 #[serde(default, skip_serializing_if = "Option::is_none")]
280 pub model: Option<ModelRef>,
281 #[serde(default, skip_serializing_if = "Option::is_none")]
282 pub location: Option<LocationRef>,
283}
284
285#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
286pub struct PromptSource {
287 pub start: u64,
288 pub end: u64,
289 pub text: String,
290}
291
292#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
293pub struct PromptFileAttachment {
294 pub uri: String,
295 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub name: Option<String>,
297 #[serde(default, skip_serializing_if = "Option::is_none")]
298 pub description: Option<String>,
299 #[serde(default, skip_serializing_if = "Option::is_none")]
300 pub source: Option<PromptSource>,
301}
302
303#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
304pub struct PromptAgentAttachment {
305 pub name: String,
306 #[serde(default, skip_serializing_if = "Option::is_none")]
307 pub source: Option<PromptSource>,
308}
309
310#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
311pub struct PromptInput {
312 pub text: String,
313 #[serde(default, skip_serializing_if = "Option::is_none")]
314 pub files: Option<Vec<PromptFileAttachment>>,
315 #[serde(default, skip_serializing_if = "Option::is_none")]
316 pub agents: Option<Vec<PromptAgentAttachment>>,
317}
318
319impl PromptInput {
320 pub fn text(text: impl Into<String>) -> Self {
321 Self {
322 text: text.into(),
323 files: None,
324 agents: None,
325 }
326 }
327}
328
329#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
330#[serde(rename_all = "lowercase")]
331pub enum Delivery {
332 Steer,
333 Queue,
334}
335
336#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
337pub struct PromptRequest {
338 #[serde(default, skip_serializing_if = "Option::is_none")]
339 pub id: Option<String>,
340 #[serde(default, skip_serializing_if = "Option::is_none")]
341 pub prompt: Option<PromptInput>,
342 #[serde(default, skip_serializing_if = "Option::is_none")]
343 pub delivery: Option<Delivery>,
344 #[serde(default, skip_serializing_if = "Option::is_none")]
345 pub resume: Option<bool>,
346}
347
348#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
349#[serde(rename_all = "camelCase")]
350pub struct SessionInputAdmitted {
351 #[serde(default)]
353 pub admitted_seq: Option<u64>,
354 pub id: String,
355 #[serde(rename = "sessionID")]
356 pub session_id: String,
357 pub prompt: Value,
359 pub delivery: Delivery,
360 pub time_created: u64,
361 #[serde(default)]
362 pub promoted_seq: Option<u64>,
363 #[serde(flatten)]
364 pub extra: BTreeMap<String, Value>,
365}
366
367impl SessionInputAdmitted {
368 pub fn from_wire(mut data: Value) -> Result<Self, serde_json::Error> {
373 let is_2x = data.get("type").and_then(Value::as_str) == Some("user")
374 && data.get("payload").is_some();
375 if is_2x {
376 if let Some(payload) = data.get("payload").cloned() {
377 data["prompt"] = payload;
378 }
379 if let Some(created) = data
380 .get("time")
381 .and_then(|time| time.get("created"))
382 .and_then(Value::as_u64)
383 {
384 data["timeCreated"] = created.into();
385 }
386 }
387 serde_json::from_value(data)
388 }
389}
390
391#[derive(Debug, Deserialize)]
392struct DataEnvelope<T> {
393 data: T,
394}
395
396pub struct SessionApi<'a> {
397 client: &'a Client,
398}
399
400impl SessionApi<'_> {
401 pub async fn list(&self, options: &ListSessionsOptions) -> Result<SessionPage, Error> {
402 let mut url = self.client.inner.url("api/session")?;
403 {
404 let mut query = url.query_pairs_mut();
405 if let Some(workspace) = options
406 .workspace
407 .as_deref()
408 .or(self.client.workspace_id.as_deref())
409 {
410 query.append_pair("workspace", workspace);
411 }
412 if let Some(limit) = options.limit {
413 query.append_pair("limit", &limit.to_string());
414 }
415 if let Some(order) = options.order {
416 query.append_pair(
417 "order",
418 match order {
419 Order::Asc => "asc",
420 Order::Desc => "desc",
421 },
422 );
423 }
424 if let Some(search) = options.search.as_deref() {
425 query.append_pair("search", search);
426 }
427 if let Some(directory) = options
428 .directory
429 .as_deref()
430 .or(self.client.directory.as_deref())
431 {
432 query.append_pair("directory", directory);
433 }
434 if let Some(project) = options.project.as_deref() {
435 query.append_pair("project", project);
436 }
437 if let Some(subpath) = options.subpath.as_deref() {
438 query.append_pair("subpath", subpath);
439 }
440 if let Some(cursor) = options.cursor.as_deref() {
441 query.append_pair("cursor", cursor);
442 }
443 }
444 let response = self
445 .client
446 .inner
447 .request_url(Method::GET, url)
448 .send()
449 .await?;
450 self.client.inner.decode(response).await
451 }
452
453 pub async fn create(&self, body: &CreateSessionRequest) -> Result<Session, Error> {
454 let mut body = body.clone();
455 if body.location.is_none()
456 && let Some(directory) = &self.client.directory
457 {
458 body.location = Some(LocationRef {
459 directory: directory.clone(),
460 workspace_id: self.client.workspace_id.clone(),
461 });
462 }
463 let response = self
464 .client
465 .inner
466 .request_base(Method::POST, "api/session")?
467 .json(&body)
468 .send()
469 .await?;
470 let envelope: DataEnvelope<Session> = self.client.inner.decode(response).await?;
471 Ok(envelope.data)
472 }
473
474 pub async fn get(&self, session_id: &str) -> Result<Session, Error> {
475 let response = self
476 .client
477 .inner
478 .request_base(Method::GET, &format!("api/session/{session_id}"))?
479 .send()
480 .await?;
481 let envelope: DataEnvelope<Session> = self.client.inner.decode(response).await?;
482 Ok(envelope.data)
483 }
484
485 pub async fn prompt(
486 &self,
487 session_id: &str,
488 body: &PromptRequest,
489 ) -> Result<SessionInputAdmitted, Error> {
490 let mut payload = serde_json::to_value(body).unwrap_or_default();
493 if let (Some(object), Some(prompt)) = (payload.as_object_mut(), body.prompt.as_ref()) {
494 object.insert("text".to_owned(), prompt.text.clone().into());
495 }
496 let response = self
497 .client
498 .inner
499 .request_base(Method::POST, &format!("api/session/{session_id}/prompt"))?
500 .json(&payload)
501 .send()
502 .await?;
503 let envelope: DataEnvelope<Value> = self.client.inner.decode(response).await?;
504 SessionInputAdmitted::from_wire(envelope.data).map_err(Error::from)
505 }
506
507 pub async fn wait(&self, session_id: &str) -> Result<(), Error> {
508 let path = match self.client.serve_dialect().await? {
509 ServeDialect::Preview1x => format!("api/session/{session_id}/wait"),
510 ServeDialect::Native2x => format!("api/experimental/session/{session_id}/wait"),
511 };
512 let response = self
513 .client
514 .inner
515 .request_base(Method::POST, &path)?
516 .send()
517 .await?;
518 self.client.inner.ensure_success(response).await
519 }
520
521 pub async fn interrupt(&self, session_id: &str) -> Result<(), Error> {
522 let response = self
523 .client
524 .inner
525 .request_base(Method::POST, &format!("api/session/{session_id}/interrupt"))?
526 .send()
527 .await?;
528 self.client.inner.ensure_success(response).await
529 }
530
531 pub async fn events(
539 &self,
540 session_id: &str,
541 after: Option<&str>,
542 ) -> Result<EventStream, Error> {
543 let dialect = self.client.serve_dialect().await?;
544 let path = match dialect {
545 ServeDialect::Preview1x => format!("api/session/{session_id}/event"),
546 ServeDialect::Native2x => "api/event".to_owned(),
547 };
548 let mut url = self.client.inner.url(&path)?;
549 if dialect == ServeDialect::Preview1x
550 && let Some(after) = after
551 {
552 url.query_pairs_mut().append_pair("after", after);
553 }
554 let response = self
555 .client
556 .inner
557 .request_url(Method::GET, url)
558 .send()
559 .await?;
560 if !response.status().is_success() {
561 self.client.inner.ensure_success(response).await?;
562 unreachable!();
563 }
564 Ok(event_stream_from_response(response))
565 }
566}
567
568pub struct EventsApi<'a> {
569 client: &'a Client,
570}
571
572impl EventsApi<'_> {
573 pub async fn subscribe(&self) -> Result<EventStream, Error> {
575 let response = self
576 .client
577 .inner
578 .request_base(Method::GET, "api/event")?
579 .send()
580 .await?;
581 if !response.status().is_success() {
582 self.client.inner.ensure_success(response).await?;
583 unreachable!();
584 }
585 Ok(event_stream_from_response(response))
586 }
587}
588
589#[derive(Debug, Clone, PartialEq, Eq)]
590pub struct Event {
591 pub id: Option<String>,
592 pub event: Option<String>,
593 pub data: String,
594}
595
596pub struct EventStream {
597 inner: BoxStream<'static, Result<Event, Error>>,
598}
599
600impl Stream for EventStream {
601 type Item = Result<Event, Error>;
602
603 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
604 Pin::new(&mut self.inner).poll_next(cx)
605 }
606}
607
608type ByteStream = BoxStream<'static, Result<Bytes, reqwest::Error>>;
609
610struct EventStreamState {
611 bytes: ByteStream,
612 decoder: SseDecoder,
613 queued: VecDeque<Event>,
614 finished: bool,
615}
616
617fn event_stream_from_response(response: reqwest::Response) -> EventStream {
618 let state = EventStreamState {
619 bytes: response.bytes_stream().boxed(),
620 decoder: SseDecoder::new(),
621 queued: VecDeque::new(),
622 finished: false,
623 };
624 let inner = stream::unfold(state, |mut state| async move {
625 loop {
626 if let Some(event) = state.queued.pop_front() {
627 return Some((Ok(event), state));
628 }
629 if state.finished {
630 return None;
631 }
632 match state.bytes.next().await {
633 Some(Ok(chunk)) => match state.decoder.push(&chunk) {
634 Ok(frames) => state.queued.extend(frames.into_iter().map(|frame| Event {
635 id: frame.id,
636 event: frame.event,
637 data: frame.data,
638 })),
639 Err(error) => return Some((Err(error), state)),
640 },
641 Some(Err(error)) => return Some((Err(Error::Http(error)), state)),
642 None => {
643 state.finished = true;
644 match state.decoder.finish() {
645 Ok(frames) => state.queued.extend(frames.into_iter().map(|frame| Event {
646 id: frame.id,
647 event: frame.event,
648 data: frame.data,
649 })),
650 Err(error) => return Some((Err(error), state)),
651 }
652 }
653 }
654 }
655 })
656 .boxed();
657 EventStream { inner }
658}