ag-contracts 0.22.1

Transport-independent agent execution contracts
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
//! Shared channel trait and provider turn request/result contracts.

use std::fmt;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;

use ag_protocol::{AgentResponse, ProtocolRequestProfile, TurnPrompt};
use tokio::sync::mpsc;

use crate::{PermissionMode, ReasoningLevel, ResponseStyle, SpeedMode};

/// Normalizes one provider-native conversation id for persisted bootstrap
/// reuse tracking.
pub fn normalize_instruction_conversation_id(
    provider_conversation_id: Option<&str>,
) -> Option<String> {
    provider_conversation_id
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(ToString::to_string)
}

/// Boxed async result used by [`AgentChannel`] trait methods.
pub type AgentFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;

/// Live transcript projection used when a provider runtime needs replay text.
pub trait LiveTranscript: fmt::Debug + Send + Sync {
    /// Returns the latest replayable transcript text, when any content exists.
    fn replay_text(&self) -> Option<String>;
}

/// Turn initiation mode for [`TurnRequest`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AgentRequestKind {
    /// Runs one focused code review with a direct structured review response.
    FocusedReview,
    /// Proposes an initial graph or asks clarification without launching nodes.
    GraphProposal,
    /// Reconcile review-request metadata using a direct typed result.
    ReviewMetadata,
    /// Starts a fresh interactive session turn with no prior context.
    SessionStart,
    /// Resumes an interactive session turn.
    SessionResume,
    /// Runs one utility prompt with utility protocol requirements.
    ///
    /// Callers may route this through an isolated one-shot channel or through
    /// an existing session channel when the utility work needs provider
    /// conversation continuity without normal post-turn auto-commit handling.
    UtilityPrompt,
    /// Reads provider account metadata without creating an agent turn.
    AccountRead,
}

impl AgentRequestKind {
    /// Returns the protocol request profile derived from this request kind.
    #[must_use]
    pub fn protocol_profile(&self) -> ProtocolRequestProfile {
        match self {
            Self::SessionStart | Self::SessionResume => ProtocolRequestProfile::SessionTurn,
            Self::FocusedReview => ProtocolRequestProfile::FocusedReview,
            Self::GraphProposal => ProtocolRequestProfile::GraphProposal,
            Self::ReviewMetadata => ProtocolRequestProfile::ReviewMetadata,
            Self::UtilityPrompt | Self::AccountRead => ProtocolRequestProfile::UtilityPrompt,
        }
    }

    /// Returns whether this request resumes a prior interactive session turn.
    #[must_use]
    pub fn is_resume(&self) -> bool {
        matches!(self, Self::SessionResume)
    }
}

/// Agent prompt state prepared for one provider turn.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct AgentDefinitionPrompt {
    current: Option<String>,
    update: AgentDefinitionPromptUpdate,
}

impl AgentDefinitionPrompt {
    /// Creates one active agent, marking whether delta-mode providers
    /// must receive its body as an update.
    #[must_use]
    pub fn active(prompt: String, changed: bool) -> Self {
        let update = if changed {
            AgentDefinitionPromptUpdate::Set(prompt.clone())
        } else {
            AgentDefinitionPromptUpdate::Unchanged
        };

        Self {
            current: Some(prompt),
            update,
        }
    }

    /// Creates a cleared agent state.
    ///
    /// `changed` is true when retained context previously held active agent
    /// instructions and must be told to discard them, including on bootstrap.
    #[must_use]
    pub fn cleared(changed: bool) -> Self {
        Self {
            current: None,
            update: if changed {
                AgentDefinitionPromptUpdate::Clear
            } else {
                AgentDefinitionPromptUpdate::Unchanged
            },
        }
    }

    /// Returns the current agent body for a full bootstrap.
    #[must_use]
    pub fn current(&self) -> Option<&str> {
        self.current.as_deref()
    }

    /// Returns the instruction update to apply when continuing context.
    pub fn update(&self) -> &AgentDefinitionPromptUpdate {
        &self.update
    }
}

/// Agent change for a provider-managed conversation or retained native history.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum AgentDefinitionPromptUpdate {
    /// Clear agent behavior that was active on the previous turn.
    Clear,
    /// Apply a new or edited agent body.
    Set(String),
    /// Reuse the agent behavior already present in provider context.
    #[default]
    Unchanged,
}

/// Continuation state for one provider-agnostic agent turn.
///
/// The concrete representation keeps provider-runtime recovery details out of
/// [`TurnRequest`] while allowing CLI channels to consume only replay text.
#[derive(Clone, Debug)]
pub struct TurnContinuation {
    kind: TurnContinuationKind,
    usage_checkpoint: Option<String>,
}

