forked from 1jehuang/jcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_api.rs
More file actions
302 lines (261 loc) · 9.2 KB
/
client_api.rs
File metadata and controls
302 lines (261 loc) · 9.2 KB
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
use super::{connect_socket, debug_socket_path, socket_path};
use crate::protocol::{HistoryMessage, Request, ServerEvent, TranscriptMode};
use crate::transport::{ReadHalf, WriteHalf};
use anyhow::Result;
use std::path::PathBuf;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
/// Client for connecting to a running server
pub struct Client {
reader: BufReader<ReadHalf>,
writer: WriteHalf,
next_id: u64,
}
impl Client {
pub async fn connect() -> Result<Self> {
Self::connect_with_path(socket_path()).await
}
pub async fn connect_with_path(path: PathBuf) -> Result<Self> {
let stream = connect_socket(&path).await?;
let (reader, writer) = stream.into_split();
Ok(Self {
reader: BufReader::new(reader),
writer,
next_id: 1,
})
}
pub async fn connect_debug() -> Result<Self> {
Self::connect_debug_with_path(debug_socket_path()).await
}
pub async fn connect_debug_with_path(path: PathBuf) -> Result<Self> {
let stream = connect_socket(&path).await?;
let (reader, writer) = stream.into_split();
Ok(Self {
reader: BufReader::new(reader),
writer,
next_id: 1,
})
}
/// Send a message and return immediately (events come via read_event)
pub async fn send_message(&mut self, content: &str) -> Result<u64> {
let id = self.next_id;
self.next_id += 1;
let request = Request::Message {
id,
content: content.to_string(),
images: vec![],
system_reminder: None,
};
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
Ok(id)
}
/// Subscribe to events
pub async fn subscribe(&mut self) -> Result<u64> {
self.subscribe_with_info(None, None, None, false, false)
.await
}
pub async fn subscribe_with_info(
&mut self,
working_dir: Option<String>,
selfdev: Option<bool>,
target_session_id: Option<String>,
client_has_local_history: bool,
allow_session_takeover: bool,
) -> Result<u64> {
let id = self.next_id;
self.next_id += 1;
let request = Request::Subscribe {
id,
working_dir,
selfdev,
target_session_id,
client_instance_id: None,
client_has_local_history,
allow_session_takeover,
};
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
Ok(id)
}
/// Read the next event from the server
pub async fn read_event(&mut self) -> Result<ServerEvent> {
let mut line = String::new();
let n = self.reader.read_line(&mut line).await?;
if n == 0 {
anyhow::bail!("Server disconnected");
}
let event: ServerEvent = serde_json::from_str(&line)?;
Ok(event)
}
pub async fn ping(&mut self) -> Result<bool> {
let id = self.next_id;
self.next_id += 1;
let request = Request::Ping { id };
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
loop {
let mut line = String::new();
let n = self.reader.read_line(&mut line).await?;
if n == 0 {
anyhow::bail!("Server disconnected");
}
let event: ServerEvent = serde_json::from_str(&line)?;
match event {
ServerEvent::Pong { id: pong_id } => return Ok(pong_id == id),
ServerEvent::Ack { id: ack_id } if ack_id == id => continue,
ServerEvent::Error { id: error_id, .. } if error_id == id => return Ok(false),
_ => return Ok(false),
}
}
}
pub async fn get_state(&mut self) -> Result<ServerEvent> {
let id = self.next_id;
self.next_id += 1;
let request = Request::GetState { id };
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
let mut line = String::new();
let n = self.reader.read_line(&mut line).await?;
if n == 0 {
anyhow::bail!("Server disconnected");
}
let event: ServerEvent = serde_json::from_str(&line)?;
Ok(event)
}
pub async fn clear(&mut self) -> Result<()> {
let id = self.next_id;
self.next_id += 1;
let request = Request::Clear { id };
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
Ok(())
}
pub async fn get_history(&mut self) -> Result<Vec<HistoryMessage>> {
let event = self.get_history_event().await?;
match event {
ServerEvent::History { messages, .. } => Ok(messages),
_ => Ok(Vec::new()),
}
}
pub async fn get_history_event(&mut self) -> Result<ServerEvent> {
let id = self.next_id;
self.next_id += 1;
let request = Request::GetHistory { id };
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
for _ in 0..10 {
let mut line = String::new();
let n = self.reader.read_line(&mut line).await?;
if n == 0 {
anyhow::bail!("Server disconnected");
}
let event: ServerEvent = serde_json::from_str(&line)?;
match event {
ServerEvent::Ack { .. } => continue,
_ => return Ok(event),
}
}
Ok(ServerEvent::Error {
id,
message: "History response not received".to_string(),
retry_after_secs: None,
})
}
pub async fn resume_session(&mut self, session_id: &str) -> Result<u64> {
self.resume_session_with_options(session_id, false, false)
.await
}
pub async fn resume_session_with_options(
&mut self,
session_id: &str,
client_has_local_history: bool,
allow_session_takeover: bool,
) -> Result<u64> {
let id = self.next_id;
self.next_id += 1;
let request = Request::ResumeSession {
id,
session_id: session_id.to_string(),
client_instance_id: None,
client_has_local_history,
allow_session_takeover,
};
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
Ok(id)
}
pub async fn notify_session(&mut self, session_id: &str, message: &str) -> Result<u64> {
let id = self.next_id;
self.next_id += 1;
let request = Request::NotifySession {
id,
session_id: session_id.to_string(),
message: message.to_string(),
};
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
Ok(id)
}
pub async fn send_transcript(
&mut self,
text: &str,
mode: TranscriptMode,
session_id: Option<String>,
) -> Result<u64> {
let id = self.next_id;
self.next_id += 1;
let request = Request::Transcript {
id,
text: text.to_string(),
mode,
session_id,
};
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
Ok(id)
}
pub async fn reload(&mut self) -> Result<()> {
let id = self.next_id;
self.next_id += 1;
let request = Request::Reload { id };
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
Ok(())
}
pub async fn cycle_model(&mut self, direction: i8) -> Result<u64> {
let id = self.next_id;
self.next_id += 1;
let request = Request::CycleModel { id, direction };
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
Ok(id)
}
pub async fn refresh_models(&mut self) -> Result<u64> {
let id = self.next_id;
self.next_id += 1;
let request = Request::RefreshModels { id };
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
Ok(id)
}
pub async fn notify_auth_changed(&mut self) -> Result<u64> {
let id = self.next_id;
self.next_id += 1;
let request = Request::NotifyAuthChanged { id };
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
Ok(id)
}
pub async fn debug_command(&mut self, command: &str, session_id: Option<&str>) -> Result<u64> {
let id = self.next_id;
self.next_id += 1;
let request = Request::DebugCommand {
id,
command: command.to_string(),
session_id: session_id.map(|s| s.to_string()),
};
let json = serde_json::to_string(&request)? + "\n";
self.writer.write_all(json.as_bytes()).await?;
Ok(id)
}
}