cf-chat-engine 0.2.1

Chat Engine module: multi-tenant conversational infrastructure with plugin-driven backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Route registration for the Chat Engine REST surface.
//!
//! Every endpoint listed in DESIGN §API and `api/http-protocol.json` is
//! wired up here via [`OperationBuilder`]. The function
//! [`register_routes`] is the single mounting point — `module.rs` calls
//! it once, then the gateway owns the rest (request tracing, CORS,
//! body limits, OpenAPI). No raw `Router::route` calls exist in this
//! module.
//!
//! `operation_id` naming follows the `chat_engine.<resource>.<action>`
//! convention from `docs/toolkit_unified_system/04_rest_operation_builder.md`.
//!
//! Service DI is attached **once** at the end via `Extension<Arc<…>>`
//! layers, matching the ModKit reference wiring.
//
// @cpt-cf-chat-engine-api-rest-routes:p14
// @cpt-cf-chat-engine-adr-http-client-protocol:p14

use std::sync::Arc;

use axum::{Extension, Router};
use http::StatusCode;
use toolkit::api::OpenApiRegistry;
use toolkit::api::operation_builder::{
    CORE_GLOBAL_BASE_LICENSE_FEATURE, LicenseFeature, OperationBuilder,
};

use crate::api::rest::WebhookEmitter;
use crate::api::rest::dto::{
    CreateSessionRequestDto, ExportAcceptedDto, MessageDto, MessageListDto, ReactionListDto,
    ReactionRequestDto, RecreateMessageRequestDto, RegisterSessionTypeRequestDto, SearchRequestDto,
    SearchResultsDto, SendMessageRequestDto, SessionDto, SessionTypeDto, ShareRequestDto,
    ShareResponseDto, SharedSessionDto, StreamingEventDto, SwitchSessionTypeRequestDto,
    VariantListDto,
};
use crate::api::rest::handlers;
use crate::domain::ports::StreamEventBuffer;
use crate::domain::service::{
    ExportService, IntelligenceService, MessageService, ReactionService, SearchService,
    SessionService, VariantService,
};

/// API tag used by every Chat Engine endpoint in the generated OpenAPI
/// document.
const API_TAG: &str = "Chat Engine";

/// License feature required by all `cf-chat-engine` endpoints.
///
/// Mirrors the gating policy used by sibling modules.
pub(crate) struct ChatEngineLicense;

impl AsRef<str> for ChatEngineLicense {
    fn as_ref(&self) -> &'static str {
        CORE_GLOBAL_BASE_LICENSE_FEATURE
    }
}

impl LicenseFeature for ChatEngineLicense {}

/// Aggregated service handle attached to every authenticated route via
/// `Extension`. Phase 15 owns the constructor; Phase 14 only requires the
/// type signature so the route wiring compiles end-to-end.
#[derive(Clone)]
pub struct ChatEngineServices {
    pub sessions: Arc<SessionService>,
    pub messages: Arc<MessageService>,
    pub variants: Arc<VariantService>,
    pub reactions: Arc<ReactionService>,
    pub search: Arc<SearchService>,
    pub intelligence: Arc<IntelligenceService>,
    pub export: Arc<ExportService>,
}

