Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "cloud-client",
crate_name = "codex_cloud_client",
)

View File

@@ -0,0 +1,37 @@
[package]
name = "codex-cloud-client"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[lib]
doctest = false
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
async-stream = { workspace = true }
bytes = { workspace = true }
codex-http-client = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
http-body-util = "0.1.3"
prost = "0.14.3"
tonic = { workspace = true }
tonic-prost = { workspace = true }
tower = { version = "0.5.3", features = ["util"] }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["time"] }
url = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
anyhow = { workspace = true }
pretty_assertions = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
hyper = { version = "1.8.1", features = ["server", "http2"] }
hyper-util = { version = "0.1.20", features = ["tokio"] }
tokio-rustls = { workspace = true }

View File

@@ -0,0 +1,109 @@
# Codex cloud client
Reusable Rust client for native ThreadService gRPC over HTTP/2, with no TUI,
conventional app-server or private monorepo dependency. This slice supports
`Resume` and live `Attach`. It does not use the HTTP `/grpc` JSON gateway.
The caller supplies a trusted native gRPC origin (scheme/host/port, no path),
ChatGPT bearer token, selected account ID and configured `HttpClientFactory`.
HTTPS is required except for direct loopback HTTP with an unrestricted, unmanaged
factory. This exception bypasses proxies to keep plaintext credentials local.
For HTTPS, the shared HTTP client supplies proxy,
custom CA and network policy handling; redirects are rejected. Tonic supplies
gRPC framing, protobuf encoding, message bounds (64 MiB) and status/trailer handling.
Bind factory policy before loading credentials; rebuild on login/account changes.
`ResumeRequest.wait = false` acknowledges admission, not readiness. Requests are
never retried by this crate: a timeout or disconnect can leave work admitted.
`Attach` has no history snapshot or replay guarantee. Dropping it detaches without
stopping the thread or answering approvals. Streams end after their first error.
Resume and Attach setup have a 150-second local deadline; live streams have no idle
deadline. Setup does not send a gRPC deadline that would expire a healthy stream.
`Event::Transcript` decodes selected text, command output, patch, and turn updates.
It validates the thread ID and exposes the decoded fields. Turn updates include
start time, completion time, and duration when the server provides them.
Other notifications and server requests remain opaque protobuf payloads, preserving
unknown fields. These are not ProtoJSON or app-server JSON-RPC. Native status
code, message and binary details are available explicitly; credentials, event
and error diagnostics are redacted. Item lifecycle updates report supported
message, command, and file-change summaries. Agent message summaries retain
structured questions even when their text is empty. Unsupported item kinds stay opaque.
Approval replies and reconnect are subsequent slices.
The minimal envelopes in `wire.rs` and `ResumeRequest` mirror ThreadService field
numbers; no monorepo checkout or protobuf compiler is required to build this crate.
Provide `CODEX_CLOUD_ACCESS_TOKEN` and `CODEX_CLOUD_ACCOUNT_ID` through your environment, then run
this standalone consumer from `codex-rs`:
```sh
cargo run -p codex-cloud-client --example attach -- "$CODEX_CLOUD_GRPC_ENDPOINT" "$CODEX_CLOUD_THREAD_ID"
```
Use an existing authorized thread and native gRPC origin. No production URL is
assumed. Public native ingress is a rollout assumption, not proved by fixture
tests. This change does not publish a package to a registry.
History reads use native `ListTurns` (stored turn metadata) and `ListItems` (one
turn or the whole thread). Calls return one page with forward/backward opaque
cursors, preserve server order and retain raw responses and rows. Reuse a cursor
with the same account, thread and filters. Keep the sort order for `next_cursor`
and reverse it for `backwards_cursor`. Calls never paginate or retry automatically.
Items with an unknown variant or command source remain in the page with no typed summary.
History pages and Attach have no shared revision or replay cursor. A page is not
an atomic history/live boundary, and timestamps are not event offsets. Do not
append buffered deltas to a fetched snapshot: it may already include that text.
Full item snapshots can replace matching account/host/thread/turn/item identities;
they must not create duplicate transcript rows. Disconnects, untyped recovery
notifications and uncertain overlap require authoritative history reload. This
crate exposes the read primitives; a coordinated resync/display state machine is
still required before claiming lossless resume or live/history reconciliation.
`add_user_message` submits ordered text and image parts using the thread's existing
configuration. Use `UserMessageInput::Text` or `UserMessageInput::Image` with an
`ImageReference::Url` (inline data URLs only) or `ImageReference::FileId` and optional
`ImageDetail`. Image-only input is supported; local paths must be converted by the
caller before submission. URL prefixes are case-insensitive and must contain
nonempty data; HTTP image URLs are rejected locally because the backend would
omit them. File IDs must be nonblank. Requests containing images have a 3.75 MiB
encoded-envelope cap, reserving 256 KiB below CCA's 4 MiB forwarding limit. Plain
text retains the 64 MiB encoded-message limit. Text parts carry optional UTF-8
byte spans through `UserMessageTextElement`; empty span lists preserve the plain
text wire encoding. User-message summaries retain ordered content and client IDs
for both text and image echoes.
Choose `StartIfIdle`, `Steer`, or `Queue` explicitly; admission distinguishes
started, steered, duplicate and queued results. Persist a unique client message ID
with each logical input and keep it unchanged when reconciling an uncertain
submission. Success means admission, not completion. `interrupt_turn` addresses
one thread/turn and does not stop the thread or delete queued input. Duplicate
admission exposes only the original turn ID when supplied. Its wire turn status
is synthesized by the backend and does not describe current lifecycle state;
reload history or observe Attach instead of treating the receipt as an active turn.
`MutationError::InvalidRequest` means local validation rejected the request before
sending. `OutcomeUnknown` retains the source error: even a server error can follow
admission, so status codes alone do not prove rejection. Malformed success replies
and mismatched response IDs are also uncertain. No automatic retry is performed;
dropping a pending call does not undo remote work. Reconcile with server state
before deciding whether another attempt is safe. Other input kinds, configuration
overrides and automated outcome reconciliation are not implemented.
The attach example accepts two optional additional arguments to explicitly send
one message after attaching: a persisted client message ID and the text. It uses
`StartIfIdle`, drains events during admission, and prints only redacted event kinds:
```sh
cargo run -p codex-cloud-client --example attach -- "$CODEX_CLOUD_GRPC_ENDPOINT" "$CODEX_CLOUD_THREAD_ID" "$CODEX_CLOUD_MESSAGE_ID" 'Explain this project'
```
`prewarm_default_thread` prepares an ordinary coding thread in the default managed
cloud environment, with optional model/provider selection. It returns the native
thread identity and resolved settings without a separate activation RPC. The
service makes the thread discoverable when it admits the first user message.
The service owns executor selection and paths; the caller supplies no local cwd,
workspace roots, custom configuration, or Aeon mode. This API does not request an
ephemeral thread. Prewarm is sent once; a timeout, disconnect or malformed response
can leave a prepared thread whose identity the caller did not receive. No retry
or cleanup is automatic.

View File

@@ -0,0 +1,99 @@
//! Standalone consumer; prints event kinds without logging payloads.
use codex_cloud_client::AddUserMessageRequest;
use codex_cloud_client::AdmissionOutcome;
use codex_cloud_client::Client;
use codex_cloud_client::Credentials;
use codex_cloud_client::ResumeRequest;
use codex_cloud_client::SubmissionMode;
use codex_cloud_client::UserMessageInput;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use futures::StreamExt;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let mut args = std::env::args().skip(1);
let endpoint = args
.next()
.ok_or_else(|| anyhow::anyhow!("expected native gRPC origin"))?;
let thread_id = args
.next()
.ok_or_else(|| anyhow::anyhow!("expected existing thread ID"))?;
// Supplying both extra arguments explicitly opts into sending one message.
let submission = match (args.next(), args.next()) {
(None, None) => None,
(Some(client_user_message_id), Some(text)) => Some(AddUserMessageRequest {
thread_id: thread_id.clone(),
client_user_message_id,
input: vec![UserMessageInput::Text {
text: text,
text_elements: vec![],
}],
turn_trigger: None,
mode: SubmissionMode::StartIfIdle,
shared_access: false,
}),
_ => anyhow::bail!("expected both client message ID and text, or neither"),
};
if args.next().is_some() {
anyhow::bail!("unexpected argument");
}
let credentials = Credentials::new(
&std::env::var("CODEX_CLOUD_ACCESS_TOKEN")?,
&std::env::var("CODEX_CLOUD_ACCOUNT_ID")?,
)?;
let client = Client::new(
&HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy),
&endpoint,
credentials,
)?;
client
.resume(&ResumeRequest {
thread_id: thread_id.clone(),
wait: false,
shared_access: false,
})
.await?;
let mut events = client.attach(&thread_id).await?;
if let Some(request) = submission {
// Drain Attach while admission is pending; events can precede its response.
let admission = client.add_user_message(&request);
tokio::pin!(admission);
let (result, stream_error) = loop {
tokio::select! {
result = &mut admission => {
break (result, None);
}
event = events.next() => match event {
Some(Ok(event)) => println!("{event:?}"),
Some(Err(error)) => break (admission.await, Some(anyhow::Error::new(error))),
None => break (admission.await, Some(anyhow::anyhow!("attachment ended"))),
}
}
};
match result {
Ok(admission) => println!(
"admission: {}",
match admission.outcome {
AdmissionOutcome::Started(_) => "started",
AdmissionOutcome::Steered(_) => "steered",
AdmissionOutcome::Duplicate { .. } => "duplicate",
AdmissionOutcome::Queued { .. } => "queued",
}
),
Err(error) => match stream_error {
Some(stream_error) => {
anyhow::bail!("attachment failed: {stream_error}; admission failed: {error}");
}
None => return Err(error.into()),
},
}
if let Some(error) = stream_error {
return Err(error.context("attachment failed"));
}
}
while let Some(event) = events.next().await {
println!("{:?}", event?);
}
Ok(())
}

View File

