Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
276 changes: 259 additions & 17 deletions native/omk-providers/README.md

Large diffs are not rendered by default.

57,833 changes: 57,833 additions & 0 deletions native/omk-providers/catalog.json

Large diffs are not rendered by default.

82 changes: 14 additions & 68 deletions native/omk-providers/src/anthropic.rs
Original file line number Diff line number Diff line change
@@ -1,46 +1,6 @@
//! First offline Anthropic parity slice; not the full provider/auth surface.
use crate::json_parse::parse_sse_with_repair;
pub use crate::anthropic_stream::{Replay, Stream};
pub use crate::request::{Input, build_request};
use crate::{
reducer::Reducer,
sse::{Decoder, Frame},
};
use serde_json::{Value, json};

pub struct Replay {
pub events: Value,
pub result: Value,
pub tool_arguments: Value,
}
fn consume(reducer: &mut Reducer, frame: Frame) -> Result<(), String> {
if frame.event == "error" {
return Err(frame.data);
}
if ![
"message_start",
"message_delta",
"message_stop",
"content_block_start",
"content_block_delta",
"content_block_stop",
]
.contains(&frame.event.as_str())
{
return Ok(());
}
let event = parse_sse_with_repair(&frame.data).map_err(|error| {
let detail = error.to_string();
format!(
"Could not parse Anthropic SSE event {}: {}; data={}; raw={}",
frame.event,
detail,
frame.data,
frame.raw.join("\\n")
)
})?;
reducer.apply(event)
}

