marona 5.2.0

Agent SDK with coordinated B2A and D2A protocols, realtime device streams, structured responses, MCP and A2A
Documentation
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
use std::{pin::Pin, sync::Arc};

use async_stream::try_stream;
use base64::Engine;
use futures_util::{Stream, StreamExt};
use reqwest::Method;
use serde_json::{json, Map, Value};

use crate::{
    core::Core, Error, FunctionTool, Input, McpConnection, Result, RoutingOptions, RunEvent,
    RuntimeResponse, ToolChoice, ToolContext,
};

pub type EventStream = Pin<Box<dyn Stream<Item = Result<RunEvent>> + Send>>;

#[async_trait::async_trait]
pub trait ResponsesHooks: Send + Sync {
    async fn on_start(&self, _context: &crate::AgentContext, _input: &Input) -> Result<()> {
        Ok(())
    }
    async fn on_event(&self, _context: &crate::AgentContext, _event: &RunEvent) -> Result<()> {
        Ok(())
    }
    async fn on_tool_call(&self, _context: &crate::AgentContext, _name: &str) -> Result<()> {
        Ok(())
    }
    async fn on_complete(
        &self,
        _context: &crate::AgentContext,
        _response: &RuntimeResponse,
    ) -> Result<()> {
        Ok(())
    }
    async fn on_error(&self, _context: &crate::AgentContext, _error: &Error) -> Result<()> {
        Ok(())
    }
}

#[derive(Clone)]
pub struct CreateRequest {
    pub model: String,
    pub input: Input,
    pub tools: Option<McpConnection>,
    pub interface: String,
    pub user_id: Option<String>,
    pub conversation_id: Option<String>,
    pub developer_instructions: Option<String>,
    pub routing: Option<RoutingOptions>,
    pub output: Option<Value>,
    pub tool_choice: ToolChoice,
    pub metadata: Map<String, Value>,
    pub function_tools: Vec<FunctionTool>,
    pub hooks: Option<Arc<dyn ResponsesHooks>>,
}
impl std::fmt::Debug for CreateRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CreateRequest")
            .field("model", &self.model)
            .finish_non_exhaustive()
    }
}

impl CreateRequest {
    pub fn new(model: impl Into<String>, input: impl Into<Input>) -> Self {
        Self {
            model: model.into(),
            input: input.into(),
            tools: None,
            interface: "api".into(),
            user_id: None,
            conversation_id: None,
            developer_instructions: None,
            routing: None,
            output: None,
            tool_choice: ToolChoice::Auto,
            metadata: Map::new(),
            function_tools: vec![],
            hooks: None,
        }
    }
    pub fn tool(mut self, tool: FunctionTool) -> Self {
        self.function_tools.push(tool);
        self
    }
}

#[derive(Clone, Debug)]
pub struct Responses {
    pub(crate) core: Arc<Core>,
}

impl Responses {
    pub async fn create(&self, request: CreateRequest) -> Result<RuntimeResponse> {
        let context = hook_context(&request);
        let result = async {
            if let Some(hooks) = &request.hooks {
                hooks.on_start(&context, &request.input).await?;
            }
            let response = self.create_without_hooks(request.clone()).await?;
            if let Some(hooks) = &request.hooks {
                hooks.on_complete(&context, &response).await?;
            }
            Ok(response)
        }
        .await;
        if let (Some(hooks), Err(error)) = (&request.hooks, &result) {
            let _ = hooks.on_error(&context, error).await;
        }
        result
    }
    async fn create_without_hooks(&self, mut request: CreateRequest) -> Result<RuntimeResponse> {
        for _ in 0..8 {
            let response = self.create_once(&request).await?;
            if request.function_tools.is_empty()
                || response
                    .agent
                    .get("function_tool_calls")
                    .and_then(Value::as_array)
                    .is_none_or(|calls| calls.is_empty())
            {
                return Ok(response);
            }
            let results = invoke_functions(&request, &response).await?;
            request
                .metadata
                .insert("marona_function_tool_results".into(), results);
        }
        Err(Error::Tool("Function execution exceeded 8 rounds".into()))
    }

