a3s-code-core 8.0.3

A3S Code Core - Embeddable AI agent library with tool execution
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
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;

use async_trait::async_trait;
use thiserror::Error;
use tokio_util::sync::CancellationToken;

use super::{
    CapabilityCatalog, CapabilityCeiling, CapabilityCommitReceipt, CapabilityId, CapabilityKind,
    CapabilityProjectionAdapter, CapabilityProjectionError, CapabilityProjectionLease,
    CapabilityScope, CapabilityScopeError, CapabilitySet, CapabilityTxn, CapabilityValue, Prepared,
    RetainedUseGeneration, Run, ScopeCloseReport, Session, Staged, UseCapabilityGeneration,
    Validated,
};

const MAX_USE_LEASE_ERROR_BYTES: usize = 1_024;

/// Bounded failure returned while retaining one exact A3S Use generation.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
#[error("{message}")]
pub struct UseGenerationLeaseError {
    message: Box<str>,
}

impl UseGenerationLeaseError {
    pub fn new(message: impl Into<String>) -> Self {
        let message = message.into();
        let message = if message.is_empty() {
            "A3S Use generation lease acquisition failed".to_owned()
        } else {
            truncate_utf8(message, MAX_USE_LEASE_ERROR_BYTES)
        };
        Self {
            message: message.into_boxed_str(),
        }
    }

    pub fn message(&self) -> &str {
        &self.message
    }
}

/// Generation-bound host seam for the real non-clone A3S Use snapshot lease.
///
/// A provider is published in the same catalog CAS as its projection. Each Run
/// calls [`Self::acquire`] again so A3S Use can reject a generation that has
/// become hidden or stale since Code installed the projection. Implementations
/// must retain the concrete `a3s_use::CapabilitySnapshotLease` inside the
/// returned [`RetainedUseGeneration`] value.
#[async_trait]
pub trait UseGenerationLeaseProvider: Send + Sync + 'static {
    fn use_generation(&self) -> &UseCapabilityGeneration;

    async fn acquire(
        &self,
        cancellation: CancellationToken,
    ) -> Result<Box<dyn RetainedUseGeneration>, UseGenerationLeaseError>;
}

/// Session-host failure that cannot expose a partial capability generation.
#[derive(Clone, Debug, Eq, Error, PartialEq)]
pub enum CapabilityRuntimeError {
    #[error(transparent)]
    Projection(#[from] CapabilityProjectionError),
    #[error(transparent)]
    Scope(#[from] CapabilityScopeError),
    #[error("A Session capability batch with an A3S Use cursor requires a lease provider")]
    MissingUseLeaseProvider,
    #[error("A Session capability batch without an A3S Use cursor cannot carry a lease provider")]
    UnexpectedUseLeaseProvider,
    #[error(
        "A3S Use lease provider does not match the batch cursor (generation {expected_generation} vs {actual_generation}, capability revision mismatch: {revision_mismatch}, Registry revision mismatch: {registry_revision_mismatch})"
    )]
    UseLeaseProviderMismatch {
        expected_generation: u64,
        actual_generation: u64,
        revision_mismatch: bool,
        registry_revision_mismatch: bool,
    },
    #[error("A3S Use generation lease acquisition failed: {message}")]
    UseLeaseAcquisition { message: String },
    #[error("Session capability Run admission was cancelled")]
    Cancelled,
    #[error("The owning Session is closed")]
    SessionClosed,
    #[error("Session capability kind '{kind}' is not migrated to the atomic host runtime")]
    UnsupportedSessionKind { kind: CapabilityKind },
    #[error("Session runtime {kind} name '{public_name}' conflicts with a compatibility value")]
    RuntimeNameConflict {
        kind: CapabilityKind,
        public_name: String,
    },
    #[error("Session runtime {kind} value '{public_name}' is invalid: {message}")]
    RuntimeValueInvalid {
        kind: CapabilityKind,
        public_name: String,
        message: String,
    },
    #[error("Session recovery capability binding is unavailable: {message}")]
    RecoveryBinding { message: String },
    #[error(
        "Capability Run close was incomplete (tasks failed: {tasks_failed}, tasks timed out: {tasks_timed_out}, child scopes failed: {child_scopes_failed}, child scopes timed out: {child_scopes_timed_out}, effects failed: {effects_failed}, effects timed out: {effects_timed_out})"
    )]
    RunCloseIncomplete {
        tasks_failed: usize,
        tasks_timed_out: usize,
        child_scopes_failed: usize,
        child_scopes_timed_out: usize,
        effects_failed: usize,
        effects_timed_out: usize,
    },
}