pub fn replay(
model: &str,
chunks: &[Vec<u8>],
Expand All @@ -64,7 +24,10 @@ fn replay_internal(
abort_after: Option<usize>,
observe: bool,
) -> Result<Replay, String> {
if model != "synthetic-anthropic" {
// Vision has a request-only oracle; do not admit unrecorded response/cancellation replay.
if model != "synthetic-anthropic"
&& (model != "synthetic-anthropic-vision" || !chunks.is_empty() || abort_after.is_some())
{
return Err("unrecorded model".into());
}
if chunks
Expand All @@ -77,33 +40,16 @@ fn replay_internal(
if abort_after.is_some_and(|n| n > chunks.len()) {
return Err("invalid cancellation boundary".into());
}
let mut reducer = Reducer::new(model, observe);
let mut decoder = Decoder::default();
let outcome = (|| {
if abort_after == Some(0) {
return Err("Request was aborted".into());
}
for (index, chunk) in chunks.iter().enumerate() {
if abort_after == Some(index) {
let mut stream = Stream::recorded(model, observe);
if abort_after != Some(0) {
for chunk in chunks.iter().take(abort_after.unwrap_or(chunks.len())) {
if stream.feed(chunk).is_err() {
break;
}
for frame in decoder.feed(chunk, false)? {
consume(&mut reducer, frame)?;
}
}
for frame in decoder.feed(&[], true)? {
consume(&mut reducer, frame)?;
}
if abort_after.is_some() && !(reducer.started && !reducer.stopped) {
return Err("Request was aborted".into());
}
Ok(())
})();
let tool_arguments = json!(std::mem::take(&mut reducer.tool_arguments));
let (events, result) = reducer.finish(outcome.err(), abort_after.is_some());
Ok(Replay {
events,
result,
tool_arguments,
})
}
Ok(stream.finish(
(abort_after == Some(0)).then(|| "Request was aborted".into()),
abort_after.is_some(),
))
}
110 changes: 110 additions & 0 deletions native/omk-providers/src/anthropic_stream.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// Incremental ownership of the existing Node-derived Anthropic decoder/reducer.
use crate::{
json_parse::parse_sse_with_repair,
reducer::Reducer,
sse::{Decoder, Frame},
};
use serde_json::{Value, json};

fn consume(reducer: &mut Reducer, frame: Frame) -> Result<(), String> {
if frame.event == "error" {
return Err(frame.data);
}
if ![
"message_start",
"message_delta",
"message_stop",
"content_block_start",
"content_block_delta",
"content_block_stop",
]
.contains(&frame.event.as_str())
{
return Ok(());
}
let event = parse_sse_with_repair(&frame.data).map_err(|error| {
let detail = error.to_string();
format!(
"Could not parse Anthropic SSE event {}: {}; data={}; raw={}",
frame.event,
detail,
frame.data,
frame.raw.join("\\n")
)
})?;
reducer.apply(event)
}
pub struct Replay {
pub events: Value,
pub result: Value,
pub tool_arguments: Value,
}
/// Incremental semantic events for the recorded text model, without retaining wire chunks.
/// This projection excludes mutable partial snapshots, timestamps and cost.
pub struct Stream {
reducer: Reducer,
decoder: Decoder,
bytes: usize,
failure: Option<String>,
}
impl Stream {
pub fn new(model: &str) -> Result<Self, String> {
if model != "synthetic-anthropic" {
return Err("unrecorded model".into());
}
Ok(Self::recorded(model, false))
}
pub(crate) fn recorded(model: &str, observe: bool) -> Self {
Self {
reducer: Reducer::new(model, observe),
decoder: Decoder::default(),
bytes: 0,
failure: None,
}
}
/// Failure is latched; drain prior events even when this call fails.
pub fn feed(&mut self, bytes: &[u8]) -> Result<(), String> {
if let Some(error) = &self.failure {
return Err(error.clone());
}
let outcome = (|| {
self.bytes = self
.bytes
.checked_add(bytes.len())
.filter(|n| *n <= 8 * 1024 * 1024)
.ok_or("stream exceeds 8 MiB")?;
self.decode(bytes, false)
})();
if let Err(error) = &outcome {
self.failure = Some(error.clone());
}
outcome
}
fn decode(&mut self, bytes: &[u8], eof: bool) -> Result<(), String> {
for frame in self.decoder.feed(bytes, eof)? {
consume(&mut self.reducer, frame)?;
}
Ok(())
}
/// Move queued events out exactly once. Call after construction and each feed.
pub fn take_events(&mut self) -> Vec<Value> {
std::mem::take(&mut self.reducer.events)
}
/// Consumes the stream, appending exactly one terminal event to undrained events.
pub fn finish(mut self, error: Option<String>, aborted: bool) -> Replay {
self.failure = self.failure.or(error);
if self.failure.is_none() {
self.failure = self.decode(&[], true).err();
}
if self.failure.is_none() && aborted && !(self.reducer.started && !self.reducer.stopped) {
self.failure = Some("Request was aborted".into());
}
let tool_arguments = json!(std::mem::take(&mut self.reducer.tool_arguments));
let (events, result) = self.reducer.finish(self.failure, aborted);
Replay {
events,
result,
tool_arguments,
}
}
}
99 changes: 99 additions & 0 deletions native/omk-providers/src/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
//! Read-only credential snapshots. The host owns file locks, environment selection and refresh.
use serde_json::Value;
use std::{collections::BTreeMap, fmt};

#[derive(Debug, PartialEq, Eq)]
pub enum Error {
InvalidInput,
UnavailableStore,
InvalidCredential,
CommandRequiresHost,
OAuthRequiresHost,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::InvalidInput => "credential input exceeds its bound",
Self::UnavailableStore => "credential store unavailable",
Self::InvalidCredential => "invalid stored credential",
Self::CommandRequiresHost => "credential command requires host execution",
Self::OAuthRequiresHost => "OAuth credential requires host refresh ownership",
})
}
}
impl std::error::Error for Error {}
/// Deliberately neither serializable nor printable. Exposure is an explicit caller action.
pub struct Secret(pub(crate) String);
impl Secret {
pub fn expose(&self) -> &str {
&self.0
}
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[REDACTED]")
}
}
/// `environment` is already selected by the host's provider-specific environment policy.
pub struct KeySources<'a> {
pub runtime: Option<&'a str>,
pub environment: Option<&'a str>,
pub fallback: Option<&'a str>,
pub include_fallback: bool,
}
/// An unreadable/malformed store is retained as failure, never converted to an empty map.
pub struct Snapshot(Result<BTreeMap<String, Value>, ()>);
impl Snapshot {
pub fn from_json(raw: Result<Option<&str>, ()>) -> Self {
Self(raw.and_then(|text| {
let text = text.filter(|text| !text.is_empty()).unwrap_or("{}");
if text.len() > 1024 * 1024 {
return Err(());
}
let mut data: BTreeMap<String, Value> = serde_json::from_str(text).map_err(|_| ())?;
data.remove("grok-oauth-proxy");
Ok(data)
}))
}
pub fn resolve(
&self,
provider: &str,
sources: KeySources<'_>,
env: impl Fn(&str) -> Option<String>,
) -> Result<Option<Secret>, Error> {
if let Some(key) = sources.runtime.filter(|key| !key.is_empty()) {
return bounded_secret(key).map(Some);
}
let data = self.0.as_ref().map_err(|_| Error::UnavailableStore)?;
if let Some(credential) = data.get(provider) {
match credential.get("type").and_then(Value::as_str) {
Some("api_key") => {
let key = credential
.get("key")
.and_then(Value::as_str)
.ok_or(Error::InvalidCredential)?;
// A missing referenced variable must not silently select another account.
return resolve_config(key, env);
}
Some("oauth") => return Err(Error::OAuthRequiresHost),
_ => return Err(Error::InvalidCredential),
}
}
if let Some(key) = sources.environment.filter(|key| !key.is_empty()) {
return bounded_secret(key).map(Some);
}
if sources.include_fallback
&& let Some(config) = sources.fallback
{
return resolve_config(config, env);
}
Ok(None)
}
}
pub(crate) fn bounded_secret(value: &str) -> Result<Secret, Error> {
if value.len() > 65536 {
return Err(Error::InvalidInput);
}
Ok(Secret(value.into()))
}
pub use crate::config_value::resolve_config;
Loading
Loading