agent-context-contract 0.2.2

Transport-neutral contracts for Agent Infra context APIs
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
//! HTTP API contract for the Context service.
//!
//! # Why this service exists
//!
//! Conversation history is durable, cross-turn state. A Runtime must be able to
//! read and append it without owning a database and without holding a platform
//! service secret. Giving history its own service does for history what
//! `agent-workspace-infra` does for sandboxes: one owner, one HTTP contract, one
//! deployable.
//!
//! # Layering
//!
//! ```text
//! agent-context-contract   paths + DTOs        (this crate)
//! agent-context-runtime    store implementation
//! agent-context-server     router + auth + bin
//! ```
//!
//! See [`api.md`](../api.md) for the full HTTP reference.

use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize};
use serde_json::Value;

mod session_log;
pub use session_log::*;
mod records;
pub use records::*;

pub const SERVICE_NAME: &str = "agent-context-infra";
pub const DEFAULT_PORT: u16 = 5120;
pub const AUDIENCE: &str = "agent-context-infra";
pub const MAX_RESOURCE_ID_CHARS: usize = 191;

/// Optional static service token. When unset, the server runs in open mode.
pub const SERVICE_TOKEN_ENV: &str = "AGENT_CONTEXT_SERVICE_TOKEN";

pub const HEALTH_PATH: &str = "/health";
pub const MESSAGES_APPEND_PATH: &str = "/internal/v1/context/messages/batch";
pub const MESSAGES_RECENT_PATH: &str = "/internal/v1/context/messages/recent";
pub const MESSAGES_SEARCH_PATH: &str = "/internal/v1/context/messages/search";
pub const MESSAGES_PAGE_PATH: &str = "/internal/v1/context/messages";
pub const CONVERSATIONS_LIST_PATH: &str = "/internal/v1/context/conversations:list";
pub const CONVERSATION_DELETE_PATH: &str = "/internal/v1/context/conversations/delete";
pub const RETENTION_PATH: &str = "/internal/v1/context/conversations/retention";
pub const CONTEXT_OPERATIONS_PATH: &str = "/internal/v1/context/operations";
pub const MAINTENANCE_STATUS_PATH: &str = "/internal/v1/context/maintenance/status";
pub const CONTEXT_INSIGHTS_PATH: &str = "/internal/v1/context/entries";
pub const CONTEXT_INSIGHT_GET_PATH: &str = "/internal/v1/context/entries/get";
pub const CONTEXT_RECALL_PATH: &str = "/internal/v1/context/recall";
pub const CONTEXT_MERGE_PATH: &str = "/internal/v1/context/entries/merge";
pub const CONTEXT_CORRECT_PATH: &str = "/internal/v1/context/entries/correct";
pub const CONTEXT_EXPIRE_PATH: &str = "/internal/v1/context/entries/expire";
pub const CONTEXT_EXPORT_PATH: &str = "/internal/v1/context/exports";
pub const CONTEXT_IMPORT_PATH: &str = "/internal/v1/context/imports";
pub const VECTOR_REBUILD_PATH: &str = "/internal/v1/context/projections/vector/rebuild";
pub const CONTEXT_ADVANCED_OPERATIONS_PATH: &str = "/internal/v1/context/advanced-operations";
pub const CONTEXT_EXPORT_ARTIFACT_PATH: &str = "/internal/v1/context/export-artifacts/get";
pub const CONTEXT_EXPORT_ARTIFACT_CHUNK_PATH: &str = "/internal/v1/context/export-artifacts/chunk";

// Trace events are NOT served here. They belong to `agent-trace` (Trace Infra service)
// (`/internal/v1/trace-infra/events/batch`).
//
// Two services accepting the same records would mean two write paths for one
// dataset, and a run's trace would split depending on which endpoint a client
// happened to call. Trace also needs different guarantees: bounded retention,
// server-side credential redaction, and a hard rule that it is never replayed
// into a model prompt.

