ag-agent 0.22.1

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
//! Shared app-server restart and retry orchestration.

use ag_contracts::{PlanLogin, PricedCost, TurnUsage};
use ag_protocol::{ProtocolSchemaInstructionMode, TurnPrompt};
use ag_telemetry::usage::{self, CostAmount};
use ag_telemetry::{Context, TraceContextExt as _};

use super::contract::{
    AppServerFuture, AppServerTurnRequest, AppServerTurnResponse, BorrowedAppServerFuture,
};
use super::error::AppServerError;
use super::prompt::{
    instruction_delivery_mode_for_runtime, read_latest_replay_transcript, turn_prompt_for_runtime,
};
use super::registry::{ActiveAppServerTurn, AppServerSessionRegistry};
use crate::agent::replay::ReplayContext;

/// Callbacks for inspecting runtime state during turn execution.
///
/// Bundles the query functions that [`run_turn_with_restart_retry`] uses to
/// check whether the runtime matches the current request, whether it restored
/// provider-native context, and to extract identifiers.
pub(crate) struct RuntimeInspector<Runtime> {
    /// Returns `true` when the existing runtime is compatible with the request.
    pub(crate) matches_request: fn(&Runtime, &AppServerTurnRequest) -> bool,
    /// Returns the OS process id of the runtime, when available.
    pub(crate) pid: fn(&Runtime) -> Option<u32>,
    /// Returns the provider-native conversation id, when available.
    pub(crate) provider_conversation_id: fn(&Runtime) -> Option<String>,
    /// Returns `true` when the runtime bootstrapped by restoring prior context.
    pub(crate) restored_context: fn(&Runtime) -> bool,
    /// Whether successful runtimes remain resident between session turns.
    pub(crate) retain_runtime_after_turn: bool,
}

/// Runs one app-server turn with restart-and-retry semantics.
///
/// Runtime lifecycle details (`start`, per-turn execution, and shutdown) are
/// injected by the provider. The function keeps a session-scoped runtime in
/// `sessions`, invalidates it when request shape changes, and retries once
/// after restarting the runtime when the first attempt fails.
///
/// Prompt transcript replay is only applied when a newly started runtime does
/// not expose restored provider-native context for the session.
///
/// `schema_instruction_mode` is selected by the provider client so bootstrap
/// prompts include the full JSON Schema only for transports that need
/// prompt-side schema guidance.
///
/// # Errors
/// Returns an error when runtime startup/execution fails, retry fails, or the
/// session registry lock is unavailable.
pub(crate) async fn run_turn_with_restart_retry<Runtime, StartRuntime, RunTurn, ShutdownRuntime>(
    sessions: &AppServerSessionRegistry<Runtime>,
    request: AppServerTurnRequest,
    inspector: RuntimeInspector<Runtime>,
    schema_instruction_mode: ProtocolSchemaInstructionMode,
    mut start_runtime: StartRuntime,
    mut run_turn_with_runtime: RunTurn,
    mut shutdown_runtime: ShutdownRuntime,
) -> Result<AppServerTurnResponse, AppServerError>
where
    StartRuntime: FnMut(&AppServerTurnRequest) -> AppServerFuture<Result<Runtime, AppServerError>>,
    RunTurn: for<'scope> FnMut(
        &'scope mut Runtime,
        &'scope TurnPrompt,
    ) -> BorrowedAppServerFuture<
        'scope,
        Result<(String, TurnUsage), AppServerError>,
    >,
    ShutdownRuntime: for<'scope> FnMut(&'scope mut Runtime) -> BorrowedAppServerFuture<'scope, ()>,
{
    let session_id = request.session_id.clone();
    let active_turn = sessions.register_active_turn(&session_id)?;
    let session_runtime =
        take_compatible_session_runtime(sessions, &request, &inspector, &mut shutdown_runtime)
            .await?;

    let had_existing_runtime = session_runtime.is_some();
    let mut session_runtime = match session_runtime {
        Some(existing_runtime) => existing_runtime,
        None => start_observed_runtime(start_runtime(&request), false).await?,
    };
    let first_replays = needs_replay(had_existing_runtime, &request, &inspector, &session_runtime);
    let first_attempt = {
        let (first_prompt, _first_replay) = build_attempt_prompt(
            &request,
            first_replays,
            (inspector.provider_conversation_id)(&session_runtime).as_deref(),
            schema_instruction_mode,
            &mut shutdown_runtime,
            &mut session_runtime,
        )
        .await?;

        run_cancellable_turn_attempt(
            &active_turn,
            &mut session_runtime,
            &first_prompt,
            request.provider_call_budget.as_ref(),
            &mut run_turn_with_runtime,
            &mut shutdown_runtime,
        )
        .await
    };
    let first_error = match first_attempt {
        Ok(attempt_output) => {
            return complete_successful_runtime_response(
                sessions,
                session_id,
                session_runtime,
                first_replays,
                attempt_output,
                &inspector,
                &mut shutdown_runtime,
            )
            .await;
        }
        Err(first_error) => first_error,
    };
    if matches!(first_error, AppServerError::InterruptedByUser(_)) {
        return Err(first_error);
    }

    shutdown_runtime(&mut session_runtime).await;
    if crate::is_input_size_error(&first_error.to_string()) {
        return Err(first_error);
    }

    let mut restarted = start_observed_runtime(start_runtime(&request), true).await?;
    let retry_replays = needs_replay(false, &request, &inspector, &restarted);
    let (retry_prompt, _retry_replay) = build_attempt_prompt(
        &request,
        retry_replays,
        (inspector.provider_conversation_id)(&restarted).as_deref(),
        schema_instruction_mode,
        &mut shutdown_runtime,
        &mut restarted,
    )
    .await?;
    match run_cancellable_turn_attempt(
        &active_turn,
        &mut restarted,
        &retry_prompt,
        request.provider_call_budget.as_ref(),
        &mut run_turn_with_runtime,
        &mut shutdown_runtime,
    )
    .await
    {
        Ok(attempt_output) => {
            complete_successful_runtime_response(
                sessions,
                session_id,
                restarted,
                retry_replays,
                attempt_output,
                &inspector,
                &mut shutdown_runtime,
            )
            .await
        }
        Err(retry_error) => {
            if matches!(retry_error, AppServerError::InterruptedByUser(_)) {
                return Err(retry_error);
            }

            shutdown_runtime(&mut restarted).await;

            Err(AppServerError::RetryExhausted {
                provider: sessions.provider_name(),
                first_error: first_error.to_string(),
                retry_error: retry_error.to_string(),
            })
        }
    }
}

