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        ticket_id: "00000000".to_string(),
210        ticket_branch: "test/agents-test".to_string(),
211        worktree_path: tmp.clone(),
212        system_prompt_file: sys_file,
213        user_message_file: msg_file,
214        skip_permissions: false,
215        profile: "test".to_string(),
216        role_prefix: None,
217        options: HashMap::new(),
218        model: None,
219        log_path: log_path.clone(),
220        container: None,
221        extra_env: HashMap::new(),
222        root: root.to_path_buf(),
223        keychain: HashMap::new(),
224        current_state: "test".to_string(),
225            command: None,
226    };
227
228    let start = std::time::Instant::now();
229    let mut child = match kind {
230        WrapperKind::Custom { script_path, manifest } => {
231            CustomWrapper { script_path, manifest }.spawn(&ctx)?
232        }
233        WrapperKind::Builtin(n) => {
234            wrapper::resolve_builtin(&n)
235                .expect("registered builtin")
236                .spawn(&ctx)?
237        }
238    };
239
240    let status = child.wait()?;
241    let wall_millis = start.elapsed().as_millis() as u64;
242    let exit_code = status.code().unwrap_or(-1);
243
244    // Classify log lines
245    let log_content = std::fs::read_to_string(&log_path).unwrap_or_default();
246    let mut canonical_events = 0usize;
247    let mut non_canonical_lines = 0usize;
248    let mut stderr_lines = 0usize;
249
250    for line in log_content.lines() {
251        if line.is_empty() {
252            continue;
253        }
254        if line.starts_with("APM_") {
255            stderr_lines += 1;
256        } else if let Ok(val) = serde_json::from_str::<serde_json::Value>(line) {
257            if val.get("type").is_some() {
258                canonical_events += 1;
259            } else {
260                non_canonical_lines += 1;
261            }
262        } else {
263            non_canonical_lines += 1;
264        }
265    }
266
267    let passed = status.success() && canonical_events >= 1;
268    let report = TestReport {
269        exit_code,
270        canonical_events,
271        non_canonical_lines,
272        stderr_lines,
273        wall_millis,
274        passed,
275    };
276
277    Ok(report)
278}
279
280pub fn eject_wrapper(root: &Path, name: &str) -> Result<()> {
281    if wrapper::resolve_builtin(name).is_none() {
282        anyhow::bail!(
283            "'{}' is not a known built-in; run apm agents list to see available wrappers",
284            name
285        );
286    }
287
288    let dir = root.join(".apm").join("agents").join(name);
289    if dir.exists() {
290        anyhow::bail!(".apm/agents/{name}/ already exists; delete it first to eject again");
291    }
292
293    std::fs::create_dir_all(&dir)?;
294
295    let script_content = match name {
296        "claude" => CLAUDE_EJECT_SCRIPT,
297        other => anyhow::bail!("eject not yet implemented for built-in {}", other),
298    };
299    let script_path = dir.join("wrapper.sh");
300    std::fs::write(&script_path, script_content)?;
301    #[cfg(unix)]
302    {
303        use std::os::unix::fs::PermissionsExt;
304        std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o755))?;
305    }
306
307    // Write manifest.toml — intentionally the same template as scaffold_wrapper:
308    // recognised as v1-canonical by 2c32a282's manifest parser and 2e772eab's version check,
309    // so the ejected script requires no extra setup.
310    std::fs::write(dir.join("manifest.toml"), MANIFEST_TEMPLATE)?;
311
312    Ok(())
313}