@@ -0,0 +1,536 @@
//! Authoritative cloud thread settings returned by deliberate native activation.
use crate::Client;
use crate::Error;
use crate::MutationError;
use crate::activation_wire as wire;
use bytes::Bytes;
use prost::Message;
use serde::Serialize;
use std::fmt;
#[cfg(test)]
#[path = "activation_tests.rs"]
mod tests;
/// Resolved settings and metadata returned after loading a cloud thread.
#[derive(Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadActivation {
pub thread: ThreadSnapshot,
pub collaboration_mode: Option<CollaborationMode>,
pub model: String,
pub model_provider: String,
pub service_tier: Option<String>,
pub cwd: String,
pub instruction_sources: Vec<String>,
pub runtime_workspace_roots: Vec<String>,
pub approval_policy: ApprovalPolicy,
pub approvals_reviewer: ApprovalsReviewer,
pub sandbox: SandboxPolicy,
pub active_permission_profile: Option<ActivePermissionProfile>,
pub reasoning_effort: Option<String>,
pub turns_backwards_cursor: Option<String>,
pub items_backwards_cursor: Option<String>,
}
/// Effective collaboration mode and its backend-resolved settings.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(tag = "mode", content = "settings", rename_all = "lowercase")]
pub enum CollaborationMode {
Plan(CollaborationSettings),
Default(CollaborationSettings),
}
/// The resume protocol uses snake_case for these nested settings.
#[derive(Clone, PartialEq, Eq, Serialize)]
pub struct CollaborationSettings {
pub model: String,
pub reasoning_effort: Option<String>,
pub developer_instructions: Option<String>,
}
/// Metadata needed to reconstruct a turn-free app-server thread snapshot.
#[derive(Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadSnapshot {
pub id: String,
pub session_id: String,
pub forked_from_id: Option<String>,
pub parent_thread_id: Option<String>,
pub preview: String,
pub ephemeral: bool,
pub daybreak_enabled: Option<bool>,
pub project_id: Option<String>,
pub history_mode: ThreadHistoryMode,
pub model_provider: String,
pub model: Option<String>,
pub reasoning_effort: Option<String>,
pub created_at: i64,
pub updated_at: i64,
pub recency_at: Option<i64>,
pub status: ThreadStatus,
pub path: Option<String>,
pub cwd: String,
pub cli_version: String,
pub originator: Option<String>,
pub source: SessionSource,
pub can_accept_direct_input: Option<bool>,
pub thread_source: Option<String>,
pub agent_nickname: Option<String>,
pub agent_role: Option<String>,
pub git_info: Option<GitInfo>,
pub name: Option<String>,
pub environments: Option<Vec<ThreadEnvironment>>,
/// Activation deliberately excludes turns; callers page history separately.
pub turns: [(); 0],
#[serde(skip)]
raw_protobuf: Bytes,
}
/// Optional repository metadata associated with a cloud conversation.
#[derive(Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GitInfo {
pub branch: Option<String>,
pub origin_url: Option<String>,
pub sha: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ThreadHistoryMode {
Legacy,
Paginated,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadEnvironment {
pub environment_id: String,
pub cwd: String,
pub runtime_workspace_roots: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum SessionSource {
Cli,
#[serde(rename = "vscode")]
VsCode,
Exec,
AppServer,
Unknown,
Custom(String),
SubAgent(SubAgentSource),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SubAgentSource {
Review,
Compact,
MemoryConsolidation,
ThreadSpawn {
parent_thread_id: String,
depth: i32,
agent_path: Option<String>,
agent_nickname: Option<String>,
agent_role: Option<String>,
},
Other(String),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(
tag = "type",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)]
pub enum ThreadStatus {
NotLoaded,
Idle,
SystemError,
Active { active_flags: Vec<ThreadActiveFlag> },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ThreadActiveFlag {
WaitingOnApproval,
WaitingOnUserInput,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ApprovalPolicy {
#[serde(rename = "untrusted")]
UnlessTrusted,
OnRequest,
Never,
Granular {
sandbox_approval: bool,
rules: bool,
skill_approval: bool,
request_permissions: bool,
mcp_elicitations: bool,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum ApprovalsReviewer {
#[serde(rename = "user")]
User,
#[serde(rename = "auto_review")]
AutoReview,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ActivePermissionProfile {
pub id: String,
pub extends: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum NetworkAccess {
Restricted,
Enabled,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(
tag = "type",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)]
pub enum SandboxPolicy {
DangerFullAccess,
ReadOnly {
network_access: bool,
},
ExternalSandbox {
network_access: NetworkAccess,
},
WorkspaceWrite {
writable_roots: Vec<String>,
network_access: bool,
exclude_tmpdir_env_var: bool,
exclude_slash_tmp: bool,
},
}
impl fmt::Debug for CollaborationSettings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("CollaborationSettings([redacted])")
}
}
impl fmt::Debug for ThreadActivation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ThreadActivation([redacted])")
}
}
impl fmt::Debug for ThreadSnapshot {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ThreadSnapshot([redacted])")
}
}
impl ThreadSnapshot {
/// Complete bounded native Thread payload, including fields this client does not interpret.
pub fn protobuf(&self) -> &Bytes {
&self.raw_protobuf
}
}
impl Client {
/// Loads a thread and returns its resolved settings without hydrating turns.
///
/// This is a mutation-capable RPC and is never retried. A timeout or disconnect
/// can leave the thread loaded even though the caller did not receive settings.
/// Local rejection sends nothing; errors after dispatch leave the outcome unknown.
pub async fn activate(&self, thread_id: &str) -> Result<ThreadActivation, MutationError> {
if thread_id.trim().is_empty() {
return Err(MutationError::InvalidRequest);
}
let bytes = self
.mutate(
wire::UpdateConfigRequest {
exclude_turns: Some(true),
thread_id: Some(thread_id.to_owned()),
},
"/oaiproto.codex_app_server_backend.ThreadService/UpdateConfig",
)
.await?;
let response = wire::UpdateConfigResponse::decode(bytes)
.map_err(|_| MutationError::OutcomeUnknown(Error::InvalidResponse))?;
let settings =
ThreadActivation::from_settings(response).map_err(MutationError::OutcomeUnknown)?;
if settings.thread.id != thread_id {
return Err(MutationError::OutcomeUnknown(Error::InvalidResponse));
}
Ok(settings)
}
}
impl ThreadActivation {
pub(crate) fn from_settings(response: wire::UpdateConfigResponse) -> Result<Self, Error> {
let raw_thread = required(response.thread)?;
let thread = ThreadSnapshot::decode(raw_thread)?;
if thread.session_id.is_empty() || thread.model_provider.is_empty() {
return Err(Error::InvalidResponse);
}
Ok(Self {
thread,
collaboration_mode: response
.collaboration_mode
.map(parse_collaboration_mode)
.transpose()?,
model: nonempty(response.model)?,
model_provider: nonempty(response.model_provider)?,
service_tier: response.service_tier.and_then(|value| match value.value {
Some(wire::nullable_string::Value::String(value)) => Some(value),
Some(wire::nullable_string::Value::Null(_)) | None => None,
}),
cwd: nonempty(response.cwd)?,
instruction_sources: response
.instruction_sources
.map_or_else(Vec::new, |sources| sources.values),
runtime_workspace_roots: response
.runtime_workspace_roots
.map_or_else(Vec::new, |roots| roots.values),
approval_policy: parse_approval(required(response.approval_policy)?)?,
approvals_reviewer: parse_reviewer(required(response.approvals_reviewer)?)?,
sandbox: parse_sandbox(required(response.sandbox)?)?,
active_permission_profile: response
.active_permission_profile
.map(|profile| -> Result<_, Error> {
Ok(ActivePermissionProfile {
id: nonempty(profile.id)?,
extends: profile.extends,
})
})
.transpose()?,
reasoning_effort: response.reasoning_effort,
turns_backwards_cursor: response.turns_backwards_cursor,
items_backwards_cursor: response.items_backwards_cursor,
})
}
}
impl ThreadSnapshot {
pub(crate) fn decode(raw_protobuf: Bytes) -> Result<Self, Error> {
let thread =
wire::Thread::decode(raw_protobuf.clone()).map_err(|_| Error::InvalidResponse)?;
Self::try_from_wire(thread, raw_protobuf)
}
fn try_from_wire(thread: wire::Thread, raw_protobuf: Bytes) -> Result<Self, Error> {
Ok(Self {
id: nonempty(thread.id)?,
session_id: required(thread.session_id)?,
forked_from_id: thread.forked_from_id,
parent_thread_id: thread.parent_thread_id,
preview: required(thread.preview)?,
ephemeral: required(thread.ephemeral)?,
daybreak_enabled: thread.daybreak_enabled,
project_id: thread.project_id,
history_mode: parse_history_mode(thread.history_mode)?,
model_provider: required(thread.model_provider)?,
model: thread.model,
reasoning_effort: thread.reasoning_effort,
created_at: required(thread.created_at)?,
updated_at: required(thread.updated_at)?,
recency_at: thread.recency_at,
status: parse_status(required(thread.status)?)?,
path: thread.path,
cwd: nonempty(thread.cwd)?,
cli_version: required(thread.cli_version)?,
originator: thread.originator,
source: parse_source(required(thread.source)?)?,
can_accept_direct_input: thread.can_accept_direct_input,
thread_source: thread.thread_source,
agent_nickname: thread.agent_nickname,
agent_role: thread.agent_role,
git_info: thread.git_info.map(|git_info| GitInfo {
branch: git_info.branch,
origin_url: git_info.origin_url,
sha: git_info.sha,
}),
name: thread.name,
environments: thread
.environments
.map(|environments| {
environments
.values
.into_iter()
.map(|environment| -> Result<_, Error> {
Ok(ThreadEnvironment {
environment_id: nonempty(environment.environment_id)?,
cwd: nonempty(environment.cwd)?,
runtime_workspace_roots: required(
environment.runtime_workspace_roots,
)?
.values,
})
})
.collect()
})
.transpose()?,
turns: [],
raw_protobuf,
})
}
}
fn parse_collaboration_mode(value: wire::CollaborationMode) -> Result<CollaborationMode, Error> {
let settings = required(value.settings)?;
let settings = CollaborationSettings {
model: nonempty(settings.model)?,
reasoning_effort: settings.reasoning_effort,
developer_instructions: settings.developer_instructions,
};
match required(value.mode)? {
1 => Ok(CollaborationMode::Plan(settings)),
2 => Ok(CollaborationMode::Default(settings)),
_ => Err(Error::UnsupportedResponse("collaboration mode")),
}
}
fn parse_history_mode(value: Option<i32>) -> Result<ThreadHistoryMode, Error> {
match value {
None | Some(1) => Ok(ThreadHistoryMode::Legacy),
Some(2) => Ok(ThreadHistoryMode::Paginated),
Some(_) => Err(Error::UnsupportedResponse("thread history mode")),
}
}
fn parse_approval(value: wire::ApprovalPolicy) -> Result<ApprovalPolicy, Error> {
match required(value.value)? {
wire::approval_policy::Value::Simple(1) => Ok(ApprovalPolicy::UnlessTrusted),
wire::approval_policy::Value::Simple(2) => Ok(ApprovalPolicy::OnRequest),
wire::approval_policy::Value::Simple(3) => Ok(ApprovalPolicy::Never),
wire::approval_policy::Value::Simple(_) => {
Err(Error::UnsupportedResponse("approval policy"))
}
wire::approval_policy::Value::Granular(wrapper) => {
let granular = required(wrapper.granular)?;
Ok(ApprovalPolicy::Granular {
sandbox_approval: required(granular.sandbox_approval)?,
rules: required(granular.rules)?,
skill_approval: granular.skill_approval.unwrap_or(false),
request_permissions: granular.request_permissions.unwrap_or(false),
mcp_elicitations: required(granular.mcp_elicitations)?,
})
}
}
}
fn parse_reviewer(value: i32) -> Result<ApprovalsReviewer, Error> {
match value {
1 => Ok(ApprovalsReviewer::User),
2 | 3 => Ok(ApprovalsReviewer::AutoReview),
_ => Err(Error::UnsupportedResponse("approvals reviewer")),
}
}
fn parse_sandbox(value: wire::SandboxPolicy) -> Result<SandboxPolicy, Error> {
match required(value.value)? {
wire::sandbox_policy::Value::DangerFullAccess(_) => Ok(SandboxPolicy::DangerFullAccess),
wire::sandbox_policy::Value::ReadOnly(policy) => Ok(SandboxPolicy::ReadOnly {
network_access: policy.network_access.unwrap_or(false),
}),
wire::sandbox_policy::Value::ExternalSandbox(policy) => {
Ok(SandboxPolicy::ExternalSandbox {
network_access: match policy.network_access {
None | Some(1) => NetworkAccess::Restricted,
Some(2) => NetworkAccess::Enabled,
Some(_) => return Err(Error::UnsupportedResponse("external network policy")),
},
})
}
wire::sandbox_policy::Value::WorkspaceWrite(policy) => Ok(SandboxPolicy::WorkspaceWrite {
writable_roots: policy
.writable_roots
.map_or_else(Vec::new, |roots| roots.values),
network_access: policy.network_access.unwrap_or(false),
exclude_tmpdir_env_var: policy.exclude_tmpdir_env_var.unwrap_or(false),
exclude_slash_tmp: policy.exclude_slash_tmp.unwrap_or(false),
}),
}
}
fn parse_source(value: wire::SessionSource) -> Result<SessionSource, Error> {
match required(value.value)? {
wire::session_source::Value::Simple(1) => Ok(SessionSource::Cli),
wire::session_source::Value::Simple(2) => Ok(SessionSource::VsCode),
wire::session_source::Value::Simple(3) => Ok(SessionSource::Exec),
wire::session_source::Value::Simple(4) => Ok(SessionSource::AppServer),
wire::session_source::Value::Simple(0) => Err(Error::UnsupportedResponse("session source")),
wire::session_source::Value::Simple(_) => Ok(SessionSource::Unknown),
wire::session_source::Value::Custom(source) => {
Ok(SessionSource::Custom(nonempty(source.custom)?))
}
wire::session_source::Value::SubAgent(wrapper) => Ok(SessionSource::SubAgent(
parse_subagent_source(required(wrapper.sub_agent)?)?,
)),
}
}
fn parse_subagent_source(value: wire::SubAgentSource) -> Result<SubAgentSource, Error> {
match required(value.value)? {
wire::sub_agent_source::Value::Simple(1) => Ok(SubAgentSource::Review),
wire::sub_agent_source::Value::Simple(2) => Ok(SubAgentSource::Compact),
wire::sub_agent_source::Value::Simple(3) => Ok(SubAgentSource::MemoryConsolidation),
wire::sub_agent_source::Value::Simple(_) => {
Err(Error::UnsupportedResponse("sub-agent source"))
}
wire::sub_agent_source::Value::ThreadSpawn(wrapper) => {
let source = required(wrapper.thread_spawn)?;
Ok(SubAgentSource::ThreadSpawn {
parent_thread_id: nonempty(source.parent_thread_id)?,
depth: i32::try_from(required(source.depth)?)
.map_err(|_| Error::InvalidResponse)?,
agent_path: source.agent_path,
agent_nickname: source.agent_nickname,
agent_role: source.agent_role,
})
}
wire::sub_agent_source::Value::Other(source) => {
Ok(SubAgentSource::Other(nonempty(source.other)?))
}
}
}
pub(super) fn parse_status(value: wire::ThreadStatus) -> Result<ThreadStatus, Error> {
match required(value.value)? {
wire::thread_status::Value::NotLoaded(_) => Ok(ThreadStatus::NotLoaded),
wire::thread_status::Value::Idle(_) => Ok(ThreadStatus::Idle),
wire::thread_status::Value::SystemError(_) => Ok(ThreadStatus::SystemError),
wire::thread_status::Value::Active(active) => Ok(ThreadStatus::Active {
active_flags: required(active.active_flags)?
.values
.into_iter()
.map(|flag| match flag {
1 => Ok(ThreadActiveFlag::WaitingOnApproval),
2 => Ok(ThreadActiveFlag::WaitingOnUserInput),
_ => Err(Error::UnsupportedResponse("thread active flag")),
})
.collect::<Result<_, _>>()?,
}),
}
}
fn required<T>(value: Option<T>) -> Result<T, Error> {
value.ok_or(Error::InvalidResponse)
}
fn nonempty(value: Option<String>) -> Result<String, Error> {
let value = required(value)?;
if value.is_empty() {
Err(Error::InvalidResponse)
} else {
Ok(value)
}
}

View File

@@ -0,0 +1,52 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn wire_debug_redacts_thread_preview_and_raw_bytes() {
let thread = wire::Thread {
preview: Some("synthetic private preview".to_owned()),
..Default::default()
};
let response = wire::UpdateConfigResponse {
thread: Some(Bytes::from(thread.encode_to_vec())),
..Default::default()
};
assert_eq!(format!("{thread:?}"), "Thread([redacted])");
assert_eq!(format!("{response:?}"), "UpdateConfigResponse([redacted])");
}
#[test]
fn missing_history_mode_uses_legacy_compatibility_default() {
assert_eq!(
parse_history_mode(/*value*/ None).unwrap(),
ThreadHistoryMode::Legacy
);
}
#[test]
fn external_sandbox_network_access_defaults_only_when_omitted() {
let decode = |network_access| {
parse_sandbox(wire::SandboxPolicy {
value: Some(wire::sandbox_policy::Value::ExternalSandbox(
wire::ExternalSandbox { network_access },
)),
})
};
for (value, network_access) in [
(None, NetworkAccess::Restricted),
(Some(1), NetworkAccess::Restricted),
(Some(2), NetworkAccess::Enabled),
] {
assert_eq!(
decode(value).unwrap(),
SandboxPolicy::ExternalSandbox { network_access }
);
}
for value in [0, 99] {
assert!(matches!(
decode(Some(value)),
Err(Error::UnsupportedResponse("external network policy"))
));
}
}

View File

@@ -0,0 +1,373 @@
//! Minimal protobuf envelopes for authoritative thread activation.
use bytes::Bytes;
use prost::Message;
use std::fmt;
#[derive(Clone, Message)]
pub(super) struct UpdateConfigRequest {
#[prost(bool, optional, tag = "7")]
pub exclude_turns: Option<bool>,
#[prost(string, optional, tag = "18")]
pub thread_id: Option<String>,
}
#[derive(Clone, Message)]
#[prost(skip_debug)]
pub(super) struct UpdateConfigResponse {
#[prost(message, optional, tag = "1")]
pub active_permission_profile: Option<ActivePermissionProfile>,
#[prost(message, optional, tag = "2")]
pub approval_policy: Option<ApprovalPolicy>,
#[prost(int32, optional, tag = "3")]
pub approvals_reviewer: Option<i32>,
#[prost(message, optional, tag = "4")]
pub collaboration_mode: Option<CollaborationMode>,
#[prost(string, optional, tag = "5")]
pub cwd: Option<String>,
#[prost(message, optional, tag = "8")]
pub instruction_sources: Option<StringList>,
#[prost(string, optional, tag = "9")]
pub items_backwards_cursor: Option<String>,
#[prost(string, optional, tag = "10")]
pub model: Option<String>,
#[prost(string, optional, tag = "11")]
pub model_provider: Option<String>,
#[prost(string, optional, tag = "13")]
pub reasoning_effort: Option<String>,
#[prost(message, optional, tag = "14")]
pub runtime_workspace_roots: Option<StringList>,
#[prost(message, optional, tag = "15")]
pub sandbox: Option<SandboxPolicy>,
#[prost(message, optional, tag = "16")]
pub service_tier: Option<NullableString>,
#[prost(bytes = "bytes", optional, tag = "17")]
pub thread: Option<Bytes>,
#[prost(string, optional, tag = "18")]
pub turns_backwards_cursor: Option<String>,
}
impl fmt::Debug for UpdateConfigResponse {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("UpdateConfigResponse([redacted])")
}
}
#[derive(Clone, Message)]
pub(super) struct CollaborationMode {
#[prost(int32, optional, tag = "1")]
pub mode: Option<i32>,
#[prost(message, optional, tag = "2")]
pub settings: Option<Settings>,
}
#[derive(Clone, Message)]
#[prost(skip_debug)]
pub(super) struct Settings {
#[prost(string, optional, tag = "1")]
pub developer_instructions: Option<String>,
#[prost(string, optional, tag = "2")]
pub model: Option<String>,
#[prost(string, optional, tag = "3")]
pub reasoning_effort: Option<String>,
}
impl fmt::Debug for Settings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Settings([redacted])")
}
}
#[derive(Clone, Message)]
pub(super) struct ActivePermissionProfile {
#[prost(string, optional, tag = "1")]
pub extends: Option<String>,
#[prost(string, optional, tag = "2")]
pub id: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct ApprovalPolicy {
#[prost(oneof = "approval_policy::Value", tags = "1, 2")]
pub value: Option<approval_policy::Value>,
}
pub(super) mod approval_policy {
#[derive(Clone, prost::Oneof)]
pub enum Value {
#[prost(int32, tag = "1")]
Simple(i32),
#[prost(message, tag = "2")]
Granular(super::GranularApprovalWrapper),
}
}
#[derive(Clone, Message)]
pub(super) struct GranularApprovalWrapper {
#[prost(message, optional, tag = "1")]
pub granular: Option<GranularApproval>,
}
#[derive(Clone, Message)]
pub(super) struct GranularApproval {
#[prost(bool, optional, tag = "1")]
pub mcp_elicitations: Option<bool>,
#[prost(bool, optional, tag = "2")]
pub request_permissions: Option<bool>,
#[prost(bool, optional, tag = "3")]
pub rules: Option<bool>,
#[prost(bool, optional, tag = "4")]
pub sandbox_approval: Option<bool>,
#[prost(bool, optional, tag = "5")]
pub skill_approval: Option<bool>,
}
#[derive(Clone, Message)]
pub(super) struct SandboxPolicy {
#[prost(oneof = "sandbox_policy::Value", tags = "1, 2, 3, 4")]
pub value: Option<sandbox_policy::Value>,
}
pub(super) mod sandbox_policy {
#[derive(Clone, prost::Oneof)]
pub enum Value {
#[prost(message, tag = "1")]
DangerFullAccess(super::Empty),
#[prost(message, tag = "2")]
ReadOnly(super::ReadOnlySandbox),
#[prost(message, tag = "3")]
ExternalSandbox(super::ExternalSandbox),
#[prost(message, tag = "4")]
WorkspaceWrite(super::WorkspaceWriteSandbox),
}
}
#[derive(Clone, Message)]
pub(super) struct Empty {}
#[derive(Clone, Message)]
pub(super) struct ReadOnlySandbox {
#[prost(bool, optional, tag = "1")]
pub network_access: Option<bool>,
}
#[derive(Clone, Message)]
pub(super) struct ExternalSandbox {
#[prost(int32, optional, tag = "1")]
pub network_access: Option<i32>,
}
#[derive(Clone, Message)]
pub(super) struct WorkspaceWriteSandbox {
#[prost(bool, optional, tag = "1")]
pub exclude_slash_tmp: Option<bool>,
#[prost(bool, optional, tag = "2")]
pub exclude_tmpdir_env_var: Option<bool>,
#[prost(bool, optional, tag = "3")]
pub network_access: Option<bool>,
#[prost(message, optional, tag = "4")]
pub writable_roots: Option<StringList>,
}
#[derive(Clone, Message)]
pub(super) struct StringList {
#[prost(string, repeated, tag = "1")]
pub values: Vec<String>,
}
#[derive(Clone, Message)]
pub(super) struct NullableString {
#[prost(oneof = "nullable_string::Value", tags = "1, 2")]
pub value: Option<nullable_string::Value>,
}
pub(super) mod nullable_string {
#[derive(Clone, prost::Oneof)]
pub enum Value {
#[prost(string, tag = "1")]
String(String),
#[prost(message, tag = "2")]
Null(super::Empty),
}
}
#[derive(Clone, Message)]
#[prost(skip_debug)]
pub(super) struct Thread {
#[prost(string, optional, tag = "1")]
pub agent_nickname: Option<String>,
#[prost(string, optional, tag = "2")]
pub agent_role: Option<String>,
#[prost(bool, optional, tag = "3")]
pub can_accept_direct_input: Option<bool>,
#[prost(string, optional, tag = "4")]
pub cli_version: Option<String>,
#[prost(int64, optional, tag = "5")]
pub created_at: Option<i64>,
#[prost(string, optional, tag = "6")]
pub cwd: Option<String>,
#[prost(bool, optional, tag = "7")]
pub daybreak_enabled: Option<bool>,
#[prost(message, optional, tag = "8")]
pub environments: Option<Environments>,
#[prost(bool, optional, tag = "9")]
pub ephemeral: Option<bool>,
#[prost(string, optional, tag = "11")]
pub forked_from_id: Option<String>,
#[prost(message, optional, tag = "12")]
pub git_info: Option<GitInfo>,
#[prost(int32, optional, tag = "13")]
pub history_mode: Option<i32>,
#[prost(string, optional, tag = "14")]
pub id: Option<String>,
#[prost(string, optional, tag = "15")]
pub model: Option<String>,
#[prost(string, optional, tag = "16")]
pub model_provider: Option<String>,
#[prost(string, optional, tag = "17")]
pub name: Option<String>,
#[prost(string, optional, tag = "18")]
pub originator: Option<String>,
#[prost(string, optional, tag = "19")]
pub parent_thread_id: Option<String>,
#[prost(string, optional, tag = "20")]
pub path: Option<String>,
#[prost(string, optional, tag = "21")]
pub preview: Option<String>,
#[prost(string, optional, tag = "22")]
pub project_id: Option<String>,
#[prost(string, optional, tag = "23")]
pub reasoning_effort: Option<String>,
#[prost(int64, optional, tag = "24")]
pub recency_at: Option<i64>,
#[prost(string, optional, tag = "27")]
pub session_id: Option<String>,
#[prost(message, optional, tag = "28")]
pub source: Option<SessionSource>,
#[prost(message, optional, tag = "29")]
pub status: Option<ThreadStatus>,
#[prost(string, optional, tag = "30")]
pub thread_source: Option<String>,
#[prost(int64, optional, tag = "32")]
pub updated_at: Option<i64>,
}
impl fmt::Debug for Thread {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Thread([redacted])")
}
}
#[derive(Clone, Message)]
#[prost(skip_debug)]
pub(super) struct GitInfo {
#[prost(string, optional, tag = "1")]
pub branch: Option<String>,
#[prost(string, optional, tag = "2")]
pub origin_url: Option<String>,
#[prost(string, optional, tag = "3")]
pub sha: Option<String>,
}
impl fmt::Debug for GitInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("GitInfo([redacted])")
}
}
#[derive(Clone, Message)]
pub(super) struct Environments {
#[prost(message, repeated, tag = "1")]
pub values: Vec<Environment>,
}
#[derive(Clone, Message)]
pub(super) struct Environment {
#[prost(string, optional, tag = "1")]
pub cwd: Option<String>,
#[prost(string, optional, tag = "2")]
pub environment_id: Option<String>,
#[prost(message, optional, tag = "3")]
pub runtime_workspace_roots: Option<StringList>,
}
#[derive(Clone, Message)]
pub(super) struct SessionSource {
#[prost(oneof = "session_source::Value", tags = "1, 2, 3")]
pub value: Option<session_source::Value>,
}
pub(super) mod session_source {
#[derive(Clone, prost::Oneof)]
pub enum Value {
#[prost(int32, tag = "1")]
Simple(i32),
#[prost(message, tag = "2")]
Custom(super::CustomSource),
#[prost(message, tag = "3")]
SubAgent(super::SubAgentSourceWrapper),
}
}
#[derive(Clone, Message)]
pub(super) struct SubAgentSourceWrapper {
#[prost(message, optional, tag = "1")]
pub sub_agent: Option<SubAgentSource>,
}
#[derive(Clone, Message)]
pub(super) struct SubAgentSource {
#[prost(oneof = "sub_agent_source::Value", tags = "1, 2, 3")]
pub value: Option<sub_agent_source::Value>,
}
pub(super) mod sub_agent_source {
#[derive(Clone, prost::Oneof)]
pub enum Value {
#[prost(int32, tag = "1")]
Simple(i32),
#[prost(message, tag = "2")]
ThreadSpawn(super::ThreadSpawnWrapper),
#[prost(message, tag = "3")]
Other(super::OtherSubAgentSource),
}
}
#[derive(Clone, Message)]
pub(super) struct OtherSubAgentSource {
#[prost(string, optional, tag = "1")]
pub other: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct ThreadSpawnWrapper {
#[prost(message, optional, tag = "1")]
pub thread_spawn: Option<ThreadSpawnSource>,
}
#[derive(Clone, Message)]
pub(super) struct ThreadSpawnSource {
#[prost(string, optional, tag = "1")]
pub agent_nickname: Option<String>,
#[prost(string, optional, tag = "2")]
pub agent_path: Option<String>,
#[prost(string, optional, tag = "3")]
pub agent_role: Option<String>,
#[prost(int64, optional, tag = "4")]
pub depth: Option<i64>,
#[prost(string, optional, tag = "5")]
pub parent_thread_id: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct CustomSource {
#[prost(string, optional, tag = "1")]
pub custom: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct ThreadStatus {
#[prost(oneof = "thread_status::Value", tags = "1, 2, 3, 4")]
pub value: Option<thread_status::Value>,
}
pub(super) mod thread_status {
#[derive(Clone, prost::Oneof)]
pub enum Value {
#[prost(message, tag = "1")]
NotLoaded(super::Empty),
#[prost(message, tag = "2")]
Idle(super::Empty),
#[prost(message, tag = "3")]
SystemError(super::Empty),
#[prost(message, tag = "4")]
Active(super::ActiveStatus),
}
}
#[derive(Clone, Message)]
pub(super) struct ActiveStatus {
#[prost(message, optional, tag = "1")]
pub active_flags: Option<IntList>,
}
#[derive(Clone, Message)]
pub(super) struct IntList {
#[prost(int32, repeated, tag = "1")]
pub values: Vec<i32>,
}

View File

@@ -0,0 +1,634 @@
//! Exercises native HTTP/2 framing, metadata, trailers and cancellation with synthetic data.
use super::*;
use bytes::Bytes;
use codex_http_client::OutboundProxyPolicy;
use http_body_util::StreamBody;
use hyper::body::Frame;
use hyper::service::service_fn;
use hyper_util::rt::TokioExecutor;
use hyper_util::rt::TokioIo;
use pretty_assertions::assert_eq;
use prost::Message;
use std::convert::Infallible;
use tokio::sync::mpsc;
struct Fixture {
client: Client,
requests: mpsc::UnboundedReceiver<(http::request::Parts, Bytes)>,
task: tokio::task::JoinHandle<()>,
}
impl Drop for Fixture {
fn drop(&mut self) {
self.task.abort();
}
}
async fn fixture(response: http::Response<Body>) -> Fixture {
fixture_responses(vec![response]).await
}
async fn fixture_responses(responses: Vec<http::Response<Body>>) -> Fixture {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let endpoint = format!("http://{}", listener.local_addr().unwrap());
let (sender, requests) = mpsc::unbounded_channel();
let responses = std::sync::Arc::new(std::sync::Mutex::new(std::collections::VecDeque::from(
responses,
)));
let task = tokio::spawn(async move {
let (socket, _) = listener.accept().await.unwrap();
let service = service_fn(move |request: http::Request<hyper::body::Incoming>| {
let sender = sender.clone();
let response = responses.lock().unwrap().pop_front().unwrap();
async move {
let (parts, body) = request.into_parts();
sender
.send((parts, body.collect().await.unwrap().to_bytes()))
.unwrap();
Ok::<_, Infallible>(response)
}
});
let _ = hyper::server::conn::http2::Builder::new(TokioExecutor::new())
.serve_connection(TokioIo::new(socket), service)
.await;
});
let client = Client::new(
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
&endpoint,
Credentials::new("synthetic-token", "synthetic-account").unwrap(),
)
.unwrap();
Fixture {
client,
requests,
task,
}
}
fn frame(payload: &[u8]) -> Bytes {
let mut bytes = vec![0];
bytes.extend_from_slice(&(payload.len() as u32).to_be_bytes());
bytes.extend_from_slice(payload);
bytes.into()
}
fn response(messages: Vec<Bytes>, status: tonic::Status) -> http::Response<Body> {
let frames = messages
.into_iter()
.map(Frame::data)
.chain([Frame::trailers(
status.into_http::<Body>().into_parts().0.headers,
)]);
http::Response::builder()
.header("content-type", "application/grpc")
.body(Body::new(StreamBody::new(futures::stream::iter(
frames.map(Ok::<_, Infallible>),
))))
.unwrap()
}
async fn assert_request(fixture: &mut Fixture, method: &str, expected: &[u8]) {
let (parts, body) = tokio::time::timeout(Duration::from_secs(5), fixture.requests.recv())
.await
.unwrap()
.unwrap();
assert_eq!(parts.method, http::Method::POST);
assert_eq!(parts.version, http::Version::HTTP_2);
assert_eq!(
parts.uri.path(),
format!("/oaiproto.codex_app_server_backend.ThreadService/{method}")
);
assert_eq!(parts.headers["authorization"], "Bearer synthetic-token");
assert_eq!(parts.headers["chatgpt-account-id"], "synthetic-account");
assert_eq!(parts.headers["content-type"], "application/grpc");
assert!(!parts.headers.contains_key("grpc-timeout"));
assert_eq!(body, frame(expected));
}
#[tokio::test]
async fn activation_sends_only_identity_and_excludes_turns() {
let mut fixture = fixture(response(vec![frame(&[])], tonic::Status::ok(""))).await;
assert!(matches!(
fixture.client.activate("t").await,
Err(MutationError::OutcomeUnknown(Error::InvalidResponse))
));
// exclude_turns=true (field 7), thread_id="t" (field 18).
assert_request(&mut fixture, "UpdateConfig", &[56, 1, 0x92, 1, 1, b't']).await;
}
#[tokio::test]
async fn activation_preserves_native_settings_and_thread_metadata() {
// Native Thread fields encoded independently of the client's wire types.
let thread_base: &[u8] = &[
0x22, 1, b'v', // cli_version (4)
0x28, 1, // created_at (5)
0x32, 1, b'/', // cwd (6)
0x48, 0, // ephemeral (9)
0x72, 1, b't', // id (14)
0x82, 1, 1, b'p', // model_provider (16)
0xaa, 1, 0, // preview (21)
0xda, 1, 1, b's', // session_id (27)
0xe2, 1, 2, 8, 99, // source (28): future simple value
0xea, 1, 2, 0x12, 0, // status (29): idle
0xfa, 1, 0, // turns (31): empty
0x80, 2, 2, // updated_at (32)
];
let encode_response = |mode: u8, daybreak: Option<bool>, approval: u8| {
let mut thread = thread_base.to_vec();
if let Some(enabled) = daybreak {
thread.extend_from_slice(&[0x38, u8::from(enabled)]); // daybreak_enabled (7)
}
// Settings has developer_instructions (1), model (2), and reasoning_effort (3).
let settings = Bytes::from_static(if mode == 1 {
b"\x0a\x01d\x12\x01m\x1a\x04high"
} else {
b"\x12\x01m"
});
let mut collaboration_mode = vec![8, mode];
prost::encoding::bytes::encode(/* settings */ 2, &settings, &mut collaboration_mode);
let mut response_bytes = vec![0x12, 2, 8, approval, 0x18, 1]; // approval and reviewer
prost::encoding::bytes::encode(
/* collaboration_mode */ 4,
&collaboration_mode,
&mut response_bytes,
);
// instruction_sources (8) wraps repeated string values (1).
response_bytes.extend_from_slice(b"\x42\x0c\x0a\x0a/AGENTS.md");
response_bytes.extend_from_slice(&[
0x2a, 1, b'/', // cwd (5)
0x52, 1, b'm', // model (10)
0x5a, 1, b'p', // model_provider (11)
0x7a, 4, 0x12, 2, 8, 1, // sandbox (15): read-only with network access
]);
prost::encoding::bytes::encode(/* thread */ 17, &thread, &mut response_bytes);
(response_bytes, thread)
};
// Activation retains stricter runtime requirements than stored list metadata.
for (session_id, model_provider) in [("", "p"), ("s", "")] {
let (response_bytes, _) = encode_response(1, Some(true), 2);
let mut settings =
crate::activation_wire::UpdateConfigResponse::decode(Bytes::from(response_bytes))
.unwrap();
let mut thread =
crate::activation_wire::Thread::decode(settings.thread.take().unwrap()).unwrap();
thread.session_id = Some(session_id.into());
thread.model_provider = Some(model_provider.into());
settings.thread = Some(thread.encode_to_vec().into());
assert!(matches!(
ThreadActivation::from_settings(settings),
Err(Error::InvalidResponse)
));
}
for (mode, daybreak) in [(1, Some(true)), (2, Some(false)), (2, None)] {
let (response_bytes, thread) = encode_response(mode, daybreak, 2);
let mut server = fixture(response(
vec![frame(&response_bytes)],
tonic::Status::ok(""),
))
.await;
let activation = server.client.activate("t").await.unwrap();
assert_eq!(activation.thread.protobuf().as_ref(), thread.as_slice());
let json = serde_json::to_value(&activation).unwrap();
assert_eq!(json["thread"]["source"], "unknown");
assert_eq!(
json["thread"].get("daybreakEnabled"),
Some(&serde_json::json!(daybreak))
);
assert_eq!(
json["instructionSources"],
serde_json::json!(["/AGENTS.md"])
);
assert_eq!(json["approvalPolicy"], "on-request");
assert_eq!(json["approvalsReviewer"], "user");
assert_eq!(
json["sandbox"],
serde_json::json!({"type": "readOnly", "networkAccess": true})
);
assert_eq!(
json["collaborationMode"],
serde_json::json!({
"mode": if mode == 1 { "plan" } else { "default" },
"settings": {
"model": "m",
"developer_instructions": if mode == 1 { Some("d") } else { None },
"reasoning_effort": if mode == 1 { Some("high") } else { None }
}
})
);
assert_request(&mut server, "UpdateConfig", &[56, 1, 0x92, 1, 1, b't']).await;
assert!(server.requests.try_recv().is_err());
}
// Unknown security policy must remain an error, never a default.
let (response_bytes, _) = encode_response(1, Some(true), 99);
let mut server = fixture(response(
vec![frame(&response_bytes)],
tonic::Status::ok(""),
))
.await;
assert!(matches!(
server.client.activate("t").await,
Err(MutationError::OutcomeUnknown(Error::UnsupportedResponse(
"approval policy"
)))
));
assert_request(&mut server, "UpdateConfig", &[56, 1, 0x92, 1, 1, b't']).await;
assert!(server.requests.try_recv().is_err());
}
#[tokio::test]
async fn prewarm_defers_readiness_only_for_selected_projects() {
let mut fixture = fixture_responses(vec![
response(vec![frame(&[])], tonic::Status::ok("")),
response(vec![frame(&[])], tonic::Status::ok("")),
])
.await;
assert!(matches!(
fixture
.client
.prewarm_default_thread(/*model*/ None, /*model_provider*/ None)
.await,
Err(Error::InvalidResponse)
));
assert_request(&mut fixture, "Prewarm", b"\x52\x04\x0a\x02\x0a\x00").await;
assert!(matches!(
fixture
.client
.prewarm_thread(
/*model*/ None,
/*model_provider*/ None,
Some(ProjectEnvironment {
name: "App".to_owned(),
cwd: Some("/workspace/acme/app".to_owned()),
origin_urls: vec![
"git@github.com:acme/app.git".to_owned(),
"https://github.com/acme/lib.git".to_owned(),
],
}),
)
.await,
Err(Error::InvalidResponse)
));
let expected = [
b"\x52\x73\x0a\x71\x0a\x6f\x0a\x0d" as &[u8],
b"asenvcfg_base",
b"\x12\x13/workspace/acme/app",
b"\x1a\x49\x0a\x42\x0a\x1d\x2a\x1b",
b"git@github.com:acme/app.git",
b"\x0a\x21\x2a\x1f",
b"https://github.com/acme/lib.git",
b"\x12\x03App\xe8\x01\x01",
]
.concat();
assert_request(&mut fixture, "Prewarm", &expected).await;
}
#[tokio::test]
async fn prewarm_uses_managed_defaults_and_preserves_resolved_settings() {
// PrewarmThread uses Thread field numbers but omits turns entirely.
let thread = Bytes::from_static(&[
0x22, 1, b'v', // cli_version (4)
0x28, 1, // created_at (5)
0x32, 1, b'/', // cwd (6)
0x48, 0, // ephemeral (9)
0x72, 1, b't', // id (14)
0x82, 1, 1, b'p', // model_provider (16)
0xaa, 1, 0, // preview (21)
0xda, 1, 1, b's', // session_id (27)
0xe2, 1, 2, 8, 1, // source (28): cli
0xea, 1, 2, 0x12, 0, // status (29): idle
0x80, 2, 2, // updated_at (32)
0xa0, 6, 7, // unknown field (100)
]);
let native_thread = [b"\xfa\x01\x00".as_slice(), thread.as_ref()].concat(); // empty turns (31)
// The settings use different field numbers in Prewarm and UpdateConfig.
let fields = [
(1, 1, b"\x0a\x01e\x12\x01i".as_slice()), // active permission profile
(2, 2, b"\x08\x02".as_slice()), // on-request approval
(4, 5, b"/".as_slice()), // cwd
(7, 10, b"m".as_slice()), // model
(8, 11, b"p".as_slice()), // provider
(10, 13, b"high".as_slice()), // reasoning effort
(11, 14, b"\x0a\x01/".as_slice()), // workspace roots
(12, 15, b"\x12\x02\x08\x01".as_slice()), // read-only sandbox
(13, 16, b"\x0a\x04fast".as_slice()), // service tier
];
let mut prewarm = vec![0x18, 1]; // approvals reviewer (3): user
let mut activation = prewarm.clone();
for (prewarm_tag, activation_tag, bytes) in fields {
prost::encoding::bytes::encode(prewarm_tag, &bytes.to_vec(), &mut prewarm);
prost::encoding::bytes::encode(activation_tag, &bytes.to_vec(), &mut activation);
}
prost::encoding::bytes::encode(/* tag */ 14, &thread, &mut prewarm);
prost::encoding::bytes::encode(/* tag */ 17, &native_thread, &mut activation);
let mut server = fixture_responses(vec![
response(vec![frame(&activation)], tonic::Status::ok("")),
response(vec![frame(&prewarm)], tonic::Status::ok("")),
response(vec![frame(&prewarm)], tonic::Status::ok("")),
])
.await;
let expected = server.client.activate("t").await.unwrap();
assert_request(&mut server, "UpdateConfig", &[56, 1, 0x92, 1, 1, b't']).await;
for (model, model_provider, request) in [
(None, None, vec![0x52, 4, 0x0a, 2, 0x0a, 0]),
(
Some("m".to_owned()),
Some("p".to_owned()),
vec![0x52, 4, 0x0a, 2, 0x0a, 0, 0x7a, 1, b'm', 0x82, 1, 1, b'p'],
),
] {
let actual = server
.client
.prewarm_default_thread(model, model_provider)
.await
.unwrap();
assert_eq!(
serde_json::to_value(&actual).unwrap(),
serde_json::to_value(&expected).unwrap()
);
assert_eq!(actual.thread.protobuf().as_ref(), native_thread.as_slice());
// Exactly one default managed selection; no custom settings or Aeon mode.
assert_request(&mut server, "Prewarm", &request).await;
assert!(server.requests.try_recv().is_err());
}
// Missing authoritative policy must fail rather than supplying local defaults.
let mut missing_sandbox = vec![0x18, 1];
for (tag, _, bytes) in fields {
if tag != 12 {
prost::encoding::bytes::encode(tag, &bytes.to_vec(), &mut missing_sandbox);
}
}
prost::encoding::bytes::encode(/* tag */ 14, &thread, &mut missing_sandbox);
let mut server = fixture(response(
vec![frame(&missing_sandbox)],
tonic::Status::ok(""),
))
.await;
assert!(matches!(
server
.client
.prewarm_default_thread(/*model*/ None, /*model_provider*/ None)
.await,
Err(Error::InvalidResponse)
));
assert_request(&mut server, "Prewarm", &[0x52, 4, 0x0a, 2, 0x0a, 0]).await;
assert!(server.requests.try_recv().is_err());
}
#[tokio::test]
async fn resume_sends_protobuf_and_preserves_admission_flags() {
for wait in [false, true] {
let mut fixture = fixture(response(vec![frame(&[])], tonic::Status::ok(""))).await;
fixture
.client
.resume(&ResumeRequest {
thread_id: "t".into(),
wait,
shared_access: true,
})
.await
.unwrap();
// Independent protobuf wire fixtures, not the client's encoder.
let expected: &[u8] = if wait {
&[10, 1, b't', 16, 1, 24, 1]
} else {
&[10, 1, b't', 24, 1]
};
assert_request(&mut fixture, "Resume", expected).await;
}
}
#[tokio::test]
async fn attach_preserves_opaque_events_and_native_error_details() {
let secret = Bytes::from_static(b"private-error-details");
let status = tonic::Status::with_details(
tonic::Code::PermissionDenied,
"private-message",
secret.clone(),
);
let data = [frame(&[10, 3, 10, 1, b'n']), frame(&[18, 3, 10, 1, b'r'])].concat();
let mut fixture = fixture(response(
data.iter().map(|b| Bytes::from(vec![*b])).collect(),
status,
))
.await;
let mut events = fixture.client.attach("t").await.unwrap();
assert_request(&mut fixture, "Attach", &[10, 1, b't']).await;
let notification = events.next().await.unwrap().unwrap();
assert_eq!(format!("{notification:?}"), "Notification([redacted])");
let Event::Notification(bytes) = notification else {
panic!("notification expected")
};
assert_eq!(bytes.as_ref(), &[10, 1, b'n']);
let Event::ServerRequest(bytes) = events.next().await.unwrap().unwrap() else {
panic!("server request expected")
};
assert_eq!(bytes.as_ref(), &[10, 1, b'r']);
let error = events.next().await.unwrap().unwrap_err();
assert!(!format!("{error:?} {error}").contains("private"));
let Error::Rpc(status) = error else {
panic!("native status expected")
};
assert_eq!(
(status.code, status.message, status.details),
(7, "private-message".into(), secret)
);
assert!(events.next().await.is_none());
}
#[tokio::test]
async fn successful_stream_ends_and_bad_frames_terminate() {
let fixture = fixture(response(vec![], tonic::Status::ok(""))).await;
assert!(
fixture
.client
.attach("t")
.await
.unwrap()
.next()
.await
.is_none()
);
for message in [
frame(&[]),
frame(&[10, 99]),
Bytes::from_static(&[0, 4, 0, 0, 1]),
] {
let fixture = self::fixture(response(vec![message], tonic::Status::ok(""))).await;
let mut stream = fixture.client.attach("t").await.unwrap();
assert!(stream.next().await.unwrap().is_err());
assert!(stream.next().await.is_none());
}
}
#[tokio::test]
async fn unary_checks_status_trailers_and_preserves_details() {
let fixture = fixture(response(
vec![frame(&[])],
tonic::Status::with_details(
tonic::Code::Unavailable,
"secret",
Bytes::from_static(b"details"),
),
))
.await;
let error = fixture
.client
.resume(&ResumeRequest {
thread_id: "t".into(),
wait: false,
shared_access: false,
})
.await
.unwrap_err();
let Error::Rpc(status) = error else {
panic!("RPC status expected")
};
assert_eq!(
(status.code, status.details),
(14, Bytes::from_static(b"details"))
);
}
#[tokio::test]
async fn dropping_attachment_cancels_idle_response() {
let (sender, dropped) = tokio::sync::oneshot::channel::<()>();
let stream = async_stream::stream! {
let _sender = sender;
yield Ok::<_, Infallible>(Frame::data(frame(&[10, 0])));
std::future::pending::<()>().await;
};
let fixture = fixture(
http::Response::builder()
.header("content-type", "application/grpc")
.body(Body::new(StreamBody::new(stream)))
.unwrap(),
)
.await;
let mut events = fixture.client.attach("t").await.unwrap();
events.next().await.unwrap().unwrap();
drop(events);
assert!(
tokio::time::timeout(Duration::from_secs(5), dropped)
.await
.unwrap()
.is_err()
);
}
#[tokio::test]
async fn redirects_and_http_failures_are_not_followed() {
for status in [307, 403] {
let fixture = fixture(
http::Response::builder()
.status(status)
.header("location", "http://127.0.0.1:1/private")
.body(Body::empty())
.unwrap(),
)
.await;
let error = match fixture.client.attach("t").await {
Ok(mut stream) => stream.next().await.unwrap().unwrap_err(),
Err(error) => error,
};
assert!(matches!(error, Error::Rpc(_)));
assert!(!format!("{error:?} {error}").contains("private"));
}
}
#[test]
fn rejects_unsafe_origins_and_redacts_credentials() {
for endpoint in [
"http://example.com",
"https://user:secret@example.com",
"https://example.com?token=secret",
"https://example.com#secret",
"https://example.com/grpc",
] {
assert!(matches!(
Client::new(
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
endpoint,
Credentials::new("token", "account").unwrap(),
),
Err(Error::InvalidEndpoint)
));
}
assert!(Credentials::new("secret\nvalue", "account").is_err());
assert!(
!format!(
"{:?}",
Credentials::new("synthetic-token", "synthetic-account").unwrap()
)
.contains("synthetic")
);
}
#[test]
fn loopback_http_rejects_managed_and_endpoint_restricted_policies() {
for policy in [
codex_http_client::NetworkPolicyController::default().policy(),
codex_http_client::NetworkPolicy::unmanaged().restrict_to_endpoints(Default::default()),
] {
let factory = HttpClientFactory::new(OutboundProxyPolicy::RespectSystemProxy)
.with_network_policy(policy);
assert!(matches!(
Client::new(
&factory,
"http://127.0.0.1:1234",
Credentials::new("token", "account").unwrap(),
),
Err(Error::InvalidEndpoint)
));
}
}
#[tokio::test]
async fn https_advertises_h2_in_tls_client_hello() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let client = HttpClientBuilder::new()
.http2_prior_knowledge()
.build_direct()
.unwrap();
let request = client.get(format!("https://{}", listener.local_addr().unwrap()));
let handshake = async {
let (socket, _) = listener.accept().await.unwrap();
let hello = tokio_rustls::LazyConfigAcceptor::new(Default::default(), socket)
.await
.unwrap();
let protocols: Vec<_> = hello
.client_hello()
.alpn()
.into_iter()
.flatten()
.map(<[u8]>::to_vec)
.collect();
assert_eq!(protocols, vec![b"h2".to_vec()]);
// Inspect negotiation without trusting a test CA or completing the TLS handshake.
};
tokio::time::timeout(Duration::from_secs(5), async {
let (_, result) = tokio::join!(handshake, request.send());
assert!(result.is_err());
})
.await
.unwrap();
}
#[tokio::test]
async fn https_enforces_unmanaged_endpoint_restrictions_before_connecting() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault).with_network_policy(
codex_http_client::NetworkPolicy::unmanaged().restrict_to_endpoints(Default::default()),
);
let client = Client::new(
&factory,
&format!("https://{}", listener.local_addr().unwrap()),
Credentials::new("token", "account").unwrap(),
)
.unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
tokio::select! {
result = client.attach("t") => assert!(result.is_err()),
_ = listener.accept() => panic!("denied destination was contacted"),
}
})
.await
.unwrap();
}
#[path = "transcript_tests.rs"]
mod transcript;
#[path = "discovery_tests.rs"]
mod discovery;

