use std::path::PathBuf;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;
use crate::{Result, observation, request, turn};
mod driver;
mod event;
pub use driver::Driver;
pub use event::{CloseReason, EVENT_FORMAT, Event};
#[derive(Clone)]
pub struct Session {
info: Info,
driver: Arc<dyn Driver>,
}
impl Session {
pub fn new(info: Info, driver: Arc<dyn Driver>) -> Self {
Self { info, driver }
}
pub fn id(&self) -> &str {
&self.info.summary.id
}
pub fn info(&self) -> &Info {
&self.info
}
pub fn subscribe(&self) -> broadcast::Receiver<Event> {
self.driver.subscribe()
}
pub fn subscribe_records(&self) -> Result<broadcast::Receiver<observation::Record>> {
self.driver.subscribe_records()
}
pub fn observation_capabilities(&self) -> Result<observation::Capabilities> {
self.driver.observation_capabilities()
}
pub async fn snapshot(&self) -> Result<observation::Snapshot> {
self.driver.snapshot().await
}
pub async fn stop_agent(&self, id: &str) -> Result<crate::observation::control::Receipt> {
self.driver.stop_agent(id).await
}
pub async fn stop_task(&self, id: &str) -> Result<crate::observation::control::Receipt> {
self.driver.stop_task(id).await
}
pub async fn task_output(
&self,
id: &str,
query: crate::observation::task::OutputQuery,
) -> Result<crate::observation::task::OutputPage> {
self.driver.task_output(id, query).await
}
pub async fn set_permissions(
&self,
configuration: crate::permission::Configuration,
) -> Result<()> {
self.driver.set_permissions(configuration).await
}
pub fn modes(&self) -> Result<Modes> {
self.driver.modes()
}
pub async fn set_mode(&self, mode_id: &str) -> Result<()> {
self.driver.set_mode(mode_id).await
}
pub async fn send(&self, input: turn::Input) -> Result<turn::Receipt> {
self.driver.send(input).await
}
pub async fn interrupt(&self, turn_id: &str) -> Result<()> {
self.driver.interrupt(turn_id).await
}
pub async fn respond(&self, request_id: &str, decision: request::Decision) -> Result<()> {
self.driver.respond(request_id, decision).await
}
pub async fn close(&self) -> Result<()> {
self.driver.close().await
}
}
impl std::fmt::Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session").field("info", &self.info).finish()
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Query {
pub cwd: Option<PathBuf>,
pub limit: Option<u32>,
pub cursor: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Page {
pub sessions: Vec<Summary>,
pub next_cursor: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Summary {
pub id: String,
pub provider: String,
pub title: Option<String>,
pub preview: String,
pub cwd: PathBuf,
pub model: Option<String>,
pub effort: Option<String>,
pub status: Status,
pub created_at: i64,
pub updated_at: i64,
pub source: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Fork {
pub at_turn: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum Status {
NotLoaded,
Idle,
Active,
Error,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Settings {
pub model: Option<String>,
pub effort: Option<String>,
pub fast_mode: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub permissions: Option<crate::permission::Configuration>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub forward_requests: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub additional_directories: Vec<std::path::PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Spec {
pub cwd: PathBuf,
#[serde(default)]
pub settings: Settings,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Info {
pub summary: Summary,
pub model: String,
pub effort: Option<String>,
pub fast_mode: bool,
pub cwd: PathBuf,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub permissions: Option<crate::permission::Info>,
pub approval_policy: Option<String>,
pub sandbox: Option<String>,
pub restored: bool,
pub persisted: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Modes {
pub current: String,
pub available: Vec<Mode>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Mode {
pub id: String,
pub name: String,
pub description: Option<String>,
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn events_serialize_with_camel_case_fields() {
let event = Event::ItemDelta {
turn_id: "u".into(),
item_id: "i".into(),
delta: turn::Delta::Text { text: "hi".into() },
};
assert_eq!(
serde_json::to_value(&event).unwrap(),
json!({ "type": "itemDelta", "turnId": "u", "itemId": "i", "delta": { "type": "text", "text": "hi" } })
);
let command = turn::ToolDetail::Command {
command: "ls".into(),
cwd: None,
output: None,
exit_code: Some(0),
};
assert_eq!(
serde_json::to_value(&command).unwrap()["exitCode"],
json!(0)
);
let fast = crate::catalog::FastMode::Available {
tier_id: "priority".into(),
label: "Fast".into(),
description: String::new(),
default_on: true,
};
assert_eq!(
serde_json::to_value(&fast).unwrap()["tierId"],
json!("priority")
);
}
#[test]
fn format_1_events_round_trip() {
let stored = [
json!({ "type": "status", "status": "active" }),
json!({ "type": "closed", "reason": { "type": "exited", "message": "boom" } }),
json!({ "type": "turnStart", "turnId": "t" }),
json!({ "type": "itemStart", "turnId": "t", "item": {
"type": "toolCall", "id": "c", "status": "inProgress", "durationMs": null,
"detail": { "kind": "command", "command": "ls", "cwd": null, "output": null, "exitCode": null }
} }),
json!({ "type": "itemDelta", "turnId": "t", "itemId": "m", "delta": { "type": "text", "text": "hi" } }),
json!({ "type": "itemEnd", "turnId": "t", "item": { "type": "agentMessage", "id": "m", "text": "hi" } }),
json!({ "type": "turnEnd", "turn": {
"id": "t", "status": "completed", "items": [], "startedAt": 1, "completedAt": 2,
"durationMs": 1000, "error": null
} }),
json!({ "type": "requestResolved", "id": "r", "outcome": {
"type": "answered", "decision": { "type": "deny", "message": null }
} }),
json!({ "type": "raw", "name": "x", "payload": { "a": 1 } }),
];
for json in stored {
let event: Event = serde_json::from_value(json.clone()).unwrap();
assert!(
!matches!(event, Event::Unknown(_)),
"{json} is a known event"
);
assert_eq!(serde_json::to_value(&event).unwrap(), json);
}
}
#[test]
fn newer_events_with_extra_fields_still_read() {
let event: Event = serde_json::from_value(json!({
"type": "turnStart", "turnId": "t", "agentId": "a", "v": 2
}))
.unwrap();
assert_eq!(
event,
Event::TurnStart {
turn_id: "t".into()
}
);
let event: Event = serde_json::from_value(json!({
"type": "itemEnd", "turnId": "t", "attachments": [],
"item": { "type": "agentMessage", "id": "m", "text": "hi", "phase": "final" }
}))
.unwrap();
assert_eq!(
event,
Event::ItemEnd {
turn_id: "t".into(),
item: turn::Item::AgentMessage {
id: "m".into(),
text: "hi".into()
},
}
);
}
#[test]
fn newer_event_types_and_values_read_as_unknown() {
let future = json!({ "type": "compaction", "turnId": "t", "tokens": 12 });
let event: Event = serde_json::from_value(future.clone()).unwrap();
assert_eq!(event, Event::Unknown(future.clone()));
assert_eq!(serde_json::to_value(&event).unwrap(), future);
let event: Event =
serde_json::from_value(json!({ "type": "status", "status": "sleeping" })).unwrap();
assert_eq!(
event,
Event::Status {
status: Status::Unknown
}
);
let event: Event = serde_json::from_value(json!({
"type": "closed", "reason": { "type": "evicted", "by": "x" }
}))
.unwrap();
assert!(matches!(
event,
Event::Closed {
reason: CloseReason::Unknown(_)
}
));
let item = json!({ "type": "webSearch", "id": "w", "query": "stubb" });
let event: Event =
serde_json::from_value(json!({ "type": "itemEnd", "turnId": "t", "item": item }))
.unwrap();
assert_eq!(
event,
Event::ItemEnd {
turn_id: "t".into(),
item: turn::Item::Unknown(item)
}
);
let event: Event = serde_json::from_value(json!({
"type": "itemEnd", "turnId": "t", "item": {
"type": "toolCall", "id": "c", "status": "queued", "durationMs": null,
"detail": { "kind": "browser", "url": "https://example.com" }
}
}))
.unwrap();
let Event::ItemEnd {
item: turn::Item::ToolCall(call),
..
} = event
else {
panic!("expected a tool call, got {event:?}");
};
assert_eq!(call.status, turn::ToolStatus::Unknown);
assert!(matches!(call.detail, turn::ToolDetail::Unknown(_)));
let event: Event = serde_json::from_value(json!({
"type": "itemDelta", "turnId": "t", "itemId": "i", "delta": { "type": "image", "data": "" }
}))
.unwrap();
assert!(matches!(
event,
Event::ItemDelta {
delta: turn::Delta::Unknown(_),
..
}
));
let event: Event = serde_json::from_value(json!({
"type": "turnEnd", "turn": { "id": "t", "status": "paused", "items": [] }
}))
.unwrap();
let Event::TurnEnd { turn } = event else {
panic!("expected a turn end, got {event:?}");
};
assert_eq!(turn.status, turn::Status::Unknown);
let event: Event = serde_json::from_value(json!({
"type": "request", "request": {
"id": "r", "turnId": null, "native": {}, "kind": { "type": "question", "text": "?" }
}
}))
.unwrap();
let Event::Request { request } = event else {
panic!("expected a request, got {event:?}");
};
assert!(matches!(request.kind, request::Kind::Unknown(_)));
}
}