/// One complete next-generation Tool/Skill/Agent/Command/Hook/MCP/Flow/
/// Knowledge Surface/Knowledge/UI/Context projection for a Session.
///
/// The batch owns every adapter before preparation starts. A Use-backed batch
/// also owns the generation-specific lease provider that will be published in
/// the same catalog compare-and-swap as the prepared projection.
#[must_use = "a Session capability batch must be applied or dropped"]
pub struct SessionCapabilityBatch {
    target: Arc<CapabilitySet>,
    staged: BTreeMap<CapabilityId, Box<dyn CapabilityProjectionAdapter>>,
    use_lease_provider: Option<Arc<dyn UseGenerationLeaseProvider>>,
}

impl SessionCapabilityBatch {
    pub fn new(target: Arc<CapabilitySet>) -> Result<Self, CapabilityRuntimeError> {
        if target.use_capability_generation().is_some() {
            return Err(CapabilityRuntimeError::MissingUseLeaseProvider);
        }
        validate_session_kinds(&target)?;
        Ok(Self {
            target,
            staged: BTreeMap::new(),
            use_lease_provider: None,
        })
    }

    pub fn from_use_projection(
        target: Arc<CapabilitySet>,
        provider: Arc<dyn UseGenerationLeaseProvider>,
    ) -> Result<Self, CapabilityRuntimeError> {
        let expected = target
            .use_capability_generation()
            .ok_or(CapabilityRuntimeError::UnexpectedUseLeaseProvider)?;
        ensure_use_generation_matches(expected, provider.use_generation())?;
        validate_session_kinds(&target)?;
        Ok(Self {
            target,
            staged: BTreeMap::new(),
            use_lease_provider: Some(provider),
        })
    }

    pub fn target(&self) -> &CapabilitySet {
        &self.target
    }

    pub fn stage<A>(
        &mut self,
        id: CapabilityId,
        adapter: A,
    ) -> Result<&mut Self, CapabilityRuntimeError>
    where
        A: CapabilityProjectionAdapter,
    {
        self.stage_boxed(id, Box::new(adapter))
    }

    pub fn stage_value(
        &mut self,
        id: CapabilityId,
        value: CapabilityValue,
    ) -> Result<&mut Self, CapabilityRuntimeError> {
        struct ReadyValue(CapabilityValue);

        #[async_trait]
        impl CapabilityProjectionAdapter for ReadyValue {
            async fn prepare(
                self: Box<Self>,
                _cancellation: CancellationToken,
            ) -> Result<super::PreparedCapability, super::CapabilityAdapterError> {
                Ok(super::PreparedCapability::new(self.0))
            }
        }

        self.stage(id, ReadyValue(value))
    }

    pub fn len(&self) -> usize {
        self.staged.len()
    }

    pub fn is_empty(&self) -> bool {
        self.staged.is_empty()
    }

    fn stage_boxed(
        &mut self,
        id: CapabilityId,
        adapter: Box<dyn CapabilityProjectionAdapter>,
    ) -> Result<&mut Self, CapabilityRuntimeError> {
        if !self.target.contains(&id) {
            return Err(CapabilityProjectionError::UnknownStagedCapability {
                capability: id.to_string(),
            }
            .into());
        }
        if self.staged.insert(id.clone(), adapter).is_some() {
            return Err(CapabilityProjectionError::DuplicateStagedCapability {
                capability: id.to_string(),
            }
            .into());
        }
        Ok(self)
    }