/// Takes the idle runtime for a request and shuts it down when it no longer
/// matches the requested model or provider context.
async fn take_compatible_session_runtime<Runtime, ShutdownRuntime>(
    sessions: &AppServerSessionRegistry<Runtime>,
    request: &AppServerTurnRequest,
    inspector: &RuntimeInspector<Runtime>,
    shutdown_runtime: &mut ShutdownRuntime,
) -> Result<Option<Runtime>, AppServerError>
where
    ShutdownRuntime: for<'scope> FnMut(&'scope mut Runtime) -> BorrowedAppServerFuture<'scope, ()>,
{
    match sessions.take_session(&request.session_id)? {
        Some(mut runtime) if !(inspector.matches_request)(&runtime, request) => {
            shutdown_runtime(&mut runtime).await;

            Ok(None)
        }
        session_runtime => Ok(session_runtime),
    }
}

/// Measures each initial or restarted provider startup independently.
async fn start_observed_runtime<Runtime>(
    startup: AppServerFuture<Result<Runtime, AppServerError>>,
    restarted: bool,
) -> Result<Runtime, AppServerError> {
    if restarted {
        ag_telemetry::milestone("runtime_restart");
    }
    ag_telemetry::Span::child("agent.startup")
        .run(startup, |_| ag_telemetry::Outcome::Failed)
        .await
}

/// Completes a successful turn, either retaining or shutting down its runtime,
/// and builds the normalized app-server response.
///
/// If the registry cannot accept the runtime, this shuts the runtime down
/// before returning the lock error so app-server child processes do not leak.
async fn complete_successful_runtime_response<Runtime, ShutdownRuntime>(
    sessions: &AppServerSessionRegistry<Runtime>,
    session_id: String,
    mut session_runtime: Runtime,
    context_reset: bool,
    attempt_output: (String, TurnUsage),
    inspector: &RuntimeInspector<Runtime>,
    shutdown_runtime: &mut ShutdownRuntime,
) -> Result<AppServerTurnResponse, AppServerError>
where
    ShutdownRuntime: for<'scope> FnMut(&'scope mut Runtime) -> BorrowedAppServerFuture<'scope, ()>,
{
    let (assistant_message, usage) = attempt_output;
    let provider_conversation_id = (inspector.provider_conversation_id)(&session_runtime);

    if !inspector.retain_runtime_after_turn {
        shutdown_runtime(&mut session_runtime).await;

        return Ok(AppServerTurnResponse {
            assistant_message,
            context_reset,
            pid: None,
            provider_conversation_id,
            usage,
        });
    }

    let pid = (inspector.pid)(&session_runtime);
    if let Err((error, mut leaked)) = sessions.store_session_or_recover(session_id, session_runtime)
    {
        shutdown_runtime(&mut leaked).await;

        return Err(error);
    }

    Ok(AppServerTurnResponse {
        assistant_message,
        context_reset,
        pid,
        provider_conversation_id,
        usage,
    })
}

