Skip to main content

agentmux_srv/server/
memory_launch_cost.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `memory:launchcost`: what an agent's next launch delivers into its context,
5//! part by part, in estimated tokens (SPEC_MEMORY_PANE_TOKENS_2026_10_15.md
6//! §4.2). A dry run of the launch's own composition — the same functions,
7//! nothing written — so its total is the estimate of the startup file a launch
8//! writes, plus what Claude Code's SessionStart hook and CLI add.
9
10use std::collections::HashMap;
11use std::sync::Arc;
12
13use agentmux_common::tokens::{count_lines, estimate_tokens};
14
15use crate::backend::rpc::engine::WshRpcEngine;
16use crate::backend::rpc_types::{CommandMemoryLaunchCostData, LaunchCost, LaunchCostPart, COMMAND_MEMORY_LAUNCH_COST};
17use crate::backend::storage::store::Store;
18use crate::backend::storage::AgentDefinition;
19
20use super::AppState;
21
22/// The agent's content by type (`soul`, `agentmd`, `memory`, …), with Global
23/// Memory for its kind and its picked bundles put before its own `memory`, as
24/// the startup file carries them. Shared by the launch
25/// (`app_api::agent_open::write_agent_config_files`) and `memory:launchcost`.
26pub(crate) fn startup_content_map(mstore: &Store, id_store: &Store, agent: &AgentDefinition) -> HashMap<String, String> {
27    let mut content_map: HashMap<String, String> = mstore
28        .agent_content_get_all(&agent.id)
29        .unwrap_or_default()
30        .into_iter()
31        .map(|fc| (fc.content_type, fc.content))
32        .collect();
33    let startup_block = startup_block(mstore, id_store, agent);
34    if !startup_block.is_empty() {
35        content_map
36            .entry("memory".to_string())
37            .and_modify(|existing| *existing = format!("{startup_block}\n\n---\n\n{existing}"))
38            .or_insert(startup_block);
39    }
40    content_map
41}
42
43/// Global Memory (minus Operator Config for another agent kind), then the
44/// agent's picked bundles in list order (SPEC_RENAME_KNOWLEDGE_TO_MEMORY_2026_10_06.md §3.6).
45fn startup_block(mstore: &Store, id_store: &Store, agent: &AgentDefinition) -> String {
46    let global = global_bundles(id_store, agent);
47    crate::backend::storage::join_startup_blocks(
48        &crate::backend::storage::format_global_bundle_block(&global),
49        &crate::backend::storage::format_agent_bundle_block(&crate::backend::storage::agent_picked_bundles(
50            mstore, id_store, &agent.id,
51        )),
52    )
53}
54
55fn global_bundles(id_store: &Store, agent: &AgentDefinition) -> Vec<crate::backend::storage::store::Bundle> {
56    crate::backend::operator_config_seed::global_bundles_for_agent(id_store.bundle_list_global().unwrap_or_default(), &agent.agent_type)
57}
58
59/// Whether AgentMux's startup text reaches the agent by file. A user-owned
60/// file isn't overwritten; Claude still gets the text through an `@import` of
61/// `.claude/AGENTMUX_MEMORY.md`.
62fn delivered_by_file(has_startup_file: bool, is_claude: bool, on_disk: Option<&str>) -> bool {
63    has_startup_file && (is_claude || on_disk.is_none_or(crate::backend::agent_config::is_agentmux_managed_instructions))
64}
65
66fn part(kind: &str, id: Option<&str>, name: &str, text: &str, via: &str) -> LaunchCostPart {
67    LaunchCostPart {
68        kind: kind.to_string(),
69        id: id.map(str::to_string),
70        name: name.to_string(),
71        tokens_est: estimate_tokens(text),
72        size_bytes: text.len() as u64,
73        lines: count_lines(text),
74        via: via.to_string(),
75    }
76}
77
78/// `agent`'s launch cost. `startup_file_on_disk` is the agent's existing
79/// startup file, if any, to tell whether AgentMux owns it; `personal` is the
80/// agent's Personal Memory files `(filename, content)` (Claude only).
81pub(crate) fn launch_cost(
82    mstore: &Store,
83    id_store: &Store,
84    identity_store: &Store,
85    agent: &AgentDefinition,
86    startup_file_on_disk: Option<&str>,
87    personal: &[(String, String)],
88) -> LaunchCost {
89    let provider = crate::backend::providers::get_provider(&agent.provider);
90    let provider_id = provider.map_or(agent.provider.as_str(), |p| p.id);
91    let is_claude = provider_id == "claude";
92    let startup_file = provider.and_then(|p| p.startup_instructions_filename).map(str::to_string);
93    let delivered_by_file = delivered_by_file(startup_file.is_some(), is_claude, startup_file_on_disk);
94
95    let mut parts = Vec::new();
96    if startup_file.is_some() {
97        const VIA: &str = "startup_file";
98        for s in crate::backend::storage::global_bundle_sections(&global_bundles(id_store, agent)) {
99            let kind = if s.is_system { "operator_config" } else { "workspace_global" };
100            parts.push(part(kind, Some(&s.id), &s.name, &s.text, VIA));
101        }
102        for b in crate::backend::storage::agent_picked_bundles(mstore, id_store, &agent.id) {
103            let text = crate::backend::storage::format_agent_bundle_block(std::slice::from_ref(&b));
104            if !text.is_empty() {
105                parts.push(part("bundle", Some(&b.id), &b.name, &text, VIA));
106            }
107        }
108        let own: HashMap<String, String> = mstore
109            .agent_content_get_all(&agent.id)
110            .unwrap_or_default()
111            .into_iter()
112            .map(|fc| (fc.content_type, fc.content))
113            .collect();
114        for (key, kind, name) in [("soul", "soul", "Soul"), ("agentmd", "agentmd", "Agent instructions"), ("memory", "agent_memory", "Agent memory")] {
115            if let Some(text) = own.get(key).filter(|t| !t.trim().is_empty()) {
116                parts.push(part(kind, None, name, text, VIA));
117            }
118        }
119        let skills = mstore.effective_skills(identity_store, &agent.id);
120        let index = crate::backend::agent_config::skills_index_text(&skills, provider_id);
121        if !index.is_empty() {
122            parts.push(part("skills_index", None, "Skills index", &index, VIA));
123        }
124        // What the parts don't count — the `# Memory` heading, separators and
125        // template expansion — so the total is the file's own estimate.
126        let file = file_text(mstore, id_store, identity_store, agent, provider_id);
127        let file_tokens = estimate_tokens(&file);
128        let counted: u64 = parts.iter().map(|p| p.tokens_est).sum();
129        if file_tokens > counted {
130            parts.push(LaunchCostPart {
131                kind: "formatting".to_string(),
132                id: None,
133                name: "Headings and separators".to_string(),
134                tokens_est: file_tokens - counted,
135                size_bytes: 0,
136                lines: 0,
137                via: VIA.to_string(),
138            });
139        }
140    }
141    if is_claude {
142        // The SessionStart hook delivers every topic file; the CLI loads
143        // MEMORY.md itself.
144        for (name, text) in personal {
145            let via = if name == "MEMORY.md" { "cli" } else { "session_hook" };
146            parts.push(part("personal", None, name, text, via));
147        }
148    }
149    let total_tokens_est = parts.iter().map(|p| p.tokens_est).sum();
150    LaunchCost {
151        agent_id: agent.id.clone(),
152        provider: provider_id.to_string(),
153        startup_file,
154        delivered_by_file,
155        parts,
156        total_tokens_est,
157    }
158}
159
160/// The startup file a launch would write for `agent`.
161fn file_text(mstore: &Store, id_store: &Store, identity_store: &Store, agent: &AgentDefinition, provider_id: &str) -> String {
162    let content_map = startup_content_map(mstore, id_store, agent);
163    let skills = mstore.effective_skills(identity_store, &agent.id);
164    let work_dir = work_dir(agent);
165    let filename = crate::backend::providers::get_provider(provider_id).and_then(|p| p.startup_instructions_filename);
166    crate::backend::agent_config::build_config_files(&content_map, &skills, &agent.name, &agent.id, &agent.slug, &work_dir, provider_id)
167        .into_iter()
168        .find(|f| Some(f.filename.as_str()) == filename)
169        .map(|f| f.content)
170        .unwrap_or_default()
171}
172
173/// The folder the agent launches in, as `agent.open` picks it.
174fn work_dir(agent: &AgentDefinition) -> String {
175    if agent.working_directory.is_empty() {
176        crate::backend::storage::agents::default_agent_working_dir(&agent.name)
177    } else {
178        agent.working_directory.clone()
179    }
180}
181
182/// Reads `*.md` in the agent's Personal Memory folder, capped like every
183/// memory read.
184fn personal_files(mstore: &Store, agent: &AgentDefinition) -> Vec<(String, String)> {
185    use std::io::Read;
186    let Some(dir) = super::native_memory_handlers::memory_dir_for_agent_by_id(mstore, agent) else {
187        return Vec::new();
188    };
189    let Ok(entries) = std::fs::read_dir(&dir) else { return Vec::new() };
190    let mut files: Vec<(String, String)> = entries
191        .flatten()
192        .filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
193        .filter_map(|e| {
194            let name = e.file_name().to_string_lossy().into_owned();
195            if !name.ends_with(".md") {
196                return None;
197            }
198            let mut buf = Vec::new();
199            std::fs::File::open(e.path())
200                .and_then(|f| f.take(super::native_memory_handlers::MAX_MEMORY_FILE_BYTES).read_to_end(&mut buf))
201                .ok()?;
202            Some((name, String::from_utf8_lossy(&buf).into_owned()))
203        })
204        .collect();
205    files.sort();
206    files
207}
208
209pub(crate) fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
210    let mstore = state.mstore.clone();
211    let id_store = state.id_store.clone();
212    let identity_store = state.identity_store.clone();
213    engine.register_typed(COMMAND_MEMORY_LAUNCH_COST, move |cmd: CommandMemoryLaunchCostData, _ctx| {
214        let (mstore, id_store, identity_store) = (mstore.clone(), id_store.clone(), identity_store.clone());
215        async move {
216            let agents = mstore.agent_def_list().map_err(|e| format!("memory:launchcost: {e}"))?;
217            let agent = agents
218                .into_iter()
219                .find(|a| a.id == cmd.agent_id)
220                .ok_or_else(|| format!("memory:launchcost: no agent {}", cmd.agent_id))?;
221            let provider = crate::backend::providers::get_provider(&agent.provider);
222            let on_disk = provider
223                .and_then(|p| p.startup_instructions_filename)
224                .and_then(|f| std::fs::read_to_string(crate::backend::base::expand_home_dir_safe(&work_dir(&agent)).join(f)).ok());
225            let personal = if provider.is_some_and(|p| p.id == "claude") { personal_files(&mstore, &agent) } else { Vec::new() };
226            Ok::<LaunchCost, String>(launch_cost(&mstore, &id_store, &identity_store, &agent, on_disk.as_deref(), &personal))
227        }
228    });
229}
230
231#[cfg(test)]
232mod tests {
233    use super::delivered_by_file;
234
235    #[test]
236    fn a_user_owned_startup_file_stops_delivery_except_for_claude() {
237        let managed = "<!-- agentmux:managed-startup-instructions -->\n\n# Memory\n";
238        assert!(delivered_by_file(true, false, None), "no file yet: the launch writes it");
239        assert!(delivered_by_file(true, false, Some(managed)));
240        assert!(!delivered_by_file(true, false, Some("# My own AGENTS.md\n")));
241        assert!(delivered_by_file(true, true, Some("# My own CLAUDE.md\n")), "Claude: through @import");
242        assert!(!delivered_by_file(false, false, None), "no startup file (Kimi)");
243    }
244}