agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! Project projection for local Herdr Core terminals.
use super::hc_layout::{
    terminal_addresses, terminal_layout, valid_id, DesktopLayout, DOCUMENT_NAME, SPACE_PREFIX,
};
use super::hc_shared_terminal::{publish_at, Placement};
use super::{
    bindings, snapshot, Action, ActionResult, Layout, NewAgent, OpenedWorkspace, Pane, SessionInfo,
    Snapshot, StartedAgent, Tab, Target, Workspace,
};
use crate::core::{
    herdr::hc::{local_address, Core},
    project_worktrees,
    skill_store::SkillStore,
};
use anyhow::{bail, ensure, Context, Result};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::{
    collections::{BTreeMap, HashMap, HashSet},
    path::{Path, PathBuf},
};

const PREFIX: &str = "hc:";
const CHECKOUT: &str = "agenthub.checkout";

pub(super) fn checkout(path: &str) -> Option<PathBuf> {
    let path = Path::new(path).canonicalize().ok()?;
    if !path.is_dir() {
        return None;
    }
    Some(
        git2::Repository::discover(&path)
            .ok()
            .and_then(|repo| repo.workdir()?.canonicalize().ok())
            .unwrap_or(path),
    )
}

fn common_directory(repo: &git2::Repository) -> PathBuf {
    if repo.is_worktree() {
        if let Ok(relative) = std::fs::read_to_string(repo.path().join("commondir")) {
            if let Ok(common) = repo.path().join(relative.trim()).canonicalize() {
                return common;
            }
        }
    }
    repo.path()
        .canonicalize()
        .unwrap_or_else(|_| repo.path().to_owned())
}

fn workspace_id(path: &Path) -> String {
    format!(
        "{PREFIX}{}",
        hex::encode(Sha256::digest(path.as_os_str().as_encoded_bytes()))
    )
}

fn pane(row: &Value, directory: &Path) -> Option<Pane> {
    let address = row["address"]
        .as_str()
        .filter(|address| local_address(address))?;
    let identity = row["identity"]
        .as_str()
        .filter(|identity| !identity.is_empty())?;
    let pane_id = format!("{PREFIX}{address}");
    let status = &row["status"];
    let app = status["app"].as_str().filter(|app| !app.is_empty());
    let kind = match app {
        Some("claude-code") => Some("claude"),
        Some("opencode") => Some("opencode"),
        other => other,
    };
    let status = match status["state"].as_str() {
        Some("error") => "blocked",
        Some(state @ ("working" | "idle" | "done" | "blocked")) => state,
        _ => "unknown",
    };
    let revision = row["turn"].as_u64().unwrap_or_default();
    let seen_turn = row["labels"]["herdr.seen"]
        .as_str()
        .and_then(|value| value.parse::<u64>().ok());
    let display_status = match (status, seen_turn) {
        ("idle" | "done", Some(seen)) => {
            Some(if revision > seen { "done" } else { "idle" }.to_owned())
        }
        _ => None,
    };
    Some(Pane {
        tab_id: pane_id.clone(),
        pane_id,
        workspace_id: workspace_id(directory),
        terminal_id: format!("{PREFIX}{identity}"),
        cwd: Some(directory.to_string_lossy().into_owned()),
        focused: true,
        revision,
        agent_status: status.to_owned(),
        agent: kind.map(str::to_owned),
        program: row["foreground"]["name"]
            .as_str()
            .filter(|name| !name.is_empty())
            .map(str::to_owned),
        name: [row["name"].as_str(), row["title"].as_str()]
            .into_iter()
            .flatten()
            .find(|name| !name.trim().is_empty())
            .map(str::to_owned),
        title: row["title"]
            .as_str()
            .filter(|title| !title.is_empty())
            .map(str::to_owned),
        display_status,
        desktop_owned: row["labels"][super::super::hc::interactive::OWNER]
            .as_str()
            .is_some(),
        status_ms: row["status_ms"].as_u64(),
        agent_session: app.map(|app| json!({ "app": app, "identity": identity })),
    })
}

fn directory(row: &Value) -> Option<PathBuf> {
    // Even a label stored by another Core client must resolve to a local directory.
    row["labels"][CHECKOUT]
        .as_str()
        .and_then(|path| Path::new(path).canonicalize().ok())
        .filter(|path| path.is_dir())
        .or_else(|| row["cwd"].as_str().and_then(checkout))
}

pub(super) fn standalone_workspace_id(row: &Value) -> Option<String> {
    directory(row).map(|path| workspace_id(&path))
}