impl TurnContinuation {
    /// Creates continuation state for a fresh turn with no prior context.
    #[must_use]
    pub fn fresh() -> Self {
        Self {
            kind: TurnContinuationKind::Fresh,
            usage_checkpoint: None,
        }
    }

    /// Creates continuation state for a stateless turn that replays prior text.
    #[must_use]
    pub fn replaying(replay_transcript: String) -> Self {
        Self {
            kind: TurnContinuationKind::Replay { replay_transcript },
            usage_checkpoint: None,
        }
    }

    /// Carries the totals of the [`crate::TurnUsage::checkpoint`] the
    /// conversation this turn continues left, from which the agent derives
    /// this turn's own usage.
    #[must_use]
    pub fn with_usage_checkpoint(mut self, usage_checkpoint: Option<String>) -> Self {
        self.usage_checkpoint = usage_checkpoint;

        self
    }

    /// Returns the usage checkpoint totals of the conversation this turn
    /// continues, when the host stored one.
    #[must_use]
    pub fn usage_checkpoint(&self) -> Option<&str> {
        self.usage_checkpoint.as_deref()
    }

    /// Creates continuation state for a provider runtime that may resume a
    /// native conversation and reconstruct context from a live transcript.
    #[must_use]
    pub fn provider(
        live_transcript: Option<Arc<dyn LiveTranscript>>,
        persisted_instruction_conversation_id: Option<String>,
        provider_conversation_id: Option<String>,
        replay_transcript: Option<String>,
    ) -> Self {
        Self {
            kind: TurnContinuationKind::Provider {
                live_transcript,
                persisted_instruction_conversation_id,
                provider_conversation_id,
                replay_transcript,
            },
            usage_checkpoint: None,
        }
    }

    /// Returns replayable transcript text when this turn carries it.
    #[must_use]
    pub fn replay_transcript(&self) -> Option<&str> {
        match &self.kind {
            TurnContinuationKind::Fresh => None,
            TurnContinuationKind::Provider {
                replay_transcript, ..
            } => replay_transcript.as_deref(),
            TurnContinuationKind::Replay { replay_transcript } => Some(replay_transcript.as_str()),
        }
    }

    /// Returns the provider-native conversation identifier when available.
    #[must_use]
    pub fn provider_conversation_id(&self) -> Option<&str> {
        match &self.kind {
            TurnContinuationKind::Provider {
                provider_conversation_id,
                ..
            } => provider_conversation_id.as_deref(),
            TurnContinuationKind::Fresh | TurnContinuationKind::Replay { .. } => None,
        }
    }

    /// Returns the conversation identifier that received the instruction
    /// bootstrap when available.
    #[must_use]
    pub fn persisted_instruction_conversation_id(&self) -> Option<&str> {
        match &self.kind {
            TurnContinuationKind::Provider {
                persisted_instruction_conversation_id,
                ..
            } => persisted_instruction_conversation_id.as_deref(),
            TurnContinuationKind::Fresh | TurnContinuationKind::Replay { .. } => None,
        }
    }

    /// Consumes continuation state for a runtime adapter.
    pub fn into_parts(self) -> TurnContinuationParts {
        match self.kind {
            TurnContinuationKind::Fresh => TurnContinuationParts::default(),
            TurnContinuationKind::Replay { replay_transcript } => TurnContinuationParts {
                replay_transcript: Some(replay_transcript),
                ..TurnContinuationParts::default()
            },
            TurnContinuationKind::Provider {
                live_transcript,
                persisted_instruction_conversation_id,
                provider_conversation_id,
                replay_transcript,
            } => TurnContinuationParts {
                live_transcript,
                persisted_instruction_conversation_id,
                provider_conversation_id,
                replay_transcript,
            },
        }
    }
}

#[derive(Clone, Debug)]
enum TurnContinuationKind {
    Fresh,
    Provider {
        live_transcript: Option<Arc<dyn LiveTranscript>>,
        persisted_instruction_conversation_id: Option<String>,
        provider_conversation_id: Option<String>,
        replay_transcript: Option<String>,
    },
    Replay {
        replay_transcript: String,
    },
}

/// Owned continuation inputs consumed by a runtime adapter.
#[derive(Default)]
pub struct TurnContinuationParts {
    /// Current replay projection, when supplied by the host.
    pub live_transcript: Option<Arc<dyn LiveTranscript>>,
    /// Conversation that received the current instructions.
    pub persisted_instruction_conversation_id: Option<String>,
    /// Opaque runtime conversation identifier.
    pub provider_conversation_id: Option<String>,
    /// Durable transcript to replay after a runtime restart.
    pub replay_transcript: Option<String>,
}