/// Runs one provider runtime attempt while watching the session-scoped
/// app-server cancellation token.
///
/// `run_turn_with_restart_retry()` temporarily owns the runtime while a turn is
/// in flight, so provider `shutdown_session()` cannot remove it from the idle
/// registry. This helper gives that shutdown path a token to fire; when it
/// fires, the running turn future is dropped, the runtime is shut down through
/// the provider lifecycle hook, and the attempt returns a user-interruption
/// error instead of retrying.
async fn run_cancellable_turn_attempt<Runtime, RunTurn, ShutdownRuntime>(
    active_turn: &ActiveAppServerTurn,
    runtime: &mut Runtime,
    prompt: &TurnPrompt,
    provider_call_budget: Option<&ag_contracts::ProviderCallBudget>,
    run_turn_with_runtime: &mut RunTurn,
    shutdown_runtime: &mut ShutdownRuntime,
) -> Result<(String, TurnUsage), AppServerError>
where
    RunTurn: for<'scope> FnMut(
        &'scope mut Runtime,
        &'scope TurnPrompt,
    ) -> BorrowedAppServerFuture<
        'scope,
        Result<(String, TurnUsage), AppServerError>,
    >,
    ShutdownRuntime: for<'scope> FnMut(&'scope mut Runtime) -> BorrowedAppServerFuture<'scope, ()>,
{
    let span = ag_telemetry::Span::child("agent.attempt");
    span.attribute("agentty.transport", "app_server");
    span.run(
        async {
            let cancellation_token = active_turn.token();
            if cancellation_token.is_cancelled() {
                shutdown_runtime(runtime).await;

                return Err(interrupted_by_user_error());
            }

            if let Some(budget) = provider_call_budget {
                budget
                    .consume()
                    .map_err(|error| AppServerError::Provider(error.to_string()))?;
            }
            let turn_outcome = {
                let turn_future = run_turn_with_runtime(runtime, prompt);
                tokio::pin!(turn_future);
                tokio::select! {
                    result = &mut turn_future => TurnAttemptOutcome::Completed(result),
                    () = cancellation_token.cancelled() => TurnAttemptOutcome::Interrupted,
                }
            };

            match turn_outcome {
                TurnAttemptOutcome::Completed(result) => {
                    if let Ok((_, usage)) = &result {
                        record_attempt_usage(usage);
                    }

                    result
                }
                TurnAttemptOutcome::Interrupted => {
                    shutdown_runtime(runtime).await;

                    Err(interrupted_by_user_error())
                }
            }
        },
        |error| match error {
            AppServerError::InterruptedByUser(_) => ag_telemetry::Outcome::Canceled,
            _ => ag_telemetry::Outcome::Failed,
        },
    )
    .await
}

/// Records what the provider requests of one completed attempt cost and saw
/// on the current `agent.attempt` span: prompt-cache writes, the estimated
/// charge and API equivalent when every model's cost is known, and the
/// latest request's input with
/// its model's context window. Unknown figures are omitted, never zero.
fn record_attempt_usage(usage: &TurnUsage) {
    let Some(total) = usage.total() else {
        return;
    };
    let count = |value: u64| i64::try_from(value).unwrap_or(i64::MAX);
    if let Some(cache_write) = total.cache_write_tokens {
        ag_telemetry::current_attribute(
            "gen_ai.usage.cache_creation.input_tokens",
            count(cache_write),
        );
    }
    if let Some(cost) = total.cost {
        let amount = |cost: PricedCost| CostAmount {
            basis: cost.basis.as_str(),
            micro_usd: cost.micro_usd,
            upper_bound: cost.upper_bound,
        };
        let api_equivalent = cost.api_equivalent();
        Context::current()
            .span()
            .set_attributes(usage::cost_attributes(
                cost.charge().map(amount),
                api_equivalent.map(|equivalent| amount(equivalent.cost)),
                api_equivalent
                    .and_then(|equivalent| equivalent.login)
                    .map(PlanLogin::as_str),
            ));
    }
    // The latest request's own fill, not the summed one, which would pair
    // its input with another model's window.
    if let Some(context) = usage.context() {
        ag_telemetry::current_attribute(
            "agentty.context.input_tokens",
            count(context.last_input_tokens),
        );
        if let Some(window) = context.window_tokens {
            ag_telemetry::current_attribute("agentty.context.window_tokens", count(window));
        }
    }
}