pub(super) fn desktop_directory(row: &Value) -> Option<PathBuf> {
    row["foreground"]["cwd"]
        .as_str()
        .and_then(checkout)
        .or_else(|| row["cwd"].as_str().and_then(checkout))
        .or_else(|| directory(row))
}

fn workspace_row(
    id: String,
    directory: &Path,
    label: Option<&str>,
    active_tab_id: String,
) -> Workspace {
    let worktree = git2::Repository::discover(directory).ok().map(|repo| {
        json!({
            "checkout_path": directory,
            "repo_key": common_directory(&repo),
            "is_linked_worktree": repo.is_worktree(),
        })
    });
    Workspace {
        workspace_id: id,
        label: label
            .filter(|label| !label.is_empty())
            .or_else(|| directory.file_name().and_then(|name| name.to_str()))
            .unwrap_or("Workspace")
            .to_owned(),
        active_tab_id,
        directory: Some(directory.to_string_lossy().into_owned()),
        worktree,
        branch: None,
        head: None,
        detached: false,
        repository_icon: None,
        ahead: None,
        behind: None,
    }
}

fn local_folder(path: &str) -> Option<PathBuf> {
    let path = Path::new(path);
    path.is_absolute()
        .then(|| path.canonicalize().ok())
        .flatten()
        .filter(|path| path.is_dir())
}

fn desktop_space_name(name: &str, folder: &Path, home: Option<&Path>) -> String {
    if !name.is_empty() {
        return name.to_owned();
    }
    if home.is_some_and(|home| {
        if cfg!(windows) {
            folder
                .to_string_lossy()
                .eq_ignore_ascii_case(&home.to_string_lossy())
        } else {
            folder == home
        }
    }) {
        return "~".to_owned();
    }
    folder
        .file_name()
        .unwrap_or(folder.as_os_str())
        .to_string_lossy()
        .into_owned()
}

fn desktop_tab_title(name: &str, lead: Option<&Value>) -> String {
    let agent = lead.and_then(|row| row["status"]["app"].as_str());
    let executable = lead.and_then(|row| row["foreground"]["name"].as_str());
    let key = agent.or(executable).unwrap_or_default();
    let program = match key {
        "" => "Terminal".to_owned(),
        "claude" | "claude-code" => "Claude Code".to_owned(),
        "opencode" => "OpenCode".to_owned(),
        "node" => "Node".to_owned(),
        _ => {
            let mut chars = key.chars();
            chars
                .next()
                .into_iter()
                .flat_map(char::to_uppercase)
                .chain(chars)
                .collect()
        }
    };
    let base = if name.is_empty() {
        program.as_str()
    } else {
        name
    };
    if let Some(row) = lead.filter(|_| agent.is_some() && (name.is_empty() || name == program)) {
        let title = row["title"].as_str().unwrap_or_default().trim();
        let title = title.trim_start_matches(|c: char| {
            c.is_whitespace() || matches!(c, '✦' | '✧' | '✳' | '✶' | '✻' | '✽' | '·' | '\u{2800}'..='\u{28ff}' | '\u{25d0}'..='\u{25d3}')
        });
        if !title.is_empty()
            && !title.starts_with(['~', '/'])
            && !title
                .as_bytes()
                .get(1..3)
                .is_some_and(|prefix| prefix == b":\\")
            && !title.contains('@')
            && !title.eq_ignore_ascii_case(key)
            && title != program
            && row["address"].as_str() != Some(title)
        {
            return title.to_owned();
        }
    }
    base.to_owned()
}

