← Back to Pull requests

feat: add OpenAI-compatible Conversations API #351

Merged
avinashsingh77 merged 33 files (3178 lines) on Sep 23, 2026 02:37 UTC
View on GitHub
avinashsingh77 avinashsingh77 commented on Sep 21, 2026 08:50 UTC
Author

Summary

Add conversation and item CRUD endpoints, including metadata updates, batch item creation, retrieval, deletion, and cursor pagination. Requests use an items array; returned items expose their typed fields directly; listing supports ascending and descending order; deleting an item returns its conversation.

Conversation ownership governs item access, including items written by Responses persistence. Item creation shares the existing conversation lock and sequence allocator. Deletion detaches items so stored response history survives, and a persisted conversation revision rejects turns prepared before an item mutation. Conversation creation and its initial items commit atomically.

Add migration 0005_conversation_revision.sql, update supervisor-managed PostgreSQL upgrade instructions, and run PostgreSQL conversation CRUD and tenant-isolation tests in CI.

Authentication integration remains a follow-up: HTTP handlers currently use default_tenant. Storage operations enforce the supplied tenant; these endpoints do not yet derive it from the authenticated principal.

Fixes: #155

Test Plan

  • Conversation HTTP tests cover batch and flattened wire formats, ordering, cursor pagination, stored Responses item visibility, deletion responses, tenant isolation, and validation.

  • Regression tests cover output-item preservation, concurrent SQLite appends, deletion conflict detection, and retained response history.

  • PostgreSQL coverage checks concurrent appends, tenant isolation, item visibility, and retained response history; the PostgreSQL CI job now runs this suite.

  • Local validation: full workspace Rust tests, Clippy with warnings denied, formatting, and all pre-commit hooks. Local Rust commands use the existing agentic-server/vendored-openssl feature because this host lacks system OpenSSL headers.
  • Diff: 3178 lines (+2916 / -262) across 33 files Reviewer: franciscojavierarceo Review duration: 2506m
    All Vouch review confidence checks passed
    Residual risk 0.10 = Change Risk (0.77) × (1 − Review Confidence (0.87)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.77 · 3178 lines diff across 33 files
    0.77
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.91 · 5 substantive comment(s)
    0.91
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    87%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    22 items
    maralbahari maralbahari commented on code on Sep 21, 2026 09:15 UTC
    Code Review
    crates/agentic-server-core/src/types/conversations.rs:1
    @@ -0,0 +1,334 @@
    +//! Types for the OpenAI-compatible Conversations API.
    +
    +use serde::{Deserialize, Serialize};
    +use serde_json::Value;
    +
    +use super::io::{InputItem, OutputItem};
    +
    +/// Request to create a new conversation.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct CreateConversationRequest {
    +    /// Optional metadata as a JSON object.
    +    #[serde(default, skip_serializing_if = "Option::is_none")]
    +    pub metadata: Option<Value>,
    +
    +    /// Optional initial items to add to the conversation.
    +    #[serde(default, skip_serializing_if = "Option::is_none")]
    +    pub items: Option<Vec<ConversationItem>>,
    +}
    +
    +/// Request to update a conversation's metadata.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct UpdateConversationRequest {
    +    /// Metadata as a JSON object.
    +    pub metadata: Value,
    +}
    +
    +/// Response for a conversation resource.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct ConversationResponse {
    +    /// Unique conversation identifier.
    +    pub id: String,
    +
    +    /// Object type, always "conversation".
    +    pub object: String,
    +
    +    /// Creation timestamp as Unix timestamp in seconds.
    +    pub created_at: i64,
    +
    +    /// Metadata as a JSON object.
    +    #[serde(default, skip_serializing_if = "Value::is_null")]
    +    pub metadata: Value,
    +}
    +
    +/// Request to create a new item in a conversation.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct CreateItemRequest {

    The item API contract does not match OpenAI. CreateItemRequest requires {"item": {...}}, and the endpoint returns a single ItemResponse. OpenAI accepts {"items": [...]} and returns a list of typed conversation items. Returned items expose their fields directly, without an additional item wrapper. See the OpenAI reference.

    A valid OpenAI request therefore fails deserialization here. The new tests assert the same incompatible structure, so passing them does not establish compatibility.

    As requested in my review of #166, please record these operations against OpenAI and the gateway, then use those recordings to define the request/response types and compatibility assertions. Preserve a canonical item ID across creation, listing, retrieval, and Responses output.

    maralbahari maralbahari commented on code on Sep 21, 2026 09:17 UTC
    Code Review
    crates/agentic-server-core/src/storage/models/item.rs:1
    @@ -254,6 +257,120 @@ pub async fn last_conversation_sequence_in_tx(
             .await
     }
     
    +/// Create items for a conversation with tenant scoping and sequence numbers.
    +///
    +/// # Errors
    +/// Returns `DbResult::Err` if the database insertion fails.
    +pub async fn create_items_for_conversation(
    +    pool: &DbPool,
    +    tenant_id: &str,
    +    conversation_id: &str,
    +    items: Vec<(String, String)>, // (item_id, data)
    +) -> DbResult<Vec<Item>> {
    +    if items.is_empty() {
    +        return Ok(Vec::new());
    +    }
    +
    +    let mut tx = pool.begin().await?;
    +
    +    // Get the current max sequence for this conversation
    +    let max_seq: Option<i64> = sqlx::query_scalar("SELECT MAX(seq) FROM items WHERE conversation_id = $1")
    +        .bind(conversation_id)
    +        .fetch_one(&mut *tx)
    +        .await?;
    +
    +    let start_seq = max_seq.map_or(1, |s| s + 1);
    +    let mut created_items = Vec::new();
    +
    +    for (idx, (item_id, data)) in items.into_iter().enumerate() {
    +        // Cast is safe: practical item counts are bounded by available memory
    +        // and request size limits, far below i64::MAX
    +        #[allow(clippy::cast_possible_wrap)]
    +        let seq = start_seq + (idx as i64);
    +        let item = sqlx::query_as::<_, Item>(
    +            "INSERT INTO items (id, data, created_at, conversation_id, tenant_id, seq) \
    +             VALUES ($1, $2, $3, $4, $5, $6) RETURNING *",
    +        )
    +        .bind(&item_id)
    +        .bind(&data)
    +        .bind(utcnow_str())
    +        .bind(conversation_id)
    +        .bind(tenant_id)
    +        .bind(seq)
    +        .fetch_one(&mut *tx)
    +        .await?;
    +
    +        created_items.push(item);
    +    }
    +
    +    tx.commit().await?;
    +    Ok(created_items)
    +}
    +
    +/// List items for a conversation with pagination.
    +///
    +/// # Errors
    +/// Returns `DbResult::Err` if the database query fails.
    +pub async fn list_items(
    +    pool: &DbPool,
    +    tenant_id: &str,
    +    conversation_id: &str,
    +    limit: i64,
    +    after: Option<&str>,
    +) -> DbResult<Vec<Item>> {
    +    if let Some(after_id) = after {
    +        sqlx::query_as::<_, Item>(
    +            "SELECT * FROM items \
    +             WHERE conversation_id = $1 AND tenant_id = $2 AND id > $3 \
    +             ORDER BY seq ASC, id ASC \
    +             LIMIT $4",
    +        )
    +        .bind(conversation_id)
    +        .bind(tenant_id)
    +        .bind(after_id)
    +        .bind(limit)
    +        .fetch_all(pool)
    +        .await
    +    } else {
    +        sqlx::query_as::<_, Item>(
    +            "SELECT * FROM items \
    +             WHERE conversation_id = $1 AND tenant_id = $2 \
    +             ORDER BY seq ASC, id ASC \
    +             LIMIT $3",
    +        )
    +        .bind(conversation_id)
    +        .bind(tenant_id)
    +        .bind(limit)
    +        .fetch_all(pool)
    +        .await
    +    }
    +}
    +
    +/// Get a single item by ID with tenant scoping.
    +///
    +/// # Errors
    +/// Returns `DbResult::Err` if the database query fails.
    +pub async fn get_item_by_tenant(pool: &DbPool, tenant_id: &str, item_id: &str) -> DbResult<Option<Item>> {
    +    sqlx::query_as::<_, Item>("SELECT * FROM items WHERE id = $1 AND tenant_id = $2")
    +        .bind(item_id)

    The new item operations and existing Responses persistence do not agree on tenant ownership. These queries require tenant_id, but ConversationStore::persist_impl() still calls item::create_in_tx(), which inserts items without it.

    Consequently, creating a conversation and completing a /v1/responses turn leaves persisted items that the new listing endpoint cannot see. Retrieval and deletion also exclude those rows.

    Please extend the existing persistence APIs and update their callers instead of introducing a separate creation path with different tenant semantics. Add an integration test that creates a conversation, executes a response, then lists and retrieves the persisted items through the conversation endpoints.

    The hard-coded "default_tenant" must also be resolved consistently across these paths. Storage-level tenant tests alone do not verify tenant isolation at the HTTP boundary.

    maralbahari maralbahari commented on code on Sep 21, 2026 09:18 UTC
    Code Review
    crates/agentic-server-core/src/executor/modes/conversation.rs:1
    @@ -21,6 +21,12 @@ impl ConversationHandler {
             Self { store }
         }
     
    +    /// Returns a reference to the underlying conversation store.
    +    #[must_use]
    +    pub fn store(&self) -> &ConversationStore {

    This repeats the architectural feedback I left on #166. Adding store() here and making ConversationStore::pool() public lets the HTTP handlers reach through ExecutionContext and bypass the application boundary.

    Please preserve this layering:

    HTTP handler
        → typed operations on exec_ctx.conv_handler
    ConversationHandler
        → ConversationStore
    Storage
        → database models and queries
    

    The new entrypoints need corresponding typed operations on ConversationHandler, following the existing Responses and conversation pattern. Request validation, item identity, storage conversion, and StorageError → ExecutorError translation should happen behind that boundary. Axum should extract the request, call the operation, and serialize its typed result.

    Currently, conversation_items.rs imports database models, accesses the raw pool, generates item IDs, serializes storage payloads, and handles database failures directly. conversations.rs also deserializes stored metadata.

    Please move these responsibilities behind ConversationHandler and remove the new public store/pool accessors. Referencing exec_ctx in the call chain does not preserve the boundary when the handler immediately reaches through it to storage.

    maralbahari maralbahari commented on code on Sep 21, 2026 09:19 UTC
    Code Review
    crates/agentic-server-core/tests/postgres_tenant_isolation_test.rs:1
    @@ -0,0 +1,211 @@
    +use std::sync::Arc;

    This PR adds local CRUD tests, but no OpenAI reference recordings, matching gateway recordings, or replay assertions for the new routes.

    Please extend the recorder with scenarios covering conversation create/retrieve/update/delete and item create/list/retrieve/delete. Record each scenario against OpenAI and against the gateway with its database and vLLM running. Cover supported item formats, generated-ID reuse, pagination, include, invalid requests, and error responses.

    The recordings also need to cover the stateful behavior described in my earlier comment:

  • Manually added items affect subsequent model context.

  • Deleting an item affects continuation through the conversation ID versus a previously created previous_response_id.

  • Branching from responses created before and after manually adding an item preserves the recorded history behavior.
  • Use equivalent requests and prompts, normalize dynamic IDs and timestamps, and compare status codes, response shapes, ordering, pagination, ID relationships, and history visibility. For streaming Responses calls, also compare the SSE lifecycle.

    The existing conv recorder mode does not exercise these management routes. Please add repeatable recording scripts and Rust integration assertions using the recorded OpenAI behavior as the reference. Captured cassette YAML must be generated by the recorder, not hand-authored.

    maralbahari maralbahari commented on code on Sep 21, 2026 09:21 UTC
    Code Review
    crates/agentic-server-core/src/storage/models/item.rs:1
    @@ -254,6 +257,120 @@ pub async fn last_conversation_sequence_in_tx(
             .await
     }
     
    +/// Create items for a conversation with tenant scoping and sequence numbers.
    +///
    +/// # Errors
    +/// Returns `DbResult::Err` if the database insertion fails.
    +pub async fn create_items_for_conversation(
    +    pool: &DbPool,
    +    tenant_id: &str,
    +    conversation_id: &str,
    +    items: Vec<(String, String)>, // (item_id, data)
    +) -> DbResult<Vec<Item>> {
    +    if items.is_empty() {
    +        return Ok(Vec::new());
    +    }
    +
    +    let mut tx = pool.begin().await?;
    +
    +    // Get the current max sequence for this conversation
    +    let max_seq: Option<i64> = sqlx::query_scalar("SELECT MAX(seq) FROM items WHERE conversation_id = $1")
    +        .bind(conversation_id)
    +        .fetch_one(&mut *tx)
    +        .await?;
    +
    +    let start_seq = max_seq.map_or(1, |s| s + 1);
    +    let mut created_items = Vec::new();
    +
    +    for (idx, (item_id, data)) in items.into_iter().enumerate() {
    +        // Cast is safe: practical item counts are bounded by available memory
    +        // and request size limits, far below i64::MAX
    +        #[allow(clippy::cast_possible_wrap)]
    +        let seq = start_seq + (idx as i64);
    +        let item = sqlx::query_as::<_, Item>(
    +            "INSERT INTO items (id, data, created_at, conversation_id, tenant_id, seq) \
    +             VALUES ($1, $2, $3, $4, $5, $6) RETURNING *",
    +        )
    +        .bind(&item_id)
    +        .bind(&data)
    +        .bind(utcnow_str())
    +        .bind(conversation_id)
    +        .bind(tenant_id)
    +        .bind(seq)
    +        .fetch_one(&mut *tx)
    +        .await?;
    +
    +        created_items.push(item);
    +    }
    +
    +    tx.commit().await?;
    +    Ok(created_items)
    +}
    +
    +/// List items for a conversation with pagination.
    +///
    +/// # Errors
    +/// Returns `DbResult::Err` if the database query fails.
    +pub async fn list_items(
    +    pool: &DbPool,
    +    tenant_id: &str,
    +    conversation_id: &str,
    +    limit: i64,
    +    after: Option<&str>,
    +) -> DbResult<Vec<Item>> {
    +    if let Some(after_id) = after {
    +        sqlx::query_as::<_, Item>(
    +            "SELECT * FROM items \

    Moving the limit into SQL addresses part of my earlier feedback, but the cursor predicate does not match the ordering: after filters by id > cursor, while results are ordered by seq, id. IDs are generated before insertion, so their order can differ from insertion order and cause pagination to skip or repeat items.

    Please resolve the cursor within the same conversation and tenant, then paginate using the actual ordering keys.

    ListItemsQuery also omits order and include. The query always returns ascending order, whereas OpenAI defaults to descending order. Please implement the recorded behavior and explicitly reject unsupported include values instead of silently ignoring them. See the OpenAI list reference.

    Finally, the HTTP handler uses filter_map with db_item.as_inout(), silently dropping malformed stored items after calculating has_more. This can return an incomplete or empty page with misleading pagination metadata. Please perform a fallible typed conversion behind the application boundary and propagate conversion errors.

    maralbahari maralbahari commented on Sep 21, 2026 09:22 UTC
    Reviewer

    Thanks for working on the Conversations API support! I’ve left inline comments covering the application/storage boundary, OpenAI compatibility, and cassette coverage. Please take a look and address those before we move forward. Some revisit feedback from #166, which I’ve linked for context. Happy to clarify anything that’s unclear.

    Copilot Copilot commented on code on Sep 21, 2026 10:31 UTC
    Code Review
    crates/agentic-server/src/handler/http/conversation_items.rs:1
    @@ -0,0 +1,437 @@
    +use axum::extract::{Path, Query, Request, State};
    +use axum::http::StatusCode;
    +use axum::response::{IntoResponse, Response};
    +use serde::Deserialize;
    +
    +use agentic_core::storage::models::item;
    +use agentic_core::types::{CreateItemRequest, DeletedResponse, ItemResponse, ListItemsResponse};
    +use agentic_core::utils::common::uuid7_str;
    +
    +use super::super::common::{error_response, extract_json, read_bytes};
    +use crate::app::AppState;
    +
    +/// Extract tenant ID from authenticated principal in request extensions.
    +///
    +/// Returns Result to support future authentication error handling.
    +#[allow(clippy::unnecessary_wraps, clippy::result_large_err)]
    +fn extract_tenant_id(_req: &Request) -> Result<String, Response> {
    +    // For now, return a placeholder until we wire up authentication
    +    // In production, this would extract from the AuthenticatedPrincipal extension
    +    // and return Err(response) for authentication failures
    +    Ok("default_tenant".to_string())

    The item endpoints duplicate the same hard-coded default_tenant mapping, so their tenant filters do not isolate authenticated callers. A caller from any tenant can operate on resources in this shared namespace if it knows the IDs. Use the authenticated principal's tenant identity consistently for item operations.

    Copilot Copilot commented on code on Sep 21, 2026 10:31 UTC
    Code Review
    crates/agentic-server/src/handler/http/conversations.rs:1
    @@ -1,42 +1,259 @@
    -use axum::extract::{Request, State};
    +use axum::extract::{Path, Request, State};
    +use axum::http::StatusCode;
     use axum::response::{IntoResponse, Response};
    -use serde_json::json;
     
    -use agentic_core::executor::{ExecutorError, create_conversation};
    +use agentic_core::storage::InOutItem;
    +use agentic_core::types::{
    +    ConversationResponse, CreateConversationRequest, DeletedResponse, UpdateConversationRequest,
    +};
     
    -use super::super::common::{executor_error_response, extract_store, read_bytes};
    +use super::super::common::{error_response, extract_json, read_bytes};
     use crate::app::AppState;
     
    +/// Extract tenant ID from authenticated principal in request extensions.
    +///
    +/// Returns Result to support future authentication error handling.
    +#[allow(clippy::unnecessary_wraps, clippy::result_large_err)]
    +fn extract_tenant_id(_req: &Request) -> Result<String, Response> {
    +    // For now, return a placeholder until we wire up authentication
    +    // In production, this would extract from the AuthenticatedPrincipal extension
    +    // and return Err(response) for authentication failures
    +    Ok("default_tenant".to_string())

    This helper ignores the authenticated request and assigns every caller to default_tenant. When OIDC is enabled, authenticated tenants therefore share the same namespace and can access or mutate one another's conversations by ID; the tenant predicates below do not provide isolation if the tenant is never extracted. Read the principal's tenant here (and return an authentication error when it is absent) before exposing these operations.

    Copilot Copilot commented on code on Sep 21, 2026 10:31 UTC
    Code Review
    crates/agentic-server-core/src/storage/conversation.rs:1
    @@ -236,4 +236,92 @@ impl ConversationStore {
     
             Ok(())
         }
    +
    +    /// Create a conversation with metadata and optional initial items.
    +    ///
    +    /// # Errors
    +    ///
    +    /// Returns error if database operation fails.
    +    pub async fn create_with_metadata_and_items(
    +        &self,
    +        tenant_id: Option<&str>,
    +        metadata: Option<serde_json::Value>,
    +        initial_items: Vec<InOutItem>,
    +    ) -> StoreResult<ConversationData> {
    +        use super::models::item;
    +
    +        let pool = self.pool()?;
    +        let conversation_id = uuid7_str("conv_");
    +        let metadata_str = metadata.map(|m| serialize_to_string(&m)).transpose()?;
    +
    +        let row =
    +            conversation::create_with_metadata(pool, &conversation_id, tenant_id, metadata_str.as_deref()).await?;
    +
    +        // If initial_items provided, persist them
    +        if !initial_items.is_empty() {
    +            let items: Vec<(String, String)> = initial_items
    +                .into_iter()
    +                .map(|item| {
    +                    let item_id = uuid7_str("item_");
    +                    let data = String::try_from(&item)?;
    +                    Ok((item_id, data))
    +                })
    +                .collect::<Result<_, StorageError>>()?;
    +
    +            if let Some(tid) = tenant_id {
    +                item::create_items_for_conversation(pool, tid, &conversation_id, items).await?;
    +            }

    The conversation row is inserted before initial items are serialized and inserted through a separate transaction. If serialization or item insertion fails, this endpoint returns an error but leaves an empty or partial conversation behind. Create the conversation and its initial items in one transaction so the request is atomic.

    Copilot Copilot commented on code on Sep 21, 2026 10:31 UTC
    Code Review
    crates/agentic-server-core/src/storage/models/item.rs:1
    @@ -35,6 +35,9 @@ pub struct Item {
     
         /// Optional sequence number within conversation.
         pub seq: Option<i64>,
    +
    +    /// Tenant identifier for multi-tenancy isolation.
    +    pub tenant_id: Option<String>,

    Adding tenant_id to Item is not propagated through the existing response persistence path: ConversationStore::persist still calls create_in_tx, whose INSERT omits this column. Consequently, input/output items appended by Responses have NULL tenant IDs and disappear from these tenant-scoped list/retrieve/delete endpoints even for conversations created by this API. Pass the authorized tenant through response persistence or migrate/handle those rows explicitly.

    This issue also appears in the following locations of the same file:

  • line 276

  • line 321
  • Copilot Copilot commented on code on Sep 21, 2026 10:31 UTC
    Code Review
    crates/agentic-server-core/src/types/conversations.rs:1
    @@ -0,0 +1,334 @@
    +//! Types for the OpenAI-compatible Conversations API.
    +
    +use serde::{Deserialize, Serialize};
    +use serde_json::Value;
    +
    +use super::io::{InputItem, OutputItem};
    +
    +/// Request to create a new conversation.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct CreateConversationRequest {
    +    /// Optional metadata as a JSON object.
    +    #[serde(default, skip_serializing_if = "Option::is_none")]
    +    pub metadata: Option<Value>,
    +
    +    /// Optional initial items to add to the conversation.
    +    #[serde(default, skip_serializing_if = "Option::is_none")]
    +    pub items: Option<Vec<ConversationItem>>,
    +}
    +
    +/// Request to update a conversation's metadata.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct UpdateConversationRequest {
    +    /// Metadata as a JSON object.
    +    pub metadata: Value,
    +}
    +
    +/// Response for a conversation resource.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct ConversationResponse {
    +    /// Unique conversation identifier.
    +    pub id: String,
    +
    +    /// Object type, always "conversation".
    +    pub object: String,
    +
    +    /// Creation timestamp as Unix timestamp in seconds.
    +    pub created_at: i64,
    +
    +    /// Metadata as a JSON object.
    +    #[serde(default, skip_serializing_if = "Value::is_null")]
    +    pub metadata: Value,
    +}
    +
    +/// Request to create a new item in a conversation.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct CreateItemRequest {
    +    /// The item to add (input or output).
    +    pub item: ConversationItem,
    +}
    +
    +/// Response for listing items with pagination.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct ListItemsResponse {
    +    /// Object type, always "list".
    +    pub object: String,
    +
    +    /// Array of conversation items.
    +    pub data: Vec<ItemResponse>,
    +
    +    /// Whether there are more items available.
    +    pub has_more: bool,
    +
    +    /// ID of the first item in this page.
    +    #[serde(skip_serializing_if = "Option::is_none")]
    +    pub first_id: Option<String>,
    +
    +    /// ID of the last item in this page.
    +    #[serde(skip_serializing_if = "Option::is_none")]
    +    pub last_id: Option<String>,
    +}
    +
    +/// Response for a single conversation item.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct ItemResponse {
    +    /// Unique item identifier.
    +    pub id: String,
    +
    +    /// Object type, always "conversation.item".
    +    pub object: String,
    +
    +    /// Creation timestamp as Unix timestamp in seconds.
    +    pub created_at: i64,
    +
    +    /// The item content (input or output).
    +    pub item: ConversationItem,
    +}
    +
    +/// A conversation item (input or output).
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[serde(untagged)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub enum ConversationItem {
    +    /// Input item (message, tool call, etc.).
    +    Input(InputItem),
    +    /// Output item (message, tool result, etc.).
    +    Output(OutputItem),
    +}

    Because InputItem's custom deserializer returns InputItem::Unknown for unrecognized type values instead of failing, this untagged enum accepts output-only items such as web_search_call or mcp_call as Input(Unknown); the Output branch is never reached for them. Those items are therefore persisted and returned with the wrong type. Dispatch by the discriminator or make unknown input variants fail so supported output variants can be selected.

    Copilot Copilot commented on code on Sep 21, 2026 10:31 UTC
    Code Review
    crates/agentic-server/src/app.rs:1
    @@ -283,7 +285,21 @@ pub fn build_router_with_auth(
             public_routes
         };
         let protected_routes = Router::new()
    -        .route("/v1/conversations", post(conversations))
    +        .route("/v1/conversations", post(create_conversation))

    This route addition does not include the Responses integration described for this PR. RequestPayload still exposes only conversation_id, rehydration still calls get_or_create, and response delivery still emits conversation_id, so standard conversation requests/response objects and unknown-ID 404 behavior remain unimplemented. Please add that integration or narrow the PR scope.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Sep 21, 2026 10:31 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    Copilot review overview

    🟡 Changes recommended

    Tenant isolation remains hard-coded to default_tenant, and Responses integration is incomplete.

    Get a fresh assessment by requesting another Copilot review.

    Review effort: Lite
    Findings: 2 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> · 4 <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture>

    <details open>
    <summary><strong>Open (6)</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Use the authenticated tenant for item operations](#discussion_r4061268763) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> [Derive tenant identity from the authenticated principal](#discussion_r4061268831) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Make conversation creation and item insertion atomic](#discussion_r4061268874) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Propagate tenant IDs through response item persistence](#discussion_r4061268930) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Reject unknown input types during item deserialization](#discussion_r4061268971) · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> [Implement Responses integration for conversations](#discussion_r4061269002) · New

  • </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    Adds OpenAI-compatible conversation and item CRUD APIs with tenant-scoped storage, pagination, schemas, and integration tests. Approval is blocked by unresolved tenant isolation and incomplete Responses integration.

    Changes:

  • Added conversation and item HTTP handlers and routes.

  • Added persistence, metadata, pagination, and deletion support.

  • Added SQLite/PostgreSQL tenant-isolation tests and OpenAPI definitions.
  • | File | Summary |
    |---|---|
    | scripts/​setup-postgres-test.sh | PostgreSQL test setup |
    | crates/​agentic-server/​tests/​conversations_test.rs | Conversation API integration tests |
    | crates/​agentic-server/​tests/​common/​mod.rs | Test helper annotations |
    | crates/​agentic-server/​src/​openapi.rs | OpenAPI registrations |
    | crates/​agentic-server/​src/​handler/​mod.rs | Handler exports |
    | crates/​agentic-server/​src/​handler/​http/​mod.rs | HTTP module exports |
    | crates/​agentic-server/​src/​handler/​http/​conversations.rs | Conversation CRUD handlers |
    | crates/​agentic-server/​src/​handler/​http/​conversation_items.rs | Item handlers and pagination |
    | crates/​agentic-server/​src/​handler/​common.rs | JSON and error helpers |
    | crates/​agentic-server/​src/​app.rs | Conversation route registration |
    | crates/​agentic-server-core/​tests/​tenant_isolation_test.rs | SQLite tenant-isolation tests |
    | crates/​agentic-server-core/​tests/​postgres_tenant_isolation_test.rs | PostgreSQL tenant-isolation tests |
    | crates/​agentic-server-core/​src/​types/​mod.rs | Type exports |
    | crates/​agentic-server-core/​src/​types/​conversations.rs | Conversation API schemas |
    | crates/​agentic-server-core/​src/​storage/​types/​conversation.rs | Tenant conversation data |
    | crates/​agentic-server-core/​src/​storage/​models/​item.rs | Tenant item persistence and queries |
    | crates/​agentic-server-core/​src/​storage/​models/​conversation.rs | Tenant conversation queries |
    | crates/​agentic-server-core/​src/​storage/​conversation.rs | Conversation store operations |
    | crates/​agentic-server-core/​src/​executor/​modes/​conversation.rs | Store access for handlers |
    </details>

    ---

    💡 <a href="/vllm-project/agentic-api/new/main?filename=.github/skills/code-review/SKILL.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add a code-review agent skill</a> or configure MCP servers for context-aware, tailored reviews. <a href="https://docs.github.com/copilot/how-tos/use-copilot-agents/request-a-code-review/use-code-review?tool=webui#mcp-servers-and-agent-skills" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn more in the docs.</a>

    avinashsingh77 avinashsingh77 commented on code on Sep 22, 2026 09:17 UTC
    Code Review
    crates/agentic-server-core/src/storage/models/item.rs:1
    @@ -254,6 +257,120 @@ pub async fn last_conversation_sequence_in_tx(
             .await
     }
     
    +/// Create items for a conversation with tenant scoping and sequence numbers.
    +///
    +/// # Errors
    +/// Returns `DbResult::Err` if the database insertion fails.
    +pub async fn create_items_for_conversation(
    +    pool: &DbPool,
    +    tenant_id: &str,
    +    conversation_id: &str,
    +    items: Vec<(String, String)>, // (item_id, data)
    +) -> DbResult<Vec<Item>> {
    +    if items.is_empty() {
    +        return Ok(Vec::new());
    +    }
    +
    +    let mut tx = pool.begin().await?;
    +
    +    // Get the current max sequence for this conversation
    +    let max_seq: Option<i64> = sqlx::query_scalar("SELECT MAX(seq) FROM items WHERE conversation_id = $1")
    +        .bind(conversation_id)
    +        .fetch_one(&mut *tx)
    +        .await?;
    +
    +    let start_seq = max_seq.map_or(1, |s| s + 1);
    +    let mut created_items = Vec::new();
    +
    +    for (idx, (item_id, data)) in items.into_iter().enumerate() {
    +        // Cast is safe: practical item counts are bounded by available memory
    +        // and request size limits, far below i64::MAX
    +        #[allow(clippy::cast_possible_wrap)]
    +        let seq = start_seq + (idx as i64);
    +        let item = sqlx::query_as::<_, Item>(
    +            "INSERT INTO items (id, data, created_at, conversation_id, tenant_id, seq) \
    +             VALUES ($1, $2, $3, $4, $5, $6) RETURNING *",
    +        )
    +        .bind(&item_id)
    +        .bind(&data)
    +        .bind(utcnow_str())
    +        .bind(conversation_id)
    +        .bind(tenant_id)
    +        .bind(seq)
    +        .fetch_one(&mut *tx)
    +        .await?;
    +
    +        created_items.push(item);
    +    }
    +
    +    tx.commit().await?;
    +    Ok(created_items)
    +}
    +
    +/// List items for a conversation with pagination.
    +///
    +/// # Errors
    +/// Returns `DbResult::Err` if the database query fails.
    +pub async fn list_items(
    +    pool: &DbPool,
    +    tenant_id: &str,
    +    conversation_id: &str,
    +    limit: i64,
    +    after: Option<&str>,
    +) -> DbResult<Vec<Item>> {
    +    if let Some(after_id) = after {
    +        sqlx::query_as::<_, Item>(
    +            "SELECT * FROM items \
    +             WHERE conversation_id = $1 AND tenant_id = $2 AND id > $3 \
    +             ORDER BY seq ASC, id ASC \
    +             LIMIT $4",
    +        )
    +        .bind(conversation_id)
    +        .bind(tenant_id)
    +        .bind(after_id)
    +        .bind(limit)
    +        .fetch_all(pool)
    +        .await
    +    } else {
    +        sqlx::query_as::<_, Item>(
    +            "SELECT * FROM items \
    +             WHERE conversation_id = $1 AND tenant_id = $2 \
    +             ORDER BY seq ASC, id ASC \
    +             LIMIT $3",
    +        )
    +        .bind(conversation_id)
    +        .bind(tenant_id)
    +        .bind(limit)
    +        .fetch_all(pool)
    +        .await
    +    }
    +}
    +
    +/// Get a single item by ID with tenant scoping.
    +///
    +/// # Errors
    +/// Returns `DbResult::Err` if the database query fails.
    +pub async fn get_item_by_tenant(pool: &DbPool, tenant_id: &str, item_id: &str) -> DbResult<Option<Item>> {
    +    sqlx::query_as::<_, Item>("SELECT * FROM items WHERE id = $1 AND tenant_id = $2")
    +        .bind(item_id)

    The tenant_id now flows consistently from HTTP extraction → ExecuteRequest → rehydrate → RequestContext → execute_turn → persist → storage, ensuring items created via /v1/responses will be visible to the onversations items API endpoints.

    avinashsingh77 avinashsingh77 commented on code on Sep 22, 2026 09:17 UTC
    Code Review
    crates/agentic-server-core/src/types/conversations.rs:1
    @@ -0,0 +1,334 @@
    +//! Types for the OpenAI-compatible Conversations API.
    +
    +use serde::{Deserialize, Serialize};
    +use serde_json::Value;
    +
    +use super::io::{InputItem, OutputItem};
    +
    +/// Request to create a new conversation.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct CreateConversationRequest {
    +    /// Optional metadata as a JSON object.
    +    #[serde(default, skip_serializing_if = "Option::is_none")]
    +    pub metadata: Option<Value>,
    +
    +    /// Optional initial items to add to the conversation.
    +    #[serde(default, skip_serializing_if = "Option::is_none")]
    +    pub items: Option<Vec<ConversationItem>>,
    +}
    +
    +/// Request to update a conversation's metadata.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct UpdateConversationRequest {
    +    /// Metadata as a JSON object.
    +    pub metadata: Value,
    +}
    +
    +/// Response for a conversation resource.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct ConversationResponse {
    +    /// Unique conversation identifier.
    +    pub id: String,
    +
    +    /// Object type, always "conversation".
    +    pub object: String,
    +
    +    /// Creation timestamp as Unix timestamp in seconds.
    +    pub created_at: i64,
    +
    +    /// Metadata as a JSON object.
    +    #[serde(default, skip_serializing_if = "Value::is_null")]
    +    pub metadata: Value,
    +}
    +
    +/// Request to create a new item in a conversation.
    +#[derive(Debug, Clone, Serialize, Deserialize)]
    +#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
    +pub struct CreateItemRequest {

    Updated as per OpenAI API contract.

    franciscojavierarceo franciscojavierarceo approved these changes on Sep 23, 2026 02:12 UTC
    Approved Reviewer

    Approved these changes.

    avinashsingh77 avinashsingh77 commented on code on Sep 23, 2026 09:22 UTC
    Code Review
    crates/agentic-server-core/src/executor/modes/conversation.rs:1
    @@ -21,6 +21,12 @@ impl ConversationHandler {
             Self { store }
         }
     
    +    /// Returns a reference to the underlying conversation store.
    +    #[must_use]
    +    pub fn store(&self) -> &ConversationStore {

    All the layering violations have been fixed.

    maralbahari maralbahari commented on code on Sep 23, 2026 09:41 UTC
    Code Review
    crates/agentic-server-core/src/executor/modes/conversation.rs:1
    @@ -21,6 +21,12 @@ impl ConversationHandler {
             Self { store }
         }
     
    +    /// Returns a reference to the underlying conversation store.
    +    #[must_use]
    +    pub fn store(&self) -> &ConversationStore {

    @avinashsingh77 unfortunately I still see the ConversationStore being exposed and dont see the preserved layers either and PR has been merged. Perhaps could help to address this in another PR along with the cassettes recording in https://github.com/vllm-project/agentic-api/pull/351#discussion_r4060744768 to ensure correct compatibility with OpenAI conversation items contract?

    avinashsingh77 avinashsingh77 commented on code on Sep 23, 2026 09:46 UTC
    Code Review
    crates/agentic-server-core/tests/postgres_tenant_isolation_test.rs:1
    @@ -0,0 +1,211 @@
    +use std::sync::Arc;

    I believe you are are talking about building a comprehensive testing infrastructure addition that goes significantly beyond the current PR scope. Here's what would need to be built:

    Required Work as per my understanding:

    1. New Specialized Recorder:

    The existing record_cassette.py only handles /v1/responses and /v1/messages. The Conversations API requires a new recorder that:
    - Makes HTTP calls to multiple endpoints (conversations, items)
    - Chains responses correctly (conversation IDs, item IDs)
    - Interleaves CRUD operations with inference calls
    - Normalizes dynamic IDs/timestamps for comparison

    2. Recording Scenarios (~10-15 cassettes)

    Basic CRUD (8 cassettes):
    - Conversation create/retrieve/update/delete × streaming/non-streaming
    - Items create/list/retrieve/delete × streaming/non-streaming

    Stateful Behavior (6+ cassettes):
    - Manual items → model context (the critical test)
    - Item deletion → continuation divergence
    - Branching before/after manual item addition

    3. Replay Tests

    Integration tests that:
    - Load OpenAI reference cassettes
    - Load gateway cassettes
    - Compare status codes, shapes, ordering, pagination, ID relationships
    - Assert history visibility matches

    4. Recording Scripts

    Similar to record_web_search_cassettes.sh, record_custom_tool_cassettes.sh, etc

    @maralbahari Should I add basic integration tests now (using real DB but no cassettes), defer cassette infrastructure to a follow-up PR.

    avinashsingh77 avinashsingh77 commented on code on Sep 23, 2026 10:14 UTC
    Code Review
    crates/agentic-server-core/src/executor/modes/conversation.rs:1
    @@ -21,6 +21,12 @@ impl ConversationHandler {
             Self { store }
         }
     
    +    /// Returns a reference to the underlying conversation store.
    +    #[must_use]
    +    pub fn store(&self) -> &ConversationStore {

    Sorry @maralbahari I am yet to push latest changes.
    I am not sure how this PR was merged.
    I will file a follow up PR to address all 4 review comments and cassettes recording .

    maralbahari maralbahari commented on code on Sep 23, 2026 10:54 UTC
    Code Review
    crates/agentic-server-core/src/executor/modes/conversation.rs:1
    @@ -21,6 +21,12 @@ impl ConversationHandler {
             Self { store }
         }
     
    +    /// Returns a reference to the underlying conversation store.
    +    #[must_use]
    +    pub fn store(&self) -> &ConversationStore {

    @avinashsingh77 no worries. Thanks for the help. once open the PR let me know

    Assignees
    avinashsingh77 avinashsingh77
    Labels
    risk: low confidence: 87.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 76.5% (HIGH) · Higher = larger blast radius
    76.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 87.1% · Lower = rushed or shallow review
    87.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 9.9% · Safe to merge
    9.9%