    async fn create_once(&self, request: &CreateRequest) -> Result<RuntimeResponse> {
        let body = runtime_body(request)?;
        let payload: Value = self
            .core
            .json(
                &self.core.runtime_url,
                Method::POST,
                "/runtime/message",
                Some(&body),
            )
            .await?;
        response_from_value(payload)
    }

    pub async fn stream(&self, request: CreateRequest) -> Result<EventStream> {
        let Some(hooks) = request.hooks.clone() else {
            return self.stream_without_hooks(request).await;
        };
        let context = hook_context(&request);
        let client = self.clone();
        Ok(Box::pin(try_stream! {
            let mut source = match async {
                hooks.on_start(&context, &request.input).await?;
                client.stream_without_hooks(request).await
            }.await {
                Ok(source) => source,
                Err(error) => { let _ = hooks.on_error(&context, &error).await; Err(error)?; unreachable!() }
            };
            while let Some(event) = source.next().await {
                let event = match event {
                    Ok(event) => event,
                    Err(error) => { let _ = hooks.on_error(&context, &error).await; Err(error)?; unreachable!() }
                };
                let observed = async {
                    hooks.on_event(&context, &event).await?;
                    if event.event_type == "run.completed" { hooks.on_complete(&context, &response_from_value(event.output.clone())?).await?; }
                    Ok::<(), Error>(())
                }.await;
                if let Err(error) = observed { let _ = hooks.on_error(&context, &error).await; Err(error)?; }
                yield event;
            }
        }))
    }

    async fn stream_without_hooks(&self, request: CreateRequest) -> Result<EventStream> {
        if request.function_tools.is_empty() {
            return self.stream_once(request).await;
        }
        let client = self.clone();
        Ok(Box::pin(try_stream! {
            let mut request = request;
            'rounds: for _ in 0..8 {
                let mut stream = client.stream_once(request.clone()).await?;
                while let Some(event) = stream.next().await {
                    let event = event?;
                    if event.event_type != "run.completed" { yield event; continue; }
                    let response = response_from_value(event.output.clone())?;
                    if response.agent.get("function_tool_calls").and_then(Value::as_array).is_none_or(|calls|calls.is_empty()) { yield event; return; }
                    let results = invoke_functions(&request, &response).await?;
                    request.metadata.insert("marona_function_tool_results".into(), results);
                    continue 'rounds;
                }
                Err(Error::Protocol("Stream ended without completion".into()))?;
            }
            Err(Error::Tool("Function execution exceeded 8 rounds".into()))?;
        }))
    }

    async fn stream_once(&self, request: CreateRequest) -> Result<EventStream> {
        let body = runtime_body(&request)?;
        let core = self.core.clone();
        Ok(Box::pin(try_stream! {
            let api_key = core.require_api_key()?;
            let response = core.client.post(format!("{}/runtime/message/stream", core.runtime_url))
                .headers(core.headers.clone()).bearer_auth(api_key).json(&body).send().await?;
            let status = response.status();
            let response = if status.is_success() {
                response
            } else {
                let bytes = core.response_body(response).await?;
                let payload = serde_json::from_slice::<Value>(&bytes).ok();
                Err(Error::api(status, payload))?
            };
            core.check_response(&response)?;
            let mut bytes = response.bytes_stream();
            let mut pending = Vec::<u8>::new();
            let mut received = 0;
            while let Some(chunk) = bytes.next().await {
                let chunk = chunk?;
                received = core.response_size(received, chunk.len())?;
                pending.extend_from_slice(&chunk);
                while let Some((index, width)) = sse_boundary(&pending) {
                    if index > 16 * 1024 * 1024 { Err(Error::Protocol("SSE frame exceeds 16 MiB".into()))?; }
                    let frame = String::from_utf8(pending[..index].to_vec()).map_err(|_| Error::Protocol("SSE is not valid UTF-8".into()))?;
                    pending.drain(..index + width);
                    let data = frame.lines().filter_map(|line| line.strip_prefix("data:")).collect::<Vec<_>>().join("\n");
                    if data.trim().is_empty() || data.trim() == "[DONE]" { continue; }
                    let value: Value = serde_json::from_str(data.trim()).map_err(|e| Error::Protocol(e.to_string()))?;
                    if value.get("error").is_some() {
                        Err(Error::stream(&value))?;
                    }
                    yield event_from_value(value);
                }
                if pending.len() > 16 * 1024 * 1024 { Err(Error::Protocol("SSE frame exceeds 16 MiB".into()))?; }
            }
        }))
    }
}