    pub(crate) async fn prepare(
        self,
        catalog: &CapabilityCatalog,
        cancellation: CancellationToken,
    ) -> Result<PreparedSessionCapabilityBatch, CapabilityRuntimeError> {
        let Self {
            target,
            staged,
            use_lease_provider,
        } = self;
        let mut transaction: CapabilityTxn<Staged> = catalog.begin(target)?;
        for (id, adapter) in staged {
            transaction.stage_boxed(id, adapter)?;
        }
        let transaction: CapabilityTxn<Prepared> = transaction.prepare(cancellation).await?;
        let transaction: CapabilityTxn<Validated> = transaction.validate()?;
        Ok(PreparedSessionCapabilityBatch {
            transaction,
            use_lease_provider,
        })
    }

    pub(crate) async fn prepare_recovery_bootstrap(
        self,
        catalog: &CapabilityCatalog,
        cancellation: CancellationToken,
    ) -> Result<PreparedSessionCapabilityBatch, CapabilityRuntimeError> {
        let Self {
            target,
            staged,
            use_lease_provider,
        } = self;
        let mut transaction: CapabilityTxn<Staged> = catalog.begin_recovery_bootstrap(target)?;
        for (id, adapter) in staged {
            transaction.stage_boxed(id, adapter)?;
        }
        let transaction: CapabilityTxn<Prepared> = transaction.prepare(cancellation).await?;
        let transaction: CapabilityTxn<Validated> = transaction.validate()?;
        Ok(PreparedSessionCapabilityBatch {
            transaction,
            use_lease_provider,
        })
    }
}

impl fmt::Debug for SessionCapabilityBatch {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SessionCapabilityBatch")
            .field("target_generation", &self.target.generation())
            .field("target_digest", &self.target.digest())
            .field("staged", &self.staged.len())
            .field("use_backed", &self.use_lease_provider.is_some())
            .finish()
    }
}

pub(crate) struct PreparedSessionCapabilityBatch {
    transaction: CapabilityTxn<Validated>,
    use_lease_provider: Option<Arc<dyn UseGenerationLeaseProvider>>,
}

impl PreparedSessionCapabilityBatch {
    pub(crate) fn projection(
        &self,
    ) -> Result<&super::CapabilityProjection, CapabilityRuntimeError> {
        self.transaction.projection().map_err(Into::into)
    }

    pub(crate) fn commit(self) -> Result<CapabilityCommitReceipt, CapabilityRuntimeError> {
        self.transaction
            .commit_with_use_lease_provider(self.use_lease_provider)
            .map_err(Into::into)
    }
}

/// Non-clone Run guard retaining one Code projection and one exact Use lease.
///
/// The Run and its generation-specific Session scope are closed together. The
/// A3S Use lease lives in the Run supervisor and is released after children,
/// tasks, and effects. The projection lease remains pinned until this guard is
/// dropped, so model definitions and execution borrow the same runtime values.
#[must_use = "a Session capability Run must remain alive for the complete execution"]
pub struct SessionCapabilityRun {
    run_scope: CapabilityScope<Run>,
    session_scope: CapabilityScope<Session>,
    projection: CapabilityProjectionLease,
}