View File

@@ -0,0 +1,226 @@
//! Typed, paginated cloud thread discovery over the native ThreadService.
use crate::Client;
use crate::Error;
use crate::ThreadSnapshot;
use bytes::Bytes;
use prost::Message;
use std::collections::HashMap;
use std::fmt;
#[derive(Clone, Copy, Debug, Default)]
pub enum ThreadSortKey {
#[default]
CreatedAt,
UpdatedAt,
RecencyAt,
}
#[derive(Clone, Copy, Debug, Default)]
pub enum ThreadSortDirection {
Asc,
#[default]
Desc,
}
/// Lists unarchived threads with the server's default source selection.
/// Reuse the same originators and order when continuing with an opaque cursor.
#[derive(Clone, Default)]
pub struct ThreadListQuery {
pub cursor: Option<String>,
pub limit: Option<u32>,
pub sort_key: ThreadSortKey,
pub sort_direction: ThreadSortDirection,
/// Empty means all originators, including conversations created by other clients.
pub originators: Vec<String>,
}
/// One bounded page in server order; no automatic pagination or deduplication.
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadPage {
pub data: Vec<ThreadSnapshot>,
pub read_states: Option<HashMap<String, ThreadReadState>>,
pub next_cursor: Option<String>,
pub backwards_cursor: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadReadState {
pub first_unread: Option<ThreadUnreadPosition>,
pub revision: String,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum ThreadUnreadPosition {
ThreadStart,
Turn {
#[serde(rename = "turnId")]
turn_id: String,
},
}
macro_rules! redacted_debug {
($($ty:ty),*) => {$(impl fmt::Debug for $ty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(concat!(stringify!($ty), "([redacted])"))
}
})*};
}
redacted_debug!(ThreadListQuery, ThreadPage);
impl Client {
/// Returns one bounded native page. Read failures are not retried automatically.
pub async fn list_threads(&self, query: &ThreadListQuery) -> Result<ThreadPage, Error> {
let bytes = self
.raw_unary(
wire::ListThreadsRequest {
cursor: query.cursor.clone(),
limit: query.limit,
sort_key: Some(match query.sort_key {
ThreadSortKey::CreatedAt => 1,
ThreadSortKey::UpdatedAt => 2,
ThreadSortKey::RecencyAt => 3,
}),
sort_direction: Some(match query.sort_direction {
ThreadSortDirection::Asc => 1,
ThreadSortDirection::Desc => 2,
}),
archived: Some(false),
originators: Some(wire::StringList {
values: query.originators.clone(),
}),
},
"/oaiproto.codex_app_server_backend.ThreadService/ListThreads",
)
.await?;
let response =
wire::ListThreadsResponse::decode(bytes).map_err(|_| Error::InvalidResponse)?;
Ok(ThreadPage {
data: response
.data
.ok_or(Error::InvalidResponse)?
.values
.into_iter()
.map(ThreadSnapshot::decode)
.collect::<Result<_, _>>()?,
read_states: response
.read_states
.map(|states| {
states
.values
.into_iter()
.map(|(thread_id, state)| {
let revision = state.revision.ok_or(Error::InvalidResponse)?;
if revision.is_empty() {
return Err(Error::InvalidResponse);
}
let first_unread = state
.first_unread
.map(|position| match position.value {
Some(wire::thread_unread_position::Value::ThreadStart(_)) => {
Ok(ThreadUnreadPosition::ThreadStart)
}
Some(wire::thread_unread_position::Value::Turn(turn)) => {
let turn_id = turn.turn_id.ok_or(Error::InvalidResponse)?;
if turn_id.is_empty() {
Err(Error::InvalidResponse)
} else {
Ok(ThreadUnreadPosition::Turn { turn_id })
}
}
None => Err(Error::InvalidResponse),
})
.transpose()?;
Ok((
thread_id,
ThreadReadState {
first_unread,
revision,
},
))
})
.collect::<Result<_, _>>()
})
.transpose()?,
next_cursor: response.next_cursor,
backwards_cursor: response.backwards_cursor,
})
}
}
mod wire {
use super::*;
#[derive(Clone, Message)]
pub(super) struct ListThreadsRequest {
#[prost(string, optional, tag = "1")]
pub cursor: Option<String>,
#[prost(uint32, optional, tag = "2")]
pub limit: Option<u32>,
#[prost(int32, optional, tag = "3")]
pub sort_key: Option<i32>,
#[prost(int32, optional, tag = "4")]
pub sort_direction: Option<i32>,
#[prost(bool, optional, tag = "5")]
pub archived: Option<bool>,
#[prost(message, optional, tag = "6")]
pub originators: Option<StringList>,
}
#[derive(Clone, Message)]
pub(super) struct StringList {
#[prost(string, repeated, tag = "1")]
pub values: Vec<String>,
}
#[derive(Clone, Message)]
pub(super) struct ListThreadsResponse {
#[prost(message, optional, tag = "1")]
pub data: Option<ThreadList>,
#[prost(string, optional, tag = "2")]
pub next_cursor: Option<String>,
#[prost(string, optional, tag = "3")]
pub backwards_cursor: Option<String>,
#[prost(message, optional, tag = "4")]
pub read_states: Option<ThreadReadStateMap>,
}
#[derive(Clone, Message)]
pub(super) struct ThreadList {
#[prost(bytes = "bytes", repeated, tag = "1")]
pub values: Vec<Bytes>,
}
#[derive(Clone, Message)]
pub(super) struct ThreadReadStateMap {
#[prost(map = "string, message", tag = "1")]
pub values: HashMap<String, ThreadReadState>,
}
#[derive(Clone, Message, PartialEq)]
pub(super) struct ThreadReadState {
#[prost(message, optional, tag = "1")]
pub first_unread: Option<ThreadUnreadPosition>,
#[prost(string, optional, tag = "2")]
pub revision: Option<String>,
}
#[derive(Clone, Message, PartialEq)]
pub(super) struct ThreadUnreadPosition {
#[prost(oneof = "thread_unread_position::Value", tags = "1, 2")]
pub value: Option<thread_unread_position::Value>,
}
pub(super) mod thread_unread_position {
#[derive(Clone, prost::Oneof, PartialEq)]
pub enum Value {
#[prost(message, tag = "1")]
ThreadStart(super::ThreadUnreadPositionThreadStart),
#[prost(message, tag = "2")]
Turn(super::ThreadUnreadPositionTurn),
}
}
#[derive(Clone, Message, PartialEq)]
pub(super) struct ThreadUnreadPositionThreadStart {}
#[derive(Clone, Message, PartialEq)]
pub(super) struct ThreadUnreadPositionTurn {
#[prost(string, optional, tag = "1")]
pub turn_id: Option<String>,
}
}

View File

@@ -0,0 +1,135 @@
#![cfg(test)]
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn discovery_preserves_pagination_and_order_on_each_request() {
let payload = b"\x0a\x00\x12\x04next\x1a\x04back";
let mut fixture = fixture_responses(vec![
response(vec![frame(payload)], tonic::Status::ok("")),
response(vec![frame(b"\x0a\x00")], tonic::Status::ok("")),
])
.await;
let mut query = ThreadListQuery {
cursor: Some("cursor".into()),
limit: Some(7),
sort_key: ThreadSortKey::UpdatedAt,
sort_direction: ThreadSortDirection::Asc,
originators: vec!["tui".into()],
};
let page = fixture.client.list_threads(&query).await.unwrap();
assert_eq!(
(
page.data,
page.next_cursor.clone(),
page.backwards_cursor,
page.read_states
),
(Vec::new(), Some("next".into()), Some("back".into()), None)
);
assert_request(
&mut fixture,
"ListThreads",
b"\x0a\x06cursor\x10\x07\x18\x02\x20\x01\x28\x00\x32\x05\x0a\x03tui",
)
.await;
query.cursor = page.next_cursor;
let last = fixture.client.list_threads(&query).await.unwrap();
assert_eq!((last.data, last.next_cursor), (Vec::new(), None));
assert_request(
&mut fixture,
"ListThreads",
b"\x0a\x04next\x10\x07\x18\x02\x20\x01\x28\x00\x32\x05\x0a\x03tui",
)
.await;
assert!(fixture.requests.try_recv().is_err());
}
#[tokio::test]
async fn discovery_preserves_native_snapshots_and_read_state() {
// Independent native Thread encodings: Git metadata and future field (99), and a legacy row.
let thread = Bytes::from_static(
b"\x22\x01v\x28\x01\x32\x01/\x48\x00\x62\x28\x0a\x04main\x12\x18https://example.com/repo\x1a\x06abc123\
\x72\x01t\x82\x01\x01p\xaa\x01\x00\xda\x01\x01s\xe2\x01\x02\x08\x63\xea\x01\x02\x12\x00\xfa\x01\x00\x80\x02\x02\x98\x06\x01",
);
let legacy = Bytes::from_static(b"\x22\x00\x28\x00\x32\x01/\x48\x00\x72\x06legacy\x82\x01\x00\xaa\x01\x00\xda\x01\x00\xe2\x01\x02\x08\x01\xea\x01\x02\x12\x00\xfa\x01\x00\x80\x02\x00");
let mut data = Vec::new();
for row in [&thread, &legacy, &thread] {
prost::encoding::bytes::encode(1, row, &mut data);
}
let mut payload = Vec::new();
prost::encoding::bytes::encode(1, &Bytes::from(data), &mut payload);
// Read state map: t -> {first_unread: thread_start, revision: r}.
payload.extend_from_slice(b"\x22\x0e\x0a\x0c\x0a\x01t\x12\x07\x0a\x02\x0a\x00\x12\x01r");
let mut fixture = fixture(response(vec![frame(&payload)], tonic::Status::ok(""))).await;
let page = fixture
.client
.list_threads(&ThreadListQuery::default())
.await
.unwrap();
assert_eq!(
page.data
.iter()
.map(ThreadSnapshot::protobuf)
.collect::<Vec<_>>(),
vec![&thread, &legacy, &thread]
);
assert_eq!(
(
page.data[1].id.as_str(),
page.data[1].session_id.as_str(),
page.data[1].model_provider.as_str(),
page.data[1].cli_version.as_str()
),
("legacy", "", "", "")
);
let page_json = serde_json::to_value(&page).unwrap();
assert_eq!(
page_json["data"][0]["gitInfo"],
serde_json::json!({"branch": "main", "originUrl": "https://example.com/repo", "sha": "abc123"})
);
assert!(page.data[1].git_info.is_none());
assert_eq!(page.data[0].status, ThreadStatus::Idle);
assert_eq!(
page.read_states,
Some(std::collections::HashMap::from([(
"t".into(),
ThreadReadState {
first_unread: Some(ThreadUnreadPosition::ThreadStart),
revision: "r".into(),
}
)]))
);
assert_request(
&mut fixture,
"ListThreads",
b"\x18\x01\x20\x02\x28\x00\x32\x00",
)
.await;
}
#[tokio::test]
async fn discovery_rejects_missing_data_invalid_snapshot_and_empty_revision() {
for payload in [
&b""[..],
&b"\x0a\x02\x0a\x00"[..],
&b"\x0a\x00\x22\x07\x0a\x05\x0a\x01t\x12\x00"[..],
] {
let mut fixture = fixture(response(vec![frame(payload)], tonic::Status::ok(""))).await;
assert!(matches!(
fixture
.client
.list_threads(&ThreadListQuery::default())
.await,
Err(Error::InvalidResponse)
));
assert_request(
&mut fixture,
"ListThreads",
b"\x18\x01\x20\x02\x28\x00\x32\x00",
)
.await;
assert!(fixture.requests.try_recv().is_err());
}
}