async fn invoke_functions(request: &CreateRequest, response: &RuntimeResponse) -> Result<Value> {
    if request.tool_choice == ToolChoice::None {
        return Err(Error::Tool("Function tools are disabled".into()));
    }
    if response.status == "planned" {
        return Err(Error::ApprovalRequired("Approval required".into()));
    }
    if response
        .extra
        .get("needs_permission")
        .and_then(Value::as_bool)
        == Some(true)
    {
        return Err(Error::PermissionRequired("Permission required".into()));
    }
    if response
        .extra
        .get("needs_service_connection")
        .and_then(Value::as_bool)
        == Some(true)
    {
        return Err(Error::ServiceConnectionRequired(
            "Service authorization required".into(),
        ));
    }
    let mut results = Vec::new();
    for call in response
        .agent
        .get("function_tool_calls")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
    {
        let name = call["name"].as_str().unwrap_or("");
        if let Some(hooks) = &request.hooks {
            hooks.on_tool_call(&hook_context(request), name).await?;
        }
        let tool = request
            .function_tools
            .iter()
            .find(|tool| tool.name == name)
            .ok_or_else(|| Error::Tool("Requested function is unavailable".into()))?;
        let args = if let Some(value) = call["arguments"].as_str() {
            serde_json::from_str(value)
                .map_err(|_| Error::Validation("Invalid tool arguments".into()))?
        } else {
            call["arguments"].clone()
        };
        let metadata = request
            .metadata
            .get("marona_tool_context")
            .cloned()
            .unwrap_or(Value::Null);
        let strings = |key: &str| {
            metadata[key]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(Value::as_str)
                .map(str::to_owned)
                .collect()
        };
        let context = ToolContext {
            user_id: request.user_id.clone(),
            session_id: metadata["session_id"]
                .as_str()
                .or(request.conversation_id.as_deref())
                .unwrap_or("default")
                .into(),
            developer_id: metadata["developer_id"].as_str().map(str::to_owned),
            permissions: strings("permissions"),
            approved_tools: strings("approved_tools"),
            metadata: request.metadata.clone(),
        };
        let output = tool.invoke(args.clone(), context).await?;
        results
            .push(json!({"name":name,"call_id":call["call_id"],"arguments":args,"output":output}));
    }
    Ok(json!(results))
}

fn hook_context(request: &CreateRequest) -> crate::AgentContext {
    crate::AgentContext {
        user_id: request.user_id.clone(),
        session_id: request
            .conversation_id
            .clone()
            .unwrap_or_else(|| "default".into()),
        agent_name: "Responses".into(),
        metadata: request.metadata.clone(),
    }
}

fn sse_boundary(bytes: &[u8]) -> Option<(usize, usize)> {
    (0..bytes.len()).find_map(|index| {
        if bytes[index..].starts_with(b"\r\n\r\n") {
            Some((index, 4))
        } else if bytes[index..].starts_with(b"\n\n") {
            Some((index, 2))
        } else {
            None
        }
    })
}