impl SessionCapabilityRun {
    pub(crate) async fn admit(
        projection: CapabilityProjectionLease,
        session_local_id: &str,
        run_local_id: &str,
        ceiling: CapabilityCeiling,
        cancellation: CancellationToken,
    ) -> Result<Self, CapabilityRuntimeError> {
        if cancellation.is_cancelled() {
            return Err(CapabilityRuntimeError::Cancelled);
        }
        let set = projection.projection().set();
        // The host invocation token is the cancellation-tree root, not a
        // resource owned by capability teardown. The Session owns a child so
        // host cancellation still cascades downward, while normal Run close
        // cannot make a successfully completed host lifecycle look cancelled.
        let session_scope = CapabilityScope::new_session_with_cancellation(
            session_local_id,
            Arc::clone(projection.projection().set_arc()),
            ceiling.clone(),
            cancellation.child_token(),
        )?;

        let run_scope = match set.use_capability_generation() {
            Some(expected) => {
                let provider = projection
                    .use_lease_provider()
                    .ok_or(CapabilityRuntimeError::MissingUseLeaseProvider)?;
                ensure_use_generation_matches(expected, provider.use_generation())?;
                let acquire = provider.acquire(cancellation.clone());
                tokio::pin!(acquire);
                let lease = tokio::select! {
                    biased;
                    _ = cancellation.cancelled() => {
                        return Err(CapabilityRuntimeError::Cancelled);
                    }
                    result = &mut acquire => result.map_err(|error| {
                        CapabilityRuntimeError::UseLeaseAcquisition {
                            message: error.message().to_owned(),
                        }
                    })?,
                };
                session_scope.admit_use_run(run_local_id, ceiling, lease)?
            }
            None => {
                if projection.use_lease_provider().is_some() {
                    return Err(CapabilityRuntimeError::UnexpectedUseLeaseProvider);
                }
                session_scope.admit_run(run_local_id, ceiling)?
            }
        };

        Ok(Self {
            run_scope,
            session_scope,
            projection,
        })
    }

    pub fn projection(&self) -> &super::CapabilityProjection {
        self.projection.projection()
    }

    pub fn run_scope(&self) -> &CapabilityScope<Run> {
        &self.run_scope
    }

    pub(crate) fn task_spawner(&self) -> super::SupervisedTaskSpawner {
        self.run_scope.task_spawner()
    }

    pub async fn close(&self) -> Result<ScopeCloseReport, CapabilityRuntimeError> {
        let report = self.session_scope.close().await?;
        if !report.is_clean() {
            return Err(CapabilityRuntimeError::RunCloseIncomplete {
                tasks_failed: report.tasks_failed,
                tasks_timed_out: report.tasks_timed_out,
                child_scopes_failed: report.child_scopes_failed,
                child_scopes_timed_out: report.child_scopes_timed_out,
                effects_failed: report.effects_failed,
                effects_timed_out: report.effects_timed_out,
            });
        }
        Ok(report)
    }
}

impl fmt::Debug for SessionCapabilityRun {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SessionCapabilityRun")
            .field("stamp", self.projection.stamp())
            .field("run_scope", &self.run_scope.id())
            .finish_non_exhaustive()
    }
}

fn validate_session_kinds(target: &CapabilitySet) -> Result<(), CapabilityRuntimeError> {
    for (_, descriptor) in target.iter() {
        if !matches!(
            descriptor.id().kind(),
            CapabilityKind::Tool
                | CapabilityKind::Skill
                | CapabilityKind::Agent
                | CapabilityKind::Command
                | CapabilityKind::Hook
                | CapabilityKind::Mcp
                | CapabilityKind::Flow
                | CapabilityKind::KnowledgeSurface
                | CapabilityKind::Knowledge
                | CapabilityKind::Ui
                | CapabilityKind::Context
        ) {
            return Err(CapabilityRuntimeError::UnsupportedSessionKind {
                kind: descriptor.id().kind(),
            });
        }
    }
    Ok(())
}

fn ensure_use_generation_matches(
    expected: &UseCapabilityGeneration,
    actual: &UseCapabilityGeneration,
) -> Result<(), CapabilityRuntimeError> {
    if expected == actual {
        return Ok(());
    }
    Err(CapabilityRuntimeError::UseLeaseProviderMismatch {
        expected_generation: expected.generation(),
        actual_generation: actual.generation(),
        revision_mismatch: expected.revision() != actual.revision(),
        registry_revision_mismatch: expected.registry_revision() != actual.registry_revision(),
    })
}

fn truncate_utf8(mut value: String, max: usize) -> String {
    if value.len() <= max {
        return value;
    }
    let mut boundary = max;
    while !value.is_char_boundary(boundary) {
        boundary -= 1;
    }
    value.truncate(boundary);
    value
}