/// Identifies the conversation a record belongs to.
///
/// `conversation_id` is the only required field: it is the partition key. The
/// rest are optional provenance used for filtering and auditing.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConversationScope {
    pub conversation_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_space_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime_type: Option<String>,
    /// Many-to-many domain associations. Legacy singular provenance fields
    /// above remain readable but are not the canonical relation model.
    #[serde(default, skip_serializing_if = "relations_are_empty")]
    pub relations: agent_registry_contract::ResourceRelations,
}

/// Scope derived from a verified gateway-issued internal credential.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AuthorizedScope {
    pub tenant_id: String,
    pub project_id: String,
    pub subject: String,
}

impl ConversationScope {
    pub fn conversation(conversation_id: impl Into<String>) -> Self {
        Self {
            conversation_id: conversation_id.into(),
            relations: Default::default(),
            ..Default::default()
        }
    }
}

fn relations_are_empty(relations: &agent_registry_contract::ResourceRelations) -> bool {
    relations.agent_ids.is_empty()
        && relations.runtime_ids.is_empty()
        && relations.user_ids.is_empty()
}

/// One durable conversation message.
///
/// `content` is a `Value` rather than a `String` because assistant turns carry
/// structured tool calls. Storing the real shape avoids a lossy round-trip
/// through a stringified envelope.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConversationRecord {
    /// Caller supplied id. Used for idempotent append: re-sending the same id is
    /// a no-op, so a retry after a timeout cannot duplicate a turn.
    pub id: String,
    pub scope: ConversationScope,
    /// `user`, `assistant`, `tool`, `system`, or `event`.
    pub role: String,
    pub content: Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_call_id: Option<String>,
    /// Monotonic order within a conversation. This value is assigned by the
    /// service; caller-provided values are ignored on the normal append path.
    #[serde(default)]
    pub sequence: i64,
    #[serde(default)]
    pub created_at_ms: i64,
    #[serde(default, skip_serializing_if = "Value::is_null")]
    pub metadata: Value,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppendMessagesRequest {
    pub messages: Vec<ConversationRecord>,
}

/// Result of an append. `appended` excludes ids that already existed, so a
/// caller can tell a fresh write from a deduplicated retry.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppendResponse {
    pub appended: usize,
    pub skipped: usize,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecentMessagesRequest {
    pub scope: ConversationScope,
    /// Maximum records to return. The server clamps this to [`MAX_PAGE_SIZE`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
    /// When set, only these roles are returned. Empty means all roles.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub roles: Vec<String>,
}

/// Records in chronological order, oldest first.
///
/// The order is part of the contract. A client that has to re-sort is a client
/// that will eventually get it wrong.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MessagesResponse {
    pub items: Vec<ConversationRecord>,
}

/// Stable opaque cursor position for `(sequence ASC, id ASC)` ordering.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MessageCursor {
    pub sequence: i64,
    pub id: String,
}

impl MessageCursor {
    pub fn encode(&self) -> Result<String, serde_json::Error> {
        serde_json::to_vec(self).map(|bytes| URL_SAFE_NO_PAD.encode(bytes))
    }