fn project_snapshot(result: Value, layout: DesktopLayout) -> Result<Snapshot> {
    let rows = result["terminals"]
        .as_array()
        .context("Herdr Core did not return terminals")?;
    let live: HashMap<_, _> = rows
        .iter()
        .filter(|row| row["state"] == "live")
        .filter_map(|row| {
            row["address"]
                .as_str()
                .filter(|id| local_address(id))
                .map(|id| (id, row))
        })
        .collect();
    let mut workspaces = Vec::new();
    let mut panes = Vec::new();
    let mut tabs = Vec::new();
    let mut placed = HashSet::new();
    let mut space_ids = HashSet::new();
    let mut folders = HashMap::new();
    let home = dirs::home_dir().and_then(|path| path.canonicalize().ok());

    for space in layout.spaces {
        if !valid_id(&space.id) || !space_ids.insert(space.id.clone()) {
            continue;
        }
        let id = format!("{SPACE_PREFIX}{}", space.id);
        let mut folder = local_folder(&space.folder);
        let mut first_tab = None;
        let mut first_checkout = None;
        let mut tab_ids = HashSet::new();
        for doc_tab in space.tabs {
            if !valid_id(&doc_tab.id) || !tab_ids.insert(doc_tab.id.clone()) {
                continue;
            }
            let tab_id = format!("hc:tab/{}/{}", space.id, doc_tab.id);
            let mut addresses = Vec::new();
            terminal_addresses(&doc_tab.root, &mut addresses);
            let mut lead = None;
            for address in addresses {
                let Some(row) = live.get(address.as_str()) else {
                    continue;
                };
                let Some(directory) = desktop_directory(row).or_else(|| folder.clone()) else {
                    continue;
                };
                let Some(mut pane) = pane(row, &directory) else {
                    continue;
                };
                if !placed.insert(pane.pane_id.clone()) {
                    continue;
                }
                first_checkout.get_or_insert_with(|| directory.clone());
                folder.get_or_insert(directory);
                first_tab.get_or_insert_with(|| tab_id.clone());
                pane.workspace_id.clone_from(&id);
                pane.tab_id.clone_from(&tab_id);
                if lead.is_none()
                    || (pane.agent.is_some()
                        && lead.is_some_and(|row: &Value| row["status"]["app"].is_null()))
                {
                    lead = Some(*row);
                }
                panes.push(pane);
            }
            tabs.push(Tab {
                tab_id,
                workspace_id: id.clone(),
                label: desktop_tab_title(&doc_tab.name, lead),
                pane_layout: terminal_layout(&doc_tab.root, 0),
            });
        }
        if let Some(checkout) = first_checkout.or(folder) {
            folders.insert(id.clone(), checkout.to_string_lossy().into_owned());
            workspaces.push(workspace_row(
                id,
                &checkout,
                Some(&desktop_space_name(&space.name, &checkout, home.as_deref())),
                first_tab.unwrap_or_default(),
            ));
        }
    }

    let mut unplaced = BTreeMap::new();
    for row in rows.iter().filter(|row| row["state"] == "live") {
        let Some(directory) = directory(row) else {
            continue;
        };
        let Some(pane) = pane(row, &directory) else {
            continue;
        };
        if !placed.insert(pane.pane_id.clone()) {
            continue;
        }
        unplaced
            .entry(pane.workspace_id.clone())
            .or_insert_with(|| {
                workspace_row(
                    pane.workspace_id.clone(),
                    &directory,
                    None,
                    pane.tab_id.clone(),
                )
            });
        tabs.push(Tab {
            tab_id: pane.tab_id.clone(),
            workspace_id: pane.workspace_id.clone(),
            label: pane.name.clone().unwrap_or_else(|| "Terminal".to_owned()),
            pane_layout: None,
        });
        panes.push(pane);
    }
    workspaces.extend(unplaced.into_values());
    let mut snapshot = Snapshot {
        version: "herdr-core".to_owned(),
        workspaces,
        tabs,
        layouts: Vec::<Layout>::new(),
        agents: panes
            .iter()
            .filter(|pane| pane.agent.is_some())
            .cloned()
            .collect(),
        panes,
    };
    snapshot::enrich_workspaces(&mut snapshot);
    for workspace in &mut snapshot.workspaces {
        if let Some(folder) = folders.remove(&workspace.workspace_id) {
            workspace.directory = Some(folder);
        }
    }
    Ok(snapshot)
}

impl Core {
    fn require_session(&self, session: &str) -> Result<()> {
        ensure!(
            session == self.session_key(),
            "Select the matching Herdr Core session"
        );
        Ok(())
    }

    pub(super) fn session_info(&self) -> Result<Vec<SessionInfo>> {
        let status = self.status()?;
        Ok(vec![SessionInfo {
            name: self.session_key(),
            running: status["pid"].as_u64().is_some(),
            default: self.session_key() == super::super::hc::sessions::DEFAULT,
            backend: Some("core".into()),
            label: None,
            socket_path: None,
        }])
    }

    pub(super) fn prepare_ui(&self) -> Result<String> {
        self.call("server.status", json!({}))?;
        Ok(self.session_key())
    }

    pub(super) fn snapshot(&self, session: &str) -> Result<Snapshot> {
        self.require_session(session)?;
        let terminals = self.call("terminal.list", json!({}))?;
        project_snapshot(terminals, self.desktop_layout()?)
    }

    fn desktop_layout(&self) -> Result<DesktopLayout> {
        let document = self.call("doc.get", json!({"name": DOCUMENT_NAME}))?;
        match document.get("value").filter(|value| !value.is_null()) {
            Some(value) => serde_json::from_value(value.clone())
                .context("Unsupported Herdr App workspace layout"),
            None => Ok(DesktopLayout::default()),
        }
    }