/// Result of racing one app-server turn against cancellation.
enum TurnAttemptOutcome {
    /// The provider turn completed before cancellation fired.
    Completed(Result<(String, TurnUsage), AppServerError>),
    /// The session cancellation token fired first.
    Interrupted,
}

/// Builds the app-server interruption error shared by initial and retry turns.
fn interrupted_by_user_error() -> AppServerError {
    AppServerError::InterruptedByUser("[Stopped] Session interrupted by user.".to_string())
}

/// Returns `true` when the attempt should replay prior transcript as
/// context for the runtime.
fn needs_replay<Runtime>(
    had_existing_runtime: bool,
    request: &AppServerTurnRequest,
    inspector: &RuntimeInspector<Runtime>,
    runtime: &Runtime,
) -> bool {
    !had_existing_runtime
        && read_latest_replay_transcript(request)
            .as_deref()
            .is_some_and(|replay_transcript| !replay_transcript.trim().is_empty())
        && !(inspector.restored_context)(runtime)
}

/// Prepares the prompt for one turn attempt, shutting down the runtime on
/// failure.
async fn build_attempt_prompt<Runtime, ShutdownRuntime>(
    request: &AppServerTurnRequest,
    replays_context: bool,
    current_provider_conversation_id: Option<&str>,
    schema_instruction_mode: ProtocolSchemaInstructionMode,
    shutdown_runtime: &mut ShutdownRuntime,
    runtime: &mut Runtime,
) -> Result<(TurnPrompt, ReplayContext), AppServerError>
where
    ShutdownRuntime: for<'scope> FnMut(&'scope mut Runtime) -> BorrowedAppServerFuture<'scope, ()>,
{
    let replay_transcript = read_latest_replay_transcript(request);
    let replay = match ReplayContext::prepare(request.folder.clone(), replay_transcript).await {
        Ok(replay) => replay,
        Err(error) => {
            shutdown_runtime(runtime).await;

            return Err(AppServerError::prompt_render(error));
        }
    };
    let instruction_delivery_mode = instruction_delivery_mode_for_runtime(
        request,
        current_provider_conversation_id,
        replays_context,
    );

    let mut prompt = request.prompt.clone();
    if !replays_context && let Some(reference) = &replay.reference {
        prompt.text = format!("{reference}\n\n{}", prompt.agent_text());
        prompt.text_source = ag_protocol::TurnPromptTextSource::AgentData;
    }

    let prepared = turn_prompt_for_runtime(
        &prompt,
        &request.request_kind,
        replay.text.as_deref(),
        instruction_delivery_mode,
        &request.agent_profile,
        schema_instruction_mode,
        &request.folder,
    );

    finish_prompt_preparation(prepared, replay, shutdown_runtime, runtime).await
}

/// Keeps the replay archive alive through rendering and shuts the runtime down
/// if the renderer fails. Accepts the fallible result so cleanup is testable
/// independently of the concrete template renderer.
async fn finish_prompt_preparation<Runtime, ShutdownRuntime>(
    prepared: Result<TurnPrompt, AppServerError>,
    replay: ReplayContext,
    shutdown_runtime: &mut ShutdownRuntime,
    runtime: &mut Runtime,
) -> Result<(TurnPrompt, ReplayContext), AppServerError>
where
    ShutdownRuntime: for<'scope> FnMut(&'scope mut Runtime) -> BorrowedAppServerFuture<'scope, ()>,
{
    match prepared {
        Ok(prompt) => Ok((prompt, replay)),
        Err(error) => {
            shutdown_runtime(runtime).await;

            Err(error)
        }
    }
}

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