1use serde::{Deserialize, Serialize};
2
3pub const RESULT_FORMAT: &str = "tool-result/v1";
4
5use crate::list_envelope::ListEnvelope;
6
7pub type StatusPayload = serde_json::Value;
9
10pub const ERROR_PERMISSION_REQUIRED: &str = "permission_required";
20
21#[derive(Debug, Clone, Serialize)]
22#[serde(rename_all = "snake_case")]
23pub enum ProgressKind {
24 Stdout,
25 Stderr,
26}
27
28#[derive(Debug, Clone, Serialize)]
29pub struct ProgressFrame {
30 #[serde(rename = "type")]
31 pub frame_type: &'static str,
32 pub request_id: String,
33 pub kind: ProgressKind,
34 pub chunk: String,
35 #[serde(skip)]
38 pub origin: Option<ProgressOrigin>,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
42pub struct ProgressOrigin {
43 pub channel: u16,
44 pub epoch: u32,
45 pub corr: u64,
46}
47
48#[derive(Debug, Clone, Serialize)]
49pub struct PermissionAskFrame {
50 #[serde(rename = "type")]
51 pub frame_type: &'static str,
52 pub request_id: String,
53 pub asks: serde_json::Value,
54}
55
56#[derive(Debug, Clone, Serialize)]
57pub struct BashCompletedFrame {
58 #[serde(skip)]
59 pub launching_identity: Option<TaskIdentity>,
60 #[serde(
61 rename = "_bash_changed_files",
62 skip_serializing_if = "Option::is_none"
63 )]
64 pub changed_files: Option<Report>,
65 #[serde(rename = "type")]
66 pub frame_type: &'static str,
67 pub task_id: String,
68 pub session_id: String,
69 pub status: BgTaskStatus,
70 pub exit_code: Option<i64>,
71 pub command: String,
72 pub output_preview: String,
77 #[serde(skip_serializing_if = "Option::is_none")]
78 pub bash_output_list_envelope: Option<ListEnvelope>,
79 pub output_truncated: bool,
83 #[serde(skip_serializing_if = "Option::is_none")]
86 pub original_tokens: Option<u32>,
87 #[serde(skip_serializing_if = "Option::is_none")]
90 pub compressed_tokens: Option<u32>,
91 pub tokens_skipped: bool,
93 #[serde(skip_serializing_if = "Option::is_none")]
94 pub status_reason: Option<String>,
95 #[serde(skip_serializing_if = "Option::is_none")]
97 pub remote_oom_kill: Option<RemoteOomKill>,
98 #[serde(skip_serializing_if = "is_false")]
100 pub output_incomplete: bool,
101 pub live_descendants: Option<Vec<LiveDescendant>>,
102 #[serde(skip_serializing_if = "is_zero_usize")]
103 pub live_descendants_omitted: usize,
104 #[serde(skip_serializing_if = "Option::is_none")]
107 pub live_descendants_unavailable: Option<LiveDescendantsUnavailable>,
108 #[serde(skip_serializing_if = "Option::is_none")]
109 pub live_descendants_summary: Option<String>,
110}
111
112fn is_zero_usize(value: &usize) -> bool {
113 *value == 0
114}
115
116fn is_false(value: &bool) -> bool {
117 !*value
118}
119
120#[derive(Debug, Clone, Serialize)]
121pub struct BashLongRunningFrame {
122 #[serde(skip)]
123 pub launching_identity: Option<TaskIdentity>,
124 #[serde(rename = "type")]
125 pub frame_type: &'static str,
126 pub task_id: String,
127 pub session_id: String,
128 pub command: String,
129 pub elapsed_ms: u64,
130}
131
132#[derive(Debug, Clone, Serialize)]
133pub struct BashPatternMatchFrame {
134 #[serde(skip)]
135 pub launching_identity: Option<TaskIdentity>,
136 #[serde(rename = "type")]
137 pub frame_type: &'static str,
138 pub task_id: String,
139 pub session_id: String,
140 pub watch_id: String,
141 pub match_text: String,
142 pub match_offset: u64,
143 pub context: String,
144 pub once: bool,
145 pub reason: &'static str,
146 #[serde(skip_serializing_if = "Option::is_none")]
147 pub batch: Option<crate::task_watch_lines::LineBatch>,
148}
149
150#[derive(Debug, Clone, Serialize)]
158pub struct ConfigureWarningsFrame {
159 #[serde(rename = "type")]
160 pub frame_type: &'static str,
161 pub session_id: Option<String>,
165 pub project_root: String,
168 pub warnings: Vec<serde_json::Value>,
170}
171
172#[derive(Debug, Clone, Serialize)]
173pub struct StatusChangedFrame {
174 #[serde(rename = "type")]
175 pub frame_type: &'static str,
176 pub session_id: Option<String>,
177 pub snapshot: StatusPayload,
178}
179
180#[derive(Debug, Clone, Serialize)]
181#[serde(untagged)]
182pub enum PushFrame {
183 Progress(ProgressFrame),
184 BashCompleted(BashCompletedFrame),
185 BashLongRunning(BashLongRunningFrame),
186 BashPatternMatch(BashPatternMatchFrame),
187 ConfigureWarnings(ConfigureWarningsFrame),
188 StatusChanged(StatusChangedFrame),
189}
190
191impl PermissionAskFrame {
192 pub fn new(request_id: impl Into<String>, asks: serde_json::Value) -> Self {
193 Self {
194 frame_type: "permission_ask",
195 request_id: request_id.into(),
196 asks,
197 }
198 }
199}
200
201impl ProgressFrame {
202 pub fn new(
203 request_id: impl Into<String>,
204 kind: ProgressKind,
205 chunk: impl Into<String>,
206 ) -> Self {
207 Self {
208 frame_type: "progress",
209 request_id: request_id.into(),
210 kind,
211 chunk: chunk.into(),
212 origin: None,
213 }
214 }
215}
216
217impl ConfigureWarningsFrame {
218 pub fn new(project_root: impl Into<String>, warnings: Vec<serde_json::Value>) -> Self {
219 Self::new_with_session_id(None, project_root, warnings)
220 }
221
222 pub fn new_with_session_id(
223 session_id: Option<String>,
224 project_root: impl Into<String>,
225 warnings: Vec<serde_json::Value>,
226 ) -> Self {
227 Self {
228 frame_type: "configure_warnings",
229 session_id,
230 project_root: project_root.into(),
231 warnings,
232 }
233 }
234}
235
236impl StatusChangedFrame {
237 pub fn new(session_id: Option<String>, snapshot: StatusPayload) -> Self {
238 Self {
239 frame_type: "status_changed",
240 session_id,
241 snapshot: status_push_payload(snapshot),
242 }
243 }
244}
245
246fn status_push_payload(mut snapshot: StatusPayload) -> StatusPayload {
247 if let Some(object) = snapshot.as_object_mut() {
248 object.remove("session");
249 if let Some(compression) = object
250 .get_mut("compression")
251 .and_then(serde_json::Value::as_object_mut)
252 {
253 compression.remove("session");
254 }
255 }
256 snapshot
257}
258
259#[cfg(test)]
260mod tests {
261 #[test]
262 fn task_identity_and_remote_oom_fields_keep_their_wire_shape() {
263 let identity = super::TaskIdentity {
264 principal: None,
265 harness: "opencode".into(),
266 session: "session".into(),
267 };
268 let value =
269 serde_json::json!({"principal": null, "harness": "opencode", "session": "session"});
270 assert_eq!(serde_json::to_value(&identity).unwrap(), value);
271 assert_eq!(
272 serde_json::from_value::<super::TaskIdentity>(value).unwrap(),
273 identity
274 );
275 let oom = super::RemoteOomKill {
276 cause: "job_limit".into(),
277 memory_stated_mib: None,
278 memory_peak_working_mib: Some(17),
279 };
280 assert_eq!(
281 serde_json::to_value(oom).unwrap(),
282 serde_json::json!({"cause":"job_limit", "memory_peak_working_mib":17})
283 );
284 }
285
286 use super::*;
287 use serde::Deserialize;
288 use serde_json::json;
289
290 #[derive(Debug, Deserialize)]
291 struct ConfigureWarningsFrameRoundTrip {
292 #[serde(rename = "type")]
293 frame_type: String,
294 session_id: Option<String>,
295 project_root: String,
296 warnings: Vec<serde_json::Value>,
297 }
298
299 #[test]
300 fn configure_warnings_frame_serializes_null_session_id_by_default() {
301 let frame = ConfigureWarningsFrame::new(
302 "/repo",
303 vec![json!({
304 "kind": "formatter_not_installed",
305 "tool": "biome",
306 "hint": "Install biome."
307 })],
308 );
309
310 let json = serde_json::to_string(&frame).expect("serialize ConfigureWarningsFrame");
311 let decoded: ConfigureWarningsFrameRoundTrip =
312 serde_json::from_str(&json).expect("deserialize ConfigureWarningsFrame JSON");
313
314 assert_eq!(decoded.session_id, None);
315 }
316
317 #[test]
318 fn configure_warnings_frame_serializes_session_id() {
319 let frame = ConfigureWarningsFrame::new_with_session_id(
320 Some("session-1".to_string()),
321 "/repo",
322 vec![json!({
323 "kind": "formatter_not_installed",
324 "tool": "biome",
325 "hint": "Install biome."
326 })],
327 );
328
329 let json = serde_json::to_string(&frame).expect("serialize ConfigureWarningsFrame");
330 let decoded: ConfigureWarningsFrameRoundTrip =
331 serde_json::from_str(&json).expect("deserialize ConfigureWarningsFrame JSON");
332
333 assert_eq!(decoded.frame_type, "configure_warnings");
334 assert_eq!(decoded.session_id.as_deref(), Some("session-1"));
335 assert_eq!(decoded.project_root, "/repo");
336 assert_eq!(decoded.warnings[0]["tool"], "biome");
337 }
338
339 #[test]
340 fn status_changed_frame_serializes_correctly() {
341 let frame = StatusChangedFrame::new(
342 None,
343 json!({
344 "version": "0.24.0",
345 "project_root": "/repo",
346 "cache_role": "main",
347 "canonical_root": "/repo",
348 "search_index": { "status": "ready" },
349 "semantic_index": { "status": "disabled" },
350 }),
351 );
352
353 let json = serde_json::to_value(PushFrame::StatusChanged(frame)).unwrap();
354 assert_eq!(json["type"], "status_changed");
355 assert!(json["session_id"].is_null());
356 assert_eq!(json["snapshot"]["cache_role"], "main");
357 assert_eq!(json["snapshot"]["project_root"], "/repo");
358 }
359
360 #[test]
361 fn status_changed_frame_strips_session_scoped_push_fields() {
362 let frame = StatusChangedFrame::new(
363 None,
364 json!({
365 "version": "0.24.0",
366 "checkpoints_total": 7,
367 "session": { "id": "default", "tracked_files": 2, "checkpoints": 1 },
368 "compression": {
369 "project": { "events": 3 },
370 "session": { "events": 99 }
371 }
372 }),
373 );
374
375 assert!(frame.snapshot.get("session").is_none());
376 assert_eq!(frame.snapshot["checkpoints_total"], 7);
377 assert_eq!(frame.snapshot["compression"]["project"]["events"], 3);
378 assert!(frame.snapshot["compression"].get("session").is_none());
379 }
380}
381
382impl BashCompletedFrame {
383 pub fn new(
384 task_id: impl Into<String>,
385 session_id: impl Into<String>,
386 status: BgTaskStatus,
387 exit_code: Option<i64>,
388 command: impl Into<String>,
389 output_preview: impl Into<String>,
390 output_truncated: bool,
391 original_tokens: Option<u32>,
392 compressed_tokens: Option<u32>,
393 tokens_skipped: bool,
394 ) -> Self {
395 Self {
396 frame_type: "bash_completed",
397 launching_identity: None,
398 changed_files: None,
399 task_id: task_id.into(),
400 session_id: session_id.into(),
401 status,
402 exit_code,
403 command: command.into(),
404 output_preview: output_preview.into(),
405 bash_output_list_envelope: None,
406 output_truncated,
407 original_tokens,
408 compressed_tokens,
409 tokens_skipped,
410 status_reason: None,
411 remote_oom_kill: None,
412 output_incomplete: false,
413 live_descendants: None,
414 live_descendants_omitted: 0,
415 live_descendants_unavailable: None,
416 live_descendants_summary: None,
417 }
418 }
419}
420
421impl BashLongRunningFrame {
422 pub fn new(
423 task_id: impl Into<String>,
424 session_id: impl Into<String>,
425 command: impl Into<String>,
426 elapsed_ms: u64,
427 ) -> Self {
428 Self {
429 frame_type: "bash_long_running",
430 launching_identity: None,
431 task_id: task_id.into(),
432 session_id: session_id.into(),
433 command: command.into(),
434 elapsed_ms,
435 }
436 }
437}
438
439impl BashPatternMatchFrame {
440 pub fn new(
441 task_id: impl Into<String>,
442 session_id: impl Into<String>,
443 watch_id: impl Into<String>,
444 match_text: impl Into<String>,
445 match_offset: u64,
446 context: impl Into<String>,
447 once: bool,
448 ) -> Self {
449 Self {
450 frame_type: "bash_pattern_match",
451 launching_identity: None,
452 batch: None,
453 task_id: task_id.into(),
454 session_id: session_id.into(),
455 watch_id: watch_id.into(),
456 match_text: match_text.into(),
457 match_offset,
458 context: context.into(),
459 once,
460 reason: "pattern_match",
461 }
462 }
463
464 pub fn task_exit(
465 task_id: impl Into<String>,
466 session_id: impl Into<String>,
467 match_text: impl Into<String>,
468 context: impl Into<String>,
469 ) -> Self {
470 Self {
471 frame_type: "bash_pattern_match",
472 launching_identity: None,
473 batch: None,
474 task_id: task_id.into(),
475 session_id: session_id.into(),
476 watch_id: "exit".to_string(),
477 match_text: match_text.into(),
478 match_offset: 0,
479 context: context.into(),
480 once: true,
481 reason: "task_exit",
482 }
483 }
484
485 pub fn watch_target_erased(
486 task_id: impl Into<String>,
487 session_id: impl Into<String>,
488 watch_id: impl Into<String>,
489 match_text: impl Into<String>,
490 context: impl Into<String>,
491 ) -> Self {
492 Self {
495 frame_type: "bash_pattern_match",
496 launching_identity: None,
497 batch: None,
498 task_id: task_id.into(),
499 session_id: session_id.into(),
500 watch_id: watch_id.into(),
501 match_text: match_text.into(),
502 match_offset: 0,
503 context: context.into(),
504 once: true,
505 reason: "task_exit",
506 }
507 }
508}
509
510pub const DEFAULT_SESSION_ID: &str = "__default__";
520
521#[derive(Debug, Clone, Deserialize)]
526pub struct RawRequest {
527 pub id: String,
530 #[serde(alias = "method")]
531 pub command: String,
532 #[serde(default)]
534 pub lsp_hints: Option<serde_json::Value>,
535 #[serde(default)]
542 pub session_id: Option<String>,
543 #[serde(flatten)]
545 pub params: serde_json::Value,
546}
547
548impl RawRequest {
549 pub fn session(&self) -> &str {
552 self.session_id.as_deref().unwrap_or(DEFAULT_SESSION_ID)
553 }
554
555 pub fn worker_session(&self) -> bool {
566 let flag = |value: &serde_json::Value| {
567 value
568 .get(WORKER_SESSION_FIELD)
569 .and_then(serde_json::Value::as_bool)
570 == Some(true)
571 };
572 flag(&self.params) || self.params.get("params").is_some_and(flag)
573 }
574
575 pub fn host_tool_names(&self) -> crate::host_tool_names::HostToolNames {
583 self.sent_host_tool_names().unwrap_or_default()
584 }
585
586 pub fn sent_host_tool_names(&self) -> Option<crate::host_tool_names::HostToolNames> {
590 use crate::host_tool_names::{HostToolNames, HOST_TOOL_NAMES_FIELD};
591 let field = self.params.get(HOST_TOOL_NAMES_FIELD).or_else(|| {
592 self.params
593 .get("params")
594 .and_then(|nested| nested.get(HOST_TOOL_NAMES_FIELD))
595 })?;
596 HostToolNames::from_request_field(Some(field))
597 .map_err(|error| {
598 log::warn!("request {}: {error}; using the default tool names", self.id);
599 })
600 .ok()
601 }
602}
603
604pub const WORKER_SESSION_FIELD: &str = "worker_session";
607
608#[derive(Debug, Serialize)]
658pub struct Response {
659 pub id: String,
660 pub success: bool,
661 #[serde(flatten)]
662 pub data: serde_json::Value,
663 #[serde(skip)]
665 pub notices: crate::pending_notices::PendingNotices,
666}
667
668#[derive(Debug, Deserialize)]
670pub struct EchoParams {
671 pub message: String,
672}
673
674impl Response {
675 pub fn success(id: impl Into<String>, data: serde_json::Value) -> Self {
677 Response {
678 id: id.into(),
679 success: true,
680 data,
681 notices: Default::default(),
682 }
683 }
684
685 pub fn error(id: impl Into<String>, code: &str, message: impl Into<String>) -> Self {
687 Response {
688 id: id.into(),
689 success: false,
690 data: serde_json::json!({
691 "code": code,
692 "message": message.into(),
693 }),
694 notices: Default::default(),
695 }
696 }
697
698 pub fn error_with_data(
702 id: impl Into<String>,
703 code: &str,
704 message: impl Into<String>,
705 extra: serde_json::Value,
706 ) -> Self {
707 let mut data = serde_json::json!({
708 "code": code,
709 "message": message.into(),
710 });
711 if let (Some(base), serde_json::Value::Object(ext)) = (data.as_object_mut(), extra) {
712 base.extend(ext);
713 }
714 Response {
715 id: id.into(),
716 success: false,
717 data,
718 notices: Default::default(),
719 }
720 }
721}
722#[test]
723fn error_response_preserves_owned_extra_fields() {
724 let extra = serde_json::json!({"nested":{"values":[1,2]}, "detail":"owned"});
725 let detail_allocation = extra["detail"].as_str().unwrap().as_ptr();
726 let response = Response::error_with_data("extra", "failure", "message", extra);
727 assert_eq!(
728 response.data["detail"].as_str().unwrap().as_ptr(),
729 detail_allocation,
730 "owned error extras must move without cloning their strings"
731 );
732 let value = serde_json::to_value(response).unwrap();
733 assert_eq!(value["nested"]["values"], serde_json::json!([1, 2]));
734 assert_eq!(value["detail"], "owned");
735 assert_eq!(value["code"], "failure");
736 assert_eq!(value["message"], "message");
737}
738
739#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
740#[serde(rename_all = "snake_case")]
741pub enum BgTaskStatus {
742 Starting,
743 Running,
744 Killing,
745 Completed,
746 Failed,
747 Killed,
748 TimedOut,
749 FateUnknown,
750}
751
752impl BgTaskStatus {
753 pub fn is_terminal(&self) -> bool {
754 matches!(
755 self,
756 BgTaskStatus::Completed
757 | BgTaskStatus::Failed
758 | BgTaskStatus::Killed
759 | BgTaskStatus::TimedOut
760 | BgTaskStatus::FateUnknown
761 )
762 }
763}
764
765#[derive(Debug, Clone, Serialize)]
766pub struct ChangedFile {
767 pub path: String,
768 pub status: &'static str,
769 #[serde(skip_serializing_if = "Option::is_none")]
770 pub diff: Option<String>,
771 #[serde(skip_serializing_if = "Option::is_none")]
772 pub reason: Option<String>,
773 #[serde(skip_serializing_if = "Option::is_none")]
774 pub diff_lines_list_envelope: Option<ListEnvelope>,
775}
776#[derive(Debug, Clone, Serialize)]
777pub struct Report {
778 pub text: String,
779 pub files: Vec<ChangedFile>,
780 pub incomplete: Vec<String>,
781 pub changed_files_list_envelope: ListEnvelope,
782}
783
784#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
785pub struct LiveDescendant {
786 pub pid: u32,
787 pub comm: String,
788 pub argv0: String,
792 #[serde(default, skip_serializing_if = "Option::is_none")]
796 pub user: Option<String>,
797 #[serde(default, skip_serializing_if = "Option::is_none")]
803 pub command: Option<String>,
804}
805
806#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
809#[serde(rename_all = "snake_case")]
810pub enum LiveDescendantsUnavailable {
811 UnsupportedPlatform,
814 NoProcessGroup,
816 ListingFailed,
819 ListingIncomplete,
824 NotChecked,
827}
828
829impl LiveDescendantsUnavailable {
830 pub fn without_group() -> Self {
832 if cfg!(any(target_os = "linux", target_os = "macos")) {
833 Self::NoProcessGroup
834 } else {
835 Self::UnsupportedPlatform
836 }
837 }
838}
839
840#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
843pub struct TaskIdentity {
844 pub principal: Option<String>,
845 #[serde(deserialize_with = "deserialize_task_harness")]
846 pub harness: String,
847 pub session: String,
848}
849
850fn deserialize_task_harness<'de, D: serde::Deserializer<'de>>(
851 deserializer: D,
852) -> Result<String, D::Error> {
853 let raw = String::deserialize(deserializer)?;
854 Ok(raw
855 .parse::<crate::harness::Harness>()
856 .map(|harness| harness.wire_label())
857 .unwrap_or(raw))
858}
859
860#[derive(Clone, Debug, Serialize)]
862pub struct RemoteOomKill {
863 pub cause: String,
864 #[serde(skip_serializing_if = "Option::is_none")]
865 pub memory_stated_mib: Option<u64>,
866 #[serde(skip_serializing_if = "Option::is_none")]
867 pub memory_peak_working_mib: Option<u64>,
868}