pub(crate) fn runtime_body(request: &CreateRequest) -> Result<Value> {
    validate_model_namespace(&request.model)?;
    if let Some(routing) = request.routing.as_ref() {
        for model in &routing.allowed_models {
            validate_model_namespace(model)?;
        }
    }
    let (text, attachments) = normalize_input(&request.input)?;
    let messages = match &request.input {
        Input::Message(value) => vec![value],
        Input::Messages(values) => values.iter().collect(),
        Input::Text(_) => vec![],
    };
    let mut instructions = Vec::new();
    for message in messages {
        if message["role"] != "developer" {
            continue;
        }
        if let Some(text) = message["content"].as_str() {
            instructions.push(text.to_owned());
        } else {
            for block in message["content"].as_array().into_iter().flatten() {
                if block["type"] == "input_text" {
                    if let Some(text) = block["text"].as_str() {
                        instructions.push(text.to_owned());
                    }
                }
            }
        }
    }
    if let Some(value) = &request.developer_instructions {
        instructions.push(value.clone());
    }
    let mut metadata = request.metadata.clone();
    if !request.function_tools.is_empty() {
        let mut names = std::collections::HashSet::new();
        for tool in &request.function_tools {
            if !names.insert(&tool.name) {
                return Err(Error::Validation("Duplicate function tool name".into()));
            }
        }
        metadata.insert(
            "marona_function_tools".into(),
            json!(request
                .function_tools
                .iter()
                .map(|tool| tool.definition())
                .collect::<Vec<_>>()),
        );
    }
    if request.tool_choice != ToolChoice::None {
        if let Some(connection) = &request.tools {
            let tools: Vec<_> = connection.descriptors().into_iter().filter_map(|tool| {
                if tool.get("function").is_some_and(Value::is_object) {
                    return Some(tool);
                }
                let name = tool.get("name").and_then(Value::as_str)?.trim();
                if name.is_empty() { return None; }
                Some(json!({"type":"function","function":{
                    "name":name,
                    "description":tool.get("description").and_then(Value::as_str).filter(|s| !s.is_empty()).unwrap_or(name),
                    "parameters":tool.get("parameters").filter(|v| v.is_object() && v.as_object().is_some_and(|o| !o.is_empty())).cloned().unwrap_or_else(||json!({"type":"object","properties":{}}))
                },"marona":tool.get("x_marona").filter(|v| !v.is_null()).cloned().unwrap_or_else(||json!({}))}))
            }).collect();
            if !tools.is_empty() {
                metadata.insert("tools".into(), json!(tools));
            }
        }
    }
    let mut agent = metadata
        .remove("marona_agent")
        .and_then(|value| value.as_object().cloned())
        .unwrap_or_default();
    agent.insert("tool_choice".into(), json!(request.tool_choice));
    agent.entry("tools_enabled").or_insert_with(|| {
        json!(
            (request.tools.is_some() || !request.function_tools.is_empty())
                && request.tool_choice != ToolChoice::None
        )
    });
    metadata.insert("marona_agent".into(), Value::Object(agent));
    let apps = request
        .tools
        .as_ref()
        .and_then(|value| value.payload.get("apps"))
        .cloned();
    let skills = request
        .tools
        .as_ref()
        .and_then(|value| value.payload.get("skills"))
        .cloned();
    Ok(json!({
        "interface": request.interface,
        "model": request.model,
        "user_id": request.user_id,
        "conversation_id": request.conversation_id,
        "text": text,
        "developer_instructions": if instructions.is_empty() { None } else { Some(instructions.join("\n")) },
        "execute": true,
        "attachments": attachments,
        "metadata": metadata,
        "routing": request.routing,
        "output": request.output,
        "apps": apps,
        "skills": skills,
    }))
}

pub(crate) fn validate_model_namespace(model: &str) -> Result<()> {
    let value = model.trim();
    if !value.starts_with("marona/") || value == "marona/" {
        return Err(Error::invalid_model_namespace());
    }
    Ok(())
}

pub(crate) fn normalize_input(input: &Input) -> Result<(String, Vec<Value>)> {
    match input {
        Input::Text(text) => Ok((text.clone(), vec![])),
        Input::Message(value) => normalize_messages(std::slice::from_ref(value)),
        Input::Messages(values) => normalize_messages(values),
    }
}

fn normalize_messages(messages: &[Value]) -> Result<(String, Vec<Value>)> {
    let mut text = Vec::new();
    let mut attachments = Vec::new();
    for message in messages {
        if message["role"] == "developer" {
            continue;
        }
        let content = message.get("content").cloned().unwrap_or(Value::Null);
        if let Some(value) = content.as_str() {
            text.push(value.to_owned());
            continue;
        }
        for block in content.as_array().into_iter().flatten() {
            match block.get("type").and_then(Value::as_str).unwrap_or("") {
                "input_text" => {
                    if let Some(value) = block.get("text").and_then(Value::as_str) {
                        text.push(value.to_owned());
                    }
                }
                "input_image" => attachments.push(attachment(block, "image")?),
                "input_audio" => attachments.push(attachment(block, "audio")?),
                "input_video" => attachments.push(attachment(block, "video")?),
                "input_file" => attachments.push(attachment(block, "file")?),
                _ => {}
            }
        }
    }
    if text.is_empty() && attachments.is_empty() {
        return Err(Error::Validation("input is empty".into()));
    }
    Ok((text.join("\n"), attachments))
}