View File

@@ -0,0 +1,198 @@
//! Bounded history page reads. Pagination cursors are not live-event replay offsets.
use crate::Client;
use crate::Error;
use crate::ItemSummary;
use crate::TurnSummary;
use crate::history_wire as wire;
use crate::transcript::DecodeFailure;
use crate::transcript::required;
use bytes::Bytes;
use prost::Message;
use std::fmt;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HistoryOrder {
Ascending,
#[default]
Descending,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum HistoryAccess {
#[default]
Default,
Shared,
}
/// A cursor belongs to its original thread and filters. Keep the order for
/// `next_cursor` and reverse it for `backwards_cursor`.
#[derive(Clone, Default)]
pub struct HistoryQuery {
pub cursor: Option<String>,
pub limit: Option<u32>,
pub order: HistoryOrder,
pub access: HistoryAccess,
}
#[derive(Clone)]
pub struct ListTurnsRequest {
pub thread_id: String,
pub page: HistoryQuery,
}
#[derive(Clone)]
pub struct ListItemsRequest {
pub thread_id: String,
pub turn_id: Option<String>,
pub page: HistoryQuery,
}
/// One server page in server order. No automatic pagination, deduplication or retries.
pub struct HistoryPage<T> {
pub thread_id: String,
pub data: Vec<T>,
pub next_cursor: Option<String>,
pub backwards_cursor: Option<String>,
payload: Bytes,
}
impl<T> HistoryPage<T> {
pub fn payload(&self) -> &Bytes {
&self.payload
}
}
pub struct HistoryTurn {
pub summary: TurnSummary,
payload: Bytes,
}
impl HistoryTurn {
/// Original Turn protobuf; includes metadata omitted from the summary.
pub fn payload(&self) -> &Bytes {
&self.payload
}
}
pub struct HistoryItem {
pub turn_id: String,
/// Unsupported items and command sources have no summary and retain their original entry.
pub summary: Option<ItemSummary>,
pub started_at_ms: Option<i64>,
pub completed_at_ms: Option<i64>,
payload: Bytes,
}
impl HistoryItem {
/// Original ThreadItemEntry protobuf, including the item and untyped metadata.
pub fn payload(&self) -> &Bytes {
&self.payload
}
}
macro_rules! redacted_debug {
($($ty:ty),*) => {$(impl fmt::Debug for $ty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(concat!(stringify!($ty), "([redacted])")) }
})*};
}
redacted_debug!(
HistoryQuery,
ListTurnsRequest,
ListItemsRequest,
HistoryTurn,
HistoryItem
);
impl<T> fmt::Debug for HistoryPage<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("HistoryPage([redacted])")
}
}
impl HistoryQuery {
fn order(&self) -> Option<i32> {
Some(match self.order {
HistoryOrder::Ascending => 1,
HistoryOrder::Descending => 2,
})
}
fn access(&self) -> Option<i32> {
match self.access {
HistoryAccess::Default => None,
HistoryAccess::Shared => Some(1),
}
}
}
impl Client {
/// Reads stored turn metadata; use `list_items` for paginated item content.
pub async fn list_turns(
&self,
request: &ListTurnsRequest,
) -> Result<HistoryPage<HistoryTurn>, Error> {
let payload = self
.raw_unary(
wire::TurnsRequest {
thread_id: request.thread_id.clone(),
cursor: request.page.cursor.clone(),
limit: request.page.limit,
order: request.page.order(),
access: request.page.access(),
},
"/oaiproto.codex_app_server_backend.ThreadService/ListTurns",
)
.await?;
decode_page(&request.thread_id, payload, |payload| {
let turn = crate::transcript_wire::Turn::decode(payload.clone())?;
Ok(HistoryTurn {
summary: turn.try_into()?,
payload,
})
})
.map_err(|_| Error::InvalidResponse)
}
/// Reads one page, across the thread or restricted to one turn. This is not an
/// atomic snapshot synchronized with Attach; do not append buffered deltas to it.
pub async fn list_items(
&self,
request: &ListItemsRequest,
) -> Result<HistoryPage<HistoryItem>, Error> {
let payload = self
.raw_unary(
wire::ItemsRequest {
thread_id: request.thread_id.clone(),
turn_id: request.turn_id.clone(),
cursor: request.page.cursor.clone(),
limit: request.page.limit,
order: request.page.order(),
access: request.page.access(),
},
"/oaiproto.codex_app_server_backend.ThreadService/ListItems",
)
.await?;
decode_page(&request.thread_id, payload, |payload| {
let entry = wire::ItemEntry::decode(payload.clone())?;
let turn_id = required(entry.turn_id)?;
if request
.turn_id
.as_ref()
.is_some_and(|expected| expected != &turn_id)
{
return Err(DecodeFailure::InvalidResponse);
}
Ok(HistoryItem {
turn_id,
summary: crate::items::summary(required(entry.item)?)?,
started_at_ms: entry.started_at_ms,
completed_at_ms: entry.completed_at_ms,
payload,
})
})
.map_err(|_| Error::InvalidResponse)
}
}
fn decode_page<T>(
thread_id: &str,
payload: Bytes,
decode: impl Fn(Bytes) -> Result<T, DecodeFailure>,
) -> Result<HistoryPage<T>, DecodeFailure> {
let page = wire::Page::decode(payload.clone())?;
let data = required(page.data)?
.values
.into_iter()
.map(decode)
.collect::<Result<_, _>>()?;
Ok(HistoryPage {
thread_id: thread_id.to_owned(),
data,
next_cursor: page.next_cursor,
backwards_cursor: page.backwards_cursor,
payload,
})
}

View File

@@ -0,0 +1,245 @@
//! Independent wire fixtures cover page requests, presence, provenance and unknown data.
use super::*;
use pretty_assertions::assert_eq;
fn page(rows: &[&[u8]]) -> Vec<u8> {
message(
/*tag*/ 1,
&rows
.iter()
.flat_map(|row| message(/*tag*/ 1, row))
.collect::<Vec<_>>(),
)
}
#[tokio::test]
async fn item_history_paginates_with_explicit_filters_and_preserves_rows() {
let entry =
b"\x0a\x01u\x12\x0f\x1a\x0d\x12\x01i\x32\x01d\x2a\x05\x0a\x03\x12\x01Q\x18\x65\x20\x67";
// A future command source alongside a known agent message.
let command = b"\x12\x01c\x1a\x00\x22\x01w\x3a\x01i\x58\x63\x60\x03";
let item = message(/*tag*/ 7, command);
let opaque = [message(/*tag*/ 1, b"u"), message(/*tag*/ 2, &item)].concat();
let mut first = page(&[entry, &opaque]);
first.extend(b"\x12\x01n\x1a\x01b\xa0\x06\x01");
let unknown = b"\x0a\x01u\x12\x03\xa2\x01\x00";
let second = page(&[unknown]);
let mut fixture = fixture_responses(vec![
response(vec![frame(&first)], tonic::Status::ok("")),
response(vec![frame(&second)], tonic::Status::ok("")),
])
.await;
let mut request = ListItemsRequest {
thread_id: "t".into(),
turn_id: Some("u".into()),
page: HistoryQuery {
cursor: None,
limit: Some(2),
order: HistoryOrder::Ascending,
access: HistoryAccess::Shared,
},
};
let first_page = fixture.client.list_items(&request).await.unwrap();
assert_request(
&mut fixture,
"ListItems",
b"\x0a\x01t\x12\x01u\x20\x02\x28\x01\x30\x01",
)
.await;
assert_eq!(
(
&first_page.thread_id,
&first_page.next_cursor,
&first_page.backwards_cursor,
first_page.payload()
),
(
&"t".to_owned(),
&Some("n".into()),
&Some("b".into()),
&Bytes::from(first)
)
);
let [item, unknown_source] = first_page.data.as_slice() else {
panic!("expected two items")
};
assert_eq!(unknown_source.summary, None);
assert_eq!(unknown_source.payload().as_ref(), opaque.as_slice());
assert_eq!(
(
&item.turn_id,
&item.summary,
item.started_at_ms,
item.completed_at_ms,
item.payload()
),
(
&"u".to_owned(),
&Some(ItemSummary::AgentMessage {
id: "i".into(),
text: "d".into(),
questions: Some(vec![AgentQuestion {
title: "Q".into(),
options: None
}]),
}),
Some(101),
Some(103),
&Bytes::from_static(entry)
)
);
request.page.cursor = first_page.next_cursor;
let second_page = fixture.client.list_items(&request).await.unwrap();
assert_request(
&mut fixture,
"ListItems",
b"\x0a\x01t\x12\x01u\x1a\x01n\x20\x02\x28\x01\x30\x01",
)
.await;
assert_eq!(
(second_page.next_cursor, second_page.backwards_cursor),
(None, None)
);
assert_eq!(second_page.data.len(), 1);
assert_eq!(
(
&second_page.data[0].summary,
second_page.data[0].started_at_ms,
second_page.data[0].payload()
),
(&None, None, &Bytes::from_static(unknown))
);
}
#[tokio::test]
async fn turn_history_reuses_summary_and_retains_omitted_metadata() {
let turn = b"\x08\x65\x10\x02\x22\x01u\x2a\x00\x38\x63\x40\x03";
let payload = page(&[turn]);
let mut fixture = fixture(response(vec![frame(&payload)], tonic::Status::ok(""))).await;
let result = fixture
.client
.list_turns(&ListTurnsRequest {
thread_id: "t".into(),
page: HistoryQuery {
cursor: Some("c".into()),
..Default::default()
},
})
.await
.unwrap();
assert_request(&mut fixture, "ListTurns", b"\x0a\x01t\x12\x01c\x20\x02").await;
assert_eq!(result.data.len(), 1);
assert_eq!(
(
&result.thread_id,
&result.data[0].summary,
result.data[0].payload(),
result.payload()
),
(
&"t".to_owned(),
&TurnSummary {
id: "u".into(),
status: TurnStatus::Failed,
started_at: Some(99),
completed_at: Some(101),
duration_ms: Some(2),
error: None
},
&Bytes::from_static(turn),
&Bytes::from(payload)
)
);
}
#[tokio::test]
async fn history_distinguishes_empty_pages_from_missing_wrappers_and_bad_rows() {
let valid_empty = page(&[]);
let fixture = fixture(response(vec![frame(&valid_empty)], tonic::Status::ok(""))).await;
let request = ListItemsRequest {
thread_id: "t".into(),
turn_id: Some("u".into()),
page: HistoryQuery::default(),
};
assert!(
fixture
.client
.list_items(&request)
.await
.unwrap()
.data
.is_empty()
);
for payload in [
vec![],
page(&[b"\x0a\x01u"]),
page(&[b"\x12\x00"]),
page(&[b"\x0a\x01u\x12\x05\x1a\x03\x12\x01i"]), // Agent message without text.
page(&[b"\x0a\x01x\x12\x00"]),
// Unknown command source and missing required status.
page(&[b"\x0a\x01u\x12\x0f\x3a\x0d\x12\x01c\x1a\x00\x22\x01w\x3a\x01i\x58\x63"]),
vec![10, 127],
] {
let server = super::fixture(response(vec![frame(&payload)], tonic::Status::ok(""))).await;
assert!(matches!(
server.client.list_items(&request).await,
Err(Error::InvalidResponse)
));
}
for turn in [b"\x22\x01u".as_slice(), b"\x40\x01"] {
let server =
super::fixture(response(vec![frame(&page(&[turn]))], tonic::Status::ok(""))).await;
assert!(matches!(
server
.client
.list_turns(&ListTurnsRequest {
thread_id: "t".into(),
page: HistoryQuery::default()
})
.await,
Err(Error::InvalidResponse)
));
}
}
#[tokio::test]
async fn history_errors_preserve_status_without_retrying() {
let mut fixture = fixture(response(
vec![],
tonic::Status::permission_denied("private error"),
))
.await;
let error = fixture
.client
.list_items(&ListItemsRequest {
thread_id: "t".into(),
turn_id: None,
page: HistoryQuery::default(),
})
.await
.unwrap_err();
assert!(!format!("{error:?}").contains("private error"));
assert!(matches!(error, Error::Rpc(status) if status.code == 7));
assert_request(&mut fixture, "ListItems", b"\x0a\x01t\x28\x02").await;
assert!(fixture.requests.try_recv().is_err());
}
#[test]
fn history_diagnostics_redact_each_public_payload_type() {
let query = HistoryQuery {
cursor: Some("secret".into()),
..Default::default()
};
let items = ListItemsRequest {
thread_id: "secret".into(),
turn_id: Some("secret".into()),
page: query.clone(),
};
let turns = ListTurnsRequest {
thread_id: "secret".into(),
page: query.clone(),
};
for value in [
format!("{query:?}"),
format!("{items:?}"),
format!("{turns:?}"),
] {
assert!(value.ends_with("([redacted])"));
assert!(!value.contains("secret"));
}
}

View File