    pub(super) fn open(
        &self,
        store: &SkillStore,
        session: &str,
        workspace: &str,
        requested: Option<&str>,
    ) -> Result<OpenedWorkspace> {
        self.require_session(session)?;
        super::hc_migration::restore_tabs(self, workspace)?;
        let snapshot = self.snapshot(session)?;
        let selected = snapshot
            .panes
            .iter()
            .find(|pane| {
                pane.workspace_id == workspace && requested.map_or(true, |id| id == pane.pane_id)
            })
            .context("Herdr Core terminal no longer exists; refresh the sidebar")?;
        let directory = Path::new(
            selected
                .cwd
                .as_deref()
                .context("Terminal directory is unavailable")?,
        );
        Ok(OpenedWorkspace {
            project_id: bindings::resolve_project(store, directory)?,
            path: directory.to_string_lossy().into_owned(),
            target: Target::from_pane(session, selected),
        })
    }

    pub(super) fn ensure(
        &self,
        store: &SkillStore,
        session: &str,
        project_id: &str,
        path: Option<&str>,
    ) -> Result<OpenedWorkspace> {
        let mut snapshot = self.snapshot(session)?;
        let directory = project_worktrees::directory(store, project_id, path)?;
        let shared = snapshot.workspaces.iter().find(|workspace| {
            workspace.workspace_id.starts_with(SPACE_PREFIX)
                && workspace
                    .directory
                    .as_deref()
                    .is_some_and(|path| Path::new(path) == directory)
        });
        if let Some(workspace) = shared {
            let restored = super::hc_migration::restore_tabs(self, &workspace.workspace_id)?;
            if restored
                || !snapshot
                    .panes
                    .iter()
                    .any(|pane| pane.workspace_id == workspace.workspace_id)
            {
                snapshot = self.snapshot(session)?;
            }
        }
        let target = match snapshot.panes.iter().find(|pane| {
            pane.cwd
                .as_deref()
                .is_some_and(|path| Path::new(path) == directory)
        }) {
            Some(pane) => Target::from_pane(session, pane),
            None => self.shell(&directory)?,
        };
        Ok(OpenedWorkspace {
            project_id: project_id.to_owned(),
            path: directory.to_string_lossy().into_owned(),
            target,
        })
    }

    fn shell(&self, directory: &Path) -> Result<Target> {
        self.launch(directory, &[], None, json!({}))
    }

    fn launch(
        &self,
        directory: &Path,
        argv: &[String],
        name: Option<&str>,
        env: Value,
    ) -> Result<Target> {
        self.launch_at(directory, argv, name, env, Placement::Checkout)
    }

    fn launch_at(
        &self,
        directory: &Path,
        argv: &[String],
        name: Option<&str>,
        env: Value,
        placement: Placement<'_>,
    ) -> Result<Target> {
        let address = self.run(
            directory,
            argv,
            name,
            json!({(CHECKOUT): directory, "herdr.seen": "0"}),
            match env {
                Value::Object(mut env) => {
                    env.entry("TERM_PROGRAM").or_insert_with(|| json!("herdr"));
                    Value::Object(env)
                }
                _ => json!({"TERM_PROGRAM": "herdr"}),
            },
        )?;
        let row = self.call("terminal.get", json!({"terminal": address}))?;
        let mut pane = pane(&row, directory).context(
            "Cannot identify the created Herdr Core terminal; inspect it before retrying",
        )?;
        let (placement, _) = publish_at(self, directory, &address, name, placement, |candidate| {
            candidate["identity"] == row["identity"]
        })
        .context("The Core terminal was started; check its placement before retrying")?;
        pane.workspace_id = placement.workspace_id();
        Ok(Target::from_pane(&self.session_key(), &pane))
    }

    fn verify(&self, target: &Target) -> Result<(String, PathBuf, Pane)> {
        self.require_session(&target.session)?;
        let address = target
            .pane_id
            .strip_prefix(PREFIX)
            .filter(|address| local_address(address))
            .context("This terminal belongs to the previous Herdr backend")?;
        let row = self.call("terminal.get", json!({"terminal": address}))?;
        let directory = if target.workspace_id.starts_with(SPACE_PREFIX) {
            desktop_directory(&row)
        } else {
            directory(&row)
        }
        .context("Terminal directory is unavailable")?;
        let pane = pane(&row, &directory).context("Herdr Core terminal identity unavailable")?;
        ensure!(
            row["state"] == "live"
                && pane.terminal_id == target.terminal_id
                && pane.pane_id == target.pane_id,
            "Herdr Core terminal changed; refresh before retrying"
        );
        let same_workspace = if target.workspace_id.starts_with(SPACE_PREFIX) {
            self.desktop_layout()?
                .contains_terminal(&target.workspace_id, address)
        } else {
            pane.workspace_id == target.workspace_id
        };
        ensure!(
            same_workspace,
            "Herdr Core terminal moved; refresh before retrying"
        );
        Ok((address.to_owned(), directory, pane))
    }