/// Input payload for one provider-agnostic agent turn.
#[derive(Debug, Clone)]
pub struct TurnRequest {
    /// Whether the turn compacts the session's earlier turns once they nearly
    /// fill the model's context window. Only in-process harness turns
    /// compact; other agents manage their own context and ignore it.
    pub context_compaction: ContextCompaction,
    /// Prior context needed to continue this turn.
    pub continuation: TurnContinuation,
    /// Resolved harness policy. The worker replaces this with its configured
    /// policy before dispatch; application callers supply the default value.
    pub execution_policy: crate::ExecutionPolicy,
    /// Session worktree folder where the agent runs.
    pub folder: PathBuf,
    /// Which dependency caches sandboxed commands of an in-process harness
    /// turn use. Agents that run without the native sandbox ignore it.
    pub host_caches: HostCacheSharing,
    /// Main repository checkout that must remain read-only during the turn,
    /// when Agentty can resolve it.
    pub main_checkout_root: Option<PathBuf>,
    /// Provider-specific model identifier.
    pub model: String,
    /// Filesystem and command permission policy for this turn.
    pub permission_mode: PermissionMode,
    /// Agent prompt state resolved from the session worktree.
    pub agent_profile: AgentDefinitionPrompt,
    /// Structured prompt payload for the turn.
    pub prompt: TurnPrompt,
    /// Shared provider-call ceiling, including retries and protocol repairs.
    pub provider_call_budget: Option<crate::ProviderCallBudget>,
    /// Reasoning effort preference for the turn.
    ///
    /// Ignored by providers/models that do not support reasoning effort.
    pub reasoning_level: ReasoningLevel,
    /// Canonical request kind that drives transport behavior and protocol
    /// semantics for this turn.
    pub request_kind: AgentRequestKind,
    /// Preferred amount of detail in user-facing session responses.
    pub response_style: ResponseStyle,
    /// Response-speed preference for the turn.
    pub speed_mode: SpeedMode,
}

/// Which dependency caches (Cargo, Go, pip, npm) sandboxed harness commands
/// use.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum HostCacheSharing {
    /// Copies in the session's own temporary directory, which host tools
    /// and other sessions never read.
    #[default]
    PerSession,
    /// The host's own caches, which commands can then write, so a session
    /// could tamper with packages that other sessions and the host's own
    /// builds later use.
    Shared,
}

impl HostCacheSharing {
    /// Returns the sharing a persisted on/off toggle selects.
    #[must_use]
    pub fn from_enabled(enabled: bool) -> Self {
        if enabled {
            Self::Shared
        } else {
            Self::PerSession
        }
    }

    /// Returns whether commands use the host's own caches.
    #[must_use]
    pub fn is_shared(self) -> bool {
        self == Self::Shared
    }
}

/// How a turn handles a session context that outgrows the model's window.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum ContextCompaction {
    /// The turn never compacts; history that no longer fits is left out of
    /// its requests, oldest first.
    #[default]
    Off,
    /// The turn first summarizes earlier turns into a checkpoint that later
    /// requests carry in their place.
    Automatic {
        /// Model that writes the summary, such as the user's Default Fast
        /// Model, or `None` for [`TurnRequest::model`]. Harness turns also
        /// use [`TurnRequest::model`] when this model cannot serve
        /// summaries.
        summary_model: Option<String>,
    },
}

/// Incremental event emitted during one agent turn.
///
/// Events are sent through an [`mpsc::UnboundedSender`] as the turn
/// progresses, enabling transient loader updates and structured activity
/// delivery without appending partial answers into the persisted transcript.
#[derive(Clone, Debug, PartialEq)]
pub enum TurnEvent {
    /// Provider-observed tool or skill lifecycle snapshot.
    Activity(crate::ActivityEvent),
    /// A streamed thinking/planning or tool-status fragment shown in the
    /// transient loader.
    ThoughtDelta(String),
    /// Model output streamed by an in-process harness turn, shown
    /// transiently until the turn result is persisted.
    Output(crate::OutputEvent),
    /// Something about how the turn ran that the user should know, such as
    /// a compaction of the session's earlier context.
    Notice(crate::TurnNotice),
    /// Cumulative usage of the turn so far, sent after each model request
    /// whose usage the backend reports while the turn runs. The final
    /// [`TurnResult::usage`] supersedes it.
    UsageUpdated(crate::TurnUsage),
    /// The turn failed with an error description.
    Failed(String),
    /// A child process PID update.
    ///
    /// Announces a running or retained runtime (`Some(pid)`) or clears it
    /// when the runtime shuts down (`None`). Consumers update resource
    /// accounting. Cancellation belongs to the runtime owner; hosts must not
    /// signal a sampled accounting PID.
    PidUpdate(Option<u32>),
}