@@ -0,0 +1,57 @@
//! Native paginated history envelopes. Raw rows and unary responses retain unknown fields.
use bytes::Bytes;
use prost::Message;
#[derive(Clone, Message)]
pub(super) struct TurnsRequest {
#[prost(string, tag = "1")]
pub thread_id: String,
#[prost(string, optional, tag = "2")]
pub cursor: Option<String>,
#[prost(uint32, optional, tag = "3")]
pub limit: Option<u32>,
#[prost(int32, optional, tag = "4")]
pub order: Option<i32>,
#[prost(int32, optional, tag = "6")]
pub access: Option<i32>,
}
#[derive(Clone, Message)]
pub(super) struct ItemsRequest {
#[prost(string, tag = "1")]
pub thread_id: String,
#[prost(string, optional, tag = "2")]
pub turn_id: Option<String>,
#[prost(string, optional, tag = "3")]
pub cursor: Option<String>,
#[prost(uint32, optional, tag = "4")]
pub limit: Option<u32>,
#[prost(int32, optional, tag = "5")]
pub order: Option<i32>,
#[prost(int32, optional, tag = "6")]
pub access: Option<i32>,
}
#[derive(Clone, Message)]
pub(super) struct Page {
#[prost(message, optional, tag = "1")]
pub data: Option<Rows>,
#[prost(string, optional, tag = "2")]
pub next_cursor: Option<String>,
#[prost(string, optional, tag = "3")]
pub backwards_cursor: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct Rows {
#[prost(bytes = "bytes", repeated, tag = "1")]
pub values: Vec<Bytes>,
}
#[derive(Clone, Message)]
pub(super) struct ItemEntry {
#[prost(string, optional, tag = "1")]
pub turn_id: Option<String>,
#[prost(message, optional, tag = "2")]
pub item: Option<crate::item_wire::Item>,
#[prost(int64, optional, tag = "3")]
pub started_at_ms: Option<i64>,
#[prost(int64, optional, tag = "4")]
pub completed_at_ms: Option<i64>,
}

View File

@@ -0,0 +1,399 @@
//! Item fixtures cover lifecycle order, outcomes, presence, and opaque fallback.
use super::*;
use pretty_assertions::assert_eq;
use prost::Message;
const AGENT: &[u8] = b"\x1a\x06\x12\x01i\x32\x01d";
const COMMAND: &[u8] =
b"\x0a\x00\x12\x01c\x1a\x07\x0a\x05\x22\x03\x0a\x01c\x22\x01w\x28\x00\x30\x00\x3a\x01i\x60\x03";
fn lifecycle(tag: u32, item: &[u8]) -> Vec<u8> {
let (at_ms, emitted_at_ms) = if tag == 27 { (3, 7) } else { (5, 11) };
let params = if tag == 27 {
[
message(/*tag*/ 1, item),
vec![16, at_ms as u8],
b"\x1a\x01t\x22\x01u".to_vec(),
]
.concat()
} else {
[
vec![8, at_ms as u8],
message(/*tag*/ 2, item),
b"\x1a\x01t\x22\x01u".to_vec(),
]
.concat()
};
message(
tag,
&[vec![8, emitted_at_ms as u8], message(/*tag*/ 2, &params)].concat(),
)
}
#[tokio::test]
async fn item_lifecycle_keeps_identity_and_timestamps() {
let payloads = [
lifecycle(/*tag*/ 27, AGENT),
notification(/*tag*/ 32, DELTA),
lifecycle(/*tag*/ 31, AGENT),
];
let fixture = fixture(response(
payloads
.iter()
.map(|payload| frame(&message(/*tag*/ 1, payload)))
.collect(),
tonic::Status::ok(""),
))
.await;
let mut stream = fixture.client.attach("t").await.unwrap();
let item = |at_ms| ItemLifecycle {
turn_id: "u".into(),
at_ms,
item: ItemSummary::AgentMessage {
id: "i".into(),
text: "d".into(),
questions: None,
},
};
let expected = [
(Some(7), TranscriptUpdate::ItemStarted(item(3))),
(
None,
TranscriptUpdate::AgentMessageDelta(ItemDelta {
item_id: "i".into(),
turn_id: "u".into(),
delta: "d".into(),
}),
),
(Some(11), TranscriptUpdate::ItemCompleted(item(5))),
];
for (emitted_at_ms, update) in expected {
let Event::Transcript(event) = stream.next().await.unwrap().unwrap() else {
panic!("expected transcript event")
};
assert_eq!(
(&event.thread_id, event.emitted_at_ms, &event.update),
(&"t".to_owned(), emitted_at_ms, &update)
);
}
assert!(stream.next().await.is_none());
}
#[test]
fn user_message_preserves_client_id_and_text() {
let user = b"\x0a\x23\x0a\x09client-id\x12\x0b\x0a\x09\x0a\x07\x0a\x05hello\x1a\x09user-item";
assert_eq!(
summary(user),
Some(ItemSummary::UserMessage {
id: "user-item".into(),
client_id: Some("client-id".into()),
content: vec![UserMessageInput::Text {
text: "hello".into(),
text_elements: vec![]
}],
})
);
}
#[test]
fn user_message_preserves_images_spans_and_client_id() {
let url = "data:image/png;base64,AA==";
let label = "[Image #1]";
let element = [
message(/*tag*/ 1, b"\x08\x0d\x10\x03"),
message(/*tag*/ 2, label.as_bytes()),
]
.concat();
let text = [
message(/*tag*/ 1, "é [Image #1]".as_bytes()),
message(/*tag*/ 2, &message(/*tag*/ 1, &element)),
]
.concat();
let image_bytes = [vec![0x08, 99], message(/*tag*/ 2, url.as_bytes())].concat();
let content = [
message(/*tag*/ 1, &message(/*tag*/ 1, &text)),
message(
/*tag*/ 1,
&message(/*tag*/ 2, &message(/*tag*/ 1, &image_bytes)),
),
]
.concat();
let user = message(
/*tag*/ 1,
&[
message(/*tag*/ 1, b"client-id"),
message(/*tag*/ 2, &content),
message(/*tag*/ 3, b"user-item"),
]
.concat(),
);
let expected = ItemSummary::UserMessage {
id: "user-item".into(),
client_id: Some("client-id".into()),
content: vec![
UserMessageInput::Text {
text: "é [Image #1]".into(),
text_elements: vec![UserMessageTextElement {
start: 3,
end: 13,
placeholder: Some(label.into()),
}],
},
UserMessageInput::Image {
image: ImageReference::Url(url.into()),
detail: None,
},
],
};
assert_eq!(summary(&user), Some(expected.clone()));
assert_eq!(format!("{expected:?}"), "ItemSummary([redacted])");
let event = TranscriptEvent::decode("t", &lifecycle(/*tag*/ 31, &user))
.unwrap()
.unwrap();
assert_eq!(
event.update,
TranscriptUpdate::ItemCompleted(ItemLifecycle {
turn_id: "u".into(),
at_ms: 5,
item: expected,
})
);
}
fn summary(bytes: &[u8]) -> Option<ItemSummary> {
crate::items::summary(crate::item_wire::Item::decode(bytes).unwrap())
.unwrap_or_else(|_| panic!("expected supported item fields"))
}
#[test]
fn command_and_patch_summaries_preserve_status_and_presence() {
let command = CommandSummary {
id: "i".into(),
command: "c".into(),
cwd: "w".into(),
actions: vec![CommandAction::Unknown {
command: "c".into(),
}],
source: CommandExecutionSource::Agent,
aggregated_output: Some(String::new()),
duration_ms: Some(0),
exit_code: Some(0),
status: ItemStatus::Failed,
};
assert_eq!(
summary(&message(/*tag*/ 7, &[COMMAND, b"\x58\x02"].concat())),
Some(ItemSummary::CommandExecution(CommandSummary {
source: CommandExecutionSource::UserShell,
..command.clone()
}))
);
let change = b"\x0a\x01d\x12\x02\x0a\x00\x1a\x01p";
for (wire_status, status) in [
(1, ItemStatus::InProgress),
(2, ItemStatus::Completed),
(3, ItemStatus::Failed),
(4, ItemStatus::Declined),
(99, ItemStatus::Unknown(99)),
] {
assert_eq!(
summary(&message(
/*tag*/ 7,
&[COMMAND, &[96, wire_status]].concat()
)),
Some(ItemSummary::CommandExecution(CommandSummary {
status,
..command.clone()
}))
);
let patch = [
message(/*tag*/ 1, &message(/*tag*/ 1, change)),
b"\x12\x01i".to_vec(),
vec![24, wire_status],
]
.concat();
assert_eq!(
summary(&message(/*tag*/ 8, &patch)),
Some(ItemSummary::FileChange {
id: "i".into(),
changes: vec![FileUpdate {
path: "p".into(),
diff: "d".into(),
kind: PatchKind::Add
}],
status,
})
);
}
// Lifecycle completion must not rewrite a failed command's outcome.
for tag in [27, 31] {
let event = TranscriptEvent::decode("t", &lifecycle(tag, &message(/*tag*/ 7, COMMAND)))
.unwrap()
.unwrap();
let (TranscriptUpdate::ItemStarted(item) | TranscriptUpdate::ItemCompleted(item)) =
event.update
else {
panic!("expected item lifecycle");
};
assert_eq!(item.item, ItemSummary::CommandExecution(command.clone()));
}
}
#[test]
fn reasoning_preserves_summary_and_content() {
let reasoning = [
message(/*tag*/ 1, &message(/*tag*/ 1, b"detail")),
b"\x12\x01i".to_vec(),
message(/*tag*/ 3, &message(/*tag*/ 1, b"summary")),
]
.concat();
assert_eq!(
summary(&message(/*tag*/ 6, &reasoning)),
Some(ItemSummary::Reasoning {
id: "i".into(),
summary: vec!["summary".into()],
content: vec!["detail".into()],
})
);
}
#[test]
fn agent_messages_keep_questions_with_empty_text() {
let choices = message(/*tag*/ 1, b"Continue");
let questions = [
message(/*tag*/ 1, &message(/*tag*/ 2, b"Freeform")),
message(/*tag*/ 1, b"\x0a\x00\x12\x05Empty"),
message(
/*tag*/ 1,
&[
message(/*tag*/ 1, &choices),
message(/*tag*/ 2, b"Proceed?"),
]
.concat(),
),
]
.concat();
let expected = vec![
AgentQuestion {
title: "Freeform".into(),
options: None,
},
AgentQuestion {
title: "Empty".into(),
options: Some(vec![]),
},
AgentQuestion {
title: "Proceed?".into(),
options: Some(vec!["Continue".into()]),
},
];
for (questions, expected) in [(questions.as_slice(), expected), (&[], vec![])] {
let item = message(
/*tag*/ 3,
&[b"\x12\x01i\x32\x00".to_vec(), message(/*tag*/ 5, questions)].concat(),
);
assert_eq!(
summary(&item),
Some(ItemSummary::AgentMessage {
id: "i".into(),
text: String::new(),
questions: Some(expected),
})
);
}
}
#[test]
fn unsupported_and_incomplete_items_stay_opaque() {
let absent_time = [message(/*tag*/ 1, AGENT), b"\x1a\x01t\x22\x01u".to_vec()].concat();
// A later audio variant replaces text in the same native UserInput oneof.
let text_then_audio = b"\x0a\x03\x0a\x01x\x22\x03\x0a\x01u";
let user_content = message(/*tag*/ 2, &message(/*tag*/ 1, text_then_audio));
let opaque = [
message(
/*tag*/ 1,
&[user_content, message(/*tag*/ 3, b"i")].concat(),
),
message(/*tag*/ 7, &[COMMAND, b"\x58\x63"].concat()), // Future command source (99).
message(/*tag*/ 9, b""),
message(/*tag*/ 20, b""),
[AGENT.to_vec(), message(/*tag*/ 19, b"")].concat(),
message(/*tag*/ 3, b"\x12\x01i"),
message(/*tag*/ 7, b"\x12\x01c\x22\x01w\x3a\x01i"),
message(/*tag*/ 8, b"\x12\x01i\x18\x01"),
];
for item in opaque {
assert!(
TranscriptEvent::decode("t", &lifecycle(/*tag*/ 27, &item))
.unwrap()
.is_none()
);
}
for input in [
message(/*tag*/ 8, b""), // Future input variant.
message(/*tag*/ 2, &message(/*tag*/ 3, b"")), // Future image reference.
message(/*tag*/ 2, &message(/*tag*/ 1, b"\x08\x01")), // Missing URL.
message(/*tag*/ 2, &message(/*tag*/ 2, b"")), // Missing file ID.
message(
/*tag*/ 1,
&[
message(/*tag*/ 1, b"hello"),
message(/*tag*/ 2, &message(/*tag*/ 1, b"")), // Missing byte range.
]
.concat(),
),
message(
/*tag*/ 1,
&[
message(/*tag*/ 1, b"hello"),
message(
/*tag*/ 2,
&message(/*tag*/ 1, &message(/*tag*/ 1, b"\x08\x01")),
), // Missing start.
]
.concat(),
),
] {
let user = message(
/*tag*/ 1,
&[
message(/*tag*/ 1, b"client-id"),
message(/*tag*/ 2, &message(/*tag*/ 1, &input)),
message(/*tag*/ 3, b"user-item"),
]
.concat(),
);
assert!(
TranscriptEvent::decode("t", &lifecycle(/*tag*/ 27, &user))
.unwrap()
.is_none()
);
}
assert!(
TranscriptEvent::decode("t", &notification(/*tag*/ 27, &absent_time))
.unwrap()
.is_none()
);
}
#[test]
fn item_decoder_rejects_malformed_items_and_foreign_owners() {
assert!(TranscriptEvent::decode("t", &lifecycle(/*tag*/ 27, &[0xff])).is_err());
assert!(TranscriptEvent::decode("other", &lifecycle(/*tag*/ 31, AGENT)).is_err());
}
#[test]
fn item_summaries_redact_sensitive_fields() {
let item = ItemSummary::AgentMessage {
questions: None,
id: "secret".into(),
text: "secret".into(),
};
let text = format!("{item:?}");
assert_eq!(text, "ItemSummary([redacted])");
assert!(!text.contains("secret"));
let action = CommandAction::Unknown {
command: "secret".into(),
};
assert_eq!(format!("{action:?}"), "CommandAction([redacted])");
}

View File

@@ -0,0 +1,202 @@
//! Native item lifecycle envelopes and the item fields used by typed events.
use prost::Message;
#[derive(Clone, Message)]
pub(super) struct Started {
#[prost(message, optional, tag = "1")]
pub item: Option<Item>,
#[prost(int64, optional, tag = "2")]
pub at_ms: Option<i64>,
#[prost(string, optional, tag = "3")]
pub thread_id: Option<String>,
#[prost(string, optional, tag = "4")]
pub turn_id: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct Completed {
#[prost(int64, optional, tag = "1")]
pub at_ms: Option<i64>,
#[prost(message, optional, tag = "2")]
pub item: Option<Item>,
#[prost(string, optional, tag = "3")]
pub thread_id: Option<String>,
#[prost(string, optional, tag = "4")]
pub turn_id: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct Item {
#[prost(
oneof = "Value",
tags = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19"
)]
pub value: Option<Value>,
}
#[derive(Clone, prost::Oneof)]
pub(super) enum Value {
#[prost(message, tag = "1")]
UserMessage(UserMessage),
#[prost(bytes, tag = "2")]
HookPrompt(Vec<u8>),
#[prost(message, tag = "3")]
AgentMessage(AgentMessage),
#[prost(bytes, tag = "4")]
FunctionCallOutput(Vec<u8>),
#[prost(bytes, tag = "5")]
Plan(Vec<u8>),
#[prost(message, tag = "6")]
Reasoning(Reasoning),
#[prost(message, tag = "7")]
Command(Command),
#[prost(message, tag = "8")]
FileChange(FileChange),
#[prost(bytes, tag = "9")]
Mcp(Vec<u8>),
#[prost(bytes, tag = "10")]
DynamicTool(Vec<u8>),
#[prost(bytes, tag = "11")]
CollabAgent(Vec<u8>),
#[prost(bytes, tag = "12")]
SubAgent(Vec<u8>),
#[prost(bytes, tag = "13")]
WebSearch(Vec<u8>),
#[prost(bytes, tag = "14")]
ImageView(Vec<u8>),
#[prost(bytes, tag = "15")]
Sleep(Vec<u8>),
#[prost(bytes, tag = "16")]
ImageGeneration(Vec<u8>),
#[prost(bytes, tag = "17")]
EnterReview(Vec<u8>),
#[prost(bytes, tag = "18")]
ExitReview(Vec<u8>),
#[prost(bytes, tag = "19")]
Compaction(Vec<u8>),
}
#[derive(Clone, Message)]
pub(super) struct AgentMessage {
#[prost(string, optional, tag = "2")]
pub id: Option<String>,
#[prost(message, optional, tag = "5")]
pub questions: Option<AgentQuestionList>,
#[prost(string, optional, tag = "6")]
pub text: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct AgentQuestionList {
#[prost(message, repeated, tag = "1")]
pub values: Vec<AgentQuestion>,
}
#[derive(Clone, Message)]
pub(super) struct AgentQuestion {
#[prost(message, optional, tag = "1")]
pub options: Option<StringList>,
#[prost(string, optional, tag = "2")]
pub title: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct Command {
#[prost(string, optional, tag = "1")]
pub output: Option<String>,
#[prost(string, optional, tag = "2")]
pub command: Option<String>,
#[prost(message, optional, tag = "3")]
pub actions: Option<CommandActionList>,
#[prost(string, optional, tag = "4")]
pub cwd: Option<String>,
#[prost(int64, optional, tag = "5")]
pub duration_ms: Option<i64>,
#[prost(int64, optional, tag = "6")]
pub exit_code: Option<i64>,
#[prost(string, optional, tag = "7")]
pub id: Option<String>,
#[prost(int32, optional, tag = "11")]
pub source: Option<i32>,
#[prost(int32, optional, tag = "12")]
pub status: Option<i32>,
}
#[derive(Clone, Message)]
pub(super) struct Reasoning {
#[prost(message, optional, tag = "1")]
pub content: Option<StringList>,
#[prost(string, optional, tag = "2")]
pub id: Option<String>,
#[prost(message, optional, tag = "3")]
pub summary: Option<StringList>,
}
#[derive(Clone, Message)]
pub(super) struct StringList {
#[prost(string, repeated, tag = "1")]
pub values: Vec<String>,
}
#[derive(Clone, Message)]
pub(super) struct CommandActionList {
#[prost(message, repeated, tag = "1")]
pub values: Vec<CommandAction>,
}
#[derive(Clone, Message)]
pub(super) struct CommandAction {
#[prost(oneof = "command_action::Value", tags = "1, 2, 3, 4")]
pub value: Option<command_action::Value>,
}
pub(super) mod command_action {
#[derive(Clone, prost::Oneof)]
pub enum Value {
#[prost(message, tag = "1")]
Read(super::ReadAction),
#[prost(message, tag = "2")]
ListFiles(super::ListFilesAction),
#[prost(message, tag = "3")]
Search(super::SearchAction),
#[prost(message, tag = "4")]
Unknown(super::UnknownAction),
}
}
#[derive(Clone, Message)]
pub(super) struct ReadAction {
#[prost(string, optional, tag = "1")]
pub command: Option<String>,
#[prost(string, optional, tag = "2")]
pub name: Option<String>,
#[prost(string, optional, tag = "3")]
pub path: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct ListFilesAction {
#[prost(string, optional, tag = "1")]
pub command: Option<String>,
#[prost(string, optional, tag = "2")]
pub path: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct SearchAction {
#[prost(string, optional, tag = "1")]
pub command: Option<String>,
#[prost(string, optional, tag = "2")]
pub path: Option<String>,
#[prost(string, optional, tag = "3")]
pub query: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct UnknownAction {
#[prost(string, optional, tag = "1")]
pub command: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct FileChange {
#[prost(message, optional, tag = "1")]
pub changes: Option<crate::transcript_wire::Changes>,
#[prost(string, optional, tag = "2")]
pub id: Option<String>,
#[prost(int32, optional, tag = "3")]
pub status: Option<i32>,
}
#[derive(Clone, Message)]
pub(super) struct UserMessage {
#[prost(string, optional, tag = "1")]
pub client_id: Option<String>,
#[prost(message, optional, tag = "2")]
pub content: Option<crate::turns_wire::Input>,
#[prost(string, optional, tag = "3")]
pub id: Option<String>,
}

View File

@@ -0,0 +1,313 @@
//! Selected item summaries for live start/completion events, without interpreting executor paths.
use crate::FileUpdate;
use crate::ImageDetail;
use crate::ImageReference;
use crate::TranscriptUpdate;
use crate::UserMessageInput;
use crate::UserMessageTextElement;
use crate::item_wire as wire;
use crate::transcript::DecodeFailure;
use crate::transcript::ITEM_STARTED;
use crate::transcript::required;
use crate::transcript_wire::Envelope;
use crate::transcript_wire::SelectedMessages;
use crate::transcript_wire::merge_messages;
use std::fmt;
/// Lifecycle identity and timestamp for a typed item event.
#[derive(Clone, PartialEq, Eq)]
pub struct ItemLifecycle {
pub turn_id: String,
/// Start or completion time in Unix milliseconds, according to the event variant.
pub at_ms: i64,
pub item: ItemSummary,
}
/// Selected fields only; this is not a complete display model.
#[derive(Clone, PartialEq, Eq)]
pub enum ItemSummary {
UserMessage {
id: String,
client_id: Option<String>,
content: Vec<UserMessageInput>,
},
AgentMessage {
id: String,
text: String,
questions: Option<Vec<AgentQuestion>>,
},
Reasoning {
id: String,
summary: Vec<String>,
content: Vec<String>,
},
CommandExecution(CommandSummary),
FileChange {
id: String,
changes: Vec<FileUpdate>,
status: ItemStatus,
},
}
/// A structured question attached to an agent message.
#[derive(Clone, PartialEq, Eq)]
pub struct AgentQuestion {
pub title: String,
pub options: Option<Vec<String>>,
}
#[derive(Clone, PartialEq, Eq)]
pub struct CommandSummary {
pub id: String,
pub command: String,
/// Executor-native path. Do not interpret it as a path on the client machine.
pub cwd: String,
pub actions: Vec<CommandAction>,
pub source: CommandExecutionSource,
pub aggregated_output: Option<String>,
pub duration_ms: Option<i64>,
pub exit_code: Option<i64>,
pub status: ItemStatus,
}
#[derive(Clone, PartialEq, Eq)]
pub enum CommandAction {
Read {
command: String,
name: String,
path: String,
},
ListFiles {
command: String,
path: Option<String>,
},
Search {
command: String,
query: Option<String>,
path: Option<String>,
},
Unknown {
command: String,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommandExecutionSource {
Agent,
UserShell,
UnifiedExecStartup,
UnifiedExecInteraction,
}
/// CommandExecutionStatus and PatchApplyStatus share these wire values.
/// Completion of the item lifecycle does not imply the command or patch succeeded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ItemStatus {
InProgress,
Completed,
Failed,
Declined,
Unknown(i32),
}
impl From<i32> for ItemStatus {
fn from(value: i32) -> Self {
match value {
1 => Self::InProgress,
2 => Self::Completed,
3 => Self::Failed,
4 => Self::Declined,
value => Self::Unknown(value),
}
}
}
macro_rules! redacted_debug {
($($ty:ty),*) => {$(impl fmt::Debug for $ty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(concat!(stringify!($ty), "([redacted])"))
}
})*};
}
redacted_debug!(
ItemLifecycle,
ItemSummary,
AgentQuestion,
CommandSummary,
CommandAction
);
pub(crate) fn decode(
tag: u32,
values: SelectedMessages<'_>,
) -> Result<Option<(String, Option<i64>, TranscriptUpdate)>, DecodeFailure> {
let (thread_id, turn_id, at_ms, item, emitted_at_ms) = if tag == ITEM_STARTED {
let envelope = merge_messages::<Envelope<wire::Started>>(values)?;
let params = required(envelope.params)?;
(
params.thread_id,
params.turn_id,
params.at_ms,
params.item,
envelope.emitted_at_ms,
)
} else {
let envelope = merge_messages::<Envelope<wire::Completed>>(values)?;
let params = required(envelope.params)?;
(
params.thread_id,
params.turn_id,
params.at_ms,
params.item,
envelope.emitted_at_ms,
)
};
let Some(item) = summary(required(item)?)? else {
return Ok(None);
};
let lifecycle = ItemLifecycle {
turn_id: required(turn_id)?,
at_ms: required(at_ms)?,
item,
};
let update = if tag == ITEM_STARTED {
TranscriptUpdate::ItemStarted(lifecycle)
} else {
TranscriptUpdate::ItemCompleted(lifecycle)
};
Ok(Some((required(thread_id)?, emitted_at_ms, update)))
}
pub(crate) fn summary(item: wire::Item) -> Result<Option<ItemSummary>, DecodeFailure> {
let summary = match item.value {
Some(wire::Value::UserMessage(value)) => {
let mut content = Vec::new();
for input in required(value.content)?.values {
let input = match input.value {
Some(crate::turns_wire::Value::Text(input)) => {
let text = required(input.text)?;
let text_elements = input
.text_elements
.map_or_else(Vec::new, |elements| elements.values)
.into_iter()
.map(|element| {
let range = required(element.byte_range)?;
let start = usize::try_from(required(range.start)?)
.map_err(|_| DecodeFailure::MissingField)?;
let end = usize::try_from(required(range.end)?)
.map_err(|_| DecodeFailure::MissingField)?;
text.get(start..end).ok_or(DecodeFailure::MissingField)?;
Ok(UserMessageTextElement {
start,
end,
placeholder: element.placeholder,
})
})
.collect::<Result<_, DecodeFailure>>()?;
UserMessageInput::Text {
text,
text_elements,
}
}
Some(crate::turns_wire::Value::Image(input)) => {
let (image, detail) = match input.value {
Some(crate::turns_wire::ImageValue::Url(image)) => {
(ImageReference::Url(required(image.value)?), image.detail)
}
Some(crate::turns_wire::ImageValue::FileId(image)) => {
(ImageReference::FileId(required(image.value)?), image.detail)
}
None => return Ok(None),
};
let detail = match detail {
Some(1) => Some(ImageDetail::Auto),
Some(2) => Some(ImageDetail::Low),
Some(3) => Some(ImageDetail::High),
Some(4) => Some(ImageDetail::Original),
// Detail is display metadata. Keep the receipt identity if it is newer.
None | Some(_) => None,
};
UserMessageInput::Image { image, detail }
}
_ => return Ok(None),
};
content.push(input);
}
ItemSummary::UserMessage {
id: required(value.id)?,
client_id: value.client_id,
content,
}
}
Some(wire::Value::AgentMessage(value)) => ItemSummary::AgentMessage {
id: required(value.id)?,
text: required(value.text)?,
questions: value
.questions
.map(|questions| {
questions
.values
.into_iter()
.map(|question| {
Ok(AgentQuestion {
title: required(question.title)?,
options: question.options.map(|options| options.values),
})
})
.collect::<Result<_, DecodeFailure>>()
})
.transpose()?,
},
Some(wire::Value::Reasoning(value)) => ItemSummary::Reasoning {
id: required(value.id)?,
summary: value.summary.map_or_else(Vec::new, |value| value.values),
content: value.content.map_or_else(Vec::new, |value| value.values),
},
Some(wire::Value::Command(value)) => ItemSummary::CommandExecution(CommandSummary {
id: required(value.id)?,
command: required(value.command)?,
cwd: required(value.cwd)?,
actions: required(value.actions)?
.values
.into_iter()
.map(command_action)
.collect::<Result<_, _>>()?,
status: required(value.status)?.into(),
source: match value.source {
None | Some(1) => CommandExecutionSource::Agent,
Some(2) => CommandExecutionSource::UserShell,
Some(3) => CommandExecutionSource::UnifiedExecStartup,
Some(4) => CommandExecutionSource::UnifiedExecInteraction,
Some(_) => return Ok(None),
},
aggregated_output: value.output,
duration_ms: value.duration_ms,
exit_code: value.exit_code,
}),
Some(wire::Value::FileChange(value)) => ItemSummary::FileChange {
id: required(value.id)?,
changes: required(value.changes)?
.values
.into_iter()
.map(FileUpdate::try_from)
.collect::<Result<_, _>>()?,
status: required(value.status)?.into(),
},
_ => return Ok(None),
};
Ok(Some(summary))
}
fn command_action(action: wire::CommandAction) -> Result<CommandAction, DecodeFailure> {
Ok(match required(action.value)? {
wire::command_action::Value::Read(value) => CommandAction::Read {
command: required(value.command)?,
name: required(value.name)?,
path: required(value.path)?,
},
wire::command_action::Value::ListFiles(value) => CommandAction::ListFiles {
command: required(value.command)?,
path: value.path,
},
wire::command_action::Value::Search(value) => CommandAction::Search {
command: required(value.command)?,
query: value.query,
path: value.path,
},
wire::command_action::Value::Unknown(value) => CommandAction::Unknown {
command: required(value.command)?,
},
})
}

View File

@@ -0,0 +1,275 @@
//! Native gRPC client for the Codex cloud ThreadService, using shared HTTP transport policy.
//!
//! Credentials and account selection belong to the caller. Requests are never retried:
//! a timeout or disconnect can leave Resume admitted. Attach delivers live events only;
//! dropping its stream detaches without interrupting the thread or answering approvals.
mod activation;
mod activation_wire;
mod discovery;
mod history;
mod history_wire;
mod item_wire;
mod items;
mod prewarm;
mod transcript;
mod transcript_wire;
mod turns;
mod turns_wire;
mod types;
mod wire;
pub use activation::ActivePermissionProfile;
pub use activation::ApprovalPolicy;
pub use activation::ApprovalsReviewer;
pub use activation::CollaborationMode;
pub use activation::CollaborationSettings;
pub use activation::GitInfo;
pub use activation::NetworkAccess;
pub use activation::SandboxPolicy;
pub use activation::SessionSource;
pub use activation::SubAgentSource;
pub use activation::ThreadActivation;
pub use activation::ThreadActiveFlag;
pub use activation::ThreadEnvironment;
pub use activation::ThreadHistoryMode;
pub use activation::ThreadSnapshot;
pub use activation::ThreadStatus;
pub use discovery::ThreadListQuery;
pub use discovery::ThreadPage;
pub use discovery::ThreadReadState;
pub use discovery::ThreadSortDirection;
pub use discovery::ThreadSortKey;
pub use discovery::ThreadUnreadPosition;
pub use history::HistoryAccess;
pub use history::HistoryItem;
pub use history::HistoryOrder;
pub use history::HistoryPage;
pub use history::HistoryQuery;
pub use history::HistoryTurn;
pub use history::ListItemsRequest;
pub use history::ListTurnsRequest;
pub use items::AgentQuestion;
pub use items::CommandAction;
pub use items::CommandExecutionSource;
pub use items::CommandSummary;
pub use items::ItemLifecycle;
pub use items::ItemStatus;
pub use items::ItemSummary;
pub use prewarm::ProjectEnvironment;
pub use transcript::FileUpdate;
pub use transcript::ItemDelta;
pub use transcript::PatchKind;
pub use transcript::PatchUpdate;
pub use transcript::TranscriptEvent;
pub use transcript::TranscriptUpdate;
pub use transcript::TurnFailure;
pub use transcript::TurnStatus;
pub use transcript::TurnSummary;
pub use turns::AddUserMessageRequest;
pub use turns::Admission;
pub use turns::AdmissionOutcome;
pub use turns::ImageDetail;
pub use turns::ImageReference;
pub use turns::InterruptTurnRequest;
pub use turns::MutationError;
pub use turns::SubmissionMode;
pub use turns::UserMessageInput;
pub use turns::UserMessageTextElement;
pub use types::Credentials;
pub use types::Error;
pub use types::Event;
pub use types::ResumeRequest;
pub use types::RpcStatus;
use codex_http_client::ClientRouteClass;
use codex_http_client::HttpClientBuilder;
use codex_http_client::HttpClientFactory;
use codex_http_client::RouteAwareClientPool;
use futures::StreamExt;
use futures::stream::BoxStream;
use http_body_util::BodyExt;
use std::io;
use std::time::Duration;
use tonic::body::Body;
use tonic::client::Grpc;
use tonic_prost::ProstCodec;
use tower::service_fn;
use tower::util::BoxCloneSyncService;
use url::Url;
const REQUEST_TIMEOUT: Duration = Duration::from_secs(150);
const MAX_MESSAGE_BYTES: usize = 64 * 1024 * 1024;
type Transport = BoxCloneSyncService<http::Request<Body>, http::Response<Body>, io::Error>;
/// One fixed origin and account. Construct a new client when credentials change.
/// Supply a trusted native gRPC origin, without a path (not the HTTP `/grpc` gateway).
pub struct Client {
grpc: Grpc<Transport>,
credentials: Credentials,
}
impl Client {
async fn raw_unary<T: prost::Message + Send + 'static>(
&self,
value: T,
path: &'static str,
) -> Result<bytes::Bytes, Error> {
let mut grpc = self.grpc.clone();
let mut request = tonic::Request::new(value);
*request.metadata_mut() =
tonic::metadata::MetadataMap::from_headers(self.credentials.headers.clone());
let response = tokio::time::timeout(
REQUEST_TIMEOUT,
grpc.unary(
request,
http::uri::PathAndQuery::from_static(path),
wire::RawResponseCodec::<T>(std::marker::PhantomData),
),
)
.await
.map_err(|_| Error::Timeout)?
.map_err(Error::from)?;
Ok(response.into_inner())
}
pub fn new(
factory: &HttpClientFactory,
endpoint: &str,
credentials: Credentials,
) -> Result<Self, Error> {
let endpoint = Url::parse(endpoint).map_err(|_| Error::InvalidEndpoint)?;
let loopback = match endpoint.host() {
Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
Some(url::Host::Domain(name)) => name == "localhost",
None => false,
};
if (endpoint.scheme() != "https" && !(endpoint.scheme() == "http" && loopback))
|| !endpoint.username().is_empty()
|| endpoint.password().is_some()
|| endpoint.query().is_some()
|| endpoint.fragment().is_some()
|| endpoint.path() != "/"
{
return Err(Error::InvalidEndpoint);
}
let local_http = endpoint.scheme() == "http";
if local_http
&& (factory.network_policy().is_managed()
|| factory
.network_policy()
.acquire_for_unsupported_sdk()
.is_err())
{
return Err(Error::InvalidEndpoint);
}
let builder = HttpClientBuilder::new()
.without_redirects()
.without_request_logging()
.http2_prior_knowledge()
.connect_timeout(Duration::from_secs(30));
let http = if local_http {
// Plaintext credentials must never leave loopback through an outbound proxy.
builder.build_direct().map_err(|_| Error::ClientBuild)?
} else {
RouteAwareClientPool::with_builder(factory.clone(), ClientRouteClass::Api, builder)
.into_client()
};
let origin = endpoint
.as_str()
.parse()
.map_err(|_| Error::InvalidEndpoint)?;
let transport = service_fn(move |request: http::Request<Body>| {
let http = http.clone();
async move {
let (parts, body) = request.into_parts();
let response = http
.request(parts.method, parts.uri.to_string())
.version(parts.version)
.headers(parts.headers)
.body_stream(body.into_data_stream())
.send()
.await
.map_err(|_| io::Error::other("gRPC transport failed"))?;
Ok(response.into_http_response().map(Body::new))
}
});
Ok(Self {
grpc: Grpc::with_origin(BoxCloneSyncService::new(transport), origin)
.max_decoding_message_size(MAX_MESSAGE_BYTES)
.max_encoding_message_size(MAX_MESSAGE_BYTES),
credentials,
})
}
/// With `wait: false`, success means admission only. Failures may leave work admitted.
pub async fn resume(&self, request: &ResumeRequest) -> Result<(), Error> {
let mut grpc = self.grpc.clone();
let mut request = tonic::Request::new(request.clone());
*request.metadata_mut() =
tonic::metadata::MetadataMap::from_headers(self.credentials.headers.clone());
// Bound the whole unary RPC, including its response body and trailers.
tokio::time::timeout(
REQUEST_TIMEOUT,
grpc.unary(
request,
http::uri::PathAndQuery::from_static(
"/oaiproto.codex_app_server_backend.ThreadService/Resume",
),
ProstCodec::<ResumeRequest, wire::ResumeResponse>::default(),
),
)
.await
.map_err(|_| Error::Timeout)?
.map_err(Error::from)?;
Ok(())
}
/// Live events only, without history or automatic reconnect. The stream terminates
/// on its first error. Setup is bounded; there is no idle or total stream deadline.
pub async fn attach(
&self,
thread_id: &str,
) -> Result<BoxStream<'static, Result<Event, Error>>, Error> {
let mut grpc = self.grpc.clone();
let mut request = tonic::Request::new(wire::AttachRequest {
thread_id: thread_id.to_owned(),
});
*request.metadata_mut() =
tonic::metadata::MetadataMap::from_headers(self.credentials.headers.clone());
let response = tokio::time::timeout(
REQUEST_TIMEOUT,
grpc.server_streaming(
request,
http::uri::PathAndQuery::from_static(
"/oaiproto.codex_app_server_backend.ThreadService/Attach",
),
ProstCodec::<wire::AttachRequest, wire::AttachResponse>::default(),
),
)
.await
.map_err(|_| Error::Timeout)?
.map_err(Error::from)?;
let mut stream = response.into_inner();
let thread_id = thread_id.to_owned();
Ok(async_stream::try_stream! {
while let Some(message) = stream.message().await.map_err(Error::from)? {
yield match message.event.ok_or(Error::InvalidResponse)? {
wire::Payload::Notification(bytes) => {
match TranscriptEvent::decode(&thread_id, &bytes)? {
Some(event) => Event::Transcript(Box::new(event)),
None => Event::Notification(bytes),
}
},
wire::Payload::ServerRequest(bytes) => Event::ServerRequest(bytes),
};
}
}
.boxed())
}
}
#[cfg(test)]
#[path = "client_tests.rs"]
mod tests;

View File

@@ -0,0 +1,185 @@
//! Prepare an ordinary cloud coding thread with server-owned managed environment defaults.
use crate::Client;
use crate::Error;
use bytes::Bytes;
use bytes::BytesMut;
use prost::Message;
/// A local project's GitHub origins to provision in the default cloud environment.
/// Callers must supply credential-free origin URLs; this client does not inspect local Git state.
#[derive(Clone)]
pub struct ProjectEnvironment {
pub name: String,
pub origin_urls: Vec<String>,
/// Working directory inside the managed environment, when a project selects one.
pub cwd: Option<String>,
}
impl std::fmt::Debug for ProjectEnvironment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("ProjectEnvironment([redacted])")
}
}
impl Client {
/// Prewarm an ordinary coding thread in the default managed environment.
/// The service makes it discoverable when it admits the first user message.
/// This mutation is never retried. A timeout or disconnect can leave a thread
/// prepared even if its identity and settings were not received. The caller
/// must not use this ordinary-thread API for an ephemeral session.
pub async fn prewarm_default_thread(
&self,
model: Option<String>,
model_provider: Option<String>,
) -> Result<crate::ThreadActivation, Error> {
self.prewarm_thread(model, model_provider, /*project*/ None)
.await
}
/// Prewarm a coding thread, deferring executor readiness for a selected project checkout.
pub async fn prewarm_thread(
&self,
model: Option<String>,
model_provider: Option<String>,
project: Option<ProjectEnvironment>,
) -> Result<crate::ThreadActivation, Error> {
let deferred_environment = project.is_some().then_some(true);
let managed = match project {
Some(ProjectEnvironment {
name,
origin_urls,
cwd,
}) => wire::ManagedEnvironment {
environment_config_id: Some("asenvcfg_base".to_owned()),
cwd,
overrides: Some(wire::EnvironmentOverrides {
repositories: Some(wire::RepositoryOverrides {
values: origin_urls
.into_iter()
.map(|origin_url| wire::RepositoryOverride {
origin_url: Some(origin_url),
})
.collect(),
}),
name: Some(name),
}),
},
None => wire::ManagedEnvironment::default(),
};
let response = self
.raw_unary(
wire::PrewarmRequest {
model,
model_provider,
deferred_environment,
environments: Some(wire::EnvironmentList {
values: vec![wire::EnvironmentSelection {
managed: Some(managed),
}],
}),
},
"/oaiproto.codex_app_server_backend.ThreadService/Prewarm",
)
.await?;
let warm = wire::PrewarmResponse::decode(response).map_err(|_| Error::InvalidResponse)?;
// PrewarmThread omits turns, but the native Thread requires an empty
// ThreadTurns message. Prefix it so the original wire bytes, including
// unknown fields, are preserved and malformed trailing data stays invalid.
let mut thread = BytesMut::new();
prost::encoding::bytes::encode(/* tag */ 31, &Bytes::new(), &mut thread);
thread.extend_from_slice(&warm.thread.ok_or(Error::InvalidResponse)?);
crate::ThreadActivation::from_settings(crate::activation_wire::UpdateConfigResponse {
active_permission_profile: warm.active_permission_profile,
approval_policy: warm.approval_policy,
approvals_reviewer: warm.approvals_reviewer,
cwd: warm.cwd,
model: warm.model,
model_provider: warm.model_provider,
reasoning_effort: warm.reasoning_effort,
runtime_workspace_roots: warm.runtime_workspace_roots,
sandbox: warm.sandbox,
service_tier: warm.service_tier,
thread: Some(thread.freeze()),
..Default::default()
})
}
}
mod wire {
use super::*;
#[derive(Clone, Message)]
pub(super) struct PrewarmRequest {
#[prost(message, optional, tag = "10")]
pub environments: Option<EnvironmentList>,
#[prost(string, optional, tag = "15")]
pub model: Option<String>,
#[prost(string, optional, tag = "16")]
pub model_provider: Option<String>,
#[prost(bool, optional, tag = "29")]
pub deferred_environment: Option<bool>,
}
#[derive(Clone, Message)]
pub(super) struct EnvironmentList {
#[prost(message, repeated, tag = "1")]
pub values: Vec<EnvironmentSelection>,
}
#[derive(Clone, Message)]
pub(super) struct EnvironmentSelection {
#[prost(message, optional, tag = "1")]
pub managed: Option<ManagedEnvironment>,
}
#[derive(Clone, Message)]
pub(super) struct ManagedEnvironment {
#[prost(string, optional, tag = "1")]
pub environment_config_id: Option<String>,
#[prost(string, optional, tag = "2")]
pub cwd: Option<String>,
#[prost(message, optional, tag = "3")]
pub overrides: Option<EnvironmentOverrides>,
}
#[derive(Clone, Message)]
pub(super) struct EnvironmentOverrides {
#[prost(message, optional, tag = "1")]
pub repositories: Option<RepositoryOverrides>,
#[prost(string, optional, tag = "2")]
pub name: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct RepositoryOverrides {
#[prost(message, repeated, tag = "1")]
pub values: Vec<RepositoryOverride>,
}
#[derive(Clone, Message)]
pub(super) struct RepositoryOverride {
#[prost(string, optional, tag = "5")]
pub origin_url: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct PrewarmResponse {
#[prost(message, optional, tag = "1")]
pub active_permission_profile: Option<crate::activation_wire::ActivePermissionProfile>,
#[prost(message, optional, tag = "2")]
pub approval_policy: Option<crate::activation_wire::ApprovalPolicy>,
#[prost(int32, optional, tag = "3")]
pub approvals_reviewer: Option<i32>,
#[prost(string, optional, tag = "4")]
pub cwd: Option<String>,
#[prost(string, optional, tag = "7")]
pub model: Option<String>,
#[prost(string, optional, tag = "8")]
pub model_provider: Option<String>,
#[prost(string, optional, tag = "10")]
pub reasoning_effort: Option<String>,
#[prost(message, optional, tag = "11")]
pub runtime_workspace_roots: Option<crate::activation_wire::StringList>,
#[prost(message, optional, tag = "12")]
pub sandbox: Option<crate::activation_wire::SandboxPolicy>,
#[prost(message, optional, tag = "13")]
pub service_tier: Option<crate::activation_wire::NullableString>,
#[prost(bytes = "bytes", optional, tag = "14")]
pub thread: Option<Bytes>,
}
}

View File

@@ -0,0 +1,284 @@
//! Typed live transcript updates for the attached thread.
use crate::Error;
use crate::Event;
use crate::ThreadStatus;
use crate::transcript_wire as wire;
use std::fmt;
/// A live update, not a history snapshot or a replay guarantee.
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TranscriptEvent {
pub thread_id: String,
pub emitted_at_ms: Option<i64>,
pub update: TranscriptUpdate,
}
#[derive(Clone, PartialEq, Eq)]
pub enum TranscriptUpdate {
ItemStarted(crate::ItemLifecycle),
ItemCompleted(crate::ItemLifecycle),
AgentMessageDelta(ItemDelta),
CommandOutputDelta(ItemDelta),
FileChangeOutputDelta(ItemDelta),
FileChangePatchUpdated(PatchUpdate),
TurnStarted(TurnSummary),
TurnCompleted(TurnSummary),
}
#[derive(Clone, PartialEq, Eq)]
pub struct ItemDelta {
pub item_id: String,
pub turn_id: String,
pub delta: String,
}
#[derive(Clone, PartialEq, Eq)]
pub struct PatchUpdate {
pub item_id: String,
pub turn_id: String,
pub changes: Vec<FileUpdate>,
}
#[derive(Clone, PartialEq, Eq)]
pub struct FileUpdate {
pub path: String,
pub diff: String,
pub kind: PatchKind,
}
#[derive(Clone, PartialEq, Eq)]
pub enum PatchKind {
Add,
Delete,
Update {
move_path: Option<String>,
},
/// The server reported an unrecognized change kind.
Unknown,
}
/// Status, timing, and failure details for a turn.
#[derive(Clone, PartialEq, Eq)]
pub struct TurnSummary {
pub id: String,
pub status: TurnStatus,
/// Turn start time in Unix seconds, if reported by the server.
pub started_at: Option<i64>,
/// Turn completion time in Unix seconds, if reported by the server.
pub completed_at: Option<i64>,
/// Turn duration in milliseconds, if reported by the server.
pub duration_ms: Option<i64>,
pub error: Option<TurnFailure>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TurnStatus {
Completed,
Interrupted,
Failed,
InProgress,
Unknown(i32),
}
#[derive(Clone, PartialEq, Eq)]
pub struct TurnFailure {
pub message: String,
pub additional_details: Option<String>,
}
// Each public payload type is safe to format independently, not just through Event.
macro_rules! redacted_debug {
($($ty:ty),* $(,)?) => {$(impl fmt::Debug for $ty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(concat!(stringify!($ty), "([redacted])"))
}
})*};
}
redacted_debug!(
TranscriptEvent,
TranscriptUpdate,
ItemDelta,
PatchUpdate,
FileUpdate,
PatchKind,
TurnSummary,
TurnFailure
);
// Field numbers in the ASB Notification.value oneof.
const THREAD_STATUS_CHANGED: u32 = 3;
const TURN_STARTED: u32 = 21;
const TURN_COMPLETED: u32 = 23;
pub(super) const ITEM_STARTED: u32 = 27;
const ITEM_COMPLETED: u32 = 31;
const ITEM_AGENT_MESSAGE_DELTA: u32 = 32;
const ITEM_COMMAND_EXECUTION_OUTPUT_DELTA: u32 = 37;
const ITEM_FILE_CHANGE_OUTPUT_DELTA: u32 = 39;
const ITEM_FILE_CHANGE_PATCH_UPDATED: u32 = 40;
pub(super) enum DecodeFailure {
MissingField,
InvalidResponse,
}
impl From<prost::DecodeError> for DecodeFailure {
fn from(_: prost::DecodeError) -> Self {
Self::InvalidResponse
}
}
pub(super) fn required<T>(value: Option<T>) -> Result<T, DecodeFailure> {
value.ok_or(DecodeFailure::MissingField)
}
impl Event {
/// Returns a supported status update for this thread from an Attach notification.
pub fn thread_status_for(&self, thread_id: &str) -> Option<ThreadStatus> {
let Self::Notification(bytes) = self else {
return None;
};
let (tag, values) = wire::notification(bytes).ok().flatten()?;
if tag != THREAD_STATUS_CHANGED {
return None;
}
let envelope = wire::merge_messages::<wire::Envelope<wire::StatusUpdate>>(values).ok()?;
let params = envelope.params?;
if params.thread_id.as_deref() != Some(thread_id) {
return None;
}
crate::activation::parse_status(params.status?).ok()
}
}
impl TranscriptEvent {
pub(crate) fn decode(thread_id: &str, payload: &[u8]) -> Result<Option<Self>, Error> {
match Self::decode_present_fields(thread_id, payload) {
Ok(event) => Ok(event),
Err(DecodeFailure::MissingField) => Ok(None),
Err(DecodeFailure::InvalidResponse) => Err(Error::InvalidResponse),
}
}
fn decode_present_fields(
thread_id: &str,
payload: &[u8],
) -> Result<Option<Self>, DecodeFailure> {
let Some((tag, values)) = wire::notification(payload)? else {
return Ok(None);
};
let (owner, emitted_at_ms, update) = match tag {
ITEM_STARTED | ITEM_COMPLETED => match crate::items::decode(tag, values)? {
Some(decoded) => decoded,
None => return Ok(None),
},
ITEM_AGENT_MESSAGE_DELTA
| ITEM_COMMAND_EXECUTION_OUTPUT_DELTA
| ITEM_FILE_CHANGE_OUTPUT_DELTA => {
let envelope = wire::merge_messages::<wire::Envelope<wire::Delta>>(values)?;
let params = required(envelope.params)?;
let delta = ItemDelta {
item_id: required(params.item_id)?,
turn_id: required(params.turn_id)?,
delta: required(params.delta)?,
};
let update = match tag {
ITEM_AGENT_MESSAGE_DELTA => TranscriptUpdate::AgentMessageDelta(delta),
ITEM_COMMAND_EXECUTION_OUTPUT_DELTA => {
TranscriptUpdate::CommandOutputDelta(delta)
}
ITEM_FILE_CHANGE_OUTPUT_DELTA => TranscriptUpdate::FileChangeOutputDelta(delta),
_ => return Ok(None),
};
(required(params.thread_id)?, envelope.emitted_at_ms, update)
}
ITEM_FILE_CHANGE_PATCH_UPDATED => {
let envelope = wire::merge_messages::<wire::Envelope<wire::PatchUpdate>>(values)?;
let params = required(envelope.params)?;
let changes = required(params.changes)?
.values
.into_iter()
.map(FileUpdate::try_from)
.collect::<Result<_, DecodeFailure>>()?;
let update = PatchUpdate {
item_id: required(params.item_id)?,
turn_id: required(params.turn_id)?,
changes,
};
(
required(params.thread_id)?,
envelope.emitted_at_ms,
TranscriptUpdate::FileChangePatchUpdated(update),
)
}
TURN_STARTED | TURN_COMPLETED => {
let envelope = wire::merge_messages::<wire::Envelope<wire::TurnUpdate>>(values)?;
let params = required(envelope.params)?;
let summary = TurnSummary::try_from(required(params.turn)?)?;
let update = if tag == TURN_STARTED {
TranscriptUpdate::TurnStarted(summary)
} else {
TranscriptUpdate::TurnCompleted(summary)
};
(required(params.thread_id)?, envelope.emitted_at_ms, update)
}
_ => return Ok(None),
};
if owner != thread_id {
// Attach also carries account-wide lifecycle notifications. Preserve them
// as opaque events rather than ending this thread's transcript stream.
return if matches!(tag, TURN_STARTED | TURN_COMPLETED) {
Ok(None)
} else {
Err(DecodeFailure::InvalidResponse)
};
}
Ok(Some(Self {
thread_id: owner,
emitted_at_ms,
update,
}))
}
}
impl TryFrom<wire::Change> for FileUpdate {
type Error = DecodeFailure;
fn try_from(change: wire::Change) -> Result<Self, DecodeFailure> {
let kind = match required(change.kind)?.value {
Some(wire::Kind::Add(_)) => PatchKind::Add,
Some(wire::Kind::Delete(_)) => PatchKind::Delete,
Some(wire::Kind::Update(value)) => PatchKind::Update {
move_path: value.move_path,
},
None => PatchKind::Unknown,
};
Ok(Self {
path: required(change.path)?,
diff: required(change.diff)?,
kind,
})
}
}
impl TryFrom<wire::Turn> for TurnSummary {
type Error = DecodeFailure;
fn try_from(turn: wire::Turn) -> Result<Self, DecodeFailure> {
let status = match required(turn.status)? {
1 => TurnStatus::Completed,
2 => TurnStatus::Interrupted,
3 => TurnStatus::Failed,
4 => TurnStatus::InProgress,
value => TurnStatus::Unknown(value),
};
let error = turn
.error
.map(|error| {
Ok::<_, DecodeFailure>(TurnFailure {
message: required(error.message)?,
additional_details: error.additional_details,
})
})
.transpose()?;
Ok(Self {
id: required(turn.id)?,
status,
started_at: turn.started_at,
completed_at: turn.completed_at,
duration_ms: turn.duration_ms,
error,
})
}
}

View File

@@ -0,0 +1,303 @@
//! Independent protobuf fixtures cover the public transcript contract.
use super::*;
use pretty_assertions::assert_eq;
fn message(tag: u32, payload: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
prost::encoding::encode_key(tag, prost::encoding::WireType::LengthDelimited, &mut out);
prost::encoding::encode_varint(payload.len() as u64, &mut out);
out.extend_from_slice(payload);
out
}
fn notification(tag: u32, params: &[u8]) -> Vec<u8> {
message(tag, &message(/*tag*/ 2, params))
}
const DELTA: &[u8] = b"\x0a\x01d\x12\x01i\x1a\x01t\x22\x01u";
#[tokio::test]
async fn attach_decodes_live_deltas_with_unknown_fields() {
let fixture = fixture(response(
[32, 37, 39]
.into_iter()
.map(|tag| {
let mut payload = notification(tag, DELTA);
payload.extend([0xa0, 0x06, 1]); // unknown field 100
frame(&message(/*tag*/ 1, &payload))
})
.collect(),
tonic::Status::ok(""),
))
.await;
let mut stream = fixture.client.attach("t").await.unwrap();
for expected in [
TranscriptUpdate::AgentMessageDelta as fn(ItemDelta) -> TranscriptUpdate,
TranscriptUpdate::CommandOutputDelta,
TranscriptUpdate::FileChangeOutputDelta,
] {
let Event::Transcript(event) = stream.next().await.unwrap().unwrap() else {
panic!("expected transcript event")
};
assert_eq!(format!("{event:?}"), "TranscriptEvent([redacted])");
assert_eq!(event.thread_id, "t");
assert_eq!(event.emitted_at_ms, None);
assert_eq!(
event.update,
expected(ItemDelta {
item_id: "i".into(),
turn_id: "u".into(),
delta: "d".into(),
})
);
}
assert!(stream.next().await.is_none());
}
#[test]
fn patches_preserve_order_kinds_and_move_paths() {
let mut changes = Vec::new();
for kind in [
b"\x0a\x00".as_slice(),
b"\x12\x00",
b"\x1a\x03\x0a\x01m",
b"\x22\x00",
] {
changes.extend(message(
/*tag*/ 1,
&[
b"\x0a\x01d".to_vec(),
message(/*tag*/ 2, kind),
b"\x1a\x01p".to_vec(),
]
.concat(),
));
}
let params = [message(/*tag*/ 1, &changes), DELTA[3..].to_vec()].concat();
let payload = notification(/*tag*/ 40, &params);
let event = TranscriptEvent::decode("t", &payload).unwrap().unwrap();
assert_eq!(
event.update,
TranscriptUpdate::FileChangePatchUpdated(PatchUpdate {
item_id: "i".into(),
turn_id: "u".into(),
changes: [
PatchKind::Add,
PatchKind::Delete,
PatchKind::Update {
move_path: Some("m".into())
},
PatchKind::Unknown,
]
.into_iter()
.map(|kind| FileUpdate {
path: "p".into(),
diff: "d".into(),
kind,
})
.collect(),
})
);
}
#[test]
fn turn_events_preserve_status_failure_and_timing() {
for (tag, status, expected) in [
(23, 1, TurnStatus::Completed),
(23, 2, TurnStatus::Interrupted),
(21, 4, TurnStatus::InProgress),
(23, 3, TurnStatus::Failed),
(23, 99, TurnStatus::Unknown(99)),
] {
let (timing, started_at, completed_at, duration_ms) = match expected {
TurnStatus::InProgress => (b"\x38\x00".as_slice(), Some(0), None, None),
TurnStatus::Completed => (
b"\x08\x0d\x10\xf4\x03\x38\x0b".as_slice(),
Some(11),
Some(13),
Some(500),
),
_ => (&[][..], None, None, None),
};
let turn = [
b"\x1a\x06\x0a\x01a\x1a\x01e\x22\x01u\x2a\x00\x40".to_vec(),
vec![status],
timing.to_vec(),
]
.concat();
let params = [b"\x0a\x01t".to_vec(), message(/*tag*/ 2, &turn)].concat();
let event = TranscriptEvent::decode(
"t",
&message(tag, &[vec![8, 7], message(/*tag*/ 2, &params)].concat()),
)
.unwrap()
.unwrap();
let turn = TurnSummary {
id: "u".into(),
status: expected,
started_at,
completed_at,
duration_ms,
error: Some(TurnFailure {
message: "e".into(),
additional_details: Some("a".into()),
}),
};
assert_eq!(event.emitted_at_ms, Some(7));
assert_eq!(
event.update,
if tag == 21 {
TranscriptUpdate::TurnStarted(turn)
} else {
TranscriptUpdate::TurnCompleted(turn)
}
);
}
}
#[tokio::test]
async fn attach_preserves_opaque_notifications_and_continues() {
let foreign_turn = b"\x0a\x01x\x12\x05\x22\x01u\x40\x01";
let opaque = [
message(/*tag*/ 100, b"unknown notification"),
notification(
/*tag*/ 27,
b"\x0a\x02\x4a\x00\x10\x03\x1a\x01t\x22\x01u",
), // Unsupported MCP item.
notification(/*tag*/ 21, foreign_turn),
notification(/*tag*/ 23, foreign_turn),
notification(/*tag*/ 32, &DELTA[..9]), // missing turn ID
];
let valid = notification(/*tag*/ 32, DELTA);
let fixture = fixture(response(
opaque
.iter()
.chain([&valid])
.map(|payload| frame(&message(/*tag*/ 1, payload)))
.collect(),
tonic::Status::ok(""),
))
.await;
let mut stream = fixture.client.attach("t").await.unwrap();
for payload in opaque {
let Some(Ok(Event::Notification(bytes))) = stream.next().await else {
panic!("expected opaque notification");
};
assert_eq!(bytes.as_ref(), payload.as_slice());
}
let Some(Ok(Event::Transcript(event))) = stream.next().await else {
panic!("expected transcript after opaque notifications");
};
assert_eq!(event.thread_id, "t");
assert!(stream.next().await.is_none());
}
#[test]
fn decoder_keeps_incomplete_events_opaque_and_rejects_foreign_deltas() {
let mut wrong_owner = DELTA.to_vec();
wrong_owner[8] = b'x';
for payload in [
notification(/*tag*/ 32, &DELTA[3..]),
notification(/*tag*/ 40, &DELTA[3..]),
notification(/*tag*/ 23, b"\x0a\x01t"),
] {
assert!(TranscriptEvent::decode("t", &payload).unwrap().is_none());
}
assert!(TranscriptEvent::decode("t", &notification(/*tag*/ 32, &wrong_owner)).is_err());
assert!(
TranscriptEvent::decode("t", &message(/*tag*/ 100, b""))
.unwrap()
.is_none()
);
}
#[test]
fn notification_selection_merges_only_repeated_variants() {
let partial = notification(/*tag*/ 32, &DELTA[..6]);
let tail = notification(/*tag*/ 32, &DELTA[6..]);
assert!(
TranscriptEvent::decode("t", &[partial.clone(), tail.clone()].concat())
.unwrap()
.is_some()
);
assert!(
TranscriptEvent::decode("t", &[partial, message(/*tag*/ 85, b""), tail].concat())
.unwrap()
.is_none()
);
assert!(
TranscriptEvent::decode(
"t",
&[notification(/*tag*/ 32, DELTA), message(/*tag*/ 89, b"")].concat()
)
.unwrap()
.is_none()
);
let envelope = message(/*tag*/ 2, DELTA);
let split_inside_params = [
message(/*tag*/ 32, &envelope[..4]),
message(/*tag*/ 32, &envelope[4..]),
]
.concat();
assert!(TranscriptEvent::decode("t", &split_inside_params).is_err());
}
#[test]
fn public_payload_debug_is_redacted() {
for formatted in [
format!(
"{:?}",
FileUpdate {
path: "secret".into(),
diff: "secret".into(),
kind: PatchKind::Update {
move_path: Some("secret".into()),
},
}
),
format!(
"{:?}",
TurnFailure {
message: "secret".into(),
additional_details: Some("secret".into()),
}
),
] {
assert!(formatted.ends_with("([redacted])"));
assert!(!formatted.contains("secret"));
}
}
#[test]
fn notification_selection_handles_many_fragments_and_obsolete_malformed_messages() {
let mut payload = message(/*tag*/ 32, b"\xff");
payload.extend(message(/*tag*/ 85, b""));
for _ in 0..100_000 {
payload.extend(message(/*tag*/ 32, b""));
}
payload.extend(notification(/*tag*/ 32, &DELTA[..6]));
payload.extend(message(/*tag*/ 100, b"\xff"));
payload.extend(notification(/*tag*/ 32, &DELTA[6..]));
let event = TranscriptEvent::decode("t", &payload).unwrap().unwrap();
assert_eq!(
event.update,
TranscriptUpdate::AgentMessageDelta(ItemDelta {
item_id: "i".into(),
turn_id: "u".into(),
delta: "d".into(),
})
);
payload.extend(message(/*tag*/ 89, b"\xff"));
assert!(TranscriptEvent::decode("t", &payload).unwrap().is_none());
}
#[path = "item_tests.rs"]
mod items;
#[path = "history_tests.rs"]
mod history;
#[path = "turns_tests.rs"]
mod turns_tests;

View File

@@ -0,0 +1,161 @@
//! Mirrors the ASB notification fields exposed by this client so it can build without
//! the monorepo's generated bindings. Keep the tag numbers in sync with `Notification.value`
//! in `native_notification.proto`. Only the final oneof variant is decoded on a second pass.
use prost::Message;
type SelectedNotification<'a> = (u32, SelectedMessages<'a>);
pub(super) struct SelectedMessages<'a> {
tag: u32,
input: &'a [u8],
}
// Known oneof members in native_notification.proto replace earlier variants, even
// when unsupported. Fields outside that schema leave the selected variant intact.
pub(super) fn notification(
input: &[u8],
) -> Result<Option<SelectedNotification<'_>>, prost::DecodeError> {
let mut cursor = input;
let mut selected = None;
while !cursor.is_empty() {
let start = input.len() - cursor.len();
let (tag, kind) = prost::encoding::decode_key(&mut cursor)?;
if (1..=89).contains(&tag) {
prost::encoding::check_wire_type(prost::encoding::WireType::LengthDelimited, kind)?;
if selected.is_none_or(|(previous, _)| previous != tag) {
selected = Some((tag, start));
}
}
prost::encoding::skip_field(kind, tag, &mut cursor, Default::default())?;
}
Ok(selected.map(|(tag, start)| {
(
tag,
SelectedMessages {
tag,
input: &input[start..],
},
)
}))
}
pub(super) fn merge_messages<T: Message + Default>(
values: SelectedMessages<'_>,
) -> Result<T, prost::DecodeError> {
let mut message = T::default();
let mut input = values.input;
while !input.is_empty() {
let (tag, kind) = prost::encoding::decode_key(&mut input)?;
if tag == values.tag {
// The first pass validated the wire type and bounded every length.
let length = prost::encoding::decode_varint(&mut input)? as usize;
let (value, tail) = input.split_at(length);
message.merge(value)?;
input = tail;
} else {
prost::encoding::skip_field(kind, tag, &mut input, Default::default())?;
}
}
Ok(message)
}
#[derive(Clone, Message)]
pub(super) struct Envelope<T: Message + Default + std::fmt::Debug> {
#[prost(int64, optional, tag = "1")]
pub emitted_at_ms: Option<i64>,
#[prost(message, optional, tag = "2")]
pub params: Option<T>,
}
#[derive(Clone, Message)]
pub(super) struct StatusUpdate {
#[prost(message, optional, tag = "1")]
pub status: Option<crate::activation_wire::ThreadStatus>,
#[prost(string, optional, tag = "2")]
pub thread_id: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct PatchUpdate {
#[prost(message, optional, tag = "1")]
pub changes: Option<Changes>,
#[prost(string, optional, tag = "2")]
pub item_id: Option<String>,
#[prost(string, optional, tag = "3")]
pub thread_id: Option<String>,
#[prost(string, optional, tag = "4")]
pub turn_id: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct Delta {
#[prost(string, optional, tag = "1")]
pub delta: Option<String>,
#[prost(string, optional, tag = "2")]
pub item_id: Option<String>,
#[prost(string, optional, tag = "3")]
pub thread_id: Option<String>,
#[prost(string, optional, tag = "4")]
pub turn_id: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct Changes {
#[prost(message, repeated, tag = "1")]
pub values: Vec<Change>,
}
#[derive(Clone, Message)]
pub(super) struct Change {
#[prost(string, optional, tag = "1")]
pub diff: Option<String>,
#[prost(message, optional, tag = "2")]
pub kind: Option<ChangeKind>,
#[prost(string, optional, tag = "3")]
pub path: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct ChangeKind {
#[prost(oneof = "Kind", tags = "1, 2, 3")]
pub value: Option<Kind>,
}
#[derive(Clone, prost::Oneof)]
pub(super) enum Kind {
#[prost(message, tag = "1")]
Add(Empty),
#[prost(message, tag = "2")]
Delete(Empty),
#[prost(message, tag = "3")]
Update(Move),
}
#[derive(Clone, Message)]
pub(super) struct Empty {}
#[derive(Clone, Message)]
pub(super) struct Move {
#[prost(string, optional, tag = "1")]
pub move_path: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct TurnUpdate {
#[prost(string, optional, tag = "1")]
pub thread_id: Option<String>,
#[prost(message, optional, tag = "2")]
pub turn: Option<Turn>,
}
#[derive(Clone, Message)]
pub(super) struct Turn {
#[prost(int64, optional, tag = "1")]
pub completed_at: Option<i64>,
#[prost(int64, optional, tag = "2")]
pub duration_ms: Option<i64>,
#[prost(message, optional, tag = "3")]
pub error: Option<TurnError>,
#[prost(string, optional, tag = "4")]
pub id: Option<String>,
#[prost(int64, optional, tag = "7")]
pub started_at: Option<i64>,
#[prost(int32, optional, tag = "8")]
pub status: Option<i32>,
}
#[derive(Clone, Message)]
pub(super) struct TurnError {
#[prost(string, optional, tag = "1")]
pub additional_details: Option<String>,
#[prost(string, optional, tag = "3")]
pub message: Option<String>,
}

View File

@@ -0,0 +1,338 @@
//! Explicit, non-retried mutations. A failed RPC may already have changed the thread.
use crate::Client;
use crate::Error;
use crate::TurnSummary;
use crate::transcript::DecodeFailure;
use crate::transcript::required;
use crate::turns_wire as wire;
use bytes::Bytes;
use prost::Message;
use std::fmt;
// CCA forwards the envelope through a 4 MiB boundary; reserve 256 KiB for forwarding.
const MAX_IMAGE_MESSAGE_BYTES: usize = 4 * 1024 * 1024 - 256 * 1024;
#[derive(Clone, Copy, Debug)]
pub enum SubmissionMode {
Steer,
Queue,
StartIfIdle,
}
/// Text and images using the existing thread configuration. Persist the message ID with
/// the input before calling; never reuse it for a different logical submission.
#[derive(Clone)]
pub struct AddUserMessageRequest {
pub thread_id: String,
pub client_user_message_id: String,
pub input: Vec<UserMessageInput>,
/// Optional classification supplied by the caller for this turn.
pub turn_trigger: Option<String>,
pub mode: SubmissionMode,
pub shared_access: bool,
}
/// Ordered input parts for one logical user message.
#[derive(Clone, PartialEq, Eq)]
pub enum UserMessageInput {
Text {
text: String,
text_elements: Vec<UserMessageTextElement>,
},
Image {
image: ImageReference,
detail: Option<ImageDetail>,
},
}
/// A placeholder span in the UTF-8 bytes of a text input part.
#[derive(Clone, PartialEq, Eq)]
pub struct UserMessageTextElement {
pub start: usize,
pub end: usize,
pub placeholder: Option<String>,
}
/// An inline data URL or an uploaded file ID. HTTP image URLs are not supported.
#[derive(Clone, PartialEq, Eq)]
pub enum ImageReference {
Url(String),
FileId(String),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImageDetail {
Auto,
Low,
High,
Original,
}
#[derive(Clone)]
pub struct InterruptTurnRequest {
pub thread_id: String,
pub turn_id: String,
pub shared_access: bool,
}
#[derive(PartialEq)]
pub enum AdmissionOutcome {
Started(TurnSummary),
Steered(TurnSummary),
/// The original turn ID, if assigned. Read history or observe Attach for its status.
Duplicate {
turn_id: Option<String>,
},
Queued {
submission_id: String,
},
}
pub struct Admission {
pub thread_id: String,
pub client_user_message_id: String,
pub outcome: AdmissionOutcome,
payload: Bytes,
}
impl Admission {
/// Complete original AddUserMessageResponse, including untyped metadata.
pub fn payload(&self) -> &Bytes {
&self.payload
}
}
/// Remote errors do not reliably identify whether admission happened. Inspect the
/// source explicitly, reconcile with the server, and never blindly resubmit.
#[derive(Debug, thiserror::Error)]
pub enum MutationError {
#[error("invalid or oversized mutation request; nothing was sent")]
InvalidRequest,
#[error("mutation outcome unknown; do not automatically retry: {0}")]
OutcomeUnknown(#[source] Error),
}
macro_rules! redacted_debug {
($($ty:ty),*) => {$(impl fmt::Debug for $ty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(concat!(stringify!($ty), "([redacted])")) }
})*};
}
redacted_debug!(
AddUserMessageRequest,
UserMessageInput,
UserMessageTextElement,
ImageReference,
InterruptTurnRequest,
Admission,
AdmissionOutcome
);
impl Client {
/// Sends once. Success is admission, not turn completion. Dropping this future
/// after polling can leave admission unknown; it does not cancel remote work.
pub async fn add_user_message(
&self,
request: &AddUserMessageRequest,
) -> Result<Admission, MutationError> {
if request.thread_id.trim().is_empty()
|| request.client_user_message_id.trim().is_empty()
|| !request.input.iter().any(|input| match input {
UserMessageInput::Text { text, .. } => !text.trim().is_empty(),
UserMessageInput::Image { .. } => true,
})
|| request.input.iter().any(|input| match input {
UserMessageInput::Text {
text,
text_elements,
} => text_elements
.iter()
.any(|element| text.get(element.start..element.end).is_none()),
UserMessageInput::Image { image, .. } => match image {
ImageReference::Url(value) => {
value.split_once(',').is_none_or(|(prefix, payload)| {
!prefix
.get(..5)
.is_some_and(|scheme| scheme.eq_ignore_ascii_case("data:"))
|| payload.trim().is_empty()
})
}
ImageReference::FileId(value) => value.trim().is_empty(),
},
})
{
return Err(MutationError::InvalidRequest);
}
let value = wire::AddRequest {
client_user_message_id: request.client_user_message_id.clone(),
input: Some(wire::Input {
values: request
.input
.iter()
.map(|input| wire::UserInput {
value: Some(match input {
UserMessageInput::Text {
text,
text_elements,
} => wire::Value::Text(wire::Text {
text: Some(text.clone()),
text_elements: (!text_elements.is_empty()).then(|| {
wire::TextElements {
values: text_elements
.iter()
.map(|element| wire::TextElement {
byte_range: Some(wire::ByteRange {
end: Some(element.end as u64),
start: Some(element.start as u64),
}),
placeholder: element.placeholder.clone(),
})
.collect(),
}
}),
}),
UserMessageInput::Image { image, detail } => {
let detail = detail.map(|detail| match detail {
ImageDetail::Auto => 1,
ImageDetail::Low => 2,
ImageDetail::High => 3,
ImageDetail::Original => 4,
});
let value = match image {
ImageReference::Url(url) => {
wire::ImageValue::Url(wire::ImageReference {
detail,
value: Some(url.clone()),
})
}
ImageReference::FileId(file_id) => {
wire::ImageValue::FileId(wire::ImageReference {
detail,
value: Some(file_id.clone()),
})
}
};
wire::Value::Image(wire::Image { value: Some(value) })
}
}),
})
.collect(),
}),
thread_id: request.thread_id.clone(),
turn_trigger: request.turn_trigger.clone(),
access: request.shared_access.then_some(1),
mode: Some(match request.mode {
SubmissionMode::Steer => 1,
SubmissionMode::Queue => 2,
SubmissionMode::StartIfIdle => 3,
}),
};
if request
.input
.iter()
.any(|input| matches!(input, UserMessageInput::Image { .. }))
&& value.encoded_len() > MAX_IMAGE_MESSAGE_BYTES
{
return Err(MutationError::InvalidRequest);
}
let payload = self
.mutate(
value,
"/oaiproto.codex_app_server_backend.ThreadService/AddUserMessage",
)
.await?;
let outcome = decode_admission(&request.client_user_message_id, payload.clone())
.map_err(|_| MutationError::OutcomeUnknown(Error::InvalidResponse))?;
Ok(Admission {
thread_id: request.thread_id.clone(),
client_user_message_id: request.client_user_message_id.clone(),
outcome,
payload,
})
}
/// Interrupts this turn only, without stopping its thread or removing queued input.
/// Success acknowledges the RPC; observe turn lifecycle events for completion.
pub async fn interrupt_turn(
&self,
request: &InterruptTurnRequest,
) -> Result<(), MutationError> {
if request.thread_id.trim().is_empty() || request.turn_id.trim().is_empty() {
return Err(MutationError::InvalidRequest);
}
let payload = self
.mutate(
wire::InterruptRequest {
thread_id: request.thread_id.clone(),
turn_id: request.turn_id.clone(),
access: request.shared_access.then_some(1),
},
"/oaiproto.codex_app_server_backend.ThreadService/InterruptTurn",
)
.await?;
crate::wire::ResumeResponse::decode(payload)
.map_err(|_| MutationError::OutcomeUnknown(Error::InvalidResponse))?;
Ok(())
}
pub(crate) async fn mutate<T: Message + Send + 'static>(
&self,
value: T,
path: &'static str,
) -> Result<Bytes, MutationError> {
if value.encoded_len() > crate::MAX_MESSAGE_BYTES {
return Err(MutationError::InvalidRequest);
}
let mut grpc = self.grpc.clone();
let mut request = tonic::Request::new(value);
*request.metadata_mut() =
tonic::metadata::MetadataMap::from_headers(self.credentials.headers.clone());
// Read the final trailers separately: initial metadata cannot acknowledge
// the mutation, and tonic permits HTTP 200 without a final gRPC status.
tokio::time::timeout(crate::REQUEST_TIMEOUT, async {
let response = grpc
.server_streaming(
request,
http::uri::PathAndQuery::from_static(path),
crate::wire::RawResponseCodec::<T>(std::marker::PhantomData),
)
.await?;
// An initial OK makes tonic skip final-status validation. A unary
// success must carry its status after the response message instead.
if response.metadata().contains_key("grpc-status") {
return Err(Error::InvalidResponse);
}
let mut response = response.into_inner();
let payload = response.message().await?.ok_or(Error::InvalidResponse)?;
let trailers = response.trailers().await?.ok_or(Error::InvalidResponse)?;
if trailers
.get("grpc-status")
.is_none_or(|status| status != "0")
{
return Err(Error::InvalidResponse);
}
Ok(payload)
})
.await
.map_err(|_| MutationError::OutcomeUnknown(Error::Timeout))?
.map_err(MutationError::OutcomeUnknown)
}
}
fn decode_admission(message_id: &str, payload: Bytes) -> Result<AdmissionOutcome, DecodeFailure> {
let response = wire::AddResponse::decode(payload)?;
if required(response.client_user_message_id)? != message_id {
return Err(DecodeFailure::InvalidResponse);
}
if response.outcome == Some(3) {
let turn_id = response.turn.map(|turn| required(turn.id)).transpose()?;
if turn_id.as_ref().is_some_and(|id| id.trim().is_empty()) {
return Err(DecodeFailure::InvalidResponse);
}
return Ok(AdmissionOutcome::Duplicate { turn_id });
}
let turn = response.turn.map(TurnSummary::try_from).transpose()?;
if turn.as_ref().is_some_and(|turn| turn.id.trim().is_empty()) {
return Err(DecodeFailure::InvalidResponse);
}
Ok(match response.outcome {
Some(1) => AdmissionOutcome::Started(required(turn)?),
Some(2) => AdmissionOutcome::Steered(required(turn)?),
Some(4) => {
let queued = required(response.queued_submission)?;
let submission_id = required(queued.id)?;
if submission_id.trim().is_empty()
|| required(queued.client_user_message_id)? != message_id
{
return Err(DecodeFailure::InvalidResponse);
}
AdmissionOutcome::Queued { submission_id }
}
_ => return Err(DecodeFailure::InvalidResponse),
})
}

View File

@@ -0,0 +1,589 @@
//! Independent wire fixtures for admission, addressed interruption and uncertain outcomes.
use super::*;
use pretty_assertions::assert_eq;
fn request() -> AddUserMessageRequest {
AddUserMessageRequest {
thread_id: "t".into(),
client_user_message_id: "m".into(),
input: vec![UserMessageInput::Text {
text: "hello".into(),
text_elements: vec![],
}],
turn_trigger: None,
mode: SubmissionMode::StartIfIdle,
shared_access: true,
}
}
fn admitted(outcome: u8) -> Vec<u8> {
[
message(/*tag*/ 1, b"\x22\x01u\x40\x04"),
vec![0x10, outcome, 0x1a, 1, b'm'],
]
.concat()
}
#[tokio::test]
async fn submission_preserves_admission_variants_and_wire_identity() {
for (mode, mode_number, outcome_number) in [
(SubmissionMode::StartIfIdle, 3, 1),
(SubmissionMode::Steer, 1, 2),
(SubmissionMode::Queue, 2, 3),
(SubmissionMode::Queue, 2, 4),
] {
let mut payload = admitted(outcome_number);
if outcome_number == 4 {
payload = [
vec![0x10, 4, 0x1a, 1, b'm'],
message(/*tag*/ 5, b"\x0a\x01q\x1a\x01m"),
]
.concat();
}
payload.extend([0xa0, 0x06, 7]); // Unknown metadata survives.
let mut fixture = fixture(response(vec![frame(&payload)], tonic::Status::ok(""))).await;
let turn_trigger = (mode_number == 3).then(|| "safety_recourse_follow_up".to_owned());
let result = fixture
.client
.add_user_message(&AddUserMessageRequest {
turn_trigger,
mode,
..request()
})
.await
.unwrap();
let turn = TurnSummary {
id: "u".into(),
status: TurnStatus::InProgress,
error: None,
started_at: None,
completed_at: None,
duration_ms: None,
};
let expected = match outcome_number {
1 => AdmissionOutcome::Started(turn),
2 => AdmissionOutcome::Steered(turn),
3 => AdmissionOutcome::Duplicate {
turn_id: Some("u".into()),
},
4 => AdmissionOutcome::Queued {
submission_id: "q".into(),
},
_ => unreachable!(),
};
assert_eq!(
(
&result.thread_id,
&result.client_user_message_id,
&result.outcome,
result.payload()
),
(
&"t".to_owned(),
&"m".to_owned(),
&expected,
&Bytes::from(payload)
)
);
assert_eq!(
format!("{result:?} {:?}", result.outcome),
"Admission([redacted]) AdmissionOutcome([redacted])"
);
let expected_request = [
message(/*tag*/ 4, b"m"),
message(
/*tag*/ 11,
&message(
/*tag*/ 1,
&message(/*tag*/ 1, &message(/*tag*/ 1, b"hello")),
),
),
message(/*tag*/ 23, b"t"),
if mode_number == 3 {
message(/*tag*/ 25, b"safety_recourse_follow_up")
} else {
Vec::new()
},
vec![0xd0, 1, 1, 0xf0, 1, mode_number],
]
.concat();
assert_request(&mut fixture, "AddUserMessage", &expected_request).await;
}
}
#[tokio::test]
async fn image_submission_preserves_order_references_and_optional_detail() {
let url = "DaTa:image/png;base64,AA==";
let label = "[Image #1]";
let text = format!("é {label}");
let input = vec![
UserMessageInput::Image {
image: ImageReference::Url(url.into()),
detail: None,
},
UserMessageInput::Text {
text: text.clone(),
text_elements: vec![UserMessageTextElement {
start: 3,
end: text.len(),
placeholder: Some(label.into()),
}],
},
UserMessageInput::Image {
image: ImageReference::FileId("file-private".into()),
detail: Some(ImageDetail::High),
},
];
for part in &input {
assert_eq!(format!("{part:?}"), "UserMessageInput([redacted])");
}
let mut fixture = fixture(response(
vec![frame(&admitted(/*outcome*/ 3))],
tonic::Status::ok(""),
))
.await;
let result = fixture
.client
.add_user_message(&AddUserMessageRequest { input, ..request() })
.await
.unwrap();
assert_eq!(
result.outcome,
AdmissionOutcome::Duplicate {
turn_id: Some("u".into())
}
);
let span = [
message(/*tag*/ 1, b"\x08\x0d\x10\x03"),
message(/*tag*/ 2, label.as_bytes()),
]
.concat();
let text = [
message(/*tag*/ 1, text.as_bytes()),
message(/*tag*/ 2, &message(/*tag*/ 1, &span)),
]
.concat();
let url = message(/*tag*/ 1, &message(/*tag*/ 2, url.as_bytes()));
let file = message(
/*tag*/ 2,
&[vec![0x08, 3], message(/*tag*/ 2, b"file-private")].concat(),
);
let values = [
message(/*tag*/ 1, &message(/*tag*/ 2, &url)),
message(/*tag*/ 1, &message(/*tag*/ 1, &text)),
message(/*tag*/ 1, &message(/*tag*/ 2, &file)),
]
.concat();
let expected = [
message(/*tag*/ 4, b"m"),
message(/*tag*/ 11, &values),
message(/*tag*/ 23, b"t"),
vec![0xd0, 1, 1, 0xf0, 1, 3],
]
.concat();
assert_request(&mut fixture, "AddUserMessage", &expected).await;
assert!(fixture.requests.try_recv().is_err());
}
#[tokio::test]
async fn duplicate_can_omit_turn_but_malformed_admission_is_unknown() {
let payloads = vec![
vec![],
admitted(/*outcome*/ 0),
admitted(/*outcome*/ 99),
b"\x10\x01\x1a\x01m".to_vec(),
// Started with a turn ID but no turn status.
b"\x0a\x03\x22\x01u\x10\x01\x1a\x01m".to_vec(),
b"\x10\x04\x1a\x01m".to_vec(),
b"\x10\x03\x1a\x01x".to_vec(),
// A present duplicate turn must have a nonblank ID.
b"\x0a\x00\x10\x03\x1a\x01m".to_vec(),
b"\x0a\x02\x22\x00\x10\x03\x1a\x01m".to_vec(),
b"\x0a\x03\x22\x01 \x10\x03\x1a\x01m".to_vec(),
vec![0x80],
[
vec![0x10, 4, 0x1a, 1, b'm'],
message(/*tag*/ 5, b"\x0a\x01q\x1a\x01x"),
]
.concat(),
];
for payload in payloads {
let mut fixture = fixture(response(vec![frame(&payload)], tonic::Status::ok(""))).await;
assert!(matches!(
fixture.client.add_user_message(&request()).await,
Err(MutationError::OutcomeUnknown(Error::InvalidResponse))
));
fixture.requests.recv().await.unwrap();
assert!(fixture.requests.try_recv().is_err());
}
// Duplicate identity is independent of absent or unknown lifecycle state.
for turn in [&b"\x22\x01u"[..], &b"\x22\x01u\x40\x63"[..]] {
let payload = [message(/*tag*/ 1, turn), b"\x10\x03\x1a\x01m".to_vec()].concat();
let fixture = fixture(response(vec![frame(&payload)], tonic::Status::ok(""))).await;
assert_eq!(
fixture
.client
.add_user_message(&request())
.await
.unwrap()
.outcome,
AdmissionOutcome::Duplicate {
turn_id: Some("u".into())
}
);
}
let fixture = fixture(response(
vec![frame(b"\x10\x03\x1a\x01m")],
tonic::Status::ok(""),
))
.await;
assert_eq!(
fixture
.client
.add_user_message(&request())
.await
.unwrap()
.outcome,
AdmissionOutcome::Duplicate { turn_id: None }
);
}
#[tokio::test]
async fn interrupt_addresses_original_turn_and_preserves_uncertain_errors() {
for status in [
tonic::Status::ok(""),
tonic::Status::permission_denied("private"),
tonic::Status::unavailable("private"),
] {
let code = status.code() as i32;
let mut fixture = fixture(response(vec![frame(&[])], status)).await;
let result = fixture
.client
.interrupt_turn(&InterruptTurnRequest {
thread_id: "t".into(),
turn_id: "u".into(),
shared_access: true,
})
.await;
if code == 0 {
result.unwrap();
} else {
let error = result.unwrap_err();
assert!(!format!("{error:?} {error}").contains("private"));
let MutationError::OutcomeUnknown(Error::Rpc(status)) = error else {
panic!("expected unknown outcome")
};
assert_eq!((status.code, status.message), (code, "private".into()));
}
assert_request(&mut fixture, "InterruptTurn", b"\x0a\x01t\x12\x01u\x18\x01").await;
assert!(fixture.requests.try_recv().is_err());
}
}
#[tokio::test]
async fn invalid_input_never_sends_and_diagnostics_redact() {
let mut fixture = fixture(response(vec![frame(&[])], tonic::Status::ok(""))).await;
for input in [
AddUserMessageRequest {
input: vec![],
..request()
},
AddUserMessageRequest {
input: vec![UserMessageInput::Text {
text: "x".repeat(MAX_MESSAGE_BYTES),
text_elements: vec![],
}],
..request()
},
AddUserMessageRequest {
input: vec![UserMessageInput::Image {
image: ImageReference::Url(format!(
"data:,{}",
"A".repeat(4 * 1024 * 1024 - 256 * 1024)
)),
detail: None,
}],
..request()
},
AddUserMessageRequest {
input: vec![UserMessageInput::Image {
image: ImageReference::Url("https://example.com/image.png".into()),
detail: None,
}],
..request()
},
AddUserMessageRequest {
input: vec![
UserMessageInput::Text {
text: "hello".into(),
text_elements: vec![],
},
UserMessageInput::Image {
image: ImageReference::FileId("".into()),
detail: Some(ImageDetail::Auto),
},
],
..request()
},
AddUserMessageRequest {
input: vec![UserMessageInput::Text {
text: " ".into(),
text_elements: vec![],
}],
..request()
},
AddUserMessageRequest {
client_user_message_id: "".into(),
..request()
},
AddUserMessageRequest {
thread_id: "".into(),
..request()
},
] {
assert_eq!(format!("{input:?}"), "AddUserMessageRequest([redacted])");
assert!(matches!(
fixture.client.add_user_message(&input).await,
Err(MutationError::InvalidRequest)
));
}
for url in ["data:image/png;base64,", "data:,", "data:no-comma"] {
let input = AddUserMessageRequest {
input: vec![UserMessageInput::Image {
image: ImageReference::Url(url.into()),
detail: None,
}],
..request()
};
assert!(matches!(
fixture.client.add_user_message(&input).await,
Err(MutationError::InvalidRequest)
));
}
let input = InterruptTurnRequest {
thread_id: "private".into(),
turn_id: "".into(),
shared_access: false,
};
assert_eq!(format!("{input:?}"), "InterruptTurnRequest([redacted])");
assert!(matches!(
fixture.client.interrupt_turn(&input).await,
Err(MutationError::InvalidRequest)
));
for thread_id in ["".to_owned(), " ".to_owned(), "t".repeat(MAX_MESSAGE_BYTES)] {
assert!(matches!(
fixture.client.activate(&thread_id).await,
Err(MutationError::InvalidRequest)
));
}
assert!(fixture.requests.try_recv().is_err());
}
#[tokio::test]
async fn image_preflight_applies_exact_encoded_envelope_boundary() {
let cap = 4 * 1024 * 1024 - 256 * 1024;
for extra in [0, 1] {
// With these IDs and settings, the nested wire envelope adds 38 bytes.
let url = format!("data:,{}", "A".repeat(cap - 38 - "data:,".len() + extra));
let expected = [
message(/*tag*/ 4, b"m"),
message(
/*tag*/ 11,
&message(
/*tag*/ 1,
&message(
/*tag*/ 2,
&message(/*tag*/ 1, &message(/*tag*/ 2, url.as_bytes())),
),
),
),
message(/*tag*/ 23, b"t"),
vec![0xd0, 1, 1, 0xf0, 1, 3],
]
.concat();
assert_eq!(expected.len(), cap + extra);
let mut fixture = fixture(response(
vec![frame(&admitted(/*outcome*/ 3))],
tonic::Status::ok(""),
))
.await;
let input = vec![UserMessageInput::Image {
image: ImageReference::Url(url),
detail: None,
}];
let result = fixture
.client
.add_user_message(&AddUserMessageRequest { input, ..request() })
.await;
if extra == 0 {
result.unwrap();
assert_request(&mut fixture, "AddUserMessage", &expected).await;
} else {
assert!(matches!(result, Err(MutationError::InvalidRequest)));
assert!(fixture.requests.try_recv().is_err());
}
}
}
#[tokio::test]
async fn plain_text_retains_limit_above_image_forwarding_cap() {
let mut fixture = fixture(response(
vec![frame(&admitted(/*outcome*/ 3))],
tonic::Status::ok(""),
))
.await;
let text = "x".repeat(4 * 1024 * 1024);
let input = vec![UserMessageInput::Text {
text: text.clone(),
text_elements: vec![],
}];
let result = fixture
.client
.add_user_message(&AddUserMessageRequest { input, ..request() })
.await
.unwrap();
assert_eq!(
result.outcome,
AdmissionOutcome::Duplicate {
turn_id: Some("u".into())
}
);
let expected = [
message(/*tag*/ 4, b"m"),
message(
/*tag*/ 11,
&message(
/*tag*/ 1,
&message(/*tag*/ 1, &message(/*tag*/ 1, text.as_bytes())),
),
),
message(/*tag*/ 23, b"t"),
vec![0xd0, 1, 1, 0xf0, 1, 3],
]
.concat();
assert_request(&mut fixture, "AddUserMessage", &expected).await;
}
#[tokio::test]
async fn dropping_pending_submission_does_not_send_a_retry_or_interrupt() {
let (sender, dropped) = tokio::sync::oneshot::channel::<()>();
let stream = async_stream::stream! {
let _sender = sender;
yield Ok::<_, Infallible>(Frame::data(frame(&admitted(/*outcome*/ 1))));
std::future::pending::<()>().await; // No final status yet: admission remains uncertain.
};
let mut fixture = fixture(
http::Response::builder()
.header("content-type", "application/grpc")
.body(Body::new(StreamBody::new(stream)))
.unwrap(),
)
.await;
{
let request = request();
let call = fixture.client.add_user_message(&request);
tokio::pin!(call);
tokio::select! {
result = &mut call => panic!("completed before trailers: {result:?}"),
observed = fixture.requests.recv() => { observed.unwrap(); }
}
}
assert!(
tokio::time::timeout(Duration::from_secs(5), dropped)
.await
.unwrap()
.is_err()
);
assert!(fixture.requests.try_recv().is_err());
}
#[tokio::test]
async fn server_rejection_and_transport_status_do_not_prove_no_admission() {
for status in [
tonic::Status::invalid_argument("private"),
tonic::Status::deadline_exceeded("private"),
tonic::Status::unavailable("private"),
] {
let code = status.code() as i32;
let mut fixture = fixture(response(vec![], status)).await;
let error = fixture
.client
.add_user_message(&request())
.await
.unwrap_err();
assert!(!format!("{error:?} {error}").contains("private"));
let MutationError::OutcomeUnknown(Error::Rpc(status)) = error else {
panic!("expected unknown outcome")
};
assert_eq!((status.code, status.message), (code, "private".into()));
fixture.requests.recv().await.unwrap();
assert!(fixture.requests.try_recv().is_err());
}
}
#[tokio::test]
async fn mutations_require_explicit_successful_grpc_status() {
let mut ok_trailers = http::HeaderMap::new();
ok_trailers.insert("grpc-status", http::HeaderValue::from_static("0"));
for (initial_status, trailers, include_message, expect_success) in [
(None, None, true, false),
(None, Some(http::HeaderMap::new()), true, false),
(Some("0"), None, true, false),
(Some("0"), None, false, false),
(Some("0"), Some(ok_trailers.clone()), true, false),
(None, Some(ok_trailers), true, true),
] {
for method in ["AddUserMessage", "InterruptTurn", "UpdateConfig"] {
let payload = match method {
"AddUserMessage" => admitted(/*outcome*/ 1),
"InterruptTurn" => vec![],
"UpdateConfig" => [
// Approval, reviewer, cwd, model, provider and read-only sandbox.
b"\x12\x02\x08\x02\x18\x01\x2a\x01/\x52\x01m\x5a\x01p\x7a\x02\x12\x00".to_vec(),
message(
/*tag*/ 17,
b"\x22\x01v\x28\x01\x32\x01/\x48\x00\x72\x01t\x82\x01\x01p\xaa\x01\x00\xda\x01\x01s\xe2\x01\x02\x08\x01\xea\x01\x02\x12\x00\x80\x02\x02",
),
].concat(),
_ => unreachable!(),
};
let frames = include_message
.then(|| Frame::data(frame(&payload)))
.into_iter()
.chain(trailers.clone().map(Frame::trailers));
let mut builder = http::Response::builder().header("content-type", "application/grpc");
if let Some(status) = initial_status {
builder = builder.header("grpc-status", status);
}
let mut fixture = fixture(
builder
.body(Body::new(StreamBody::new(futures::stream::iter(
frames.map(Ok::<_, Infallible>),
))))
.unwrap(),
)
.await;
let result = if method == "AddUserMessage" {
fixture
.client
.add_user_message(&request())
.await
.map(|_| ())
} else if method == "UpdateConfig" {
fixture.client.activate("t").await.map(|_| ())
} else {
fixture
.client
.interrupt_turn(&InterruptTurnRequest {
thread_id: "t".into(),
turn_id: "u".into(),
shared_access: false,
})
.await
};
if expect_success {
result.unwrap();
} else {
assert!(matches!(
result,
Err(MutationError::OutcomeUnknown(Error::InvalidResponse))
));
}
fixture.requests.recv().await.unwrap();
assert!(fixture.requests.try_recv().is_err());
}
}
}

View File

@@ -0,0 +1,118 @@
//! Native text/image submission and interruption envelopes; omitted settings inherit thread config.
use prost::Message;
#[derive(Clone, Message)]
pub(super) struct AddRequest {
#[prost(string, tag = "4")]
pub client_user_message_id: String,
#[prost(message, optional, tag = "11")]
pub input: Option<Input>,
#[prost(string, tag = "23")]
pub thread_id: String,
#[prost(string, optional, tag = "25")]
pub turn_trigger: Option<String>,
#[prost(int32, optional, tag = "26")]
pub access: Option<i32>,
#[prost(int32, optional, tag = "30")]
pub mode: Option<i32>,
}
#[derive(Clone, Message)]
pub(super) struct Input {
#[prost(message, repeated, tag = "1")]
pub values: Vec<UserInput>,
}
#[derive(Clone, Message)]
pub(super) struct UserInput {
#[prost(oneof = "Value", tags = "1, 2, 3, 4, 5, 6, 7")]
pub value: Option<Value>,
}
#[derive(Clone, prost::Oneof)]
pub(super) enum Value {
#[prost(message, tag = "1")]
Text(Text),
#[prost(message, tag = "2")]
Image(Image),
#[prost(bytes, tag = "3")]
LocalImage(Vec<u8>),
#[prost(bytes, tag = "4")]
Audio(Vec<u8>),
#[prost(bytes, tag = "5")]
LocalAudio(Vec<u8>),
#[prost(bytes, tag = "6")]
Skill(Vec<u8>),
#[prost(bytes, tag = "7")]
Mention(Vec<u8>),
}
#[derive(Clone, Message)]
pub(super) struct Text {
#[prost(string, optional, tag = "1")]
pub text: Option<String>,
#[prost(message, optional, tag = "2")]
pub text_elements: Option<TextElements>,
}
#[derive(Clone, Message)]
pub(super) struct TextElements {
#[prost(message, repeated, tag = "1")]
pub values: Vec<TextElement>,
}
#[derive(Clone, Message)]
pub(super) struct TextElement {
#[prost(message, optional, tag = "1")]
pub byte_range: Option<ByteRange>,
#[prost(string, optional, tag = "2")]
pub placeholder: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct ByteRange {
#[prost(uint64, optional, tag = "1")]
pub end: Option<u64>,
#[prost(uint64, optional, tag = "2")]
pub start: Option<u64>,
}
#[derive(Clone, Message)]
pub(super) struct Image {
#[prost(oneof = "ImageValue", tags = "1, 2")]
pub value: Option<ImageValue>,
}
#[derive(Clone, prost::Oneof)]
pub(super) enum ImageValue {
#[prost(message, tag = "1")]
Url(ImageReference),
#[prost(message, tag = "2")]
FileId(ImageReference),
}
// Both native image alternatives have the same field layout.
#[derive(Clone, Message)]
pub(super) struct ImageReference {
#[prost(int32, optional, tag = "1")]
pub detail: Option<i32>,
#[prost(string, optional, tag = "2")]
pub value: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct AddResponse {
#[prost(message, optional, tag = "1")]
pub turn: Option<crate::transcript_wire::Turn>,
#[prost(int32, optional, tag = "2")]
pub outcome: Option<i32>,
#[prost(string, optional, tag = "3")]
pub client_user_message_id: Option<String>,
#[prost(message, optional, tag = "5")]
pub queued_submission: Option<QueuedSubmission>,
}
#[derive(Clone, Message)]
pub(super) struct QueuedSubmission {
#[prost(string, optional, tag = "1")]
pub id: Option<String>,
#[prost(string, optional, tag = "3")]
pub client_user_message_id: Option<String>,
}
#[derive(Clone, Message)]
pub(super) struct InterruptRequest {
#[prost(string, tag = "1")]
pub thread_id: String,
#[prost(string, tag = "2")]
pub turn_id: String,
#[prost(int32, optional, tag = "3")]
pub access: Option<i32>,
}

View File

@@ -0,0 +1,108 @@
//! Caller-facing native gRPC types. Diagnostics never include credentials or server payloads.
use bytes::Bytes;
use codex_http_client::CHATGPT_ACCOUNT_ID_HEADER;
use http::HeaderMap;
use http::HeaderValue;
use http::header::AUTHORIZATION;
use std::fmt;
/// Caller-owned ChatGPT bearer token and selected account, validated as HTTP headers.
#[derive(Clone, Debug)]
pub struct Credentials {
pub(crate) headers: HeaderMap,
}
impl Credentials {
pub fn new(bearer_token: &str, account_id: &str) -> Result<Self, Error> {
if bearer_token.is_empty() || account_id.is_empty() {
return Err(Error::InvalidCredentials);
}
let mut headers = HeaderMap::new();
for (name, value) in [
(AUTHORIZATION, format!("Bearer {bearer_token}")),
(
http::HeaderName::from_static(CHATGPT_ACCOUNT_ID_HEADER),
account_id.to_owned(),
),
] {
let mut value = HeaderValue::from_str(&value).map_err(|_| Error::InvalidCredentials)?;
value.set_sensitive(true);
headers.insert(name, value);
}
Ok(Self { headers })
}
}
/// Resume an existing thread; `wait` distinguishes admission from readiness.
#[derive(Clone, prost::Message)]
#[prost(skip_debug)]
pub struct ResumeRequest {
#[prost(string, tag = "1")]
pub thread_id: String,
#[prost(bool, tag = "2")]
pub wait: bool,
#[prost(bool, tag = "3")]
pub shared_access: bool,
}
/// An Attach event with selected typed transcript updates and otherwise opaque payloads.
/// The opaque variants carry the original native Notification or ServerRequest protobuf bytes.
pub enum Event {
Notification(Bytes),
Transcript(Box<crate::TranscriptEvent>),
ServerRequest(Bytes),
}
impl fmt::Debug for Event {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Notification(_) => "Notification([redacted])",
Self::Transcript(_) => "Transcript([redacted])",
Self::ServerRequest(_) => "ServerRequest([redacted])",
})
}
}
/// Native gRPC status, including binary error details. Payloads are redacted in diagnostics.
pub struct RpcStatus {
pub code: i32,
pub message: String,
pub details: Bytes,
}
impl fmt::Debug for RpcStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RpcStatus")
.field("code", &self.code)
.finish_non_exhaustive()
}
}
impl From<tonic::Status> for Error {
fn from(status: tonic::Status) -> Self {
Self::Rpc(RpcStatus {
code: status.code() as i32,
message: status.message().to_owned(),
details: Bytes::copy_from_slice(status.details()),
})
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("invalid gRPC origin (HTTPS required except on unrestricted unmanaged loopback)")]
InvalidEndpoint,
#[error("invalid bearer token or account header")]
InvalidCredentials,
#[error("could not construct the HTTP client")]
ClientBuild,
#[error("gRPC request timed out; request outcome may be unknown")]
Timeout,
#[error("gRPC failed; request outcome may be unknown: {0:?}")]
Rpc(RpcStatus),
#[error("invalid gRPC event envelope")]
InvalidResponse,
#[error("cloud response contains an unsupported {0}")]
UnsupportedResponse(&'static str),
}

View File

@@ -0,0 +1,57 @@
//! Minimal ThreadService protobuf envelopes; field numbers are the wire contract.
//! Length-delimited nested events remain intact, including unknown protobuf fields.
use bytes::Buf;
use bytes::Bytes;
use prost::Message;
use std::marker::PhantomData;
use tonic::codec::Codec;
#[derive(Clone, prost::Message)]
pub(crate) struct ResumeResponse {}
#[derive(Clone, prost::Message)]
pub(crate) struct AttachRequest {
#[prost(string, tag = "1")]
pub thread_id: String,
}
#[derive(Clone, prost::Message)]
pub(crate) struct AttachResponse {
#[prost(oneof = "Payload", tags = "1, 2")]
pub event: Option<Payload>,
}
#[derive(Clone, prost::Oneof)]
pub(crate) enum Payload {
#[prost(bytes = "bytes", tag = "1")]
Notification(bytes::Bytes),
#[prost(bytes = "bytes", tag = "2")]
ServerRequest(bytes::Bytes),
}
// Tonic enforces message bounds and status trailers while callers decode the raw payload.
pub(super) struct RawResponseCodec<T>(pub PhantomData<T>);
impl<T: Message + Send + 'static> Codec for RawResponseCodec<T> {
type Encode = T;
type Decode = Bytes;
type Encoder = tonic_prost::ProstEncoder<T>;
type Decoder = RawDecoder;
fn encoder(&mut self) -> Self::Encoder {
tonic_prost::ProstCodec::<T, ResumeResponse>::default().encoder()
}
fn decoder(&mut self) -> Self::Decoder {
RawDecoder
}
}
pub(super) struct RawDecoder;
impl tonic::codec::Decoder for RawDecoder {
type Item = Bytes;
type Error = tonic::Status;
fn decode(
&mut self,
buffer: &mut tonic::codec::DecodeBuf<'_>,
) -> Result<Option<Bytes>, tonic::Status> {
Ok(Some(buffer.copy_to_bytes(buffer.remaining())))
}
}