| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you under the Apache License, Version 2.0 (the | |
| * "License"); you may not use this file except in compliance | |
| * with the License. You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, | |
| * software distributed under the License is distributed on an | |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| * KIND, either express or implied. See the License for the | |
| * specific language governing permissions and limitations | |
| * under the License. | |
| */ | |
| use super::{super::events::model_usage, Result}; | |
| use maka_agent_facts::model::{ | |
| ModelEvent, ModelFinishReason, ModelSource, ModelToolCall, ModelUsage, PlaintextResponses, | |
| TextKind, ToolInput, | |
| }; | |
| use maka_agent_facts::tools::ToolDefinition; | |
| use maka_provider_protocol::{ | |
| output::{Stop, TextKind as WireTextKind}, | |
| responses::{self as wire, Event, ItemMetadata, MessagePhase, PartMetadata}, | |
| }; | |
| use serde_json::{Value, json}; | |
| use std::sync::Arc; | |
| pub struct Decoder { | |
| native_compaction: bool, | |
| compaction: Option<maka_agent_facts::model::NativeCompaction>, | |
| inner: wire::decode::Decoder, | |
| plaintext: Option<PlaintextResponses>, | |
| pub observed_output: bool, | |
| pub replay_safe: bool, | |
| } | |
| impl Decoder { | |
| pub fn new(plaintext: Option<PlaintextResponses>, tools: &[Arc<ToolDefinition>]) -> Self { | |
| let search_name = tools | |
| .iter() | |
| .find(|tool| { | |
| tool.provider | |
| .as_ref() | |
| .is_some_and(|provider| super::request::search_kind(&provider.id).is_some()) | |
| }) | |
| .map(|tool| tool.name.clone()); | |
| Self { | |
| native_compaction: false, | |
| compaction: None, | |
| inner: wire::decode::Decoder::new( | |
| super::request::reasoning_mode(plaintext), | |
| search_name, | |
| ), | |
| plaintext, | |
| observed_output: false, | |
| replay_safe: true, | |
| } | |
| } | |
| pub fn operation(mut self, operation: maka_agent_facts::context::ModelOperation) -> Self { | |
| self.native_compaction = | |
| operation == maka_agent_facts::context::ModelOperation::CodexCompaction; | |
| self | |
| } | |
| fn accept_compaction(&mut self, item: Value, terminal: bool) -> Result<()> { | |
| if !self.native_compaction { | |
| return Err(super::Error::Invalid( | |
| "unexpected native compaction output".into(), | |
| )); | |
| } | |
| if item["encrypted_content"].as_str().is_none_or(str::is_empty) { | |
| return Err(super::Error::Invalid( | |
| "invalid native compaction output".into(), | |
| )); | |
| } | |
| match &self.compaction { | |
| None => { | |
| self.compaction = Some( | |
| maka_agent_facts::model::NativeCompaction::new(item) | |
| .map_err(|e| super::Error::Invalid(e.into()))?, | |
| ) | |
| } | |
| Some(previous) if terminal && previous.item() == &item => {} | |
| _ => { | |
| return Err(super::Error::Invalid( | |
| "multiple native compaction output items".into(), | |
| )); | |
| } | |
| } | |
| self.observed_output = true; | |
| self.replay_safe = false; | |
| Ok(()) | |
| } | |
| pub fn finished(&self) -> bool { | |
| self.inner.finished() | |
| } | |
| pub fn end(&self) -> Result<()> { | |
| if self.compaction.is_some() && !self.inner.finished() { | |
| return Err(super::Error::Truncated { | |
| replay_safe: false, | |
| retained_output_safe: false, | |
| }); | |
| } | |
| self.inner.end().map_err(Into::into) | |
| } | |
| pub fn retained_output_safe(&self) -> bool { | |
| self.compaction.is_none() && self.inner.retained_output_safe() | |
| } | |
| #[cfg(test)] | |
| fn push(&mut self, value: Value) -> Result<Vec<ModelEvent>> { | |
| self.push_with_terminal_usage(value, |_| {}) | |
| } | |
| pub fn push_with_terminal_usage( | |
| &mut self, | |
| mut value: Value, | |
| observe_terminal_usage: impl FnOnce(ModelUsage), | |
| ) -> Result<Vec<ModelEvent>> { | |
| let event_type = value["type"].as_str().unwrap_or_default().to_owned(); | |
| if value["item"]["type"] == "compaction" { | |
| if !self.native_compaction { | |
| return Err(super::Error::Invalid( | |
| "unexpected native compaction output".into(), | |
| )); | |
| } | |
| if event_type == "response.output_item.done" { | |
| self.accept_compaction(value["item"].take(), false)?; | |
| } | |
| return Ok(vec![]); | |
| } | |
| if matches!( | |
| event_type.as_str(), | |
| "response.completed" | "response.incomplete" | |
| ) { | |
| if let Some(items) = value | |
| .get_mut("response") | |
| .and_then(|response| response.get_mut("output")) | |
| .and_then(Value::as_array_mut) | |
| { | |
| let native = items | |
| .iter() | |
| .filter(|item| item["type"] == "compaction") | |
| .cloned() | |
| .collect::<Vec<_>>(); | |
| if native.len() > 1 { | |
| return Err(super::Error::Invalid( | |
| "multiple native compaction output items".into(), | |
| )); | |
| } | |
| for item in native { | |
| self.accept_compaction(item, true)?; | |
| } | |
| items.retain(|item| item["type"] != "compaction"); | |
| } | |
| if self.native_compaction | |
| && (event_type != "response.completed" | |
| || self.compaction.is_none() | |
| || value["response"]["id"].as_str().is_none_or(str::is_empty)) | |
| { | |
| return Err(super::Error::Invalid( | |
| "native compaction did not complete".into(), | |
| )); | |
| } | |
| } | |
| let live_item = event_type == "response.output_item.added" | |
| && !matches!( | |
| value["item"]["status"].as_str(), | |
| Some("completed" | "failed" | "incomplete") | |
| ); | |
| let events = self | |
| .inner | |
| .push_with_terminal_usage(value, |usage| observe_terminal_usage(model_usage(usage))); | |
| self.observed_output = self.inner.observed_output || self.compaction.is_some(); | |
| self.replay_safe = self.inner.replay_safe && self.compaction.is_none(); | |
| events.map_err(Into::into).map(|events| { | |
| let mut projected = Vec::with_capacity(events.len()); | |
| for event in events { | |
| let event = self.project(event); | |
| if live_item | |
| && let ModelEvent::ToolCall(call) = &event | |
| && call.provider_executed | |
| { | |
| projected.push(ModelEvent::ToolInputStarted { | |
| id: call.id.clone(), | |
| name: call.name.clone(), | |
| provider_executed: true, | |
| }); | |
| } | |
| projected.push(event); | |
| } | |
| projected | |
| }) | |
| } | |
| fn project(&self, event: Event) -> ModelEvent { | |
| match event { | |
| Event::ResponseMetadata { | |
| id, | |
| model, | |
| created_at_unix_seconds, | |
| } => ModelEvent::ResponseMetadata { | |
| id, | |
| model, | |
| timestamp: created_at_unix_seconds | |
| .filter(|seconds| { | |
| seconds.is_finite() && seconds.abs() <= 8_640_000_000_000.0 | |
| }) | |
| .and_then(|seconds| { | |
| jiff::Timestamp::from_millisecond((seconds * 1000.0) as i64).ok() | |
| }) | |
| .map(|value| format!("{value:.3}")), | |
| }, | |
| Event::PartStarted { id, kind, phase } => ModelEvent::PartStarted { | |
| id, | |
| text_kind: match kind { | |
| WireTextKind::Text => TextKind::Text, | |
| WireTextKind::Reasoning => TextKind::Thinking, | |
| }, | |
| provider_options: phase | |
| .filter(|phase| !matches!(phase, MessagePhase::Unknown)) | |
| .map(|phase| json!({"openai":{"messagePhase":phase}})), | |
| }, | |
| Event::PartDelta { id, text, summary_breaks } => ModelEvent::PartDelta { | |
| id, | |
| text, | |
| provider_options: summary_breaks.map(|breaks| json!({"makaSummaryBreaks": breaks})), | |
| }, | |
| Event::PartFinished { id, metadata } => ModelEvent::PartFinished { | |
| id, | |
| provider_options: metadata.map(|metadata| match metadata { | |
| PartMetadata::Item(metadata) => item_options(metadata), | |
| PartMetadata::Message { item, phase } => { | |
| let mut options = item_options(item); | |
| options["openai"]["messagePhase"] = json!(phase); | |
| options | |
| } | |
| PartMetadata::PlaintextSummary { | |
| item_id, | |
| summary_part_lengths, | |
| } => json!({ | |
| "makaResponses": { | |
| "version": 1, | |
| "profile": self.plaintext.expect("plaintext summary contract").profile(), | |
| "itemId": item_id, | |
| "summaryPartLengths": summary_part_lengths, | |
| } | |
| }), | |
| }), | |
| }, | |
| Event::ToolInputStarted { id, name } => ModelEvent::ToolInputStarted { | |
| id, | |
| name: super::request::local_name(&name).into(), | |
| provider_executed: false, | |
| }, | |
| Event::ToolInputDelta { id, text } => ModelEvent::ToolInputDelta { id, text }, | |
| Event::ToolInputFinished { id } => ModelEvent::ToolInputFinished { id }, | |
| Event::ToolCall { | |
| id, | |
| name, | |
| input, | |
| provider_executed, | |
| metadata, | |
| } => { | |
| let mut options = item_options(metadata); | |
| let input = match input { | |
| wire::ToolInput::Function(input) => ToolInput::from_json(input), | |
| wire::ToolInput::Custom(input) => { | |
| options["openai"]["toolKind"] = json!("custom"); | |
| ToolInput::Json(json!(input)) | |
| } | |
| }; | |
| ModelEvent::ToolCall(ModelToolCall { | |
| id, | |
| name: if provider_executed { | |
| name | |
| } else { | |
| super::request::local_name(&name).into() | |
| }, | |
| input, | |
| provider_executed, | |
| provider_options: Some(options), | |
| }) | |
| } | |
| Event::ToolResult { | |
| id, | |
| name, | |
| action, | |
| is_error, | |
| metadata, | |
| } => ModelEvent::ProviderToolResult { | |
| id, | |
| name, | |
| output: json!({"action": action}), | |
| is_error, | |
| provider_options: Some(item_options(metadata)), | |
| }, | |
| Event::HostedResult { id, name, items, is_error } => ModelEvent::ProviderToolResult { | |
| id, name, output: Value::Array(items), is_error, provider_options: Some(json!({"openai":{"responsesHostedItems":true}})), | |
| }, | |
| Event::Citation(citation) => ModelEvent::Source { anchor: citation.anchor, source: ModelSource::Url { | |
| id: citation.id, | |
| url: citation.url, | |
| title: citation.title, | |
| provider_options: Some(json!({"openai": { | |
| "itemId": citation.item_id, | |
| "contentIndex": citation.content_index, | |
| "startIndex": citation.start_index, | |
| "endIndex": citation.end_index, | |
| }})), | |
| } }, | |
| Event::Finished { | |
| reason, | |
| usage, | |
| response_id, | |
| } => ModelEvent::Finished { | |
| reason: match reason { | |
| Stop::Stop => ModelFinishReason::Stop, | |
| Stop::Length => ModelFinishReason::Length, | |
| Stop::ToolCalls => ModelFinishReason::ToolCalls, | |
| _ => unreachable!("Responses decoder finish reason"), | |
| }, | |
| usage: model_usage(&usage), | |
| compaction: self.compaction.clone(), | |
| provider_options: response_id.map(|id| json!({"openai":{"responseId":id}})), | |
| }, | |
| } | |
| } | |
| } | |
| fn item_options(metadata: ItemMetadata) -> Value { | |
| let mut options = json!({"openai": {}}); | |
| if !metadata.id.is_empty() { | |
| options["openai"]["itemId"] = json!(metadata.id); | |
| } | |
| if let Some(replay) = metadata.replay { | |
| options["openai"]["responsesReplay"] = json!(replay); | |
| } | |
| if let Some(encrypted) = metadata.encrypted_content { | |
| options["openai"]["reasoningEncryptedContent"] = json!(encrypted); | |
| } | |
| options | |
| } | |
| #[cfg(test)] | |
| mod native_tests; |