1use super::*;
2
3fn disable_mbx_cache_shims(
4 session_id: &str,
5 backend: &targets::TargetLocator,
6 worker_root: &str,
7 executor: &impl CommandExecutor,
8 reason: &str,
9) {
10 let cleanup = remove_generated_mbx_shims(executor, backend, worker_root);
11 if let Err(error) = &cleanup {
12 tracing::warn!(
13 session_id,
14 "could not remove marked shared-mbx launchers: {error:#}"
15 );
16 }
17 let cleanup_note = cleanup
18 .err()
19 .map(|error| format!(" Mjolnir could not remove its marked launchers: {error:#}."))
20 .unwrap_or_default();
21 tracing::warn!(
22 session_id,
23 "shared mbx is unavailable in this container: {reason}"
24 );
25 executor.notify_notice(&format!(
26 "The Rust build cache is unavailable in this container: {reason}.{cleanup_note} The session will start without it."
27 ));
28}
29
30fn build_cache_config_roots(launch: &WorkerLaunchConfig) -> Vec<PathBuf> {
31 [&launch.target_environment, &launch.environment]
32 .into_iter()
33 .filter_map(|environment| environment.get("XDG_CONFIG_HOME").map(PathBuf::from))
34 .collect::<std::collections::BTreeSet<_>>()
35 .into_iter()
36 .collect()
37}
38
39impl Controller {
40 pub(in crate::controller) fn worker_placement(
44 &self,
45 session_id: &str,
46 ) -> Result<(targets::TargetLocator, String)> {
47 let session = self
48 .state
49 .sessions
50 .get(session_id)
51 .with_context(|| format!("unknown session {session_id}"))?;
52 let locator = session
53 .target
54 .as_ref()
55 .context("session target is missing")?;
56 if let Some(owner) = crate::worker_lifecycle::current(session_id) {
57 owner.verify_target(locator)?;
58 }
59 let backend = backend_locator(locator, session, &self.config)?;
60 let worker_root = targets::worker_root(&backend, session_id)?;
61 Ok((backend, worker_root))
62 }
63
64 pub(in crate::controller) fn prepare_worker_files(
65 &self,
66 session_id: &str,
67 backend: &targets::TargetLocator,
68 worker_root: &str,
69 executor: &impl CommandExecutor,
70 ) -> Result<()> {
71 let owner = crate::worker_lifecycle::require(session_id)?;
72 let session = self
73 .state
74 .sessions
75 .get(session_id)
76 .with_context(|| format!("unknown session {session_id}"))?;
77 if let Some(target) = session.target.as_ref() {
78 owner.verify_target(target)?;
79 }
80 let profile = self
81 .config
82 .profiles
83 .get(&session.last_profile)
84 .context("session profile is missing")?;
85 profile.ensure_ready(&session.last_profile)?;
86 let (mut launch, project_memory, target_profile_home) =
87 self.session_launch_config(session_id, backend)?;
88
89 if session.native_session_id.is_some()
90 && profile.kind == mj_core::config::HarnessKind::Codex
91 {
92 launch.goal_resume_request = Some(mj_core::state::new_session_id()?);
93 }
94 let staging = tempfile::tempdir().context("create worker staging directory")?;
95 let launch_path = staging.path().join("launch.json");
96 launch.write(&launch_path)?;
97 let ownership_path = staging.path().join("ownership.json");
98 WorkerOwnership {
99 version: WorkerOwnership::VERSION,
100 workspace_id: session.workspace_id.clone(),
101 session_id: session_id.to_string(),
102 profile_id: session.last_profile.clone(),
103 bundle_id: session.bundle_id.clone(),
104 target_template_id: session.target_template_id.clone(),
105 instance_id: Some(mj_core::config::instance_identity()),
106 }
107 .write(&ownership_path)?;
108 let profile_stage = staging.path().join("profile");
112 let started = Instant::now();
113 let result = stage_profile(profile, &profile_stage);
114 tracing::debug!(
115 session_id,
116 elapsed_ms = started.elapsed().as_millis(),
117 "profile staging completed"
118 );
119 result?;
120 stage_managed_skills(
121 profile.kind,
122 &profile_stage,
123 session
124 .target
125 .as_ref()
126 .context("session target is missing")?
127 .skills_scope(),
128 )?;
129 stage_codex_catalog(
130 &session.last_profile,
131 profile,
132 &profile_stage,
133 &fetch_catalog_over_https,
134 &SharedCatalogCache,
135 )?;
136 append_hel_target_environment(profile.kind, &profile_stage, backend)?;
137 append_container_storage_guidance(
138 profile.kind,
139 &profile_stage,
140 backend,
141 session.container_workspace.as_deref(),
142 targets::has_managed_temporary_volume(backend, executor)?,
143 )?;
144 append_subagent_policy(
145 profile.kind,
146 &profile_stage,
147 &launch.subagents,
148 self.config.subagents.max_concurrent,
149 )?;
150 apply_staged_execution_setting(profile.kind, launch.execution_policy, &profile_stage)?;
151 if profile.kind == mj_core::config::HarnessKind::Claude {
152 if let Some(role) = launch.subagents.parent_role() {
153 configure_claude_subagent_mcp(&profile_stage, worker_root, role)?;
154 } else if launch.handback_tool {
155 configure_claude_subagent_mcp(
156 &profile_stage,
157 worker_root,
158 mj_core::subagent::SubagentMcpRole::Child,
159 )?;
160 }
161 }
162 stage_memory_replica(
163 &project_memory,
164 Path::new(&target_profile_home),
165 &profile_stage,
166 )?;
167 if project_memory.mcp_delivery == ProjectMemoryMcpDelivery::HarnessProfile {
168 configure_kimi_history_mcp(
169 &profile_stage,
170 worker_root,
171 project_memory.history_socket.as_deref(),
172 )?;
173 }
174 let worker_binary = worker_binary_for(backend, executor)?;
175
176 install_worker_files(
177 executor,
178 backend,
179 session_id,
180 worker_root,
181 &target_profile_home,
182 &worker_binary,
183 &launch_path,
184 &ownership_path,
185 &profile_stage,
186 )?;
187 if session.build_cache.is_some() {
188 self.install_build_cache_shim(session, backend, &launch, executor)
189 .context("install shared machine build cache configuration")?;
190 }
191 prepare_installed_managed_harness(executor, backend, worker_root, &launch)
192 }
193
194 pub(in crate::controller) fn install_build_cache_shim(
197 &self,
198 session: &mj_core::state::SessionRecord,
199 backend: &targets::TargetLocator,
200 launch: &WorkerLaunchConfig,
201 executor: &impl CommandExecutor,
202 ) -> Result<()> {
203 let Some(cache) = session.build_cache.as_ref() else {
204 return Ok(());
205 };
206 let worker_root = targets::worker_root(backend, &session.id)?;
207 let config_roots = build_cache_config_roots(launch);
208 let configuration = crate::controller::mbx::shared_configuration_file(&cache.directory);
209 if link_legacy_mbx_configuration(
210 executor,
211 backend,
212 &worker_root,
213 &configuration,
214 &config_roots,
215 )? {
216 return Ok(());
217 }
218 let binary = match crate::controller::mbx::sync_mbx_binary_for_container(
219 backend,
220 &cache.directory,
221 executor,
222 ) {
223 Ok(crate::controller::mbx::CachedMbxSync::Ready(binary)) => binary,
224 Ok(crate::controller::mbx::CachedMbxSync::Unavailable(reason)) => {
225 disable_mbx_cache_shims(&session.id, backend, &worker_root, executor, &reason);
226 return Ok(());
227 }
228 Err(error) => {
229 disable_mbx_cache_shims(
230 &session.id,
231 backend,
232 &worker_root,
233 executor,
234 &format!("{error:#}"),
235 );
236 return Ok(());
237 }
238 };
239 if let Err(error) = verify_mbx_binary(executor, backend, &binary.path, &binary.version) {
240 disable_mbx_cache_shims(
241 &session.id,
242 backend,
243 &worker_root,
244 executor,
245 &format!("{error:#}"),
246 );
247 return Ok(());
248 }
249 let (configuration, config_roots) =
250 self.build_cache_configuration(session, backend, launch, executor)?;
251 install_mbx_shims(
252 executor,
253 backend,
254 &worker_root,
255 &binary.path,
256 &configuration,
257 &config_roots,
258 )
259 }
260
261 pub(in crate::controller) fn prepare_build_cache_links(
262 &self,
263 session: &mj_core::state::SessionRecord,
264 backend: &targets::TargetLocator,
265 launch: &WorkerLaunchConfig,
266 executor: &impl CommandExecutor,
267 ) -> Result<()> {
268 self.install_build_cache_shim(session, backend, launch, executor)
269 }
270
271 fn build_cache_configuration(
272 &self,
273 session: &mj_core::state::SessionRecord,
274 backend: &targets::TargetLocator,
275 launch: &WorkerLaunchConfig,
276 executor: &impl CommandExecutor,
277 ) -> Result<(PathBuf, Vec<PathBuf>)> {
278 let configuration = crate::controller::mbx::prepare_session_configuration(
279 &self.config,
280 backend,
281 session
282 .build_cache
283 .as_ref()
284 .context("session has no build cache")?,
285 executor,
286 )?;
287 let config_roots = build_cache_config_roots(launch);
288 Ok((configuration, config_roots))
289 }
290
291 pub fn diagnose_worker(&self, session_id: &str) -> Option<String> {
295 self.diagnose_worker_controlled(session_id, &crate::targets::ProcessExecutor)
296 }
297
298 pub fn diagnose_worker_controlled(
299 &self,
300 session_id: &str,
301 executor: &impl CommandExecutor,
302 ) -> Option<String> {
303 let session = self.state.sessions.get(session_id)?;
304 let locator = session.target.as_ref()?;
305 let backend = match backend_locator(locator, session, &self.config) {
306 Ok(backend) => backend,
307 Err(error) => {
308 tracing::debug!(
309 session_id,
310 error = format!("{error:#}"),
311 "could not construct a worker diagnostic probe"
312 );
313 return None;
314 }
315 };
316 let worker_root = match targets::worker_root(&backend, session_id) {
317 Ok(root) => root,
318 Err(error) => {
319 tracing::debug!(
320 session_id,
321 error = format!("{error:#}"),
322 "could not derive the worker diagnostic root"
323 );
324 return None;
325 }
326 };
327 let binary_failure = worker_binary_probe_failure(executor, &backend, &worker_root);
328 let probe = match probe_worker(executor, &backend, &worker_root) {
329 Ok(probe) => probe.to_string(),
330 Err(error) => format!("the worker could not be probed: {error:#}"),
331 };
332 Some(match binary_failure {
333 Some(binary_failure) => format!("{binary_failure}; {probe}"),
334 None => probe,
335 })
336 }
337
338 pub fn worker_recovery_plan(
342 &self,
343 session_id: &str,
344 operation: Option<&mj_core::state::MoveOperation>,
345 ) -> Result<WorkerRecoveryPlan> {
346 let (backend, worker_root) = self.worker_placement(session_id)?;
347 let launch = self.worker_launch_config_for_move(session_id, &backend, operation)?;
348 let workspace = worker_workspace_for_recovery(&backend, &launch.cwd);
349 Ok(WorkerRecoveryPlan {
350 source_target: self.state.sessions[session_id]
351 .target
352 .clone()
353 .context("session target is missing")?,
354 target: targets::target_recovery_plan(&backend, session_id)?,
355 workspace,
356 liveness_probe: worker_liveness_command(&backend, &worker_root),
357 exit_record: Some(worker_exit_record_command(&backend, &worker_root)),
358 binary_refresh: worker_binary_refresh_plan(&backend, session_id)?,
359 launch_refresh: Some(worker_launch_refresh_plan(&backend, session_id, &launch)?),
360 restart: CommandPlan {
361 description: format!("restart Mjolnir worker for session {session_id}"),
362 commands: vec![
363 stop_worker_command(&backend, &worker_root),
364 start_worker_command(&backend, &worker_root),
365 ],
366 },
367 })
368 }
369
370 fn session_launch_config(
375 &self,
376 session_id: &str,
377 backend: &targets::TargetLocator,
378 ) -> Result<(WorkerLaunchConfig, ProjectMemoryLaunchConfig, String)> {
379 let session = self
380 .state
381 .sessions
382 .get(session_id)
383 .with_context(|| format!("unknown session {session_id}"))?;
384 session.validate_configuration(&self.config)?;
385 let profile = self
386 .config
387 .profiles
388 .get(&session.last_profile)
389 .context("session profile is missing")?;
390 let bundle = session
391 .project_directory
392 .is_none()
393 .then(|| session.project_bundle(&self.config))
394 .flatten();
395 let target = session.target_runtime_settings(&self.config)?;
396 let subagent = self.state.subagents.get(session_id);
397 let (workspace_session_id, workspace_container) = match subagent.as_ref() {
400 Some(child) => {
401 let parent = self
402 .state
403 .sessions
404 .get(&child.parent_session_id)
405 .context("sub-agent parent session is missing")?;
406 (parent.id.clone(), parent.container_workspace.clone())
407 }
408 None => (session_id.to_owned(), session.container_workspace.clone()),
409 };
410 let (mut launch, project_memory, target_profile_home) = worker_launch_config(
411 session,
412 profile,
413 bundle,
414 backend,
415 LaunchWorkspace {
416 session_id: &workspace_session_id,
417 container: workspace_container.as_deref(),
418 parent_worktree: self.subagent_parent_worktree(session_id),
419 },
420 &target,
421 )?;
422 apply_jev_switch(&mut launch, self.config.jev.enabled);
423 apply_continuation_switch(&mut launch, self.config.automatic_continuation_enabled());
424 launch.subagents = session
425 .subagents
426 .clone()
427 .unwrap_or_default()
428 .for_launch(profile.kind, subagent.is_some());
429 launch.handback_tool = subagent.as_ref().is_some_and(|child| child.handback_tool);
431 launch.initial_model = subagent.as_ref().and_then(|child| child.model.clone());
434 launch.review_capture =
440 mj_core::review::settings::can_review(&self.config) && subagent.is_none();
441 if let Some(subagent) = &subagent {
442 let parent = self
443 .state
444 .sessions
445 .get(&subagent.parent_session_id)
446 .context("sub-agent parent session is missing")?;
447 let parent_profile = self
448 .config
449 .profiles
450 .get(&parent.last_profile)
451 .context("sub-agent parent profile is missing")?;
452 let parent_target = parent.target_runtime_settings(&self.config)?;
453 let parent_locator = parent
454 .target
455 .as_ref()
456 .context("sub-agent parent has no live target")?;
457 let parent_backend = backend_locator(parent_locator, parent, &self.config)?;
458 let parent_bundle = parent
459 .project_directory
460 .is_none()
461 .then(|| parent.project_bundle(&self.config))
462 .flatten();
463 let (parent_launch, _, _) = worker_launch_config(
464 parent,
465 parent_profile,
466 parent_bundle,
467 &parent_backend,
468 LaunchWorkspace {
469 session_id: &parent.id,
470 container: parent.container_workspace.as_deref(),
471 parent_worktree: None,
472 },
473 &parent_target,
474 )?;
475 launch.cwd = if subagent.working_directory.as_os_str().is_empty() {
476 parent_launch.cwd
477 } else {
478 parent_launch.cwd.join(&subagent.working_directory)
479 };
480 launch.additional_directories = parent_launch.additional_directories;
481 }
482 Ok((launch, project_memory, target_profile_home))
483 }
484
485 pub(in crate::controller) fn current_worker_launch_config(
486 &self,
487 session_id: &str,
488 backend: &targets::TargetLocator,
489 ) -> Result<WorkerLaunchConfig> {
490 let operation = crate::database::load_move_operation(session_id)?;
491 self.worker_launch_config_for_move(session_id, backend, operation.as_ref())
492 }
493
494 fn worker_launch_config_for_move(
495 &self,
496 session_id: &str,
497 backend: &targets::TargetLocator,
498 operation: Option<&mj_core::state::MoveOperation>,
499 ) -> Result<WorkerLaunchConfig> {
500 let session = self
501 .state
502 .sessions
503 .get(session_id)
504 .with_context(|| format!("unknown session {session_id}"))?;
505 let (mut launch, _, _) = self.session_launch_config(session_id, backend)?;
506 if operation.is_some_and(|operation| {
507 operation.source_checkpoint_only
508 && operation.destination_target.is_none()
509 && matches!(
510 operation.phase,
511 mj_core::state::MovePhase::Preparing
512 | mj_core::state::MovePhase::ClosingSource
513 | mj_core::state::MovePhase::Failed
514 | mj_core::state::MovePhase::Cancelled
515 )
516 && session.last_profile == operation.source_profile_id
517 && session.target == operation.source_target
518 && matches!(
519 session.state,
520 mj_core::state::SessionState::Running
521 | mj_core::state::SessionState::Disconnected
522 | mj_core::state::SessionState::Closing
523 )
524 }) {
525 launch.run_mode = mj_core::worker_launch::WorkerRunMode::CheckpointOnly;
526 }
527 Ok(launch)
528 }
529
530 pub fn project_memory_sync_target(&self, session_id: &str) -> Result<ProjectMemorySyncTarget> {
531 let session = self
532 .state
533 .sessions
534 .get(session_id)
535 .with_context(|| format!("unknown session {session_id}"))?;
536 session.validate_configuration(&self.config)?;
537 let locator = session
538 .target
539 .as_ref()
540 .context("session target is missing")?;
541 let backend = backend_locator(locator, session, &self.config)?;
542 let profile = self
543 .config
544 .profiles
545 .get(&session.last_profile)
546 .context("session profile is missing")?;
547 let bundle = session
548 .project_directory
549 .is_none()
550 .then(|| session.project_bundle(&self.config))
551 .flatten();
552 let workspace = if let Some(project_directory) = &session.project_directory {
553 (project_directory.to_string_lossy().into_owned(), Vec::new())
554 } else {
555 workspace_paths(
556 &backend,
557 bundle.context("session bundle is missing")?,
558 session_id,
559 session.container_workspace.as_deref(),
560 )?
561 };
562 let target_home = target_profile_home(&backend, session_id, profile);
563 let launch = project_memory_launch(
564 session,
565 bundle,
566 &workspace,
567 &target_home,
568 self.subagent_parent_worktree(session_id),
569 )?;
570 Ok(ProjectMemorySyncTarget {
571 canonical_root: canonical_memory_root(&launch.project_key),
572 })
573 }
574}
575
576pub(super) fn apply_jev_switch(launch: &mut WorkerLaunchConfig, enabled: bool) {
580 if enabled {
581 return;
582 }
583 for environment in [&mut launch.target_environment, &mut launch.environment] {
584 environment.remove("TYPESAFE_API_KEY");
585 environment.insert(
586 mj_core::jev::DISABLED_ENVIRONMENT.to_owned(),
587 "1".to_owned(),
588 );
589 }
590}
591
592pub(super) fn apply_continuation_switch(launch: &mut WorkerLaunchConfig, enabled: bool) {
595 if enabled {
596 return;
597 }
598 for environment in [&mut launch.target_environment, &mut launch.environment] {
599 environment.insert(
600 mj_core::jev::CONTINUATION_DISABLED_ENVIRONMENT.to_owned(),
601 "1".to_owned(),
602 );
603 }
604}
605
606#[cfg(test)]
613pub(super) fn subagent_tools_enabled(
614 session: &mj_core::state::SessionRecord,
615 is_child: bool,
616) -> bool {
617 session
618 .subagents
619 .clone()
620 .unwrap_or_default()
621 .for_launch(session.harness_kind, is_child)
622 .uses_mjolnir()
623}
624
625pub(super) fn worker_workspace_for_recovery(
626 backend: &targets::TargetLocator,
627 directory: &Path,
628) -> Option<WorkerWorkspace> {
629 let target = match backend {
630 targets::TargetLocator::LocalBare { .. } => mj_core::state::ManagedWorktreeTarget::Local,
631 targets::TargetLocator::SshBare { ssh, .. } => mj_core::state::ManagedWorktreeTarget::Ssh {
632 destination: ssh.destination.clone(),
633 ssh_args: ssh.ssh_args.clone(),
634 },
635 targets::TargetLocator::LocalPodman { .. }
636 | targets::TargetLocator::LocalDocker { .. }
637 | targets::TargetLocator::AppleContainer { .. }
638 | targets::TargetLocator::AwsEc2 { .. }
639 | targets::TargetLocator::SshPodman { .. }
640 | targets::TargetLocator::SshDocker { .. } => return None,
641 };
642 Some(WorkerWorkspace {
643 target,
644 directory: directory.to_path_buf(),
645 })
646}
647
648pub(super) struct LaunchWorkspace<'a> {
649 pub session_id: &'a str,
650 pub container: Option<&'a Path>,
651 pub parent_worktree: Option<&'a mj_core::state::ManagedWorktree>,
652}
653
654pub(super) fn worker_launch_config(
655 session: &mj_core::state::SessionRecord,
656 profile: &mj_core::config::HarnessProfile,
657 bundle: Option<&ProjectBundle>,
658 backend: &targets::TargetLocator,
659 worker_workspace: LaunchWorkspace<'_>,
660 target: &mj_core::state::TargetRuntimeSettings,
661) -> Result<(WorkerLaunchConfig, ProjectMemoryLaunchConfig, String)> {
662 let session_id = session.id.as_str();
663 let execution_policy = target.execution_policy;
664 let target_profile_home = target_profile_home(backend, session_id, profile);
665 let workspace = if let Some(project_directory) = &session.project_directory {
666 (project_directory.to_string_lossy().into_owned(), Vec::new())
667 } else {
668 workspace_paths(
669 backend,
670 bundle.context("session bundle is missing")?,
671 worker_workspace.session_id,
672 worker_workspace.container,
673 )?
674 };
675 let mut additional_directories = workspace.1.iter().map(PathBuf::from).collect::<Vec<_>>();
676 additional_directories.extend(
677 session
678 .additional_mounts
679 .iter()
680 .map(|resource| resource.destination.clone()),
681 );
682 if profile.kind == mj_core::config::HarnessKind::Muse && !additional_directories.is_empty() {
683 bail!(
684 "{} ACP does not support multiple workspace roots; use a single-repository bundle",
685 profile.kind.display_name()
686 );
687 }
688 let (bridge_command, bridge_args) = bridge_launch(profile.kind, execution_policy);
689 let mut target_environment = target.environment.clone();
690 let podman_container = backend.container_engine() == Some("podman");
691 if podman_container {
692 target_environment.insert(
696 mj_core::worker_launch::SESSION_GIT_CONFIG_INCLUDE_PATH.into(),
697 "/home/hel/.gitconfig".into(),
698 );
699 }
700 for name in [
710 "MJ_TURN_STALL_TIMEOUT_MS",
711 "MJ_TURN_TOOL_STALL_TIMEOUT_MS",
712 "RUST_LOG",
713 ] {
714 if let Ok(value) = std::env::var(name) {
715 target_environment.insert(name.to_owned(), value);
716 }
717 }
718 if let Some(key) = mj_core::activity::verdict::api_key() {
721 target_environment.insert("TYPESAFE_API_KEY".to_owned(), key);
722 }
723 if let Some(build_cache) = &session.build_cache {
726 target_environment.insert(
727 "MBX_CACHE_DIR".into(),
728 build_cache.directory.to_string_lossy().into_owned(),
729 );
730 target_environment.insert(
731 "MJ_MBX_CONFIG_DIR".into(),
732 mj_core::config::build_cache_configuration_directory(&build_cache.directory)
733 .to_string_lossy()
734 .into_owned(),
735 );
736 target_environment.insert(
739 "MBX_SHIMS_DIR".into(),
740 Path::new(&targets::worker_root(backend, session_id)?)
741 .join("mbx-shims")
742 .to_string_lossy()
743 .into_owned(),
744 );
745 target_environment.insert("MBX_SUMMARY".into(), "off".into());
748 target_environment.insert("MBX_SAVINGS".into(), "off".into());
749 }
750 let mut environment = target_environment.clone();
751 environment.extend(profile.environment.resolved().clone());
752 if session
753 .target
754 .as_ref()
755 .is_some_and(|target| target.skills_scope() == mj_core::skills::SkillsScope::Localhost)
756 {
757 environment.insert(
760 "MJ_CONFIG_DIR".into(),
761 std::path::absolute(mj_core::config::config_dir())
762 .context("resolve host Mjolnir configuration directory")?
763 .to_string_lossy()
764 .into_owned(),
765 );
766 environment.insert(
767 "MJ_DATA_DIR".into(),
768 std::path::absolute(data_dir())
769 .context("resolve host Mjolnir data directory")?
770 .to_string_lossy()
771 .into_owned(),
772 );
773 if let Some(instance) = mj_core::config::instance_name() {
774 environment.insert("MJ_INSTANCE".into(), instance);
775 } else {
776 environment.remove("MJ_INSTANCE");
777 }
778 }
779 profile
780 .kind
781 .configure_home_environment(Path::new(&target_profile_home), &mut environment);
782 profile
783 .kind
784 .configure_execution_environment(execution_policy, &mut environment)?;
785 let mut project_memory = project_memory_launch(
786 session,
787 bundle,
788 &workspace,
789 &target_profile_home,
790 worker_workspace.parent_worktree,
791 )?;
792 project_memory.mcp_delivery = project_memory_mcp_delivery(profile.kind, backend);
793 project_memory.history_socket =
794 Some(Path::new(&targets::worker_root(backend, &session.id)?).join("control.sock"));
795 if profile.kind == mj_core::config::HarnessKind::Claude {
796 environment.insert(
797 "CLAUDE_CODE_PROJECT_DIR_NAME".into(),
798 project_memory_replica_slug(&project_memory.project_key, session_id),
799 );
800 }
801 apply_claude_setup_token(
802 &mut environment,
803 profile.kind,
804 &mj_core::credentials::claude_oauth_token_path(&session.last_profile),
805 );
806 let excluded_environment =
807 exclude_harness_environment(&session.last_profile, profile, &mut environment);
808 if podman_container && profile.kind == mj_core::config::HarnessKind::Claude {
809 environment.insert("IS_SANDBOX".into(), "1".into());
814 }
815 Ok((
816 WorkerLaunchConfig {
817 goal_resume_request: None,
818 target_environment,
819 seed_image_environment: backend.container_engine().is_some(),
820 run_mode: Default::default(),
821 session_id: session_id.to_string(),
822 subagents: mj_core::subagent::SubagentPolicy::Native,
823 handback_tool: false,
824 initial_model: None,
825 review_capture: false,
826 harness: profile.kind,
827 harness_home: PathBuf::from(&target_profile_home),
828 authentication_marker: profile
834 .authentication_marker()
835 .strip_prefix(&profile.home)
836 .ok()
837 .map(|name| name.to_string_lossy().into_owned()),
838 bridge_command: PathBuf::from(bridge_command),
839 bridge_args,
840 harness_runtime: harness_runtime_policy(backend),
841 environment,
842 excluded_environment,
843 cwd: PathBuf::from(&workspace.0),
844 additional_directories,
845 native_session_id: session.native_session_id.clone(),
846 project_memory: Some(project_memory.clone()),
847 execution_policy,
848 },
849 project_memory,
850 target_profile_home,
851 ))
852}
853
854pub(super) fn exclude_harness_environment(
861 profile_id: &str,
862 profile: &mj_core::config::HarnessProfile,
863 environment: &mut std::collections::BTreeMap<String, String>,
864) -> Vec<String> {
865 static REPORTED: std::sync::Mutex<std::collections::BTreeSet<String>> =
866 std::sync::Mutex::new(std::collections::BTreeSet::new());
867 let before = environment.clone();
868 let excluded = profile.exclude_harness_environment(environment);
869 let removed = excluded
870 .iter()
871 .filter(|name| before.contains_key(*name))
872 .cloned()
873 .collect::<Vec<_>>();
874 if !removed.is_empty()
875 && REPORTED
876 .lock()
877 .map(|mut reported| reported.insert(profile_id.to_owned()))
878 .unwrap_or(true)
879 {
880 tracing::info!(
881 profile_id,
882 removed = removed.join(", "),
883 "left API key settings out of the harness environment: this Codex profile signs in with ChatGPT and must not fall back to an API key"
884 );
885 }
886 excluded
887}
888
889pub(super) fn harness_runtime_policy(backend: &targets::TargetLocator) -> HarnessRuntimePolicy {
890 match backend {
891 targets::TargetLocator::LocalBare { .. }
892 | targets::TargetLocator::AwsEc2 { .. }
893 | targets::TargetLocator::SshBare { .. } => HarnessRuntimePolicy::Managed,
894 _ => HarnessRuntimePolicy::Ambient,
895 }
896}