1mod child_runtime;
10mod policy_prompt;
11mod profile_hash;
12mod project_capabilities;
13mod project_rules;
14mod runtime;
15mod search_tools;
16mod subagent_roles;
17mod workflow_commands;
18mod workspace;
19mod worktree;
20
21#[cfg(test)]
22mod tests;
23
24pub use policy_prompt::{
25 CODING_AGENT_POLICY_PROMPT, builtin_subagent_role_instructions, coding_subagent_policy_prompt,
26};
27pub use profile_hash::CodingAgentProfileHash;
28pub use project_rules::{
29 MAX_ROOT_PROJECT_RULES_BYTES, ProjectRulesLoadError, ROOT_PROJECT_RULES_FILE,
30 load_root_project_rules,
31};
32pub use runtime::{
33 CodingAutoFallback, CodingModelRoleConfig, CodingModelRoleConfigError, CodingPermissionMode,
34 CodingPermissionPolicy, CodingPermissionPolicyError, CodingRuntime, CodingRuntimeBuildError,
35 CodingRuntimeBuilder, CodingRuntimeInput, CodingSubagentsConfig,
36};
37pub use subagent_roles::{
38 MAX_ROLE_PROMPT_FILE_BYTES, ResolvedSubagentRuntime, SubagentDefaultOverride,
39 SubagentModelOverride, SubagentResolutionInput, SubagentRoleCatalog, SubagentRoleError,
40 SubagentRoleOverlay, SubagentRoleSpec, SubagentWorkspaceAccess, load_workspace_prompt_file,
41 resolve_subagent_runtime,
42};
43pub use workflow_commands::CodingWorkflowCommand;
44pub use worktree::{
45 WorktreeError, WorktreeGcReport, WorktreeIsolationManager, cleanup_orphaned_worktrees,
46 cleanup_orphaned_worktrees_default, default_worktree_base_dir,
47};
48
49use merry_core::{CoreError, HostPathPolicy, ToolName};
50use merry_llm::ModelRetryPolicy;
51use merry_process::ProcessSession;
52use merry_runtime::{
53 AgentLoopConfig, DurableMemory, PermissionAdmissionError, ProcessCommandToolError,
54 ProcessRunner, ProjectRules, PromptBlock, PromptError, PromptProfile, RegisteredTool,
55 RuntimeBuilder, RuntimeError, RuntimeProfile, RuntimeProfileError, SkillCatalog, TaskAnchor,
56 Tool, ToolBuildError,
57};
58pub use merry_tools::{
59 BrowserLaunchSpec, BrowserLauncherFuture, BrowserProcessHandle, BrowserProcessLauncher,
60 WorkspaceToolConfigError, WorkspaceToolLimits,
61};
62use serde_json::Error as JsonError;
63use std::{path::PathBuf, sync::Arc};
64use thiserror::Error;
65use workspace::{WorkspaceCodingProfileBuildError, WorkspaceCodingProfileBuilder};
66
67use profile_hash::coding_agent_profile_hash;
68
69pub const CODING_AGENT_PROFILE_ID: &str = "coding-agent-profile";
71
72pub const CODING_AGENT_STABLE_PREFIX_LAYOUT: &str =
74 "runtime-instructions|progress-commentary|skill-catalog|project-rules|tools";
75
76pub const CODING_AGENT_DYNAMIC_CONTEXT_LAYOUT: &str =
78 "checkpoint|task-anchor|plan-control|compiled-context|transcript|tool-results|user-input";
79
80pub const MIN_CODING_SUBAGENT_MODEL_TURNS: u32 = 1;
82
83pub const DEFAULT_CODING_SUBAGENT_MAX_MODEL_TURNS: u32 = 80;
85
86pub const DEFAULT_CODING_AGENT_MAX_MODEL_TURNS: usize = usize::MAX;
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
91pub enum CodingFinalReportPolicy {
92 EvidenceBackedSummary,
94}
95
96impl CodingFinalReportPolicy {
97 #[must_use]
99 pub const fn as_str(self) -> &'static str {
100 match self {
101 Self::EvidenceBackedSummary => "evidence_backed_summary",
102 }
103 }
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
108pub struct CodingAgentRunPolicy {
109 max_model_turns: usize,
110 final_report: CodingFinalReportPolicy,
111}
112
113impl CodingAgentRunPolicy {
114 pub fn new(
116 max_model_turns: usize,
117 final_report: CodingFinalReportPolicy,
118 ) -> Result<Self, CodingAgentRunPolicyError> {
119 if max_model_turns == 0 {
120 return Err(CodingAgentRunPolicyError::MaxModelTurnsMustBeNonZero);
121 }
122 Ok(Self {
123 max_model_turns,
124 final_report,
125 })
126 }
127
128 #[must_use]
130 pub const fn max_model_turns(self) -> usize {
131 self.max_model_turns
132 }
133
134 #[must_use]
136 pub const fn final_report(self) -> CodingFinalReportPolicy {
137 self.final_report
138 }
139
140 pub fn loop_config(self) -> Result<AgentLoopConfig, merry_runtime::AgentLoopConfigError> {
142 AgentLoopConfig::new(self.max_model_turns)
143 }
144}
145
146impl Default for CodingAgentRunPolicy {
147 fn default() -> Self {
148 Self {
149 max_model_turns: DEFAULT_CODING_AGENT_MAX_MODEL_TURNS,
150 final_report: CodingFinalReportPolicy::EvidenceBackedSummary,
151 }
152 }
153}
154
155#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
157pub enum CodingAgentRunPolicyError {
158 #[error("coding agent max_model_turns must be greater than zero")]
160 MaxModelTurnsMustBeNonZero,
161}
162
163pub fn coding_agent_loop_config() -> Result<AgentLoopConfig, merry_runtime::AgentLoopConfigError> {
165 CodingAgentRunPolicy::default().loop_config()
166}
167
168#[must_use]
170pub fn coding_agent(root: impl Into<PathBuf>) -> CodingAgentProfileBuilder {
171 CodingAgentProfileBuilder::new(root)
172}
173
174#[derive(Clone)]
181pub struct CodingAgentProfile {
182 runtime_profile: RuntimeProfile,
183 profile_hash: CodingAgentProfileHash,
184 run_policy: CodingAgentRunPolicy,
185}
186
187impl CodingAgentProfile {
188 #[must_use]
190 pub fn builder(root: impl Into<PathBuf>) -> CodingAgentProfileBuilder {
191 CodingAgentProfileBuilder::new(root)
192 }
193
194 pub fn apply_to(&self, builder: RuntimeBuilder) -> Result<RuntimeBuilder, RuntimeError> {
196 builder.with_profile(self.runtime_profile.clone())
197 }
198
199 pub fn loop_config(&self) -> Result<AgentLoopConfig, merry_runtime::AgentLoopConfigError> {
201 self.run_policy.loop_config()
202 }
203
204 #[must_use]
206 pub const fn run_policy(&self) -> CodingAgentRunPolicy {
207 self.run_policy
208 }
209
210 #[must_use]
212 pub fn runtime_profile(&self) -> RuntimeProfile {
213 self.runtime_profile.clone()
214 }
215
216 #[must_use]
218 pub fn registered_tools(&self) -> &[RegisteredTool] {
219 self.runtime_profile.registered_tools()
220 }
221
222 #[must_use]
224 pub fn tool_names(&self) -> Vec<&ToolName> {
225 self.registered_tools()
226 .iter()
227 .map(|tool| tool.spec().name())
228 .collect()
229 }
230
231 #[must_use]
233 pub fn profile_hash(&self) -> &CodingAgentProfileHash {
234 &self.profile_hash
235 }
236}
237
238#[derive(Clone)]
240pub struct CodingAgentProfileBuilder {
241 workspace: WorkspaceCodingProfileBuilder,
242 retry_policy: Option<ModelRetryPolicy>,
243 run_policy: CodingAgentRunPolicy,
244 allow_bridge_tools: bool,
245 skill_catalog: Option<SkillCatalog>,
246 project_rules: Option<ProjectRules>,
247 task_anchor: Option<TaskAnchor>,
248 prompt_profile_override: Option<PromptProfile>,
249 tools: Vec<Tool>,
250 registered_tools: Vec<RegisteredTool>,
251}
252
253impl CodingAgentProfileBuilder {
254 #[must_use]
256 pub fn new(root: impl Into<PathBuf>) -> Self {
257 Self {
258 workspace: WorkspaceCodingProfileBuilder::new(root),
259 retry_policy: None,
260 run_policy: CodingAgentRunPolicy::default(),
261 allow_bridge_tools: false,
262 skill_catalog: None,
263 project_rules: None,
264 task_anchor: None,
265 prompt_profile_override: None,
266 tools: Vec::new(),
267 registered_tools: Vec::new(),
268 }
269 }
270
271 #[must_use]
273 pub fn workspace_root(&self) -> &std::path::Path {
274 &self.workspace.root
275 }
276
277 #[must_use]
281 pub fn prompt_profile(mut self, prompt_profile: PromptProfile) -> Self {
282 self.prompt_profile_override = Some(prompt_profile);
283 self
284 }
285
286 #[must_use]
288 pub fn root(mut self, root: impl Into<PathBuf>) -> Self {
289 self.workspace = self.workspace.root(root);
290 self
291 }
292
293 #[must_use]
295 pub fn readonly_resource_roots<I, P>(mut self, roots: I) -> Self
296 where
297 I: IntoIterator<Item = P>,
298 P: Into<PathBuf>,
299 {
300 self.workspace = self.workspace.readonly_resource_roots(roots);
301 self
302 }
303
304 #[must_use]
306 pub fn limits(mut self, limits: WorkspaceToolLimits) -> Self {
307 self.workspace = self.workspace.limits(limits);
308 self
309 }
310
311 #[must_use]
313 pub fn patch_tool(mut self) -> Self {
314 self.workspace = self.workspace.patch_tool();
315 self
316 }
317
318 #[must_use]
320 pub fn web_tools(mut self) -> Self {
321 self.workspace = self.workspace.web_tools();
322 self
323 }
324
325 #[must_use]
327 pub fn read_scope<I, P>(mut self, paths: I) -> Self
328 where
329 I: IntoIterator<Item = P>,
330 P: Into<PathBuf>,
331 {
332 self.workspace = self.workspace.read_scope(paths);
333 self
334 }
335
336 #[must_use]
338 pub fn patch_write_scope<I, P>(mut self, paths: I) -> Self
339 where
340 I: IntoIterator<Item = P>,
341 P: Into<PathBuf>,
342 {
343 self.workspace = self.workspace.patch_write_scope(paths);
344 self
345 }
346
347 #[must_use]
349 pub fn read_only_patch_scope(mut self) -> Self {
350 self.workspace = self.workspace.read_only_patch_scope();
351 self
352 }
353
354 #[must_use]
356 pub fn forbidden_paths<I, P>(mut self, paths: I) -> Self
357 where
358 I: IntoIterator<Item = P>,
359 P: Into<PathBuf>,
360 {
361 self.workspace = self.workspace.forbidden_paths(paths);
362 self
363 }
364
365 #[must_use]
368 pub fn host_path_policy(mut self, policy: HostPathPolicy) -> Self {
369 self.workspace = self.workspace.host_path_policy(policy);
370 self
371 }
372
373 #[must_use]
375 pub fn read_only_process_runner(mut self, runner: Arc<dyn ProcessRunner>) -> Self {
376 self.workspace = self.workspace.read_only_process_runner(runner);
377 self
378 }
379
380 pub(crate) fn read_only_process_session(mut self, session: ProcessSession) -> Self {
384 self.workspace = self.workspace.read_only_process_session(session);
385 self
386 }
387
388 #[must_use]
390 pub fn accepted_process_session(mut self, session: ProcessSession) -> Self {
391 self.workspace = self.workspace.accepted_process_session(session);
392 self
393 }
394
395 #[must_use]
399 pub fn browser_process_launcher(mut self, launcher: Arc<dyn BrowserProcessLauncher>) -> Self {
400 self.workspace = self.workspace.browser_process_launcher(launcher);
401 self
402 }
403
404 #[must_use]
406 pub fn retry_policy(mut self, retry_policy: ModelRetryPolicy) -> Self {
407 self.retry_policy = Some(retry_policy);
408 self
409 }
410
411 #[must_use]
413 pub fn run_policy(mut self, run_policy: CodingAgentRunPolicy) -> Self {
414 self.run_policy = run_policy;
415 self
416 }
417
418 #[doc(hidden)]
420 #[must_use]
421 pub fn allow_bridge_tools(mut self) -> Self {
422 self.allow_bridge_tools = true;
423 self
424 }
425
426 #[must_use]
428 pub fn project_rules(mut self, project_rules: ProjectRules) -> Self {
429 self.project_rules = Some(project_rules);
430 self
431 }
432
433 #[must_use]
435 pub fn skill_catalog(mut self, skill_catalog: SkillCatalog) -> Self {
436 self.skill_catalog = Some(skill_catalog);
437 self
438 }
439
440 #[must_use]
442 pub fn task_anchor(mut self, task_anchor: TaskAnchor) -> Self {
443 self.task_anchor = Some(task_anchor);
444 self
445 }
446
447 #[must_use]
449 pub fn tool(mut self, tool: Tool) -> Self {
450 self.tools.push(tool);
451 self
452 }
453
454 #[doc(hidden)]
456 #[must_use]
457 pub fn register_tool(mut self, tool: RegisteredTool) -> Self {
458 self.registered_tools.push(tool);
459 self
460 }
461
462 #[doc(hidden)]
464 #[must_use]
465 pub fn register_tools<I>(mut self, tools: I) -> Self
466 where
467 I: IntoIterator<Item = RegisteredTool>,
468 {
469 self.registered_tools.extend(tools);
470 self
471 }
472
473 #[must_use]
478 pub fn durable_memory(mut self, memory: Arc<DurableMemory>) -> Self {
479 self.workspace = self.workspace.durable_memory(memory);
480 self
481 }
482
483 #[must_use]
485 pub fn durable_memory_handle(&self) -> Option<Arc<DurableMemory>> {
486 self.workspace.durable_memory.clone()
487 }
488
489 pub fn build(self) -> Result<CodingAgentProfile, CodingAgentProfileBuildError> {
491 let Self {
492 workspace,
493 retry_policy,
494 run_policy,
495 allow_bridge_tools,
496 skill_catalog,
497 project_rules,
498 task_anchor,
499 prompt_profile_override,
500 tools,
501 registered_tools,
502 } = self;
503 let workspace_hash_material = workspace.hash_material();
504 let memory_instructions = workspace
505 .durable_memory
506 .as_deref()
507 .map(DurableMemory::instructions);
508 let mut prompt_profile = match prompt_profile_override {
509 Some(profile) => profile,
510 None => PromptProfile::default().with_stable_block(PromptBlock::new(
511 "merry_coding_policy",
512 CODING_AGENT_POLICY_PROMPT,
513 )?)?,
514 };
515 if let Some(instructions) = memory_instructions {
516 prompt_profile = prompt_profile
517 .with_stable_block(PromptBlock::new("merry_memory", instructions)?)?;
518 }
519 let mut builder = RuntimeProfile::builder().prompt_profile(prompt_profile);
520 builder = workspace
521 .apply_to_runtime_profile(builder)
522 .map_err(|error| match error {
523 WorkspaceCodingProfileBuildError::WorkspaceTools(source) => {
524 CodingAgentProfileBuildError::WorkspaceTools(source)
525 }
526 WorkspaceCodingProfileBuildError::ProcessTool(source) => {
527 CodingAgentProfileBuildError::ProcessTool(source)
528 }
529 WorkspaceCodingProfileBuildError::PermissionTool(source) => {
530 CodingAgentProfileBuildError::PermissionTool(source)
531 }
532 WorkspaceCodingProfileBuildError::Core(source) => {
533 CodingAgentProfileBuildError::Core(source)
534 }
535 WorkspaceCodingProfileBuildError::WebToolBuild(source) => {
536 CodingAgentProfileBuildError::WebToolBuild(source)
537 }
538 })?;
539 if allow_bridge_tools {
540 builder = builder.allow_bridge_tools();
541 }
542 if let Some(retry_policy) = retry_policy {
543 builder = builder.model_retry_policy(retry_policy);
544 }
545 if let Some(skill_catalog) = skill_catalog {
546 builder = builder.skill_catalog(skill_catalog);
547 }
548 if let Some(project_rules) = project_rules {
549 builder = builder.project_rules(project_rules);
550 }
551 if let Some(task_anchor) = task_anchor {
552 builder = builder.task_anchor(task_anchor);
553 }
554 for tool in tools {
555 builder = builder.register_tool(tool.into_registered_tool());
556 }
557 for tool in registered_tools {
558 builder = builder.register_tool(tool);
559 }
560 let runtime_profile = builder.build()?;
561 let profile_hash =
562 coding_agent_profile_hash(&runtime_profile, run_policy, &workspace_hash_material)?;
563 Ok(CodingAgentProfile {
564 runtime_profile,
565 profile_hash,
566 run_policy,
567 })
568 }
569}
570
571#[derive(Debug, Error)]
573pub enum CodingAgentProfileBuildError {
574 #[error(transparent)]
576 WorkspaceTools(#[from] WorkspaceToolConfigError),
577 #[error(transparent)]
579 ProcessTool(#[from] ProcessCommandToolError),
580 #[error(transparent)]
582 PermissionTool(#[from] PermissionAdmissionError),
583 #[error(transparent)]
585 Core(#[from] CoreError),
586 #[error(transparent)]
588 RuntimeProfile(#[from] RuntimeProfileError),
589 #[error("coding agent profile hash material could not be serialized: {0}")]
591 HashSerialization(#[from] JsonError),
592 #[error(transparent)]
594 Prompt(#[from] PromptError),
595 #[error(transparent)]
597 WebToolBuild(#[from] ToolBuildError),
598}
599
600pub const CODING_LOOP_PROCESS_TOOL: &str = "run_process";