artifactize-provider 0.30.0

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
//! Bounded, cancellation-safe framing of a Claude Code stream. The caller owns its process.

use std::io;

use serde_json::Value;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};

use super::Line;

/// A line carries one message, tool result or verdict. Even a 16 MiB tool result can
/// expand in JSON; 32 MiB leaves room for that without allowing an unbounded line.
const LINE_LIMIT: usize = 32 * 1024 * 1024;

#[derive(Debug)]
pub enum ChannelError {
    Write(io::Error),
    Read(io::Error),
    Oversize,
    Parse(serde_json::Error),
}

impl std::fmt::Display for ChannelError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Write(error) => {
                write!(formatter, "Claude Code stopped reading its input: {error}.")
            }
            Self::Read(error) => write!(formatter, "Cannot read Claude Code's output: {error}."),
            Self::Oversize => formatter.write_str("Claude Code wrote a line over 32 MiB."),
            Self::Parse(error) => write!(
                formatter,
                "Claude Code wrote a line artifactize cannot read: {error}."
            ),
        }
    }
}

impl std::error::Error for ChannelError {}

pub struct Channel<R, W> {
    reader: BufReader<R>,
    // `next` can lose a select! after reading only part of a line.
    partial: Vec<u8>,
    writer: W,
}

impl<R: AsyncRead + Unpin, W: AsyncWrite + Unpin> Channel<R, W> {
    pub fn new(reader: R, writer: W) -> Self {
        Self {
            reader: BufReader::new(reader),
            partial: Vec::new(),
            writer,
        }
    }

    pub async fn send(&mut self, line: &Value) -> Result<(), ChannelError> {
        let mut bytes = line.to_string().into_bytes();
        bytes.push(b'\n');
        self.writer
            .write_all(&bytes)
            .await
            .map_err(ChannelError::Write)?;
        self.writer.flush().await.map_err(ChannelError::Write)
    }

    /// The next line, or `None` once Claude Code's output ended.
    pub async fn next(&mut self) -> Result<Option<Line>, ChannelError> {
        loop {
            if self.partial.len() > LINE_LIMIT {
                return Err(ChannelError::Oversize);
            }
            let remaining = LINE_LIMIT + 1 - self.partial.len();
            (&mut self.reader)
                .take(remaining as u64)
                .read_until(b'\n', &mut self.partial)
                .await
                .map_err(ChannelError::Read)?;
            if self.partial.is_empty() {
                return Ok(None);
            }
            if self.partial.len() > LINE_LIMIT {
                return Err(ChannelError::Oversize);
            }
            if self.partial.iter().all(u8::is_ascii_whitespace) {
                self.partial.clear();
                continue;
            }
            let parsed = serde_json::from_slice(&self.partial);
            self.partial.clear();
            return parsed.map(Some).map_err(ChannelError::Parse);
        }
    }
}