    pub fn decode(value: &str) -> Result<Self, String> {
        let bytes = URL_SAFE_NO_PAD
            .decode(value)
            .map_err(|_| "invalid message cursor encoding".to_string())?;
        serde_json::from_slice(&bytes).map_err(|_| "invalid message cursor payload".to_string())
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PageMessagesRequest {
    pub scope: ConversationScope,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub roles: Vec<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MessagePage {
    pub items: Vec<ConversationRecord>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

/// Agent-scoped conversation directory query.
///
/// Context owns this projection because it owns the durable transcript. Trace
/// and Execution consumers must not reconstruct a conversation index from
/// their secondary event streams.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ListConversationsRequest {
    pub agent_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConversationSummary {
    pub conversation_id: String,
    pub agent_id: String,
    pub message_count: u64,
    pub created_at_ms: i64,
    pub updated_at_ms: i64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConversationsResponse {
    pub items: Vec<ConversationSummary>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RetentionPolicy {
    pub max_age_days: Option<u32>,
    pub max_messages: Option<u32>,
}

impl Default for RetentionPolicy {
    fn default() -> Self {
        Self {
            max_age_days: Some(90),
            max_messages: Some(100_000),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RetentionRequest {
    pub scope: ConversationScope,
    #[serde(default)]
    pub policy: RetentionPolicy,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DeleteConversationRequest {
    pub scope: ConversationScope,
    #[serde(default)]
    pub reason: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeletionOperation {
    pub id: String,
    pub state: String,
    pub deleted_messages: u64,
    pub created_at_ms: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_poll_after_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GetDeletionOperationRequest {
    pub operation_id: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ContextMaintenanceStatus {
    pub projector_last_run_ms: Option<i64>,
    pub projector_processed: u64,
    pub retention_last_run_ms: Option<i64>,
    pub retention_processed: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub index_watermark: Option<IndexWatermark>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextInsightStatus {
    Active,
    Corrected,
    Merged,
    Expired,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextInsightKind {
    Fact,
    Preference,
    Decision,
    Task,
    Summary,
    Custom,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ContextProvenance {
    pub conversation_id: String,
    #[serde(default)]
    pub message_ids: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extractor_ref: Option<String>,
    #[serde(default)]
    pub observed_at_ms: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ContextInsight {
    pub id: String,
    pub kind: ContextInsightKind,
    pub content: Value,
    #[serde(default)]
    pub attributes: Value,
    pub version: u64,
    pub status: ContextInsightStatus,
    pub provenance: ContextProvenance,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub superseded_by: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at_ms: Option<i64>,
    pub created_at_ms: i64,
    pub updated_at_ms: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct PutContextInsightRequest {
    pub entry: ContextInsight,
    #[serde(default)]
    pub expected_version: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GetContextInsightRequest {
    pub entry_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CorrectContextInsightRequest {
    pub entry_id: String,
    pub expected_version: u64,
    pub content: Value,
    #[serde(default)]
    pub reason: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ExpireContextInsightRequest {
    pub entry_id: String,
    pub expected_version: u64,
    #[serde(default)]
    pub reason: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MergeContextInsightsRequest {
    pub source_entry_ids: Vec<String>,
    pub merged_entry: ContextInsight,
    #[serde(default)]
    pub expected_versions: std::collections::BTreeMap<String, u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RecallContextRequest {
    pub query: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub conversation_id: Option<String>,
    #[serde(default = "default_recall_limit")]
    pub limit: usize,
    #[serde(default = "default_lexical_weight")]
    pub lexical_weight: f64,
    #[serde(default = "default_vector_weight")]
    pub vector_weight: f64,
}

fn default_recall_limit() -> usize {
    20
}
fn default_lexical_weight() -> f64 {
    0.35
}
fn default_vector_weight() -> f64 {
    0.65
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecallScoreBreakdown {
    pub lexical: f64,
    pub vector: f64,
    pub recency: f64,
    pub final_score: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecalledContext {
    pub entry: ContextInsight,
    pub score: RecallScoreBreakdown,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexWatermark {
    pub projected_version: u64,
    pub source_version: u64,
    pub lag: u64,
    pub updated_at_ms: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecallContextResponse {
    pub items: Vec<RecalledContext>,
    pub index_watermark: IndexWatermark,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextOperationKind {
    Delete,
    Export,
    Import,
    RebuildVector,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContextOperationState {
    Queued,
    Running,
    Succeeded,
    Failed,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ContextOperation {
    pub id: String,
    pub kind: ContextOperationKind,
    pub state: ContextOperationState,
    pub phase: String,
    pub processed: u64,
    pub total: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub artifact_ref: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Stable machine-readable terminal/retry classification. Provider and DB
    /// messages remain in `error` and are never reused as protocol codes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
    pub created_at_ms: i64,
    pub updated_at_ms: i64,
    pub version: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_poll_after_ms: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GetContextOperationRequest {
    pub operation_id: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ExportContextRequest {
    #[serde(default)]
    pub include_expired: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ImportContextRequest {
    /// Preferred durable import source. When set, inline vectors must be
    /// empty and the worker parses the tenant-scoped artifact incrementally.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub artifact_ref: Option<String>,
    #[serde(default)]
    pub messages: Vec<ConversationRecord>,
    #[serde(default)]
    pub entries: Vec<ContextInsight>,
    pub idempotency_key: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ContextExportArtifact {
    pub id: String,
    pub schema_version: u32,
    pub messages: Vec<ConversationRecord>,
    pub entries: Vec<ContextInsight>,
    pub created_at_ms: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GetContextExportArtifactRequest {
    pub artifact_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct GetContextExportArtifactChunkRequest {
    pub artifact_id: String,
    #[serde(default)]
    pub offset: u64,
    #[serde(default = "default_artifact_chunk_bytes")]
    pub limit: usize,
}

fn default_artifact_chunk_bytes() -> usize {
    1024 * 1024
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ContextExportArtifactChunk {
    pub artifact_id: String,
    pub offset: u64,
    pub data_base64: String,
    pub next_offset: u64,
    pub eof: bool,
    pub digest: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RebuildVectorProjectionRequest {
    #[serde(default)]
    pub force: bool,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchMessagesRequest {
    pub scope: ConversationScope,
    /// Case-insensitive substring match against textual content.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

/// Upper bound the server enforces on any page size.
///
/// An unbounded read is a denial-of-service waiting to happen once a
/// conversation grows, so the limit lives in the contract where both sides see
/// it.
pub const MAX_PAGE_SIZE: usize = 500;

/// Default page size when a request omits `limit`.
pub const DEFAULT_PAGE_SIZE: usize = 50;

/// Maximum number of records accepted by one atomic append.
pub const MAX_APPEND_MESSAGES: usize = 500;

/// Maximum serialized payload bytes accepted by one atomic append.
pub const MAX_APPEND_BYTES: usize = 8 * 1024 * 1024;
pub const MAX_SEARCH_QUERY_BYTES: usize = 4 * 1024;

/// Error body shared by every non-2xx response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiError {
    pub status: u16,
    pub message: String,
}

/// Extract plain text from a message `content` value.
///
/// Content is either a string or an OpenAI-style array of parts. Callers that
/// need text (prompt assembly, substring search) must agree on one reading, so
/// it lives in the contract instead of being reimplemented per crate.
pub fn content_text(content: &Value) -> String {
    match content {
        Value::String(value) => value.clone(),
        Value::Array(parts) => parts
            .iter()
            .filter_map(|part| {
                part.get("text")
                    .and_then(Value::as_str)
                    .or_else(|| part.as_str())
            })
            .collect::<Vec<_>>()
            .join("\n"),
        Value::Null => String::new(),
        other => other.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn scope_serialises_camel_case_and_omits_absent_provenance() {
        let value =
            serde_json::to_value(ConversationScope::conversation("conv-1")).expect("serialize");
        assert_eq!(value, json!({"conversationId": "conv-1"}));
    }

    #[test]
    fn content_text_reads_strings_and_part_arrays() {
        assert_eq!(content_text(&json!("hello")), "hello");
        assert_eq!(
            content_text(&json!([{"type": "text", "text": "a"}, {"type": "text", "text": "b"}])),
            "a\nb"
        );
        assert_eq!(content_text(&Value::Null), "");
    }

    #[test]
    fn a_message_round_trips_through_json() {
        let record = ConversationRecord {
            id: "m-1".into(),
            scope: ConversationScope::conversation("conv-1"),
            role: "assistant".into(),
            content: json!("done"),
            name: None,
            tool_call_id: None,
            sequence: 7,
            created_at_ms: 1_700_000_000_000,
            metadata: Value::Null,
        };
        let encoded = serde_json::to_value(&record).expect("serialize");
        assert_eq!(encoded["createdAtMs"], 1_700_000_000_000_i64);
        let decoded: ConversationRecord = serde_json::from_value(encoded).expect("deserialize");
        assert_eq!(decoded, record);
    }
}