    pub(super) fn attach_target(
        &self,
        store: &SkillStore,
        project: &str,
        path: &str,
        target: &Target,
    ) -> Result<portable_pty::CommandBuilder> {
        let expected = project_worktrees::directory(store, project, Some(path))?;
        let (address, actual, _) = self.verify(target)?;
        ensure!(
            expected == actual,
            "Terminal no longer belongs to the selected checkout"
        );
        self.attach(&address)
    }

    pub(super) fn action(
        &self,
        target: &Target,
        action: Action,
        text: Option<&str>,
    ) -> Result<ActionResult> {
        let (address, directory, pane) = self.verify(target)?;
        let mut output = None;
        let mut next = None;
        match action {
            Action::Read => {
                let value = self.call("terminal.read", json!({"terminal": address, "lines": 0}))?;
                output = Some(
                    value["text"]
                        .as_str()
                        .context("Herdr Core did not return terminal output")?
                        .to_owned(),
                );
            }
            Action::Prompt => {
                let text = text
                    .filter(|text| !text.trim().is_empty() && text.len() <= 32 * 1024)
                    .context("Enter a task of up to 32 KiB")?;
                ensure!(pane.agent_session.is_some() && pane.agent_session == target.agent_session && pane.revision == target.revision
                    && matches!(pane.agent_status.as_str(), "idle" | "done"),
                    "Agent is not idle or its identity changed; inspect the terminal before sending");
                self.call(
                    "terminal.send",
                    json!({"terminal": address, "text": text, "if": "idle", "wait": false}),
                )?;
            }
            Action::Interrupt => {
                ensure!(
                    pane.agent_session.is_some()
                        && pane.agent_session == target.agent_session
                        && pane.revision == target.revision
                        && pane.agent_status == "working",
                    "Agent is no longer working or its identity changed"
                );
                self.call(
                    "terminal.interrupt",
                    json!({"terminal": address, "timeout": 5}),
                )?;
            }
            Action::Close => {
                self.stop_terminal(&address)?;
                if target.workspace_id.starts_with(SPACE_PREFIX) {
                    super::hc_shared_terminal::remove_stopped_terminal(
                        self,
                        &target.workspace_id,
                        &address,
                    )?;
                }
            }
            Action::RenameTab => {
                super::hc_shared_terminal::rename_tab(
                    self,
                    &target.workspace_id,
                    &address,
                    text.context("A tab name is required")?,
                )?;
            }
            Action::NewTab | Action::SplitRight | Action::SplitDown => {
                let workspace = target.workspace_id.as_str();
                let placement = if !workspace.starts_with(SPACE_PREFIX) {
                    Placement::Checkout
                } else if matches!(action, Action::NewTab) {
                    Placement::After {
                        workspace,
                        terminal: &address,
                    }
                } else {
                    Placement::Split {
                        workspace,
                        terminal: &address,
                        axis: if matches!(action, Action::SplitRight) {
                            "row"
                        } else {
                            "column"
                        },
                    }
                };
                next = Some(self.launch_at(&directory, &[], None, json!({}), placement)?)
            }
            Action::Zoom => bail!("Zoom is controlled by the terminal layout"),
        }
        Ok(ActionResult {
            output,
            target: next,
        })
    }

    pub(super) fn start_agent(
        &self,
        target: &Target,
        input: NewAgent,
        created: impl FnOnce(&Target) -> Result<()>,
    ) -> Result<StartedAgent> {
        let (_, directory, _) = self.verify(target)?;
        let launch = crate::core::agent_launch_config::resolve_scheme(
            &input.kind,
            input.scheme_id.as_deref(),
        )?;
        let argv = Self::agent_argv(&directory, launch, Some(&input.prompt))?;
        let env = if input.teams {
            ensure!(input.kind == "claude", "Agent Teams requires Claude");
            json!({"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"})
        } else {
            json!({})
        };
        let target = self.launch(&directory, &argv, Some(&input.name), env)?;
        let warning = created(&target).err().map(|error| error.to_string());
        Ok(StartedAgent { target, warning })
    }
}

#[cfg(test)]
#[path = "hc_tests.rs"]
mod tests;