Skip to main content

aft_base/
protocol.rs

1use serde::{Deserialize, Serialize};
2
3pub const RESULT_FORMAT: &str = "tool-result/v1";
4
5use crate::list_envelope::ListEnvelope;
6
7/// Full payload returned by the `status` command and cached by status push frames.
8pub type StatusPayload = serde_json::Value;
9
10/// v0.18 streaming semantics for hoisted bash.
11///
12/// Foreground `bash` execution may emit zero or more `progress` frames before
13/// its final `Response`. Each progress frame is NDJSON on stdout with the same
14/// `request_id` as the original request and a `kind` of `stdout` or `stderr`.
15/// The final response remains the existing `{ id, success, ... }` envelope so
16/// older callers can ignore streaming frames. Bash permission prompts surface
17/// through the `permission_required` error code, which carries the permission
18/// ask payload the plugin uses to prompt and retry.
19pub 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    /// Transport-only destination, captured by the request's dispatch scope.
36    /// It is never part of the JSON body consumed by bridges.
37    #[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    /// Tail of stdout+stderr (≤300 bytes), already decoded as lossy UTF-8.
73    /// Empty string when no output was captured. Used by plugins to inline
74    /// short results in the system-reminder so agents don't need a follow-up
75    /// `bash_status` round-trip for typical short commands.
76    pub output_preview: String,
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub bash_output_list_envelope: Option<ListEnvelope>,
79    /// True when the task produced more output than `output_preview` shows
80    /// (rotated buffer, file > 300 bytes, etc). Plugins use this to render a
81    /// `…` prefix and signal that `bash_status` would return more.
82    pub output_truncated: bool,
83    /// Token count of raw stdout+stderr before compression. Omitted when the
84    /// payload exceeded the 128 KiB per-stream tokenization cap.
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub original_tokens: Option<u32>,
87    /// Token count of the compressed completion payload. Omitted when raw
88    /// tokenization was skipped due to the cap.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub compressed_tokens: Option<u32>,
91    /// True when output exceeded the tokenization cap and was not measured.
92    pub tokens_skipped: bool,
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub status_reason: Option<String>,
95    /// The build server's memory-kill cause and measurements, when reported.
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub remote_oom_kill: Option<RemoteOomKill>,
98    /// True when capture was incomplete; status still reflects the child exit.
99    #[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    /// For a finished task, why `live_descendants` is null, or, with
105    /// `listing_incomplete`, why the list may be only part of the group.
106    #[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/// Pushed after configure has completed, when the deferred file walk and
151/// language detection produce warnings (missing formatter/checker/LSP binaries,
152/// and search-index file-count warnings). The walk runs in a background
153/// thread so configure itself returns in <100 ms even on huge directories
154/// (e.g. user's $HOME). When the walk finishes, AFT pushes one frame with
155/// the merged warnings — the plugin delivers them through the same path as
156/// the synchronous warnings that configure used to return.
157#[derive(Debug, Clone, Serialize)]
158pub struct ConfigureWarningsFrame {
159    #[serde(rename = "type")]
160    pub frame_type: &'static str,
161    /// Session id from the configure request that spawned the deferred walk.
162    /// Project-shared bridges can serve multiple sessions, so plugins need this
163    /// to route async warning notifications back to the initiating session.
164    pub session_id: Option<String>,
165    /// Project root the warnings refer to. Plugins use this to scope the
166    /// session-id deduplication of repeated identical warnings.
167    pub project_root: String,
168    /// Merged formatter/checker/LSP missing-binary warnings.
169    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        // Erasure ends the watch just like task exit. Keep the existing terminal
493        // reason because clients only accept pattern_match and task_exit.
494        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
510/// Fallback session identifier used when a request arrives without one.
511///
512/// Introduced alongside project-shared bridges (issue #14): one `aft` process
513/// can now serve many OpenCode sessions in the same project. Undo/checkpoint
514/// state is partitioned by session inside Rust, but callers that haven't been
515/// updated to pass `session_id` (older plugins, direct CLI usage, tests) still
516/// need to work — they share this default namespace.
517///
518/// Also used as the migration target for legacy pre-session backups on disk.
519pub const DEFAULT_SESSION_ID: &str = "__default__";
520
521/// Inbound request envelope.
522///
523/// Two-stage parse: deserialize this first to get `id` + `command`, then
524/// dispatch on `command` and pull specific params from the flattened `params`.
525#[derive(Debug, Clone, Deserialize)]
526pub struct RawRequest {
527    /// Unique while pending on one standalone connection, across all sessions.
528    /// Reusing an ID is allowed after the earlier response has completed.
529    pub id: String,
530    #[serde(alias = "method")]
531    pub command: String,
532    /// Optional LSP hints from the plugin (R031 forward compatibility).
533    #[serde(default)]
534    pub lsp_hints: Option<serde_json::Value>,
535    /// Optional session namespace for undo/checkpoint isolation.
536    ///
537    /// When the plugin passes `session_id`, Rust partitions backup/checkpoint
538    /// state by it so concurrent OpenCode sessions sharing one bridge can't
539    /// see or restore each other's snapshots. When absent, falls back to
540    /// [`DEFAULT_SESSION_ID`].
541    #[serde(default)]
542    pub session_id: Option<String>,
543    /// All remaining fields are captured here for per-command deserialization.
544    #[serde(flatten)]
545    pub params: serde_json::Value,
546}
547
548impl RawRequest {
549    /// Session namespace for this request, falling back to [`DEFAULT_SESSION_ID`]
550    /// when the plugin didn't supply one.
551    pub fn session(&self) -> &str {
552        self.session_id.as_deref().unwrap_or(DEFAULT_SESSION_ID)
553    }
554
555    /// Whether the caller is a delegated worker (subagent) session rather than
556    /// a primary one.
557    ///
558    /// The plugins attach `worker_session: true` to every request from a
559    /// worker, next to `session_id`; it is absent (false) for a primary
560    /// session and for any caller that predates it. A worker cannot be woken
561    /// once its turn ends, so the text it is shown must never promise a later
562    /// reminder or tell it to end its turn. The field normally sits at the top
563    /// level; it is also read from a nested `params` object, the shape some
564    /// in-process requests are built in.
565    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    /// The names the caller's host registered AFT's command and patch tools
576    /// under (see [`crate::host_tool_names`]), for reply text that tells the
577    /// agent which tool to call. Read from the `host_tool_names` envelope field,
578    /// at the top level or in a nested `params` object like
579    /// [`RawRequest::worker_session`]. Absent, or not a valid map, gives the
580    /// default names: the field only changes how text is worded, so a bad value
581    /// is logged and never fails the request.
582    pub fn host_tool_names(&self) -> crate::host_tool_names::HostToolNames {
583        self.sent_host_tool_names().unwrap_or_default()
584    }
585
586    /// The names from the `host_tool_names` envelope field, or `None` when the
587    /// request has no usable field. Lets a caller forward the names onward
588    /// only when the request carried them.
589    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
604/// Request field that marks the caller as a delegated worker session; see
605/// [`RawRequest::worker_session`].
606pub const WORKER_SESSION_FIELD: &str = "worker_session";
607
608/// Outbound response envelope.
609///
610/// `data` is flattened into the top-level JSON object, so a response like
611/// `Response { id: "1", success: true, data: json!({"command": "pong"}) }`
612/// serializes to `{"id":"1","success":true,"command":"pong"}`.
613///
614/// # Honest reporting convention (tri-state)
615///
616/// Tools that search, check, or otherwise produce results MUST follow this
617/// convention so agents can distinguish "did the work, found nothing" from
618/// "couldn't do the work" from "partially did the work":
619///
620/// 1. **`success: false`** — the requested work could not be performed.
621///    Includes a `code` (e.g., `"path_not_found"`, `"no_lsp_server"`,
622///    `"project_too_large"`) and a human-readable `message`. The agent
623///    should treat this as an error and read the message.
624///
625/// 2. **`success: true` + completion signaling** — the work was performed.
626///    Tools must report whether the result is *complete* OR which subset
627///    was actually performed. Conventional fields:
628///    - `complete: true` — full result, agent can trust absence of items
629///    - `complete: false` + `pending_files: [...]` / `unchecked_files: [...]`
630///      / `scope_warnings: [...]` — partial result, with named gaps
631///    - `removed: true|false` (for mutations) — did the file actually change
632///    - `skipped_files: [{file, reason}]` — files we couldn't process inside
633///      the requested scope
634///    - `no_files_matched_scope: bool` — the scope (path/glob) found zero
635///      candidates (distinct from "candidates found, no matches")
636///
637/// 3. **Side-effect skip codes** — when the main work succeeded but a
638///    non-essential side step was skipped (e.g., post-write formatting),
639///    use a `<step>_skipped_reason` field. Approved values:
640///    - `format_skipped_reason`: `"unsupported_language"` |
641///      `"no_formatter_configured"` | `"formatter_not_installed"` |
642///      `"formatter_excluded_path"` | `"timeout"` | `"error"`
643///    - `validate_skipped_reason`: `"unsupported_language"` |
644///      `"no_checker_configured"` | `"checker_not_installed"` |
645///      `"timeout"` | `"error"`
646///
647/// **Anti-patterns to avoid:**
648/// - Returning `success: true` with empty results when the scope didn't
649///   resolve to any files — agent reads as "all clear" but really nothing
650///   was checked. Use `no_files_matched_scope: true` or
651///   `success: false, code: "path_not_found"`.
652/// - Reusing `format_skipped_reason: "not_found"` for two different causes
653///   ("no formatter configured" vs "configured formatter binary missing").
654///   The agent can't act on the ambiguous code.
655///
656/// See ARCHITECTURE.md "Honest reporting convention" for the full rationale.
657#[derive(Debug, Serialize)]
658pub struct Response {
659    pub id: String,
660    pub success: bool,
661    #[serde(flatten)]
662    pub data: serde_json::Value,
663    /// Delivery decisions are internal and never appear in a tool response.
664    #[serde(skip)]
665    pub notices: crate::pending_notices::PendingNotices,
666}
667
668/// Parameters for the `echo` command.
669#[derive(Debug, Deserialize)]
670pub struct EchoParams {
671    pub message: String,
672}
673
674impl Response {
675    /// Build a success response with arbitrary data merged at the top level.
676    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    /// Build an error response with `code` and `message` fields.
686    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    /// Build an error response with `code`, `message`, and additional structured data.
699    ///
700    /// The `extra` fields are merged into the top-level response alongside `code` and `message`.
701    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    /// The first word of the process's first argument (normally the program
789    /// path it was started as), or its command name when that argument cannot
790    /// be read. Never any later argument.
791    pub argv0: String,
792    /// Name of the user that owns the process (its real user ID), or the
793    /// numeric ID when the account has no name. Absent when it could not be
794    /// read, and on records written before AFT recorded it.
795    #[serde(default, skip_serializing_if = "Option::is_none")]
796    pub user: Option<String>,
797    /// The process's executable name, followed by `…` when it was started
798    /// with arguments. The arguments themselves are never kept: they can hold
799    /// a credential (`--token "$DEPLOY_TOKEN"`, a value read from a file) that
800    /// no pattern can recognise, and this field reaches the task record, the
801    /// status reply and the completion notice. Absent on older records.
802    #[serde(default, skip_serializing_if = "Option::is_none")]
803    pub command: Option<String>,
804}
805
806/// Why a task has no list of surviving process-group members. A list, even an
807/// empty one, always means AFT checked; this says why it could not.
808#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
809#[serde(rename_all = "snake_case")]
810pub enum LiveDescendantsUnavailable {
811    /// This platform has no process-group listing AFT can use (Windows, and
812    /// Unix systems other than Linux and macOS).
813    UnsupportedPlatform,
814    /// The task has no recorded process group.
815    NoProcessGroup,
816    /// Listing the group's members failed, for example because `/proc`
817    /// could not be read.
818    ListingFailed,
819    /// The listing could not account for every process that may belong to the
820    /// group: some were hidden or unreadable, for example because `/proc` is
821    /// mounted with `hidepid`. Any members it did identify are still listed;
822    /// others may also be running.
823    ListingIncomplete,
824    /// AFT did not check this task's group: a remote job, a pseudoterminal
825    /// task that ended on its own, or a record written by an older AFT.
826    NotChecked,
827}
828
829impl LiveDescendantsUnavailable {
830    /// The reason to record when a task has no process group to list.
831    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/// A consumer's session namespace, attested by the transport rather than tool arguments.
841/// Route channels and epochs are deliberately excluded so reconnects retain ownership.
842#[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/// Memory-kill facts reported by the build server, not the local memory cap.
861#[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}