1use super::*;
9
10pub(super) struct ResyncCtx<'a> {
13 pub block: &'a Block,
14 pub tab_id: &'a str,
15 pub rt_opts: Option<serde_json::Value>,
16 pub force: bool,
17 pub respawn_if_done: bool,
18 pub broker: Option<Arc<Broker>>,
19 pub event_bus: Option<Arc<EventBus>>,
20 pub mstore: Option<Arc<Store>>,
21 pub filestore: Option<Arc<FileStore>>,
22 pub id_store: Option<Arc<Store>>,
23 pub identity_store: Option<Arc<Store>>,
24 pub registry: Option<Arc<crate::registry::Registry>>,
25 pub boot_id: Arc<str>,
26 pub auth_key: &'a str,
27 pub config: Option<Arc<crate::backend::wconfig::ConfigState>>,
28}
29
30const HOST_SIDE_CONTROLLERS: [&str; 3] = [BLOCK_CONTROLLER_ACP, BLOCK_CONTROLLER_MSP, BLOCK_CONTROLLER_APP_SERVER];
32
33pub(super) fn effective_controller_type(block: &Block, controller_type: String) -> Result<String, String> {
39 let runtime = super::super::runtime_adapter::RuntimeKind::of_block_meta(&block.meta).adapter();
40 if runtime.kind().is_container() && HOST_SIDE_CONTROLLERS.contains(&controller_type.as_str()) {
41 tracing::warn!(block_id = %block.oid, controller_type = %controller_type, "container agent's pane has a host-side controller in meta — refusing to start it");
42 return Err(format!(
43 "this agent runs in its container; its pane's {controller_type} controller would start it on this computer, so it is not started"
44 ));
45 }
46 if !runtime.accepts_persistent_controller() && controller_type == BLOCK_CONTROLLER_PERSISTENT {
47 tracing::warn!(
48 block_id = %block.oid,
49 "container agent has persistent controller in meta — overriding to subprocess"
50 );
51 Ok(BLOCK_CONTROLLER_SUBPROCESS.to_string())
52 } else {
53 Ok(controller_type)
54 }
55}
56
57impl ResyncCtx<'_> {
58 pub(super) fn resync_existing(
62 &self,
63 ctrl: &Arc<dyn Controller>,
64 controller_type: &str,
65 ) -> Option<Result<(), String>> {
66 let block_id = &self.block.oid;
67 let block_meta = &self.block.meta;
68 let needs_replace = if ctrl.controller_type() != controller_type || self.force {
69 true } else {
71 let status = ctrl.get_runtime_status();
72 let new_conn = super::super::obj::meta_get_string(block_meta, META_KEY_CONNECTION, "local");
74 status.shellprocconnname != new_conn
75 };
76
77 if needs_replace
104 && is_runtime_config_only_replace(ctrl.controller_type(), controller_type, self.force)
105 {
106 if let Some(p) = ctrl
107 .as_any()
108 .downcast_ref::<persistent::PersistentSubprocessController>()
109 {
110 if p.request_restart_when_idle() {
111 return Some(Ok(()));
112 }
113 }
114 }
115
116 if needs_replace {
117 let _ = crate::backend::teardown_hooks::hooks().replace_now(ctrl.as_ref());
123 if let Some(old) = ctrl.as_any().downcast_ref::<super::subprocess::SubprocessController>() {
124 old.hand_over_held_to_replacement();
125 }
126 remove_controller_entry_only(block_id);
127 return None;
128 }
129
130 let status = ctrl.get_runtime_status();
132 tracing::info!(
133 block_id = %block_id,
134 status = %status.shellprocstatus,
135 "[dnd-debug] existing controller — skipping spawn (no cmd:cwd seed)"
136 );
137 if status.shellprocstatus == STATUS_INIT {
138 return Some(self.restart_existing(ctrl));
139 }
140 if status.shellprocstatus == STATUS_DONE {
141 if self.respawn_if_done {
142 return Some(self.restart_existing(ctrl));
143 }
144 return Some(Err(RESYNC_ERR_ALREADY_EXITED.to_string()));
145 }
146 Some(Ok(()))
147 }
148
149 fn restart_existing(&self, ctrl: &Arc<dyn Controller>) -> Result<(), String> {
150 refresh_agent_skill_files(&self.block.meta, &self.mstore, &self.identity_store);
151 ctrl.start(self.block.meta.clone(), self.rt_opts.clone(), self.force)
152 }
153
154 pub(super) fn create_and_start(self, controller_type: &str) -> Result<(), String> {
159 if let Some(why) = start_refusal(controller_type, &self.block.meta) {
160 return Err(why);
161 }
162 refresh_agent_skill_files(&self.block.meta, &self.mstore, &self.identity_store);
163 match controller_type {
164 BLOCK_CONTROLLER_SHELL
168 if durable_mode::wants(
169 &self.block.meta,
170 self.config.as_ref().map(|c| c.get_full_config()).as_deref(),
171 ) =>
172 {
173 self.start_durable_ssh()
174 }
175 BLOCK_CONTROLLER_SHELL | BLOCK_CONTROLLER_CMD => self.start_shell(controller_type),
176 BLOCK_CONTROLLER_SUBPROCESS => self.start_subprocess(),
177 BLOCK_CONTROLLER_PERSISTENT => self.start_persistent(),
178 BLOCK_CONTROLLER_ACP => self.start_acp(),
179 BLOCK_CONTROLLER_MSP => self.start_msp(),
180 BLOCK_CONTROLLER_APP_SERVER => self.start_app_server(),
181 _ => Err(format!("unknown controller type: {controller_type}")),
182 }
183 }
184
185 fn durable_fallback(&self) -> durable_ssh::Fallback {
189 let block_id = self.block.oid.clone();
190 let (tab_id, rt_opts) = (self.tab_id.to_string(), self.rt_opts.clone());
191 let (broker, event_bus, mstore, filestore) = (
192 self.broker.clone(),
193 self.event_bus.clone(),
194 self.mstore.clone(),
195 self.filestore.clone(),
196 );
197 let (id_store, identity_store, registry) =
198 (self.id_store.clone(), self.identity_store.clone(), self.registry.clone());
199 let (boot_id, auth_key, config) = (self.boot_id.clone(), self.auth_key.to_string(), self.config.clone());
200 Arc::new(move || {
201 let Some(block) = mstore.as_ref().and_then(|s| s.get::<Block>(&block_id).ok().flatten()) else {
202 return false;
203 };
204 if durable_mode::wants(&block.meta, config.as_ref().map(|c| c.get_full_config()).as_deref()) {
207 tracing::warn!(block_id = %block_id, "durable ssh: still durable, not falling back");
208 return false;
209 }
210 if let Err(e) = resync_controller(
211 &block,
212 &tab_id,
213 rt_opts.clone(),
214 true,
215 true,
216 broker.clone(),
217 event_bus.clone(),
218 mstore.clone(),
219 filestore.clone(),
220 id_store.clone(),
221 identity_store.clone(),
222 registry.clone(),
223 boot_id.clone(),
224 &auth_key,
225 config.clone(),
226 ) {
227 tracing::warn!(block_id = %block_id, error = %e, "durable ssh: plain terminal fallback failed");
228 return false;
229 }
230 true
231 })
232 }
233
234 fn start_durable_ssh(self) -> Result<(), String> {
235 let fallback = self.durable_fallback();
236 let ctrl = Arc::new(durable_ssh::DurableSshController::new(
237 self.block.oid.clone(),
238 self.broker,
239 self.event_bus,
240 self.mstore,
241 self.filestore,
242 self.auth_key.to_string(),
243 self.config.clone(),
244 Some(fallback),
245 ));
246 register_controller(&self.block.oid, ctrl.clone());
247 ctrl.start(self.block.meta.clone(), self.rt_opts, self.force)
248 }
249
250 fn start_shell(self, controller_type: &str) -> Result<(), String> {
251 let ctrl = shell::ShellController::new(
252 controller_type.to_string(),
253 self.tab_id.to_string(),
254 self.block.oid.clone(),
255 self.broker,
256 self.event_bus,
257 self.mstore,
258 self.filestore,
259 self.auth_key.to_string(),
260 )
261 .with_config(self.config);
262 let ctrl = Arc::new(ctrl);
263 register_controller(&self.block.oid, ctrl.clone());
264 let result = ctrl.start(self.block.meta.clone(), self.rt_opts, self.force);
265 notify_tracked_blocks_changed();
273 result
274 }
275
276 fn start_subprocess(self) -> Result<(), String> {
277 let ctrl = subprocess::SubprocessController::new(
278 self.tab_id.to_string(),
279 self.block.oid.clone(),
280 self.broker,
281 self.event_bus,
282 self.mstore,
283 self.filestore,
284 self.registry,
285 self.boot_id,
286 );
287 let ctrl = Arc::new(ctrl);
288 ctrl.set_self_ref();
289 register_controller(&self.block.oid, ctrl.clone());
290 ctrl.run_queue_left_by_replaced();
292 let result = ctrl.start(self.block.meta.clone(), self.rt_opts, self.force);
293 notify_tracked_blocks_changed();
294 result
295 }
296
297 fn start_persistent(self) -> Result<(), String> {
298 let ctrl = persistent::PersistentSubprocessController::new(
299 self.tab_id.to_string(),
300 self.block.oid.clone(),
301 self.broker,
302 self.event_bus,
303 self.mstore,
304 self.filestore,
305 )
306 .with_identity_stores(self.id_store, self.identity_store, self.auth_key.to_string())
307 .with_agent_lease_store(self.registry, self.boot_id);
309 let ctrl = Arc::new(ctrl);
310 ctrl.set_self_ref();
311 register_controller(&self.block.oid, ctrl.clone());
312 let result = ctrl.start(self.block.meta.clone(), self.rt_opts, self.force);
313 notify_tracked_blocks_changed();
314 result
315 }
316
317 fn start_acp(self) -> Result<(), String> {
318 if let Some(refusal) = handed_over_start_refusal(&self.mstore, &self.block.meta) {
319 return Err(refusal);
320 }
321 let ctrl = acp::AcpController::new(
322 self.tab_id.to_string(),
323 self.block.oid.clone(),
324 self.broker,
325 self.event_bus,
326 self.mstore,
327 self.filestore,
328 )
329 .with_auth_key(self.auth_key.to_string());
330 let ctrl = Arc::new(ctrl);
331 register_controller(&self.block.oid, ctrl.clone());
332 let result = ctrl.start(self.block.meta.clone(), self.rt_opts, self.force);
333 notify_tracked_blocks_changed();
334 result
335 }
336
337 fn start_msp(self) -> Result<(), String> {
338 if let Some(refusal) = handed_over_start_refusal(&self.mstore, &self.block.meta) {
339 return Err(refusal);
340 }
341 let ctrl = msp::MspController::new(
342 self.block.oid.clone(),
343 self.broker,
344 self.event_bus,
345 self.mstore,
346 self.filestore,
347 )
348 .with_auth_key(self.auth_key.to_string());
349 let ctrl = Arc::new(ctrl);
350 register_controller(&self.block.oid, ctrl.clone());
351 let result = ctrl.start(self.block.meta.clone(), self.rt_opts, self.force);
352 notify_tracked_blocks_changed();
353 result
354 }
355
356 fn start_app_server(self) -> Result<(), String> {
357 if let Some(refusal) = handed_over_start_refusal(&self.mstore, &self.block.meta) {
358 return Err(refusal);
359 }
360 let ctrl = app_server_controller::AppServerController::new(
361 self.block.oid.clone(),
362 self.broker,
363 self.event_bus,
364 self.mstore,
365 self.filestore,
366 );
367 let ctrl = Arc::new(ctrl);
368 ctrl.set_self_ref();
369 register_controller(&self.block.oid, ctrl.clone());
370 ctrl.start(self.block.meta.clone(), self.rt_opts, self.force)
371 }
372}
373
374fn handed_over_start_refusal(mstore: &Option<Arc<Store>>, meta: &crate::backend::obj::MetaMapType) -> Option<String> {
377 let uid = crate::backend::obj::meta_get_string(meta, "agentId", "");
378 let name = crate::backend::obj::meta_get_string(meta, "agentName", "");
379 crate::backend::agent_admission::handed_over_check(mstore.as_ref()?, &uid, &name)
380}
381
382pub(super) fn start_refusal(controller_type: &str, meta: &crate::backend::obj::MetaMapType) -> Option<String> {
388 if matches!(controller_type, BLOCK_CONTROLLER_SUBPROCESS | BLOCK_CONTROLLER_PERSISTENT) {
389 return None;
390 }
391 crate::backend::mcp_folder_rule::refusal(meta)
392}