fn attachment(block: &Value, kind: &str) -> Result<Value> {
    let data_key = format!("{kind}_data");
    let url_key = format!("{kind}_url");
    let mut keys = vec![
        data_key.as_str(),
        url_key.as_str(),
        "url",
        "file_id",
        "path",
    ];
    if kind == "image" {
        keys.push("file_data");
    }
    let supplied: Vec<_> = keys
        .into_iter()
        .filter_map(|key| {
            block
                .get(key)
                .and_then(Value::as_str)
                .filter(|v| !v.is_empty())
                .map(|v| (key, v))
        })
        .collect();
    if supplied.len() != 1 && !(supplied.is_empty() && kind == "file" && block["text"].is_string())
    {
        return Err(Error::Validation(
            "Attachment requires exactly one document source".into(),
        ));
    }
    let mut result = json!({"kind":kind});
    let mut metadata = json!({});
    let mut mime = block["mime_type"].as_str().map(str::to_owned);
    if let Some((key, value)) = supplied.first().copied() {
        if matches!(key, "file_id" | "path") {
            metadata[key] = json!(value);
        } else if let Some(data) = value.strip_prefix("data:") {
            let (header, payload) = data
                .split_once(',')
                .ok_or_else(|| Error::Validation("Malformed attachment data URL".into()))?;
            let declared = header.split(';').next().unwrap_or("");
            if !declared.is_empty() {
                mime = Some(declared.into());
            }
            let bytes = percent_bytes(payload)?;
            result["data_base64"] = if header.contains(";base64") {
                json!(valid_base64(std::str::from_utf8(&bytes).map_err(
                    |_| Error::Validation("Invalid attachment Base64".into())
                )?)?)
            } else {
                json!(base64::engine::general_purpose::STANDARD.encode(bytes))
            };
        } else if key.ends_with("_data") {
            result["data_base64"] = json!(valid_base64(value)?);
        } else {
            let uri = url::Url::parse(value).map_err(|_| {
                Error::Validation("Attachment URL must be credential-free HTTP(S)".into())
            })?;
            if !matches!(uri.scheme(), "http" | "https")
                || uri.host_str().is_none()
                || !uri.username().is_empty()
                || uri.password().is_some()
            {
                return Err(Error::Validation(
                    "Attachment URL must be credential-free HTTP(S)".into(),
                ));
            }
            result["url"] = json!(value);
        }
    }
    let filename = block["filename"].as_str().map(str::to_owned).or_else(|| {
        result["url"]
            .as_str()
            .and_then(|v| url::Url::parse(v).ok())
            .and_then(|url| {
                url.path_segments()
                    .and_then(|mut parts| parts.next_back())
                    .map(str::to_owned)
            })
    });
    if let Some(filename) = &filename {
        result["filename"] = json!(filename);
    }
    let mime = mime.unwrap_or_else(|| {
        match filename
            .as_deref()
            .unwrap_or("")
            .rsplit('.')
            .next()
            .unwrap_or("")
            .to_lowercase()
            .as_str()
        {
            "pdf" => "application/pdf".into(),
            "png" => "image/png".into(),
            "jpg" | "jpeg" => "image/jpeg".into(),
            "gif" => "image/gif".into(),
            "webp" => "image/webp".into(),
            "txt" => "text/plain".into(),
            "wav" => "audio/wav".into(),
            "mp3" => "audio/mpeg".into(),
            "mp4" => "video/mp4".into(),
            _ => {
                if kind == "file" {
                    "application/octet-stream".into()
                } else {
                    format!("{kind}/*")
                }
            }
        }
    });
    if kind == "file" {
        result["kind"] = json!(if mime.starts_with("image/") {
            "image"
        } else if mime.starts_with("audio/") {
            "audio"
        } else if mime.starts_with("video/") {
            "video"
        } else if mime == "application/pdf" || mime.starts_with("text/") {
            "document"
        } else {
            "file"
        });
    }
    result["mime_type"] = json!(mime);
    if let Some(value) = block.get("text") {
        result["text"] = value.clone();
    }
    if let Some(value) = block.get("detail") {
        metadata["detail"] = value.clone();
    }
    if !metadata.as_object().unwrap().is_empty() {
        result["metadata"] = metadata;
    }
    Ok(result)
}
fn valid_base64(value: &str) -> Result<&str> {
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(value)
        .map_err(|_| {
            Error::Validation("Attachment data must contain valid standard Base64".into())
        })?;
    if bytes.is_empty() || base64::engine::general_purpose::STANDARD.encode(bytes) != value {
        return Err(Error::Validation(
            "Attachment data must contain valid standard Base64".into(),
        ));
    }
    Ok(value)
}
fn percent_bytes(value: &str) -> Result<Vec<u8>> {
    let source = value.as_bytes();
    let mut bytes = Vec::new();
    let mut index = 0;
    while index < source.len() {
        if source[index] == b'%' {
            let high = source
                .get(index + 1)
                .and_then(|v| (*v as char).to_digit(16));
            let low = source
                .get(index + 2)
                .and_then(|v| (*v as char).to_digit(16));
            match (high, low) {
                (Some(high), Some(low)) => bytes.push((high * 16 + low) as u8),
                _ => return Err(Error::Validation("Malformed attachment data URL".into())),
            }
            index += 3;
        } else {
            bytes.push(source[index]);
            index += 1;
        }
    }
    Ok(bytes)
}

