-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmod.rs
More file actions
721 lines (658 loc) · 28.1 KB
/
mod.rs
File metadata and controls
721 lines (658 loc) · 28.1 KB
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! Compiler extension trait and MCPG types.
//!
//! The [`CompilerExtension`] trait provides a unified interface for runtimes
//! and first-party tools to declare their compilation requirements (network
//! hosts, bash commands, prompt supplements, prepare steps, MCPG entries).
//!
//! Instead of scattering special-case `if` blocks across the compiler,
//! each runtime/tool implements this trait and the compiler collects
//! requirements via [`collect_extensions`].
//!
//! ## Adding a new runtime or tool
//!
//! 1. Create a struct wrapping your config type
//! 2. Implement [`CompilerExtension`] for it
//! 3. Add a variant to the [`Extension`] enum and update [`collect_extensions`]
use anyhow::Result;
use serde::Serialize;
use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
use super::types::FrontMatter;
// ──────────────────────────────────────────────────────────────────────
// MCPG types (used by both the trait and standalone compiler)
// ──────────────────────────────────────────────────────────────────────
/// MCPG server configuration for a single MCP upstream.
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct McpgServerConfig {
/// Server type: "stdio" for container-based, "http" for HTTP backends
#[serde(rename = "type")]
pub server_type: String,
/// Docker container image (for stdio type, per MCPG spec §4.1.2)
#[serde(skip_serializing_if = "Option::is_none")]
pub container: Option<String>,
/// Container entrypoint override (for stdio type)
#[serde(skip_serializing_if = "Option::is_none")]
pub entrypoint: Option<String>,
/// Arguments passed to the container entrypoint (for stdio type)
#[serde(skip_serializing_if = "Option::is_none")]
pub entrypoint_args: Option<Vec<String>>,
/// Volume mounts for containerized servers (format: "source:dest:mode")
#[serde(skip_serializing_if = "Option::is_none")]
pub mounts: Option<Vec<String>>,
/// Additional Docker runtime arguments (inserted before image in `docker run`)
#[serde(skip_serializing_if = "Option::is_none")]
pub args: Option<Vec<String>>,
/// URL for HTTP backends
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
/// HTTP headers (e.g., Authorization)
#[serde(skip_serializing_if = "Option::is_none")]
pub headers: Option<BTreeMap<String, String>>,
/// Environment variables for the server process
#[serde(skip_serializing_if = "Option::is_none")]
pub env: Option<BTreeMap<String, String>>,
/// Tool allow-list (if empty or absent, all tools are allowed)
#[serde(skip_serializing_if = "Option::is_none")]
pub tools: Option<Vec<String>>,
}
/// MCPG gateway configuration.
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct McpgGatewayConfig {
pub port: u16,
pub domain: String,
pub api_key: String,
pub payload_dir: String,
}
/// Top-level MCPG configuration.
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct McpgConfig {
pub mcp_servers: BTreeMap<String, McpgServerConfig>,
pub gateway: McpgGatewayConfig,
}
// ──────────────────────────────────────────────────────────────────────
// Compile context
// ──────────────────────────────────────────────────────────────────────
use crate::configure::AdoContext;
use crate::engine::{self, Engine};
use std::path::Path;
/// Metadata resolved at compile time from the local environment.
///
/// Built once via [`CompileContext::new`] and passed to all extension
/// methods. Follows the same pattern as
/// [`ExecutionContext`](crate::safeoutputs::result::ExecutionContext)
/// for Stage 3 — a single context struct with all resolved metadata.
pub struct CompileContext<'a> {
/// The agent name from front matter.
pub agent_name: &'a str,
/// The full front matter (for cross-cutting checks like bash access level).
pub front_matter: &'a FrontMatter,
/// ADO context inferred from the git remote (org URL, project, repo name).
/// `None` if the compile directory has no ADO remote.
pub ado_context: Option<AdoContext>,
/// Resolved engine based on the front matter `engine:` field.
pub engine: Engine,
}
impl<'a> CompileContext<'a> {
/// Build a fully-resolved compile context.
///
/// Resolves the engine implementation from front matter and infers ADO
/// context from the git remote in `compile_dir`. Returns an error if
/// the engine identifier is unsupported.
pub async fn new(front_matter: &'a FrontMatter, compile_dir: &Path) -> Result<Self> {
let engine = engine::get_engine(front_matter.engine.engine_id())?;
let ado_context = Self::infer_ado_context(compile_dir).await;
Ok(Self {
agent_name: &front_matter.name,
front_matter,
ado_context,
engine,
})
}
/// Convenience accessor: extract the ADO org name from the inferred context.
pub fn ado_org(&self) -> Option<&str> {
self.ado_context.as_ref().and_then(|ctx| {
let org = ctx.org_url.trim_end_matches('/').rsplit('/').next()?;
if org.is_empty() { None } else { Some(org) }
})
}
async fn infer_ado_context(dir: &Path) -> Option<AdoContext> {
match crate::configure::get_git_remote_url(dir).await {
Ok(url) => match crate::configure::parse_ado_remote(&url) {
Ok(ctx) => {
log::info!(
"Inferred ADO org from git remote: {}",
ctx.org_url
.trim_end_matches('/')
.rsplit('/')
.next()
.unwrap_or("?")
);
Some(ctx)
}
Err(_) => {
log::debug!("Git remote is not an ADO URL — cannot infer org");
None
}
},
Err(_) => {
log::debug!("No git remote found — cannot infer ADO context");
None
}
}
}
/// Create a context for tests (no async, no git remote inference).
// TODO: resolve engine from front_matter.engine when multiple engines are supported,
// instead of hardcoding Engine::Copilot. Currently safe because "copilot" is the only
// engine variant, but this will need to call get_engine() once more are added.
#[cfg(test)]
pub fn for_test(front_matter: &'a FrontMatter) -> Self {
Self {
agent_name: &front_matter.name,
front_matter,
ado_context: None,
engine: crate::engine::Engine::Copilot,
}
}
/// Create a context for tests with a specific ADO org.
#[cfg(test)]
pub fn for_test_with_org(front_matter: &'a FrontMatter, org: &str) -> Self {
Self {
agent_name: &front_matter.name,
front_matter,
ado_context: Some(AdoContext {
org_url: format!("https://dev.azure.com/{}", org),
project: "test-project".to_string(),
repo_name: "test-repo".to_string(),
}),
engine: crate::engine::Engine::Copilot,
}
}
}
// ──────────────────────────────────────────────────────────────────────
// CompilerExtension trait
// ──────────────────────────────────────────────────────────────────────
/// Execution phase for extension ordering.
///
/// Extensions are collected and processed in phase order. Runtimes run
/// before tools because tools may depend on runtimes (e.g., `uv` requires
/// a Python runtime to already be installed).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ExtensionPhase {
/// Language runtimes (Lean, Python, Node, etc.) — installed first.
Runtime = 0,
/// First-party tools (azure-devops, cache-memory, etc.) — may depend
/// on runtimes being available.
Tool = 1,
}
/// Unified interface for runtimes and first-party tools to declare
/// compilation requirements.
///
/// The compiler calls [`collect_extensions`] to gather all enabled
/// extensions, then iterates over them **in phase order** to merge
/// requirements into the generated pipeline.
///
/// ## Ordering policy
///
/// Extensions declare their [`phase`](CompilerExtension::phase) which
/// controls the order in which `prepare_steps` and `prompt_supplement`
/// are emitted. Runtimes ([`ExtensionPhase::Runtime`]) always run
/// before tools ([`ExtensionPhase::Tool`]) because tools may depend on
/// runtimes being installed (e.g., a Python-based tool needs the Python
/// runtime first).
pub trait CompilerExtension {
/// Human-readable name for logging and diagnostics (e.g., "Lean 4").
fn name(&self) -> &str;
/// The execution phase of this extension, controlling ordering.
fn phase(&self) -> ExtensionPhase;
/// Network hosts this extension requires (added to AWF allowlist).
fn required_hosts(&self) -> Vec<String> {
vec![]
}
/// Bash commands this extension needs in the agent's allow-list.
fn required_bash_commands(&self) -> Vec<String> {
vec![]
}
/// Markdown prompt content to append to the agent prompt.
///
/// The compiler wraps the returned content in a `cat >>` pipeline
/// step so it is appended to the agent prompt file.
fn prompt_supplement(&self) -> Option<String> {
None
}
/// Pipeline steps (YAML strings) to run before the agent.
///
/// Each element is a complete YAML step (e.g., `- bash: |...`).
fn prepare_steps(&self) -> Vec<String> {
vec![]
}
/// Pipeline steps (YAML strings) to inject into the Setup job.
///
/// Unlike `prepare_steps()` which injects into the Execution job,
/// these steps run in the Setup job (before the Execution job starts).
/// Used by extensions that need to run gate logic or pre-activation
/// checks before the agent is launched.
fn setup_steps(&self, _ctx: &CompileContext) -> Result<Vec<String>> {
Ok(vec![])
}
/// MCPG server entries this extension contributes.
///
/// Returns `(server_name, config)` pairs inserted into the MCPG
/// JSON configuration. Only consumed by the standalone compiler.
fn mcpg_servers(&self, _ctx: &CompileContext) -> Result<Vec<(String, McpgServerConfig)>> {
Ok(vec![])
}
/// Copilot CLI `--allow-tool` values this extension requires.
///
/// Returns tool names (e.g., `"github"`, `"safeoutputs"`, `"azure-devops"`)
/// that are emitted as `--allow-tool <name>` in the Copilot CLI invocation.
fn allowed_copilot_tools(&self) -> Vec<String> {
vec![]
}
/// Compile-time warnings to emit. Errors in the `Result` abort
/// compilation; the inner `Vec<String>` contains non-fatal warnings
/// printed to stderr.
fn validate(&self, _ctx: &CompileContext) -> Result<Vec<String>> {
Ok(vec![])
}
/// Pipeline variable mappings needed by this extension's MCP containers.
///
/// Each mapping declares that a container env var (e.g., `AZURE_DEVOPS_EXT_PAT`)
/// should be populated from a pipeline variable (e.g., `SC_READ_TOKEN`).
/// The compiler uses these to generate:
/// 1. `env:` block on the MCPG step (maps ADO secret → bash var)
/// 2. `-e` flags on the MCPG docker run (passes bash var → MCPG process)
/// 3. MCPG config keeps `""` (MCPG passthrough from its env → child container)
fn required_pipeline_vars(&self) -> Vec<PipelineEnvMapping> {
vec![]
}
/// AWF volume mounts this extension requires inside the chroot.
///
/// AWF replaces `$HOME` with an empty directory overlay for security,
/// only mounting specific known subdirectories. Extensions that install
/// toolchains under `$HOME` (e.g., elan for Lean 4) must declare mounts
/// here so the toolchain is accessible inside the chroot.
///
/// Shell variables like `$HOME` are expanded at runtime by bash, not at
/// compile time. AWF auto-adjusts container paths for chroot by prefixing
/// `/host`.
fn required_awf_mounts(&self) -> Vec<AwfMount> {
vec![]
}
/// Directories to prepend to `PATH` inside the AWF chroot.
///
/// Extensions that install toolchains outside standard system paths
/// (e.g., elan installs Lean to `$HOME/.elan/bin`) should declare their
/// bin directories here. The compiler collects these and generates a
/// `GITHUB_PATH` file that AWF reads at startup to merge into the chroot
/// PATH — bypassing the `sudo` PATH reset.
///
/// Shell variables like `$HOME` are expanded at runtime by bash, not at
/// compile time.
fn awf_path_prepends(&self) -> Vec<String> {
vec![]
}
/// Environment variables to inject into the agent execution environment.
///
/// Returns `(key, value)` pairs that are emitted as `KEY: "value"` in
/// the `{{ engine_env }}` YAML block. Used by runtimes to configure
/// package managers via env vars (e.g., `PIP_INDEX_URL`, `NPM_CONFIG_REGISTRY`).
///
/// Keys are validated against `BLOCKED_ENV_KEYS` at collection time.
fn agent_env_vars(&self) -> Vec<(String, String)> {
vec![]
}
}
/// Mount access mode for an AWF bind mount.
///
/// Maps to the Docker bind-mount mode string: `ro` (read-only) or `rw`
/// (read-write, the Docker default when no mode is specified).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AwfMountMode {
/// Read-only mount (`ro`). The process inside the container cannot write
/// to this path.
ReadOnly,
/// Read-write mount (`rw`). The container can write to this path.
ReadWrite,
}
impl fmt::Display for AwfMountMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ReadOnly => f.write_str("ro"),
Self::ReadWrite => f.write_str("rw"),
}
}
}
impl FromStr for AwfMountMode {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"ro" => Ok(Self::ReadOnly),
"rw" => Ok(Self::ReadWrite),
other => anyhow::bail!(
"Unknown AWF mount mode '{}': expected 'ro' or 'rw'",
other
),
}
}
}
impl serde::Serialize for AwfMountMode {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_string())
}
}
impl<'de> serde::Deserialize<'de> for AwfMountMode {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
s.parse().map_err(serde::de::Error::custom)
}
}
/// An AWF `--mount` specification in Docker bind-mount format.
///
/// The format is `host_path:container_path[:mode]`
/// (e.g. `"$HOME/.elan:$HOME/.elan:ro"`).
///
/// Serializes and deserializes as the Docker format string so it round-trips
/// cleanly through YAML/JSON configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AwfMount {
/// Host path to bind-mount into the container.
pub host_path: String,
/// Corresponding path inside the container.
pub container_path: String,
/// Mount access mode. Defaults to [`AwfMountMode::ReadOnly`] when not
/// specified in the input — the secure default for AWF chroot mounts.
pub mode: AwfMountMode,
}
impl AwfMount {
/// Creates an `AwfMount` with the given host path, container path, and
/// access mode.
pub fn new(
host_path: impl Into<String>,
container_path: impl Into<String>,
mode: AwfMountMode,
) -> Self {
Self {
host_path: host_path.into(),
container_path: container_path.into(),
mode,
}
}
}
impl fmt::Display for AwfMount {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}:{}", self.host_path, self.container_path, self.mode)
}
}
impl FromStr for AwfMount {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = s.splitn(3, ':').collect();
match parts.as_slice() {
[host, container] => Ok(Self {
host_path: (*host).to_string(),
container_path: (*container).to_string(),
mode: AwfMountMode::ReadOnly,
}),
[host, container, mode_str] => Ok(Self {
host_path: (*host).to_string(),
container_path: (*container).to_string(),
mode: mode_str.parse()?,
}),
_ => anyhow::bail!(
"Invalid AWF mount spec '{}': expected 'host:container[:mode]'",
s
),
}
}
}
impl serde::Serialize for AwfMount {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
serializer.serialize_str(&self.to_string())
}
}
impl<'de> serde::Deserialize<'de> for AwfMount {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
s.parse().map_err(serde::de::Error::custom)
}
}
/// Maps a container environment variable to a pipeline variable.
///
/// Used by extensions to declare that an MCP container needs a specific
/// pipeline variable (typically a secret) injected into its environment.
#[derive(Debug, Clone)]
pub struct PipelineEnvMapping {
/// The env var name inside the MCP container (e.g., `AZURE_DEVOPS_EXT_PAT`).
pub container_var: String,
/// The ADO pipeline variable name (e.g., `SC_READ_TOKEN`).
pub pipeline_var: String,
}
// ──────────────────────────────────────────────────────────────────────
// Extension enum (static dispatch)
// ──────────────────────────────────────────────────────────────────────
/// Delegates every [`CompilerExtension`] method on an enum to the
/// inner variant, eliminating boilerplate when adding new extensions.
///
/// Usage:
/// ```ignore
/// extension_enum! {
/// pub enum Extension {
/// Lean(LeanExtension),
/// AzureDevOps(AzureDevOpsExtension),
/// CacheMemory(CacheMemoryExtension),
/// }
/// }
/// ```
macro_rules! extension_enum {
(
$(#[$meta:meta])*
pub enum $Enum:ident {
$( $Variant:ident($Inner:ty) ),+ $(,)?
}
) => {
$(#[$meta])*
pub enum $Enum {
$( $Variant($Inner), )+
}
impl CompilerExtension for $Enum {
fn name(&self) -> &str {
match self { $( $Enum::$Variant(e) => e.name(), )+ }
}
fn phase(&self) -> ExtensionPhase {
match self { $( $Enum::$Variant(e) => e.phase(), )+ }
}
fn required_hosts(&self) -> Vec<String> {
match self { $( $Enum::$Variant(e) => e.required_hosts(), )+ }
}
fn required_bash_commands(&self) -> Vec<String> {
match self { $( $Enum::$Variant(e) => e.required_bash_commands(), )+ }
}
fn prompt_supplement(&self) -> Option<String> {
match self { $( $Enum::$Variant(e) => e.prompt_supplement(), )+ }
}
fn prepare_steps(&self) -> Vec<String> {
match self { $( $Enum::$Variant(e) => e.prepare_steps(), )+ }
}
fn setup_steps(&self, ctx: &CompileContext) -> Result<Vec<String>> {
match self { $( $Enum::$Variant(e) => e.setup_steps(ctx), )+ }
}
fn mcpg_servers(&self, ctx: &CompileContext) -> Result<Vec<(String, McpgServerConfig)>> {
match self { $( $Enum::$Variant(e) => e.mcpg_servers(ctx), )+ }
}
fn allowed_copilot_tools(&self) -> Vec<String> {
match self { $( $Enum::$Variant(e) => e.allowed_copilot_tools(), )+ }
}
fn validate(&self, ctx: &CompileContext) -> Result<Vec<String>> {
match self { $( $Enum::$Variant(e) => e.validate(ctx), )+ }
}
fn required_pipeline_vars(&self) -> Vec<PipelineEnvMapping> {
match self { $( $Enum::$Variant(e) => e.required_pipeline_vars(), )+ }
}
fn required_awf_mounts(&self) -> Vec<AwfMount> {
match self { $( $Enum::$Variant(e) => e.required_awf_mounts(), )+ }
}
fn awf_path_prepends(&self) -> Vec<String> {
match self { $( $Enum::$Variant(e) => e.awf_path_prepends(), )+ }
}
fn agent_env_vars(&self) -> Vec<(String, String)> {
match self { $( $Enum::$Variant(e) => e.agent_env_vars(), )+ }
}
}
};
}
mod github;
mod safe_outputs;
pub(crate) mod trigger_filters;
// Re-export tool/runtime extensions from their colocated homes
pub use crate::tools::azure_devops::AzureDevOpsExtension;
pub use crate::tools::cache_memory::CacheMemoryExtension;
pub use github::GitHubExtension;
pub use crate::runtimes::lean::LeanExtension;
pub use crate::runtimes::node::NodeExtension;
pub use crate::runtimes::python::PythonExtension;
pub use safe_outputs::SafeOutputsExtension;
pub use trigger_filters::TriggerFiltersExtension;
extension_enum! {
/// All known compiler extensions, collected via [`collect_extensions`].
///
/// Uses static dispatch (no `Box<dyn>`) — each variant delegates to
/// the inner type's [`CompilerExtension`] implementation.
pub enum Extension {
GitHub(GitHubExtension),
SafeOutputs(SafeOutputsExtension),
Lean(LeanExtension),
Python(PythonExtension),
Node(NodeExtension),
AzureDevOps(AzureDevOpsExtension),
CacheMemory(CacheMemoryExtension),
TriggerFilters(TriggerFiltersExtension),
}
}
// ──────────────────────────────────────────────────────────────────────
// Collection
// ──────────────────────────────────────────────────────────────────────
/// Collect all enabled compiler extensions from front matter.
///
/// ## Ordering policy
///
/// Extensions are sorted by [`ExtensionPhase`] before being returned:
/// runtimes run before tools. This guarantees that runtime install steps
/// execute before tool steps — critical when a tool depends on a runtime
/// (e.g., a Python-based tool like `uv` needs the Python runtime first).
///
/// Within the same phase, extensions preserve definition order
/// (runtimes in `RuntimesConfig` field order, tools in `ToolsConfig`
/// field order).
pub fn collect_extensions(front_matter: &FrontMatter) -> Vec<Extension> {
let mut extensions = Vec::new();
// ── Always-on internal extensions ──
extensions.push(Extension::GitHub(GitHubExtension));
extensions.push(Extension::SafeOutputs(SafeOutputsExtension));
// ── Runtimes (ExtensionPhase::Runtime) ──
if let Some(lean) = front_matter.runtimes.as_ref().and_then(|r| r.lean.as_ref()) {
if lean.is_enabled() {
extensions.push(Extension::Lean(LeanExtension::new(lean.clone())));
}
}
if let Some(python) = front_matter.runtimes.as_ref().and_then(|r| r.python.as_ref()) {
if python.is_enabled() {
extensions.push(Extension::Python(PythonExtension::new(python.clone())));
}
}
if let Some(node) = front_matter.runtimes.as_ref().and_then(|r| r.node.as_ref()) {
if node.is_enabled() {
extensions.push(Extension::Node(NodeExtension::new(node.clone())));
}
}
// ── First-party tools (ExtensionPhase::Tool) ──
if let Some(tools) = front_matter.tools.as_ref() {
if let Some(ado) = tools.azure_devops.as_ref() {
if ado.is_enabled() {
extensions.push(Extension::AzureDevOps(
AzureDevOpsExtension::new(ado.clone()),
));
}
}
if let Some(memory) = tools.cache_memory.as_ref() {
if memory.is_enabled() {
extensions.push(Extension::CacheMemory(CacheMemoryExtension::new(
memory.clone(),
)));
}
}
}
// ── Trigger filters (ExtensionPhase::Tool) ──
// Activated when Tier 2/3 filters require the Python evaluator.
let pr_filters = front_matter.pr_filters().cloned();
let pipeline_filters = front_matter.pipeline_filters().cloned();
if TriggerFiltersExtension::is_needed(
pr_filters.as_ref(),
pipeline_filters.as_ref(),
) {
extensions.push(Extension::TriggerFilters(TriggerFiltersExtension::new(
pr_filters,
pipeline_filters,
)));
}
// Enforce phase ordering: runtimes before tools.
// sort_by_key is stable, preserving definition order within the same phase.
extensions.sort_by_key(|ext| ext.phase());
extensions
}
/// Wrap prompt supplement content in a `cat >>` pipeline step.
///
/// This is the generic wrapper used by the compiler to append extension
/// prompt supplements to the agent prompt file. Each line of content is
/// indented by 4 spaces to match the YAML block scalar indentation.
///
/// Returns an error if `display_name` contains characters unsafe for
/// embedding in bash `echo` or YAML `displayName` fields.
pub fn wrap_prompt_append(content: &str, display_name: &str) -> Result<String> {
// Reject names that would break bash echo or YAML displayName.
// This is a runtime guard (not debug_assert) because wrap_prompt_append
// is pub and callable from future extension implementations.
anyhow::ensure!(
display_name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_')),
"Extension display_name '{}' contains characters unsafe for bash/YAML embedding. \
Only ASCII alphanumerics, spaces, hyphens, and underscores are allowed.",
display_name
);
// Generate a unique heredoc delimiter from the display name
let delimiter = display_name
.to_uppercase()
.replace(' ', "_")
.replace(|c: char| !c.is_ascii_alphanumeric() && c != '_', "");
let delimiter = format!("{}_EOF", delimiter);
// Indent every line of content by 4 spaces to match the heredoc indentation
let indented_content: String = content
.trim()
.lines()
.map(|line| {
if line.is_empty() {
String::new()
} else {
format!(" {}", line)
}
})
.collect::<Vec<_>>()
.join("\n");
Ok(format!(
r#"- bash: |
cat >> "/tmp/awf-tools/agent-prompt.md" << '{delimiter}'
{indented_content}
{delimiter}
echo "{display_name} prompt appended"
displayName: "Append {display_name} prompt""#,
delimiter = delimiter,
indented_content = indented_content,
display_name = display_name,
))
}
#[cfg(test)]
mod tests;