Repository navigation
Expand file tree
/
Copy pathlaunch.rs
More file actions
1404 lines (1278 loc) · 46.6 KB
/
Copy pathlaunch.rs
File metadata and controls
1404 lines (1278 loc) · 46.6 KB
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Launch command: `hcom [N] <tool> [--tag X] [--terminal X] [--headless] [--hcom-prompt X] [--hcom-system-prompt X] [--batch-id X] [tool-args...]`
//!
//!
//! Parses hcom-level flags, merges env config with CLI args via tool-specific
//! parsers, then delegates to `launcher::launch()`.
use crate::config::HcomConfig;
use crate::core::launch_status::{self, LaunchStatus};
use crate::core::tips::{self, LaunchTipsContext};
use crate::db::HcomDb;
use crate::identity;
use crate::launcher::{self, LaunchParams, LaunchResult, LaunchTool};
use crate::log::log_info;
use crate::router::GlobalFlags;
use crate::shared::HcomContext;
use anyhow::{Result, bail};
use serde_json::json;
use std::time::Instant;
pub(crate) const INLINE_SINGLE_LAUNCH_WAIT_SECS: u64 = 10;
/// Run the launch command. `argv` is the full argv[1..] including count/tool.
pub fn run(argv: &[String], flags: &GlobalFlags) -> Result<i32> {
let (count, tool, hcom_flags, tool_args) = parse_launch_argv(argv)?;
let launch_tool = LaunchTool::from_str(&tool)?;
// Count validation
if count == 0 {
bail!("Count must be positive.");
}
let max_count = launch_tool.spec().launch.max_launch_count;
if count > max_count {
bail!("Too many agents requested (max {}).", max_count);
}
let tag = hcom_flags.tag;
let terminal = hcom_flags.terminal;
let headless = hcom_flags.headless;
let remote_device = hcom_flags.device.clone();
let dir_override = hcom_flags.dir.clone();
let tag_for_output = tag.clone();
let terminal_for_output = terminal.clone();
let hcom_config = load_hcom_config();
let preview_background = headless || is_background_from_args(&launch_tool, &tool_args);
let ctx = HcomContext::from_os();
if ctx.is_inside_ai_tool() && !flags.go && (!tool_args.is_empty() || count > 5) {
let remote_launch_note = "Remote launch requested; the target device will still apply its own configured defaults.";
let remote_preview_note = "Mode shown here is only a local preview; the remote target decides the final launch mode.";
let notes = if remote_device.is_some() {
[remote_launch_note, remote_preview_note]
} else {
["", ""]
};
print_launch_preview(LaunchPreview {
action: "launch",
tool: &tool,
count,
background: preview_background,
args: &tool_args,
tag: tag.as_deref(),
cwd: dir_override.as_deref(),
terminal: terminal.as_deref(),
config: &hcom_config,
show_config_args: remote_device.is_none(),
notes: if remote_device.is_some() { ¬es } else { &[] },
});
return Ok(0);
}
if let Some(ref device) = remote_device {
if hcom_flags.run_here == Some(true) {
bail!("Remote launch does not support --run-here");
}
let remote_cwd = dir_override.as_ref().ok_or_else(|| {
anyhow::anyhow!(
"Remote launch requires --dir to specify the working directory on the target device"
)
})?;
let db = HcomDb::open()?;
let launcher_name =
resolve_launcher_name(&db, flags, std::env::var("HCOM_PROCESS_ID").ok().as_deref());
let params = json!({
"tool": tool,
"count": count,
"args": tool_args,
"tag": tag,
"launcher": launcher_name,
"background": headless,
"terminal": terminal.clone(),
"cwd": remote_cwd,
"initial_prompt": hcom_flags.initial_prompt,
"system_prompt": hcom_flags.system_prompt,
});
match crate::relay::control::dispatch_remote(
&db,
device,
None,
crate::relay::control::rpc_action::LAUNCH,
¶ms,
crate::relay::control::RPC_LAUNCH_TIMEOUT,
) {
Ok(inner) => {
let launch_result = launch_result_from_json(&inner).map_err(anyhow::Error::msg)?;
let remote_output = build_remote_launch_output(
&db,
flags,
&launch_result,
tag_for_output.clone(),
terminal_for_output.clone(),
hcom_flags.run_here,
);
let output = LaunchOutputContext {
action: "launch",
tool: &remote_output.tool,
requested_count: count,
tag: remote_output.tag.as_deref(),
launcher_name: &remote_output.launcher_name,
terminal: remote_output.terminal.as_deref(),
background: remote_output.background,
run_here: remote_output.run_here,
hcom_config: &hcom_config,
inline_readiness_wait_secs: None,
};
print_launch_feedback(&db, &launch_result, &output)?;
return Ok(0);
}
Err(e) => bail!("Remote launch failed for device {device}: {e}"),
}
}
// System/initial prompt handling
let system_prompt = hcom_flags.system_prompt;
let initial_prompt = hcom_flags.initial_prompt;
// Merge env config args with CLI args
let (merged_args, background) =
prepare_launch_execution(&launch_tool, &tool_args, &hcom_config, headless);
validate_claude_headless_launch(&tool, background, &merged_args, initial_prompt.as_deref())?;
// Open DB
let db = HcomDb::open()?;
let launcher_name =
resolve_launcher_name(&db, flags, std::env::var("HCOM_PROCESS_ID").ok().as_deref());
let launcher_name_ref = launcher_name.as_str();
let output = LaunchOutputContext {
action: "launch",
tool: &tool,
requested_count: count,
tag: tag_for_output.as_deref(),
launcher_name: launcher_name_ref,
terminal: terminal_for_output.as_deref(),
background,
run_here: hcom_flags.run_here,
hcom_config: &hcom_config,
inline_readiness_wait_secs: if ctx.is_inside_ai_tool() && count == 1 {
Some(INLINE_SINGLE_LAUNCH_WAIT_SECS)
} else {
None
},
};
let result = launcher::launch(
&db,
LaunchParams {
tool: tool.clone(),
count,
args: merged_args,
persisted_args: None,
prior_session_id: None,
resume_cursor: None,
tag,
system_prompt,
initial_prompt,
background,
cwd: Some(if let Some(ref dir) = dir_override {
let path = std::path::Path::new(dir);
if !path.is_dir() {
bail!("--dir path does not exist or is not a directory: {}", dir);
}
path.canonicalize()
.map(|p| crate::shared::platform::child_process_path(&p))
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| dir.clone())
} else {
std::env::current_dir()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| ".".to_string())
}),
env: None,
launcher: Some(launcher_name.clone()),
run_here: hcom_flags.run_here,
batch_id: hcom_flags.batch_id,
name: None, // --name is caller identity, not instance name
skip_validation: false,
terminal,
append_reply_handoff: true,
},
)?;
print_launch_feedback(&db, &result, &output)?;
let readiness_state = output
.inline_readiness_wait_secs
.filter(|_| result.launched == 1)
.map(|secs| print_inline_launch_readiness(&db, &result, secs));
// Log summary
log_info(
"launch",
"cmd.launch",
&format!(
"tool={} count={} launched={} failed={} batch={}",
tool, count, result.launched, result.failed, result.batch_id
),
);
Ok(readiness_exit_code(readiness_state, result.failed))
}
pub(crate) fn prepare_launch_execution(
tool: &LaunchTool,
cli_args: &[String],
config: &HcomConfig,
headless: bool,
) -> (Vec<String>, bool) {
let mut merged_args = merge_tool_args(tool, cli_args, config);
let background = headless || is_background_from_args(tool, &merged_args);
// Print mode needs stream-json for the stop-hook loop. Keep this deliberately
// grammar-free: hcom appends its required defaults and lets Claude resolve
// duplicates or reject incompatible combinations.
if matches!(tool, LaunchTool::Claude | LaunchTool::ClaudePty)
&& background
&& args_contain_any(&merged_args, &["-p", "--print"])
{
merged_args.extend([
"--output-format".to_string(),
"stream-json".to_string(),
"--verbose".to_string(),
]);
}
(merged_args, background)
}
pub(crate) fn validate_claude_headless_launch(
tool: &str,
background: bool,
merged_args: &[String],
initial_prompt: Option<&str>,
) -> Result<()> {
if tool != "claude" || !background {
return Ok(());
}
if !args_contain_any(merged_args, &["-p", "--print"]) {
return Ok(());
}
let has_hcom_prompt = initial_prompt.is_some_and(|p| !p.trim().is_empty());
if has_hcom_prompt {
return Ok(());
}
// User positionals cannot be identified without duplicating Claude's flag
// grammar. Let Claude validate whether print mode received a prompt.
Ok(())
}
pub(crate) fn launch_result_to_json(result: &LaunchResult) -> serde_json::Value {
serde_json::to_value(result).unwrap_or_else(|_| json!({}))
}
pub(crate) fn launch_result_from_json(value: &serde_json::Value) -> Result<LaunchResult, String> {
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
}
struct RemoteLaunchOutput {
tool: String,
tag: Option<String>,
launcher_name: String,
terminal: Option<String>,
background: bool,
run_here: Option<bool>,
}
fn build_remote_launch_output(
db: &HcomDb,
flags: &GlobalFlags,
launch_result: &LaunchResult,
tag: Option<String>,
terminal: Option<String>,
run_here: Option<bool>,
) -> RemoteLaunchOutput {
let launcher_name =
resolve_launcher_name(db, flags, std::env::var("HCOM_PROCESS_ID").ok().as_deref());
RemoteLaunchOutput {
tool: launch_result.tool.clone(),
tag,
launcher_name,
terminal,
background: launch_result.background,
run_here,
}
}
pub(crate) fn resolve_launcher_name(
db: &HcomDb,
flags: &GlobalFlags,
process_id: Option<&str>,
) -> String {
// Launch caller identity only needs explicit --name, then process binding.
flags
.name
.as_deref()
.map(|name| {
crate::identity::resolve_display_name(db, name).unwrap_or_else(|| name.to_string())
})
.or_else(|| flags.name.clone())
.unwrap_or_else(|| {
identity::resolve_identity(db, None, None, None, process_id, None)
.map(|id| id.name)
.unwrap_or_else(|_| "user".to_string())
})
}
fn capitalize(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().to_string() + c.as_str(),
}
}
/// Print launch preview when --go gate blocks inside AI tool.
pub(crate) struct LaunchPreview<'a> {
pub action: &'a str,
pub tool: &'a str,
pub count: usize,
pub background: bool,
pub args: &'a [String],
pub tag: Option<&'a str>,
pub cwd: Option<&'a str>,
pub terminal: Option<&'a str>,
pub config: &'a HcomConfig,
pub show_config_args: bool,
pub notes: &'a [&'a str],
}
pub(crate) fn print_launch_preview(preview: LaunchPreview<'_>) {
let mode = if preview.background {
"headless"
} else {
"interactive"
};
let cwd = preview.cwd.map(|s| s.to_string()).unwrap_or_else(|| {
std::env::current_dir()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_else(|_| ".".to_string())
});
// Drive the args-env label from the spec so we never invent a key (e.g.
// `HCOM_ANTIGRAVITY_ARGS`) for tools that don't have one.
let args_key: Option<&'static str> = preview
.tool
.parse::<crate::tool::Tool>()
.ok()
.and_then(|t| t.spec().launch.args_env);
let env_args = if preview.show_config_args {
match preview.tool {
"claude" => preview.config.claude_args.as_str(),
"gemini" => preview.config.gemini_args.as_str(),
"codex" => preview.config.codex_args.as_str(),
"opencode" => preview.config.opencode_args.as_str(),
"kilo" | "kilocode" => preview.config.kilo_args.as_str(),
"pi" | "pi-agent" => preview.config.pi_args.as_str(),
"omp" | "omp-agent" => preview.config.omp_args.as_str(),
"cursor" | "cursor-agent" => preview.config.cursor_args.as_str(),
"copilot" => preview.config.copilot_args.as_str(),
"kimi" => preview.config.kimi_args.as_str(),
"qoder" | "qodercli" => preview.config.qoder_args.as_str(),
"grok" | "grok-build" => preview.config.grok_args.as_str(),
_ => "",
}
} else {
""
};
let terminal = preview
.terminal
.map(|s| s.to_string())
.or_else(|| std::env::var("HCOM_TERMINAL").ok())
.unwrap_or_else(|| preview.config.terminal.clone());
println!("\n== LAUNCH PREVIEW ==");
println!("Add --go to proceed.\n");
println!("Action: {}", preview.action);
println!(
"Tool: {:<10} Count: {:<4} Mode: {}",
preview.tool, preview.count, mode
);
println!("Directory: {}", cwd);
println!("Terminal: {}", terminal);
if let Some(t) = preview.tag {
println!("Tag: {} (names will be {}-*)", t, t);
}
for note in preview.notes {
println!("{note}");
}
// Args — only show if there's something to show
if !env_args.is_empty() || !preview.args.is_empty() {
println!("\nArgs:");
if !env_args.is_empty() {
match args_key {
Some(key) => println!(" From config ({}): {}", key, env_args),
None => println!(" From config: {}", env_args),
}
}
if !preview.args.is_empty() {
println!(" From CLI: {}", preview.args.join(" "));
}
if !env_args.is_empty() && !preview.args.is_empty() {
println!(
" (config args are passed first, then CLI args; the tool resolves duplicates)"
);
}
}
println!("\n[Preview Mode] Add --go to proceed with launch.");
}
/// Hcom-level flags extracted from launch argv.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub(crate) struct HcomLaunchFlags {
pub tag: Option<String>,
pub terminal: Option<String>,
pub device: Option<String>,
pub headless: bool,
pub system_prompt: Option<String>,
pub initial_prompt: Option<String>,
pub run_here: Option<bool>,
pub batch_id: Option<String>,
pub dir: Option<String>,
}
/// Parse launch argv: extract count, tool name, hcom flags, and tool-specific args.
///
/// Input forms: `[N] <tool> [--tag X] [--terminal X] [--headless] [--hcom-prompt X] [--hcom-system-prompt X] [--batch-id X] [tool-args...]`
fn parse_launch_argv(argv: &[String]) -> Result<(usize, String, HcomLaunchFlags, Vec<String>)> {
if argv.is_empty() {
bail!("Usage: hcom [N] <tool> [args...]");
}
let mut idx = 0;
// Skip --name/--go (global flags already extracted by router)
while idx < argv.len() {
match argv[idx].as_str() {
"--name" => {
idx += 2;
continue;
}
"--go" => {
idx += 1;
continue;
}
_ => break,
}
}
if idx >= argv.len() {
bail!("Missing tool name");
}
// Count (optional numeric prefix)
let count: usize = if argv[idx].parse::<u32>().is_ok() {
let c = argv[idx].parse::<usize>().unwrap_or(1);
idx += 1;
c
} else {
1
};
if idx >= argv.len() {
bail!("Missing tool name after count");
}
// Tool name
let tool = argv[idx].to_string();
idx += 1;
let (flags, tool_args) = extract_launch_flags(&argv[idx..]);
Ok((count, tool, flags, tool_args))
}
/// Merge env config args with CLI args via tool-specific parsers.
fn append_config_args(config_args: &str, cli_args: &[String]) -> Vec<String> {
let mut tokens = if config_args.is_empty() {
Vec::new()
} else {
// Don't silently drop hand-edited config args on a parse error (e.g. an
// unterminated quote) — surface it so the launch isn't quietly missing
// flags the user configured.
crate::tools::args_common::shell_split(config_args, cfg!(windows)).unwrap_or_else(|err| {
eprintln!("hcom: ignoring malformed configured args ({err}): {config_args}");
Vec::new()
})
};
tokens.extend(cli_args.iter().cloned());
tokens
}
pub(crate) fn merge_tool_args(
tool: &LaunchTool,
cli_args: &[String],
config: &HcomConfig,
) -> Vec<String> {
match tool {
LaunchTool::Claude | LaunchTool::ClaudePty => {
append_config_args(&config.claude_args, cli_args)
}
LaunchTool::Gemini => append_config_args(&config.gemini_args, cli_args),
LaunchTool::Codex => append_config_args(&config.codex_args, cli_args),
LaunchTool::Cursor => {
// env config args first, explicit CLI args last (CLI wins under
// commander.js last-wins). Print-mode conflicts are rejected by the
// unified launcher so their meaning is never silently changed.
append_config_args(&config.cursor_args, cli_args)
}
LaunchTool::Copilot => append_config_args(&config.copilot_args, cli_args),
LaunchTool::Grok => append_config_args(&config.grok_args, cli_args),
LaunchTool::Pi => append_config_args(&config.pi_args, cli_args),
LaunchTool::Omp => append_config_args(&config.omp_args, cli_args),
LaunchTool::OpenCode => append_config_args(&config.opencode_args, cli_args),
LaunchTool::Kilo => append_config_args(&config.kilo_args, cli_args),
LaunchTool::Kimi => append_config_args(&config.kimi_args, cli_args),
LaunchTool::Qoder => append_config_args(&config.qoder_args, cli_args),
LaunchTool::Antigravity => {
// IntegrationSpec.launch.args_env is explicitly None: Antigravity
// has no persisted *_args config to merge.
cli_args.to_vec()
}
}
}
fn args_contain_any(args: &[String], needles: &[&str]) -> bool {
args.iter().any(|arg| needles.contains(&arg.as_str()))
}
/// Check if args indicate background/headless mode.
pub(crate) fn is_background_from_args(tool: &LaunchTool, args: &[String]) -> bool {
match tool {
LaunchTool::Claude | LaunchTool::ClaudePty => args_contain_any(args, &["-p", "--print"]),
// These tools are always hosted in hcom's PTY. Their native
// non-interactive modes are rejected by validate_tool_args.
LaunchTool::Gemini
| LaunchTool::Codex
| LaunchTool::OpenCode
| LaunchTool::Kilo
| LaunchTool::Pi
| LaunchTool::Antigravity
| LaunchTool::Cursor
| LaunchTool::Kimi
| LaunchTool::Copilot
| LaunchTool::Qoder
| LaunchTool::Grok
| LaunchTool::Omp => false,
}
}
pub(crate) fn load_hcom_config() -> HcomConfig {
HcomConfig::load(None).unwrap_or_else(|_| {
let mut c = HcomConfig::default();
c.normalize();
c
})
}
pub(crate) fn extract_launch_flags(args: &[String]) -> (HcomLaunchFlags, Vec<String>) {
let mut flags = HcomLaunchFlags::default();
let mut tool_args = Vec::new();
let mut i = 0;
while i < args.len() {
if args[i] == "--" {
tool_args.extend_from_slice(&args[i + 1..]);
break;
}
if args[i].starts_with("--tag=") {
flags.tag = Some(args[i][6..].to_string());
i += 1;
continue;
}
if args[i].starts_with("--terminal=") {
flags.terminal = Some(args[i][11..].to_string());
i += 1;
continue;
}
if args[i].starts_with("--device=") {
flags.device = Some(args[i][9..].to_string());
i += 1;
continue;
}
if args[i].starts_with("--dir=") {
flags.dir = Some(args[i][6..].to_string());
i += 1;
continue;
}
match args[i].as_str() {
"--tag" if i + 1 < args.len() => {
flags.tag = Some(args[i + 1].clone());
i += 2;
}
"--terminal" if i + 1 < args.len() => {
flags.terminal = Some(args[i + 1].clone());
i += 2;
}
"--device" if i + 1 < args.len() => {
flags.device = Some(args[i + 1].clone());
i += 2;
}
"--dir" if i + 1 < args.len() => {
flags.dir = Some(args[i + 1].clone());
i += 2;
}
"--headless" => {
flags.headless = true;
i += 1;
}
"--hcom-system-prompt" if i + 1 < args.len() => {
flags.system_prompt = Some(args[i + 1].clone());
i += 2;
}
"--system" if i + 1 < args.len() => {
flags.system_prompt = Some(args[i + 1].clone());
i += 2;
}
"--hcom-prompt" if i + 1 < args.len() => {
flags.initial_prompt = Some(args[i + 1].clone());
i += 2;
}
"--batch-id" if i + 1 < args.len() => {
flags.batch_id = Some(args[i + 1].clone());
i += 2;
}
"--run-here" => {
flags.run_here = Some(true);
i += 1;
}
"--no-run-here" => {
flags.run_here = Some(false);
i += 1;
}
"--name" if i + 1 < args.len() => {
i += 2;
}
"--go" => {
i += 1;
}
"--pty" => {
// Deprecated no-op: --pty was previously used to request a
// pseudo-terminal session. PTY behaviour is now the default
// (or controlled by --headless). Silently consume the flag so
// legacy scripts continue to work.
i += 1;
}
_ => {
tool_args.push(args[i].clone());
i += 1;
}
}
}
(flags, tool_args)
}
pub(crate) struct LaunchOutputContext<'a> {
pub action: &'a str,
pub tool: &'a str,
pub requested_count: usize,
pub tag: Option<&'a str>,
pub launcher_name: &'a str,
pub terminal: Option<&'a str>,
pub background: bool,
pub run_here: Option<bool>,
pub hcom_config: &'a HcomConfig,
pub inline_readiness_wait_secs: Option<u64>,
}
pub(crate) fn print_launch_feedback(
db: &HcomDb,
result: &LaunchResult,
ctx: &LaunchOutputContext<'_>,
) -> Result<()> {
if result.failed > 0 {
for err in &result.errors {
if let Some(msg) = err.get("error").and_then(|v| v.as_str()) {
eprintln!("Error: {}", msg);
}
}
}
if result.launched == 0 && result.failed > 0 {
return Ok(());
}
let tool_label = capitalize(ctx.tool);
let plural = if ctx.requested_count != 1 { "s" } else { "" };
if result.failed > 0 {
println!(
"Started the {} process for {}/{} {} agent{} ({} failed)",
ctx.action, result.launched, ctx.requested_count, tool_label, plural, result.failed
);
} else {
let s = if result.launched != 1 { "s" } else { "" };
println!(
"Started the {} process for {} {} agent{}",
ctx.action, result.launched, tool_label, s
);
}
let instance_names: Vec<&str> = result
.handles
.iter()
.filter_map(|h| h.get("instance_name").and_then(|v| v.as_str()))
.collect();
if !instance_names.is_empty() {
println!("Names: {}", instance_names.join(" "));
}
println!("Batch id: {}", result.batch_id);
if ctx.inline_readiness_wait_secs.is_none() {
println!("To block until ready or fail (30s timeout), run: hcom events launch");
}
let launcher_participating = db
.get_instance_full(ctx.launcher_name)
.ok()
.flatten()
.is_some();
let (terminal_mode, terminal_auto_detected) = crate::terminal::resolve_terminal_mode_for_tips(
ctx.terminal,
&ctx.hcom_config.terminal,
ctx.background,
ctx.run_here.unwrap_or(false),
);
tips::print_launch_tips(
db,
LaunchTipsContext {
launched: result.launched,
tag: ctx.tag,
launcher_name: Some(ctx.launcher_name),
launcher_participating,
background: ctx.background,
terminal_mode: &terminal_mode,
terminal_auto_detected,
},
);
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum InlineLaunchReadiness {
Ready,
Failed,
Blocked,
Launching,
}
/// Map an inline-readiness outcome to a process exit code, shared by launch
/// and resume/fork so all three report readiness the same way. `None` means
/// no readiness wait ran (not inside an AI tool, or multi-launch).
pub(crate) fn readiness_exit_code(state: Option<InlineLaunchReadiness>, failed: usize) -> i32 {
match state {
Some(InlineLaunchReadiness::Failed) => 1,
Some(InlineLaunchReadiness::Launching) | Some(InlineLaunchReadiness::Blocked) => 2,
_ if failed == 0 => 0,
_ => 1,
}
}
pub(crate) fn print_inline_launch_readiness(
db: &HcomDb,
result: &LaunchResult,
timeout_secs: u64,
) -> InlineLaunchReadiness {
println!("Waiting up to {timeout_secs}s for launch readiness...");
let start = Instant::now();
let wait = launch_status::wait_for_launch(db, None, Some(&result.batch_id), timeout_secs);
let elapsed_secs = start.elapsed().as_secs_f64();
let (state, details) = match wait.status {
LaunchStatus::Ready => (InlineLaunchReadiness::Ready, Vec::new()),
LaunchStatus::Error => (InlineLaunchReadiness::Failed, wait.failures),
LaunchStatus::Blocked => (InlineLaunchReadiness::Blocked, wait.blockers),
LaunchStatus::Timeout | LaunchStatus::NoLaunches => {
(InlineLaunchReadiness::Launching, Vec::new())
}
};
println!(
"{}",
format_inline_launch_readiness(state, result, &wait.instances, elapsed_secs, &details)
);
state
}
fn instance_names_from_launch_result(result: &LaunchResult) -> Vec<String> {
result
.handles
.iter()
.filter_map(|h| {
h.get("instance_name")
.and_then(|v| v.as_str())
.map(ToString::to_string)
})
.collect()
}
fn format_inline_launch_readiness(
state: InlineLaunchReadiness,
result: &LaunchResult,
ready_instances: &[String],
elapsed_secs: f64,
failures: &[String],
) -> String {
let names = instance_names_from_launch_result(result);
let target = if names.is_empty() {
"agent".to_string()
} else {
names.join(" ")
};
let progress = format!("{}/{} ready", ready_instances.len(), result.launched);
let elapsed = format!("{elapsed_secs:.1}s");
match state {
InlineLaunchReadiness::Ready => {
let ready = if ready_instances.is_empty() {
target
} else {
ready_instances.join(" ")
};
format!("Launch ready: {ready} ({progress}, {elapsed}).")
}
InlineLaunchReadiness::Failed => {
let detail = if failures.is_empty() {
"no failure detail available".to_string()
} else {
failures.join("; ")
};
format!("Launch failed: {detail} (batch: {}).", result.batch_id)
}
InlineLaunchReadiness::Blocked => {
let detail = if failures.is_empty() {
"human attention needed".to_string()
} else {
failures.join("; ")
};
format!("Launch blocked: {detail} (batch: {}).", result.batch_id)
}
InlineLaunchReadiness::Launching => format!(
"Still launching after {elapsed}: {target} ({progress}, batch: {}). Check `hcom list -v` or `hcom events launch {} --timeout 30`.",
result.batch_id, result.batch_id
),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn s(items: &[&str]) -> Vec<String> {
items.iter().map(|i| i.to_string()).collect()
}
fn lt(tool: &str) -> LaunchTool {
LaunchTool::from_str(tool).unwrap()
}
#[test]
fn test_parse_launch_argv_simple() {
let (count, tool, _flags, args) = parse_launch_argv(&s(&["claude"])).unwrap();
assert_eq!(count, 1);
assert_eq!(tool, "claude");
assert!(args.is_empty());
}
#[test]
fn test_parse_launch_argv_with_count() {
let (count, tool, _, args) =
parse_launch_argv(&s(&["3", "gemini", "-m", "flash"])).unwrap();
assert_eq!(count, 3);
assert_eq!(tool, "gemini");
assert_eq!(args, s(&["-m", "flash"]));
}
#[test]
fn test_parse_launch_argv_with_tag() {
let (_, tool, flags, args) =
parse_launch_argv(&s(&["claude", "--tag", "test", "--model", "haiku"])).unwrap();
assert_eq!(tool, "claude");
assert_eq!(flags.tag, Some("test".to_string()));
assert_eq!(args, s(&["--model", "haiku"]));
}
#[test]
fn test_parse_launch_argv_accepts_legacy_pty() {
let (_, tool, flags, args) =
parse_launch_argv(&s(&["claude", "--headless", "--pty", "--model", "haiku"])).unwrap();
assert_eq!(tool, "claude");
assert!(flags.headless);
assert_eq!(args, s(&["--model", "haiku"]));
}
#[test]
fn test_parse_launch_argv_tag_after_tool_args() {
// --tag after tool-specific args should still be extracted (order-independent)
let (_, tool, flags, args) =
parse_launch_argv(&s(&["claude", "--model", "haiku", "--tag", "test"])).unwrap();
assert_eq!(tool, "claude");
assert_eq!(flags.tag, Some("test".to_string()));
assert_eq!(args, s(&["--model", "haiku"]));
}
#[test]
fn test_parse_launch_argv_headless() {
let (_, _, flags, _) = parse_launch_argv(&s(&["claude", "--headless"])).unwrap();
assert!(flags.headless);
}
#[test]
fn test_parse_launch_argv_no_run_here() {
let (_, _, flags, _) = parse_launch_argv(&s(&["claude", "--no-run-here"])).unwrap();
assert_eq!(flags.run_here, Some(false));
}
#[test]
fn test_parse_launch_argv_with_terminal() {
let (_, _, flags, _) =
parse_launch_argv(&s(&["claude", "--terminal", "kitty-tab"])).unwrap();
assert_eq!(flags.terminal, Some("kitty-tab".to_string()));
}
#[test]
fn test_parse_launch_argv_skips_global_flags() {
let (count, tool, _, _) =
parse_launch_argv(&s(&["--name", "bot", "--go", "2", "codex"])).unwrap();
assert_eq!(count, 2);
assert_eq!(tool, "codex");
}
#[test]
fn test_parse_launch_argv_empty_fails() {
assert!(parse_launch_argv(&[]).is_err());
}
#[test]
fn test_primary_tool_args_are_concatenated_verbatim() {
for (tool, field) in [
("claude", "claude_args"),
("gemini", "gemini_args"),
("codex", "codex_args"),
] {
let mut config = HcomConfig::default();
config.set_field(field, "--future-config value").unwrap();
let cli = s(&["--future-upstream-flag", "raw-value"]);
let merged = merge_tool_args(<(tool), &cli, &config);
assert_eq!(
merged,
s(&[
"--future-config",
"value",
"--future-upstream-flag",
"raw-value"
])
);
}
}
#[test]
fn test_merge_tool_args_applies_config_for_opencode_family_kimi_and_qoder() {
// These tools previously fell through to the `_` pass-through arm, which
// silently dropped their `*_args` config at launch.
let cli = s(&["--yolo"]);
for (tool, field) in [
("opencode", "opencode_args"),
("kilo", "kilo_args"),
("kimi", "kimi_args"),
("qoder", "qoder_args"),
] {
let mut config = HcomConfig::default();
config.set_field(field, "--model from-config").unwrap();
let merged = merge_tool_args(<(tool), &cli, &config);
assert_eq!(
merged,
s(&["--model", "from-config", "--yolo"]),