/// Mount the Chat Engine REST surface onto the gateway-supplied `router`.
///
/// The function follows the ModKit pattern verbatim:
///
/// - `OperationBuilder::<verb>(path)` chain per endpoint.
/// - `.authenticated()` + `.require_license_features([&ChatEngineLicense])`
///   on every protected route (the only public route is
///   `POST /chat-engine/v1/shared/{share_token}` which uses `.public()`).
/// - `.json_response_with_schema::<…>(openapi, status, desc)` for typed
///   responses; `.json_request::<…>(openapi, desc)` for typed bodies.
/// - `.standard_errors(openapi)` registers the RFC-9457 error variants.
/// - Per-service `Extension` layers attached once at the end.
pub fn register_routes(
    router: Router,
    openapi: &dyn OpenApiRegistry,
    services: ChatEngineServices,
    webhooks: Arc<dyn WebhookEmitter>,
    stream_buffer: Arc<dyn StreamEventBuffer>,
    enable_search: bool,
) -> Router {
    let mut router = router;

    // -------------------------------------------------------------------
    // Session types (developer-scope registration)
    // -------------------------------------------------------------------

    router = OperationBuilder::post("/chat-engine/v1/session-types")
        .operation_id("chat_engine.session_type.register")
        .summary("Register a session type and bind it to a backend plugin")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .json_request::<RegisterSessionTypeRequestDto>(openapi, "Session type registration")
        .handler(handlers::session_types::register_session_type)
        .json_response_with_schema::<SessionTypeDto>(
            openapi,
            StatusCode::CREATED,
            "Registered session type",
        )
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::get("/chat-engine/v1/session-types")
        .operation_id("chat_engine.session_type.list")
        .summary("List registered session types")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .handler(handlers::session_types::list_session_types)
        .json_response_with_schema::<Vec<SessionTypeDto>>(
            openapi,
            StatusCode::OK,
            "Session type list",
        )
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::get("/chat-engine/v1/session-types/{id}")
        .operation_id("chat_engine.session_type.get")
        .summary("Get a session type")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Session type UUID")
        .handler(handlers::session_types::get_session_type)
        .json_response_with_schema::<SessionTypeDto>(openapi, StatusCode::OK, "Session type")
        .standard_errors(openapi)
        .register(router, openapi);

    // -------------------------------------------------------------------
    // Session lifecycle
    // -------------------------------------------------------------------

    router = OperationBuilder::post("/chat-engine/v1/sessions")
        .operation_id("chat_engine.session.create")
        .summary("Create a chat session")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .json_request::<CreateSessionRequestDto>(openapi, "Session creation parameters")
        .handler(handlers::sessions::create_session)
        .json_response_with_schema::<SessionDto>(openapi, StatusCode::CREATED, "Created session")
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::get("/chat-engine/v1/sessions/{id}")
        .operation_id("chat_engine.session.get")
        .summary("Get a session")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Session UUID")
        .handler(handlers::sessions::get_session)
        .json_response_with_schema::<SessionDto>(openapi, StatusCode::OK, "Session details")
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::delete("/chat-engine/v1/sessions/{id}")
        .operation_id("chat_engine.session.delete")
        .summary("Delete a session (soft or hard)")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Session UUID")
        .query_param_typed(
            "hard",
            false,
            "When true, perform a cascading hard delete",
            "boolean",
        )
        .handler(handlers::sessions::delete_session)
        .json_response_with_schema::<SessionDto>(openapi, StatusCode::OK, "Soft-deleted session")
        .no_content_response(StatusCode::NO_CONTENT, "Hard delete completed")
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::post("/chat-engine/v1/sessions/{id}/switch-type")
        .operation_id("chat_engine.session.switch_type")
        .summary("Switch the session type of an existing session")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Session UUID")
        .json_request::<SwitchSessionTypeRequestDto>(openapi, "Target session type")
        .handler(handlers::variants::switch_session_type)
        .json_response_with_schema::<SessionDto>(openapi, StatusCode::OK, "Updated session")
        .standard_errors(openapi)
        .register(router, openapi);

    // -------------------------------------------------------------------
    // Export / Share
    // -------------------------------------------------------------------

    router = OperationBuilder::post("/chat-engine/v1/sessions/{id}/export")
        .operation_id("chat_engine.session.export")
        .summary("Export a session (returns a download URL)")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Session UUID")
        .query_param_typed(
            "format",
            false,
            "Export format (`json` or `markdown`)",
            "string",
        )
        .query_param_typed(
            "include_plugin_metadata",
            false,
            "Include plugin-defined per-message metadata in the export",
            "boolean",
        )
        .handler(handlers::export::export_session)
        .json_response_with_schema::<ExportAcceptedDto>(
            openapi,
            StatusCode::ACCEPTED,
            "Export accepted",
        )
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::post("/chat-engine/v1/sessions/{id}/share")
        .operation_id("chat_engine.session.share")
        .summary("Generate a share link for a session")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Session UUID")
        .json_request::<ShareRequestDto>(openapi, "Share options")
        .handler(handlers::export::create_share)
        .json_response_with_schema::<ShareResponseDto>(
            openapi,
            StatusCode::CREATED,
            "Share link issued",
        )
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::post("/chat-engine/v1/shared/{share_token}")
        .operation_id("chat_engine.session.access_shared")
        .summary("Access a session via a public share token")
        .tag(API_TAG)
        .public()
        .path_param("share_token", "Opaque share token (bearer secret)")
        .handler(handlers::export::access_shared)
        .json_response_with_schema::<SharedSessionDto>(
            openapi,
            StatusCode::OK,
            "Shared session payload",
        )
        // The handler maps share-expired conflicts to 410 Gone via
        // `map_share_error`; document the response explicitly so
        // clients / codegen know about it.
        .problem_response(
            openapi,
            StatusCode::GONE,
            "Share token has expired or been revoked",
        )
        .standard_errors(openapi)
        .register(router, openapi);

    // -------------------------------------------------------------------
    // Search
    //
    // Gated by `enable_search`: the production tsvector/LIKE backends are
    // still stubs that return `Internal` on every call, so registering
    // these routes by default would advertise an endpoint that 500s on
    // every real request. Operators flip the config flag once a real
    // backend lands.
    // -------------------------------------------------------------------

    if enable_search {
        router = OperationBuilder::post("/chat-engine/v1/sessions/{id}/search")
            .operation_id("chat_engine.session.search")
            .summary("Search inside a single session")
            .tag(API_TAG)
            .authenticated()
            .require_license_features([&ChatEngineLicense])
            .path_param("id", "Session UUID")
            .json_request::<SearchRequestDto>(openapi, "Search query")
            .handler(handlers::glue::search_in_session)
            .json_response_with_schema::<SearchResultsDto>(
                openapi,
                StatusCode::OK,
                "Search results",
            )
            .standard_errors(openapi)
            .register(router, openapi);

        router = OperationBuilder::post("/chat-engine/v1/sessions/search")
            .operation_id("chat_engine.sessions.search")
            .summary("Search across all sessions for the current user")
            .tag(API_TAG)
            .authenticated()
            .require_license_features([&ChatEngineLicense])
            .json_request::<SearchRequestDto>(openapi, "Search query")
            .handler(handlers::glue::search_across_sessions)
            .json_response_with_schema::<SearchResultsDto>(
                openapi,
                StatusCode::OK,
                "Search results",
            )
            .standard_errors(openapi)
            .register(router, openapi);
    }

    // -------------------------------------------------------------------
    // Summarize (202 Accepted)
    // -------------------------------------------------------------------

    router = OperationBuilder::post("/chat-engine/v1/sessions/{id}/summarize")
        .operation_id("chat_engine.session.summarize")
        .summary("Trigger an asynchronous session summary")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Session UUID")
        .handler(handlers::glue::summarize_session)
        .json_response_with_schema::<StreamingEventDto>(
            openapi,
            StatusCode::OK,
            "SSE typed delta stream of message.start/message.text.delta/message.complete/message.error events (text/event-stream)",
        )
        .standard_errors(openapi)
        .register(router, openapi);

    // -------------------------------------------------------------------
    // Messages
    // -------------------------------------------------------------------

    router = OperationBuilder::post("/chat-engine/v1/sessions/{id}/messages")
        .operation_id("chat_engine.message.send")
        .summary("Send a message and stream the assistant response as NDJSON")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Session UUID")
        .json_request::<SendMessageRequestDto>(openapi, "Message payload")
        .handler(handlers::glue::send_message_in_session)
        .json_response_with_schema::<StreamingEventDto>(
            openapi,
            StatusCode::OK,
            "SSE typed delta stream of message.start/message.text.delta/message.complete/message.error events (text/event-stream)",
        )
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::get("/chat-engine/v1/sessions/{id}/messages")
        .operation_id("chat_engine.message.list")
        .summary("List messages on the active path of a session")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Session UUID")
        .query_param_typed(
            "parent_message_id",
            false,
            "Optional parent message UUID for partial listings",
            "string",
        )
        .handler(handlers::glue::list_messages)
        .json_response_with_schema::<MessageListDto>(openapi, StatusCode::OK, "Message list")
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::get("/chat-engine/v1/messages/{id}")
        .operation_id("chat_engine.message.get")
        .summary("Get a single message")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Message UUID")
        .handler(handlers::glue::get_message)
        .json_response_with_schema::<MessageDto>(openapi, StatusCode::OK, "Message details")
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::get("/chat-engine/v1/messages/{id}/stream")
        .operation_id("chat_engine.message.stream")
        .summary("Resume an assistant message's SSE delta stream (Last-Event-ID)")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Message UUID")
        .handler(handlers::glue::resume_message_stream)
        .json_response_with_schema::<StreamingEventDto>(
            openapi,
            StatusCode::OK,
            "SSE delta stream replayed from Last-Event-ID then live-tailed (text/event-stream)",
        )
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::delete("/chat-engine/v1/messages/{id}")
        .operation_id("chat_engine.message.delete")
        .summary("Delete a message and its descendants (cascade)")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Message UUID")
        .handler(handlers::messages::delete_message)
        .json_response_with_schema::<MessageDto>(openapi, StatusCode::OK, "Cascade deletion result")
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::post("/chat-engine/v1/messages/{id}/recreate")
        .operation_id("chat_engine.message.recreate")
        .summary("Recreate an assistant variant (NDJSON stream)")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Message UUID")
        .json_request::<RecreateMessageRequestDto>(openapi, "Recreate options")
        .handler(handlers::glue::recreate_message)
        .json_response_with_schema::<StreamingEventDto>(
            openapi,
            StatusCode::OK,
            "SSE typed delta stream of message.start/message.text.delta/message.complete/message.error events (text/event-stream)",
        )
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::get("/chat-engine/v1/messages/{id}/variants")
        .operation_id("chat_engine.message.variants")
        .summary("List variants for a message")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Message UUID")
        .handler(handlers::glue::list_variants)
        .json_response_with_schema::<VariantListDto>(openapi, StatusCode::OK, "Variant list")
        .standard_errors(openapi)
        .register(router, openapi);

    router = OperationBuilder::post("/chat-engine/v1/messages/{id}/reactions")
        .operation_id("chat_engine.message.react")
        .summary("Set or update a reaction on a message")
        .tag(API_TAG)
        .authenticated()
        .require_license_features([&ChatEngineLicense])
        .path_param("id", "Message UUID")
        .json_request::<ReactionRequestDto>(openapi, "Reaction payload")
        .handler(handlers::glue::set_reaction)
        .json_response_with_schema::<ReactionListDto>(
            openapi,
            StatusCode::OK,
            "Updated reaction list",
        )
        .standard_errors(openapi)
        .register(router, openapi);

    // -------------------------------------------------------------------
    // Service & webhook DI attached once at the end.
    // -------------------------------------------------------------------

    router
        .layer(Extension(services.sessions))
        .layer(Extension(services.messages))
        .layer(Extension(services.variants))
        .layer(Extension(services.reactions))
        .layer(Extension(services.search))
        .layer(Extension(services.intelligence))
        .layer(Extension(services.export))
        .layer(Extension(webhooks))
        .layer(Extension(stream_buffer))
}