pub(crate) fn response_from_value(mut value: Value) -> Result<RuntimeResponse> {
    let object = value
        .as_object_mut()
        .ok_or_else(|| Error::Protocol("runtime response must be an object".into()))?;
    if !object.contains_key("output") {
        let reply = object
            .get("reply")
            .cloned()
            .unwrap_or(Value::String(String::new()));
        let artifacts = object
            .get("artifacts")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default();
        object.insert(
            "output".into(),
            if artifacts.is_empty() {
                reply
            } else {
                let mut output = Vec::new();
                if let Some(text) = reply.as_str().filter(|v| !v.is_empty()) {
                    output.push(json!({"type":"output_text","text":text}));
                }
                output.extend(artifacts);
                Value::Array(output)
            },
        );
    }
    let object = value
        .as_object()
        .ok_or_else(|| Error::Protocol("runtime response must be an object".into()))?;
    let mut safe = Map::new();
    for name in [
        "status",
        "reply",
        "output",
        "interface",
        "conversation_id",
        "ui",
        "artifacts",
        "selected_app",
        "selected_tool",
        "permission_request",
        "needs_permission",
        "needs_service_connection",
        "service_connection",
        "tool_call",
        "model",
        "usage",
        "agent",
    ] {
        if let Some(item) = object.get(name) {
            safe.insert(name.into(), item.clone());
        }
    }
    let raw_routing = object.get("routing").and_then(Value::as_object);
    let mut routing = Map::new();
    for name in [
        "requested_model",
        "selected_model",
        "strategy",
        "fallback_used",
    ] {
        if let Some(item) = raw_routing.and_then(|value| value.get(name)) {
            routing.insert(name.into(), item.clone());
        }
    }
    safe.insert("routing".into(), Value::Object(routing));
    serde_json::from_value(Value::Object(safe)).map_err(|error| Error::Protocol(error.to_string()))
}

fn event_from_value(value: Value) -> RunEvent {
    RunEvent {
        event_type: value
            .get("type")
            .and_then(Value::as_str)
            .unwrap_or("unknown")
            .to_owned(),
        delta: value
            .get("delta")
            .and_then(Value::as_str)
            .map(str::to_owned),
        output: value.get("output").cloned().unwrap_or(Value::Null),
        data: value
            .get("data")
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default(),
    }
}