lifeloop-cli 0.3.0

Provider-neutral lifecycle abstraction and normalizer for AI harnesses
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
//! Core wire vocabularies, validation helpers, frame context, and payload shapes.

use serde::{Deserialize, Serialize};

use crate::SCHEMA_VERSION;

// ============================================================================
// Wire enums
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IntegrationMode {
    ManualSkill,
    LauncherWrapper,
    NativeHook,
    ReferenceAdapter,
    TelemetryOnly,
}

impl IntegrationMode {
    pub const ALL: &'static [Self] = &[
        Self::ManualSkill,
        Self::LauncherWrapper,
        Self::NativeHook,
        Self::ReferenceAdapter,
        Self::TelemetryOnly,
    ];
}

/// Support states for adapter capability claims.
///
/// Per `docs/specs/lifecycle-contract/body.md` ("Support states"), the
/// pre-issue-#6 vocabulary distinguished `simulated` from `inferred`.
/// Issue #6 simplified to one synthesizing state plus `partial`:
///
/// * `simulated` → renamed to `synthesized` (clearer about derivation).
/// * `inferred` → folded into `partial` (telemetry-derived behavior is
///   partial behavior).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SupportState {
    Native,
    Synthesized,
    Manual,
    Partial,
    Unavailable,
}

impl SupportState {
    pub const ALL: &'static [Self] = &[
        Self::Native,
        Self::Synthesized,
        Self::Manual,
        Self::Partial,
        Self::Unavailable,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AdapterRole {
    PrimaryWorker,
    Worker,
    Supervisor,
    Observer,
}

impl AdapterRole {
    pub const ALL: &'static [Self] = &[
        Self::PrimaryWorker,
        Self::Worker,
        Self::Supervisor,
        Self::Observer,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize)]
pub enum LifecycleEventKind {
    #[serde(rename = "session.starting")]
    SessionStarting,
    #[serde(rename = "session.started")]
    SessionStarted,
    #[serde(rename = "frame.opening")]
    FrameOpening,
    #[serde(rename = "frame.opened")]
    FrameOpened,
    #[serde(rename = "context.pressure_observed")]
    ContextPressureObserved,
    #[serde(rename = "context.compacted")]
    ContextCompacted,
    #[serde(rename = "frame.ending")]
    FrameEnding,
    #[serde(rename = "frame.ended")]
    FrameEnded,
    #[serde(rename = "session.ending")]
    SessionEnding,
    #[serde(rename = "session.ended")]
    SessionEnded,
    #[serde(rename = "supervisor.tick")]
    SupervisorTick,
    #[serde(rename = "capability.degraded")]
    CapabilityDegraded,
    #[serde(rename = "receipt.emitted")]
    ReceiptEmitted,
    #[serde(rename = "receipt.gap_detected")]
    ReceiptGapDetected,
}

impl LifecycleEventKind {
    pub const ALL: &'static [Self] = &[
        Self::SessionStarting,
        Self::SessionStarted,
        Self::FrameOpening,
        Self::FrameOpened,
        Self::ContextPressureObserved,
        Self::ContextCompacted,
        Self::FrameEnding,
        Self::FrameEnded,
        Self::SessionEnding,
        Self::SessionEnded,
        Self::SupervisorTick,
        Self::CapabilityDegraded,
        Self::ReceiptEmitted,
        Self::ReceiptGapDetected,
    ];
}

