Skip to main content

apm_core/
agents.rs

1use std::collections::HashMap;
2use std::path::Path;
3use anyhow::Result;
4use crate::wrapper::{self, Wrapper, WrapperContext, WrapperKind};
5use crate::wrapper::custom::CustomWrapper;
6use crate::config::Config;
7
8pub struct WrapperEntry {
9    pub name: String,
10    pub kind: WrapperKind,
11    pub parser: String,
12    pub configured_as: Vec<String>,
13}
14
15#[derive(Debug)]
16pub struct TestReport {
17    pub exit_code: i32,
18    pub canonical_events: usize,
19    pub non_canonical_lines: usize,
20    pub stderr_lines: usize,
21    pub wall_millis: u64,
22    pub passed: bool,
23}
24
25const MANIFEST_TEMPLATE: &str =
26    "[wrapper]\ncontract_version = 1\nparser = \"canonical\"\n";
27
28const WRAPPER_TEMPLATE: &str = r#"#!/usr/bin/env bash
29# APM wrapper skeleton
30#
31# Environment variables provided by APM:
32#   APM_AGENT_NAME          - name of this worker (from config)
33#   APM_TICKET_ID           - 8-char hex ticket ID
34#   APM_TICKET_BRANCH       - git branch for this ticket
35#   APM_TICKET_WORKTREE     - absolute path to the ticket worktree
36#   APM_SYSTEM_PROMPT_FILE  - path to a file containing the system prompt
37#   APM_USER_MESSAGE_FILE   - path to a file containing the user message (ticket content)
38#   APM_SKIP_PERMISSIONS    - "1" if --dangerously-skip-permissions should be passed; "0" otherwise
39#   APM_PROFILE             - active worker profile name
40#   APM_ROLE_PREFIX         - optional role label prepended to the worker identity
41#   APM_WRAPPER_VERSION     - contract version this APM build implements (currently "1")
42#   APM_BIN                 - absolute path to the running apm binary
43#   APM_OPT_*               - key-value options from [workers.options] in config.toml
44#
45# Contract:
46#   stdout  - emit JSONL events (one JSON object per line, each with a "type" key)
47#   stderr  - free-form log output (not parsed by APM)
48#   exit 0  - success; non-zero signals failure
49#
50set -euo pipefail
51
52# Dump all APM_* env vars to stderr for debugging
53env | grep '^APM_' >&2 || true
54
55# Read inputs
56SYSTEM_PROMPT="$(cat "$APM_SYSTEM_PROMPT_FILE")"
57USER_MESSAGE="$(cat "$APM_USER_MESSAGE_FILE")"
58
59# TODO: replace this printf with a real agent invocation that:
60#   1. Sends SYSTEM_PROMPT + USER_MESSAGE to your AI tool
61#   2. Emits JSONL events on stdout as the tool runs
62printf '{"type":"text","text":"wrapper skeleton -- replace with real invocation"}\n'
63
64# TODO: when the agent finishes, transition the ticket:
65#   apm state "$APM_TICKET_ID" <target-state>
66
67exit 0
68"#;
69
70const CLAUDE_EJECT_SCRIPT: &str = r#"#!/usr/bin/env bash
71# Ejected from APM built-in: claude
72set -euo pipefail
73
74ARGS=(--print --output-format stream-json --verbose)
75
76ARGS+=(--system-prompt "$(cat "$APM_SYSTEM_PROMPT_FILE")")
77
78if [[ -n "${APM_OPT_MODEL:-}" ]]; then
79    ARGS+=(--model "$APM_OPT_MODEL")
80fi
81
82if [[ "${APM_SKIP_PERMISSIONS:-0}" == "1" ]]; then
83    ARGS+=(--dangerously-skip-permissions)
84fi
85
86exec claude "${ARGS[@]}" "$(cat "$APM_USER_MESSAGE_FILE")"
87"#;
88
89const DEFAULT_WORKER_MD: &str = include_str!("default/agents/default/apm.worker.md");
90const DEFAULT_SPEC_WRITER_MD: &str = include_str!("default/agents/default/apm.spec-writer.md");
91
92pub fn list_wrappers(root: &Path, config: &Config) -> Result<Vec<WrapperEntry>> {
93    let mut entries: Vec<WrapperEntry> = Vec::new();
94
95    // Built-in entries
96    for name in wrapper::list_builtin_names() {
97        entries.push(WrapperEntry {
98            name: name.to_string(),
99            kind: WrapperKind::Builtin(name.to_string()),
100            parser: "canonical".to_string(),
101            configured_as: vec![],
102        });
103    }
104
105    // Project entries from .apm/agents/
106    let agents_dir = root.join(".apm").join("agents");
107    if agents_dir.is_dir() {
108        let rd = match std::fs::read_dir(&agents_dir) {
109            Ok(rd) => rd,
110            Err(_) => return Ok(entries),
111        };
112        let mut names: Vec<String> = rd
113            .filter_map(|e| e.ok())
114            .filter(|e| e.path().is_dir())
115            .filter_map(|e| e.file_name().into_string().ok())
116            .collect();
117        names.sort();
118
119        for entry_name in names {
120            if let Ok(Some(WrapperKind::Custom { script_path, manifest })) =
121                wrapper::resolve_wrapper(root, &entry_name)
122            {
123                let parser = manifest
124                    .as_ref()
125                    .map(|m| m.parser.clone())
126                    .unwrap_or_else(|| "canonical".to_string());
127                entries.push(WrapperEntry {
128                    name: entry_name,
129                    kind: WrapperKind::Custom { script_path, manifest },
130                    parser,
131                    configured_as: vec![],
132                });
133            }
134        }
135    }
136
137    // Configured marker: global [workers].agent plus per-profile [worker_profiles.*].agent.
138    let global_agent = config.workers.agent.as_deref().unwrap_or("claude").to_string();
139    for entry in &mut entries {
140        if entry.name == global_agent {
141            entry.configured_as.push("(configured)".to_string());
142        }
143        for (profile_name, profile) in &config.worker_profiles {
144            if let Some(ref agent) = profile.agent {
145                if entry.name == *agent {
146                    entry.configured_as.push(format!("({profile_name})"));
147                }
148            }
149        }
150    }
151
152    Ok(entries)
153}
154
155pub fn scaffold_wrapper(root: &Path, name: &str, force: bool) -> Result<()> {
156    let dir = root.join(".apm").join("agents").join(name);
157    if dir.exists() && !force {
158        anyhow::bail!(".apm/agents/{name}/ already exists; use --force to overwrite");
159    }
160    std::fs::create_dir_all(&dir)?;
161
162    // Write wrapper.sh
163    let wrapper_path = dir.join("wrapper.sh");
164    std::fs::write(&wrapper_path, WRAPPER_TEMPLATE)?;
165    #[cfg(unix)]
166    {
167        use std::os::unix::fs::PermissionsExt;
168        std::fs::set_permissions(&wrapper_path, std::fs::Permissions::from_mode(0o755))?;
169    }
170
171    // Write manifest.toml
172    std::fs::write(dir.join("manifest.toml"), MANIFEST_TEMPLATE)?;
173
174    // Write apm.worker.md
175    let worker_md = std::fs::read_to_string(root.join(".apm").join("apm.worker.md"))
176        .unwrap_or_else(|_| DEFAULT_WORKER_MD.to_string());
177    std::fs::write(dir.join("apm.worker.md"), &worker_md)?;
178
179    // Write apm.spec-writer.md
180    let spec_writer_md =
181        std::fs::read_to_string(root.join(".apm").join("apm.spec-writer.md"))
182            .unwrap_or_else(|_| DEFAULT_SPEC_WRITER_MD.to_string());
183    std::fs::write(dir.join("apm.spec-writer.md"), &spec_writer_md)?;
184
185    Ok(())
186}
187
188pub fn test_wrapper(root: &Path, name: &str) -> Result<TestReport> {
189    let kind = wrapper::resolve_wrapper(root, name)?.ok_or_else(|| {
190        anyhow::anyhow!(
191            "agent '{}' not found: checked built-ins and .apm/agents/{}/",
192            name,
193            name
194        )
195    })?;
196
197    let tmp_dir = tempfile::tempdir()?;
198    let tmp = tmp_dir.path().to_path_buf();
199
200    let sys_file = tmp.join("system.txt");
201    let msg_file = tmp.join("message.txt");
202    let log_path = tmp.join("wrapper.log");
203
204    std::fs::write(&sys_file, "You are a test agent.")?;
205    std::fs::write(&msg_file, "Test run -- apm agents test.")?;
206
207    let ctx = WrapperContext {
208        worker_name: "agents-test".to_string(),
209        agent_type: name.to_string(),
210        ticket_id: "00000000".to_string(),
211        ticket_branch: "test/agents-test".to_string(),
212        worktree_path: tmp.clone(),
213        system_prompt_file: sys_file,
214        user_message_file: msg_file,
215        skip_permissions: false,
216        profile: "test".to_string(),
217        role_prefix: None,
218        options: HashMap::new(),
219        model: None,
220        log_path: log_path.clone(),
221        container: None,
222        extra_env: HashMap::new(),
223        root: root.to_path_buf(),
224        keychain: HashMap::new(),
225        current_state: "test".to_string(),
226            command: None,
227    };
228
229    let start = std::time::Instant::now();
230    let mut child = match kind {
231        WrapperKind::Custom { script_path, manifest } => {
232            CustomWrapper { script_path, manifest }.spawn(&ctx)?
233        }
234        WrapperKind::Builtin(n) => {
235            wrapper::resolve_builtin(&n)
236                .expect("registered builtin")
237                .spawn(&ctx)?
238        }
239    };
240
241    let status = child.wait()?;
242    let wall_millis = start.elapsed().as_millis() as u64;
243    let exit_code = status.code().unwrap_or(-1);
244
245    // Classify log lines
246    let log_content = std::fs::read_to_string(&log_path).unwrap_or_default();
247    let mut canonical_events = 0usize;
248    let mut non_canonical_lines = 0usize;
249    let mut stderr_lines = 0usize;
250
251    for line in log_content.lines() {
252        if line.is_empty() {
253            continue;
254        }
255        if line.starts_with("APM_") {
256            stderr_lines += 1;
257        } else if let Ok(val) = serde_json::from_str::<serde_json::Value>(line) {
258            if val.get("type").is_some() {
259                canonical_events += 1;
260            } else {
261                non_canonical_lines += 1;
262            }
263        } else {
264            non_canonical_lines += 1;
265        }
266    }
267
268    let passed = status.success() && canonical_events >= 1;
269    let report = TestReport {
270        exit_code,
271        canonical_events,
272        non_canonical_lines,
273        stderr_lines,
274        wall_millis,
275        passed,
276    };
277
278    Ok(report)
279}
280
281pub fn eject_wrapper(root: &Path, name: &str) -> Result<()> {
282    if wrapper::resolve_builtin(name).is_none() {
283        anyhow::bail!(
284            "'{}' is not a known built-in; run apm agents list to see available wrappers",
285            name
286        );
287    }
288
289    let dir = root.join(".apm").join("agents").join(name);
290    if dir.exists() {
291        anyhow::bail!(".apm/agents/{name}/ already exists; delete it first to eject again");
292    }
293
294    std::fs::create_dir_all(&dir)?;
295
296    let script_content = match name {
297        "claude" => CLAUDE_EJECT_SCRIPT,
298        other => anyhow::bail!("eject not yet implemented for built-in {}", other),
299    };
300    let script_path = dir.join("wrapper.sh");
301    std::fs::write(&script_path, script_content)?;
302    #[cfg(unix)]
303    {
304        use std::os::unix::fs::PermissionsExt;
305        std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755))?;
306    }
307
308    // Write manifest.toml — intentionally the same template as scaffold_wrapper:
309    // recognised as v1-canonical by 2c32a282's manifest parser and 2e772eab's version check,
310    // so the ejected script requires no extra setup.
311    std::fs::write(dir.join("manifest.toml"), MANIFEST_TEMPLATE)?;
312
313    Ok(())
314}