/// Normalized result returned when one agent turn completes successfully.
#[derive(Debug)]
pub struct TurnResult {
    /// Parsed agent response containing structured protocol messages.
    pub assistant_message: AgentResponse,
    /// Whether the provider reset its context to complete this turn.
    pub context_reset: bool,
    /// Content-free JSON report of an in-process harness turn: per-request
    /// usage, context fitting, corrections, and tool activity. Other agents
    /// return `None`.
    pub harness_report: Option<String>,
    /// Provider-native conversation identifier observed after the turn.
    ///
    /// App-server providers return this so the worker can persist it for
    /// future runtime restarts. CLI channels always return `None`.
    /// Opaque runtime conversation identifier.
    pub provider_conversation_id: Option<String>,
    /// Tokens and estimated charge of every model the turn used, as its
    /// backend reported them.
    pub usage: crate::TurnUsage,
}

/// Opaque reference to an active agent session.
pub struct SessionRef {
    /// Stable session identifier.
    pub session_id: String,
}

/// Input payload for initiating a new agent session.
pub struct StartSessionRequest {
    /// Session worktree folder.
    pub folder: PathBuf,
    /// Stable session identifier.
    pub session_id: String,
}

/// Typed error returned by [`AgentChannel`] operations.
///
/// Discriminates failure causes so the app layer can route errors without
/// parsing formatted messages.
#[derive(Debug, thiserror::Error)]
pub enum AgentError {
    /// An infrastructure or lifecycle failure reported by the runtime adapter.
    #[error("{0}")]
    Runtime(String),

    /// A CLI backend command or process execution failure.
    #[error("{0}")]
    Backend(String),

    /// The user explicitly interrupted the active turn.
    #[error("{0}")]
    InterruptedByUser(String),

    /// A subprocess IO error such as a spawn failure or unavailable pipe.
    #[error("{0}")]
    Io(String),
}

/// Provider-agnostic session channel for executing agent turns.
///
/// Implementations bridge a specific transport - CLI subprocess or app-server
/// RPC - to the unified [`TurnEvent`] stream consumed by session workers. The
/// trait is object-safe so it can be held as `Arc<dyn AgentChannel>`.
#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
pub trait AgentChannel: Send + Sync {
    /// Initialises a provider session for the given session identifier.
    ///
    /// Implementations that do not maintain persistent sessions return
    /// immediately with a [`SessionRef`] wrapping the supplied identifier.
    fn start_session(
        &self,
        req: StartSessionRequest,
    ) -> AgentFuture<Result<SessionRef, AgentError>>;

    /// Executes one prompt turn and streams incremental events to `events`.
    ///
    /// Implementations may emit [`TurnEvent::ThoughtDelta`] values for
    /// transient loader updates. Final transcript output is derived from the
    /// returned [`TurnResult`] after the turn finishes.
    /// Dropping the returned future must release its owned execution resources;
    /// cancellation callers will not poll the future again to drain it.
    ///
    /// # Errors
    /// Returns [`AgentError`] when the turn cannot be executed (spawn failure,
    /// transport error) or is interrupted by a signal.
    fn run_turn(
        &self,
        session_id: String,
        req: TurnRequest,
        events: mpsc::UnboundedSender<TurnEvent>,
    ) -> AgentFuture<Result<TurnResult, AgentError>>;

    /// Delivers one user prompt to the in-flight interactive session turn for
    /// `session_id`, so the agent reads it before that turn ends.
    ///
    /// `Ok` means the provider accepted the prompt into the running turn; the
    /// caller then owns recording it in the transcript. Any error leaves the
    /// prompt undelivered so callers can submit it as a later turn. Only
    /// session-start and session-resume turns accept steering; utility and
    /// review turns reject it. The default reports that the harness cannot
    /// steer.
    ///
    /// # Errors
    /// Returns [`AgentError::Runtime`] when the harness cannot steer, no
    /// interactive turn is running, or the provider rejects the prompt.
    fn steer_turn(
        &self,
        session_id: String,
        prompt: TurnPrompt,
    ) -> AgentFuture<Result<(), AgentError>> {
        // Nothing is delivered; callers keep their own copy for a later turn.
        drop((session_id, prompt));

        Box::pin(async {
            Err(AgentError::Runtime(
                "This agent cannot receive messages during a turn".to_string(),
            ))
        })
    }

    /// Tears down the provider session associated with `session_id`.
    ///
    /// Cancellation must be idempotent and must never start an unpolled turn.
    /// Implementations release persistent resources or cancel active CLI turns.
    fn shutdown_session(&self, session_id: String) -> AgentFuture<Result<(), AgentError>>;
}

#[cfg(test)]
#[path = "contract_test.rs"]
mod tests;