pub fn lifecycle_event_kinds() -> Vec<LifecycleEventKind> {
    LifecycleEventKind::ALL.to_vec()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReceiptStatus {
    Observed,
    Delivered,
    Skipped,
    Degraded,
    Failed,
}

impl ReceiptStatus {
    pub const ALL: &'static [Self] = &[
        Self::Observed,
        Self::Delivered,
        Self::Skipped,
        Self::Degraded,
        Self::Failed,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FailureClass {
    AdapterUnavailable,
    CapabilityUnsupported,
    CapabilityDegraded,
    PlacementUnavailable,
    PayloadTooLarge,
    PayloadRejected,
    IdentityUnavailable,
    TransportError,
    Timeout,
    OperatorRequired,
    StateConflict,
    InvalidRequest,
    InternalError,
}

impl FailureClass {
    pub const ALL: &'static [Self] = &[
        Self::AdapterUnavailable,
        Self::CapabilityUnsupported,
        Self::CapabilityDegraded,
        Self::PlacementUnavailable,
        Self::PayloadTooLarge,
        Self::PayloadRejected,
        Self::IdentityUnavailable,
        Self::TransportError,
        Self::Timeout,
        Self::OperatorRequired,
        Self::StateConflict,
        Self::InvalidRequest,
        Self::InternalError,
    ];

    /// Default retry-class mapping per the spec's failure-to-retry table.
    pub fn default_retry(self) -> RetryClass {
        match self {
            Self::AdapterUnavailable => RetryClass::RetryAfterReconfigure,
            Self::CapabilityUnsupported => RetryClass::DoNotRetry,
            Self::CapabilityDegraded => RetryClass::RetryAfterReread,
            Self::PlacementUnavailable => RetryClass::RetryAfterReconfigure,
            Self::PayloadTooLarge => RetryClass::DoNotRetry,
            Self::PayloadRejected => RetryClass::RetryAfterReconfigure,
            Self::IdentityUnavailable => RetryClass::RetryAfterReconfigure,
            Self::TransportError => RetryClass::SafeRetry,
            Self::Timeout => RetryClass::SafeRetry,
            Self::OperatorRequired => RetryClass::RetryAfterOperator,
            Self::StateConflict => RetryClass::RetryAfterReread,
            Self::InvalidRequest => RetryClass::DoNotRetry,
            Self::InternalError => RetryClass::RetryAfterReread,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RetryClass {
    SafeRetry,
    RetryAfterReread,
    RetryAfterReconfigure,
    RetryAfterOperator,
    DoNotRetry,
}

impl RetryClass {
    pub const ALL: &'static [Self] = &[
        Self::SafeRetry,
        Self::RetryAfterReread,
        Self::RetryAfterReconfigure,
        Self::RetryAfterOperator,
        Self::DoNotRetry,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlacementClass {
    DeveloperEquivalentFrame,
    PrePromptFrame,
    SideChannelContext,
    ReceiptOnly,
}

impl PlacementClass {
    pub const ALL: &'static [Self] = &[
        Self::DeveloperEquivalentFrame,
        Self::PrePromptFrame,
        Self::SideChannelContext,
        Self::ReceiptOnly,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlacementOutcome {
    Delivered,
    Skipped,
    Degraded,
    Failed,
}

impl PlacementOutcome {
    pub const ALL: &'static [Self] =
        &[Self::Delivered, Self::Skipped, Self::Degraded, Self::Failed];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RequirementLevel {
    Required,
    Preferred,
    Optional,
}

impl RequirementLevel {
    pub const ALL: &'static [Self] = &[Self::Required, Self::Preferred, Self::Optional];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NegotiationOutcome {
    Satisfied,
    Degraded,
    Unsupported,
    RequiresOperator,
}

impl NegotiationOutcome {
    pub const ALL: &'static [Self] = &[
        Self::Satisfied,
        Self::Degraded,
        Self::Unsupported,
        Self::RequiresOperator,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrameClass {
    TopLevel,
    Subcall,
}

impl FrameClass {
    pub const ALL: &'static [Self] = &[Self::TopLevel, Self::Subcall];
}

// ============================================================================
// Validation
// ============================================================================

/// Reasons a Lifeloop envelope, payload, or receipt failed validation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", content = "detail")]
pub enum ValidationError {
    EmptyField(String),
    SchemaVersionMismatch { expected: String, found: String },
    InvalidFrameContext(String),
    InvalidPayload(String),
    InvalidReceipt(String),
    InvalidRequest(String),
    InvalidResponse(String),
    InvalidManifest(String),
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::EmptyField(name) => write!(f, "empty sentinel string in field `{name}`"),
            Self::SchemaVersionMismatch { expected, found } => write!(
                f,
                "schema_version mismatch: expected `{expected}`, found `{found}`"
            ),
            Self::InvalidFrameContext(msg) => write!(f, "invalid frame_context: {msg}"),
            Self::InvalidPayload(msg) => write!(f, "invalid payload: {msg}"),
            Self::InvalidReceipt(msg) => write!(f, "invalid receipt: {msg}"),
            Self::InvalidRequest(msg) => write!(f, "invalid callback request: {msg}"),
            Self::InvalidResponse(msg) => write!(f, "invalid callback response: {msg}"),
            Self::InvalidManifest(msg) => write!(f, "invalid adapter manifest: {msg}"),
        }
    }
}

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

pub(crate) fn require_non_empty(value: &str, field: &'static str) -> Result<(), ValidationError> {
    if value.is_empty() {
        return Err(ValidationError::EmptyField(field.to_string()));
    }
    Ok(())
}

// ============================================================================
// Frame context
// ============================================================================

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FrameContext {
    pub frame_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_frame_id: Option<String>,
    pub frame_class: FrameClass,
}

impl FrameContext {
    pub fn top_level(frame_id: impl Into<String>) -> Self {
        Self {
            frame_id: frame_id.into(),
            parent_frame_id: None,
            frame_class: FrameClass::TopLevel,
        }
    }

    pub fn subcall(frame_id: impl Into<String>, parent_frame_id: impl Into<String>) -> Self {
        Self {
            frame_id: frame_id.into(),
            parent_frame_id: Some(parent_frame_id.into()),
            frame_class: FrameClass::Subcall,
        }
    }

    pub fn validate(&self) -> Result<(), ValidationError> {
        require_non_empty(&self.frame_id, "frame_context.frame_id")?;
        if let Some(parent) = &self.parent_frame_id {
            require_non_empty(parent, "frame_context.parent_frame_id")?;
        }
        match (self.frame_class, &self.parent_frame_id) {
            (FrameClass::TopLevel, Some(_)) => Err(ValidationError::InvalidFrameContext(
                "frame_class=top_level must not carry parent_frame_id".into(),
            )),
            (FrameClass::Subcall, None) => Err(ValidationError::InvalidFrameContext(
                "frame_class=subcall requires parent_frame_id".into(),
            )),
            _ => Ok(()),
        }
    }
}

// ============================================================================
// Payload envelope and references
// ============================================================================

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AcceptablePlacement {
    pub placement: PlacementClass,
    pub requirement: RequirementLevel,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PayloadRef {
    pub payload_id: String,
    pub payload_kind: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_digest: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub byte_size: Option<u64>,
}

impl PayloadRef {
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_non_empty(&self.payload_id, "payload_ref.payload_id")?;
        require_non_empty(&self.payload_kind, "payload_ref.payload_kind")?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PayloadEnvelope {
    pub schema_version: String,
    pub payload_id: String,
    pub client_id: String,
    pub payload_kind: String,
    pub format: String,
    pub content_encoding: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body_ref: Option<String>,
    pub byte_size: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_digest: Option<String>,
    pub acceptable_placements: Vec<AcceptablePlacement>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at_epoch_s: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redaction: Option<String>,
    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub metadata: serde_json::Map<String, serde_json::Value>,
}

impl PayloadEnvelope {
    pub fn effective_byte_size(&self) -> u64 {
        self.body
            .as_ref()
            .map(|body| body.len() as u64)
            .unwrap_or(self.byte_size)
    }

    pub fn validate(&self) -> Result<(), ValidationError> {
        if self.schema_version != SCHEMA_VERSION {
            return Err(ValidationError::SchemaVersionMismatch {
                expected: SCHEMA_VERSION.to_string(),
                found: self.schema_version.clone(),
            });
        }
        require_non_empty(&self.payload_id, "payload.payload_id")?;
        require_non_empty(&self.client_id, "payload.client_id")?;
        require_non_empty(&self.payload_kind, "payload.payload_kind")?;
        require_non_empty(&self.format, "payload.format")?;
        require_non_empty(&self.content_encoding, "payload.content_encoding")?;
        match (self.body.is_some(), self.body_ref.is_some()) {
            (true, true) => Err(ValidationError::InvalidPayload(
                "body and body_ref are mutually exclusive".into(),
            )),
            (false, false) => Err(ValidationError::InvalidPayload(
                "exactly one of body or body_ref must be present".into(),
            )),
            _ => Ok(()),
        }?;
        if let Some(body) = &self.body {
            let actual = body.len() as u64;
            if actual != self.byte_size {
                return Err(ValidationError::InvalidPayload(format!(
                    "body byte length {actual} does not match byte_size {}",
                    self.byte_size
                )));
            }
        }
        if let Some(idem) = &self.idempotency_key {
            require_non_empty(idem, "payload.idempotency_key")?;
        }
        if self.acceptable_placements.is_empty() {
            return Err(ValidationError::InvalidPayload(
                "acceptable_placements must list at least one placement".into(),
            ));
        }
        Ok(())
    }
}

// ============================================================================
// Receipts
// ============================================================================

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PayloadReceipt {
    pub payload_id: String,
    pub payload_kind: String,
    pub placement: PlacementClass,
    pub status: PlacementOutcome,
    pub byte_size: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_digest: Option<String>,
}

impl PayloadReceipt {
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_non_empty(&self.payload_id, "payload_receipt.payload_id")?;
        require_non_empty(&self.payload_kind, "payload_receipt.payload_kind")?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CapabilityDegradation {
    pub capability: String,
    pub previous_support: SupportState,
    pub current_support: SupportState,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evidence: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_class: Option<RetryClass>,
}

impl CapabilityDegradation {
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_non_empty(&self.capability, "capability_degradation.capability")?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Warning {
    pub code: String,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capability: Option<String>,
}

impl Warning {
    pub fn validate(&self) -> Result<(), ValidationError> {
        require_non_empty(&self.code, "warning.code")?;
        Ok(())
    }
}