Repository navigation
Expand file tree
/
Copy pathlauncher.rs
More file actions
4175 lines (3855 loc) · 155 KB
/
Copy pathlauncher.rs
File metadata and controls
4175 lines (3855 loc) · 155 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
//! Unified launcher pipeline for released AI-tool integrations.
//!
//!
//! Provides a single entry point for launching all supported AI tools
//! with consistent batch tracking, environment setup, and error handling.
use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::Path;
use anyhow::{Result, bail};
use rand::RngExt;
use serde_json::json;
use crate::config::{self, HcomConfig};
use crate::db::HcomDb;
use crate::instance_binding;
use crate::instance_names;
use crate::instances;
use crate::paths;
use crate::shared::constants::HCOM_IDENTITY_VARS;
use crate::shared::tool_detection::tool_marker_vars;
use crate::terminal;
use crate::tools::launch_arg_validation::{
ANTIGRAVITY_REJECTED_ARGS, GEMINI_REJECTED_ARGS, GROK_REJECTED_ARGS, KILO_REJECTED_ARGS,
KIMI_REJECTED_ARGS, OMP_REJECTED_ARGS, OPENCODE_REJECTED_ARGS, PI_REJECTED_ARGS,
QODER_REJECTED_ARGS, validate_rejected_args,
};
use crate::tools::{
codex_preprocessing, copilot_preprocessing, cursor_preprocessing, opencode_preprocessing,
qoder_preprocessing,
};
/// Canonical tool types for launch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LaunchTool {
Claude,
ClaudePty,
Gemini,
Codex,
OpenCode,
Kilo,
Pi,
Antigravity,
Cursor,
Kimi,
Copilot,
Qoder,
Grok,
Omp,
}
impl LaunchTool {
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Result<Self> {
match s {
"claude" => Ok(LaunchTool::Claude),
"claude-pty" => Ok(LaunchTool::ClaudePty),
"gemini" => Ok(LaunchTool::Gemini),
"codex" => Ok(LaunchTool::Codex),
"opencode" => Ok(LaunchTool::OpenCode),
"kilo" | "kilocode" => Ok(LaunchTool::Kilo),
"pi" | "pi-agent" => Ok(LaunchTool::Pi),
"omp" | "omp-agent" => Ok(LaunchTool::Omp),
"antigravity" | "agy" => Ok(LaunchTool::Antigravity),
"cursor" | "cursor-agent" => Ok(LaunchTool::Cursor),
"kimi" => Ok(LaunchTool::Kimi),
"copilot" => Ok(LaunchTool::Copilot),
"qoder" | "qodercli" => Ok(LaunchTool::Qoder),
"grok" | "grok-build" => Ok(LaunchTool::Grok),
_ => bail!("Unknown tool: {}", s),
}
}
pub fn as_str(&self) -> &'static str {
match self {
LaunchTool::Claude => "claude",
LaunchTool::ClaudePty => "claude-pty",
LaunchTool::Gemini => "gemini",
LaunchTool::Codex => "codex",
LaunchTool::OpenCode => "opencode",
LaunchTool::Kilo => "kilo",
LaunchTool::Pi => "pi",
LaunchTool::Omp => "omp",
LaunchTool::Antigravity => "antigravity",
LaunchTool::Cursor => "cursor",
LaunchTool::Kimi => "kimi",
LaunchTool::Copilot => "copilot",
LaunchTool::Qoder => "qoder",
LaunchTool::Grok => "grok",
}
}
/// Canonical [`Tool`] for this launch surface.
///
/// `ClaudePty` is a launch-surface alias (PTY-wrapped Claude); it resolves
/// to `Tool::Claude` so all per-tool data flows through one spec.
pub fn tool(&self) -> crate::tool::Tool {
match self {
LaunchTool::Claude | LaunchTool::ClaudePty => crate::tool::Tool::Claude,
LaunchTool::Gemini => crate::tool::Tool::Gemini,
LaunchTool::Codex => crate::tool::Tool::Codex,
LaunchTool::OpenCode => crate::tool::Tool::OpenCode,
LaunchTool::Kilo => crate::tool::Tool::Kilo,
LaunchTool::Pi => crate::tool::Tool::Pi,
LaunchTool::Omp => crate::tool::Tool::Omp,
LaunchTool::Antigravity => crate::tool::Tool::Antigravity,
LaunchTool::Cursor => crate::tool::Tool::Cursor,
LaunchTool::Kimi => crate::tool::Tool::Kimi,
LaunchTool::Copilot => crate::tool::Tool::Copilot,
LaunchTool::Qoder => crate::tool::Tool::Qoder,
LaunchTool::Grok => crate::tool::Tool::Grok,
}
}
/// Integration spec for this launch surface (shared with the base `Tool`).
pub fn spec(&self) -> &'static crate::integration_spec::IntegrationSpec {
self.tool().spec()
}
/// Base tool name (without -pty suffix). Equivalent to `self.tool().as_str()`.
pub fn base_tool(&self) -> &'static str {
self.tool().as_str()
}
/// Whether this tool uses the PTY wrapper.
pub fn uses_pty(&self) -> bool {
// ClaudePty is a launch surface (alias), not a Tool variant — it always
// takes the PTY path. Everything else defers to the canonical spec.
if matches!(self, LaunchTool::ClaudePty) {
return true;
}
self.spec().launch.uses_pty_default
}
/// Executable name on PATH for this tool.
pub fn cli_binary(&self) -> &'static str {
self.spec().cli_binary
}
}
/// How the child process is hosted. Computed from (tool, background, pty) at
/// launch time so dispatch doesn't have to re-derive the combination.
///
/// - `InteractiveVisible`: foreground, user-visible terminal. All tools.
/// - `HeadlessPty`: background, PTY wrapper in a detached runner. Default
/// for gemini/codex/opencode/kilo/pi/omp/antigravity/cursor/kimi/copilot/qoder and for default claude `--headless`.
/// - `NativePrint`: background, direct claude spawn in print mode
/// (`-p --output-format stream-json --verbose`). Claude only, opt-in via an
/// explicit `-p`/`--print`; kept alive across turns by hcom's stop-hook loop.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LaunchBackend {
InteractiveVisible,
HeadlessPty,
NativePrint,
}
impl LaunchBackend {
/// Resolve from the already-prepared (tool, background) pair.
///
/// The PTY-vs-print decision for Claude is encoded in the [`LaunchTool`]
/// surface chosen by `launch()`: `Claude` is the `-p`/`--print` surface
/// (→ `NativePrint`), `ClaudePty` is the live PTY surface (→ `HeadlessPty`).
/// Background Claude defaults to `ClaudePty`; it only becomes
/// `Claude`/`NativePrint` when the caller passes `-p`/`--print`.
pub fn resolve(tool: &LaunchTool, background: bool) -> Self {
if !background {
return LaunchBackend::InteractiveVisible;
}
match tool {
LaunchTool::Claude => LaunchBackend::NativePrint,
LaunchTool::ClaudePty => LaunchBackend::HeadlessPty,
LaunchTool::Gemini
| LaunchTool::Codex
| LaunchTool::OpenCode
| LaunchTool::Kilo
| LaunchTool::Pi
| LaunchTool::Omp
| LaunchTool::Antigravity
| LaunchTool::Cursor
| LaunchTool::Kimi
| LaunchTool::Copilot
| LaunchTool::Qoder
| LaunchTool::Grok => LaunchBackend::HeadlessPty,
}
}
}
/// Launch parameters.
#[derive(Clone)]
pub struct LaunchParams {
pub tool: String,
pub count: usize,
pub args: Vec<String>,
/// Raw user/config args to persist for future resume, before hcom injections.
pub persisted_args: Option<Vec<String>>,
/// Session id being resumed, inherited by the recreated instance row so a
/// kill before the tool's first turn (no hook re-bind yet) stays resumable.
pub prior_session_id: Option<String>,
/// Saved unread position for a tracked resume; zero is a valid cursor.
pub resume_cursor: Option<i64>,
pub tag: Option<String>,
pub system_prompt: Option<String>,
pub initial_prompt: Option<String>,
pub background: bool,
pub cwd: Option<String>,
pub env: Option<HashMap<String, String>>,
pub launcher: Option<String>,
pub run_here: Option<bool>,
pub batch_id: Option<String>,
pub name: Option<String>,
pub skip_validation: bool,
pub terminal: Option<String>,
pub append_reply_handoff: bool,
}
impl Default for LaunchParams {
fn default() -> Self {
Self {
tool: "claude".to_string(),
count: 1,
args: Vec::new(),
persisted_args: None,
prior_session_id: None,
resume_cursor: None,
tag: None,
system_prompt: None,
initial_prompt: None,
background: false,
cwd: None,
env: None,
launcher: None,
run_here: None,
batch_id: None,
name: None,
skip_validation: false,
terminal: None,
append_reply_handoff: true,
}
}
}
/// Launch result.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct LaunchResult {
pub tool: String,
pub batch_id: String,
pub launched: usize,
pub failed: usize,
pub background: bool,
pub log_files: Vec<String>,
pub handles: Vec<serde_json::Value>,
pub errors: Vec<serde_json::Value>,
}
/// Predict if launch will block current terminal (run in same window).
/// Find tool executable path with fallbacks.
/// Claude has special fallback locations; other tools just use PATH.
fn find_tool_path(tool: &str) -> Option<String> {
crate::terminal::which_bin(tool)
}
/// Check if tool CLI is installed (PATH + fallbacks).
fn is_tool_installed(tool: &str) -> bool {
find_tool_path(tool).is_some()
}
pub fn will_run_in_current_terminal(
count: usize,
background: bool,
run_here: Option<bool>,
terminal: Option<&str>,
inside_ai_tool: bool,
) -> bool {
if let Some(rh) = run_here {
return rh;
}
// terminal=here forces current terminal
if terminal == Some("here") {
return true;
}
if inside_ai_tool {
return false;
}
if background {
return false;
}
count == 1
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LaunchEnvRegime {
HumanShell,
ContaminatedParent,
RunHere,
}
pub fn launch_env_regime(run_here: bool, inside_ai_tool: bool) -> LaunchEnvRegime {
if run_here {
LaunchEnvRegime::RunHere
} else if contaminated_parent_with_inside_ai_tool(inside_ai_tool) {
LaunchEnvRegime::ContaminatedParent
} else {
LaunchEnvRegime::HumanShell
}
}
pub fn contaminated_parent() -> bool {
contaminated_parent_with_inside_ai_tool(crate::shared::platform::is_inside_ai_tool())
}
fn contaminated_parent_with_inside_ai_tool(inside_ai_tool: bool) -> bool {
inside_ai_tool
|| std::env::var_os("CI").is_some()
|| std::env::var_os("GITHUB_ACTIONS").is_some()
|| std::env::vars_os().any(|(key, _)| key.to_string_lossy().starts_with("CARGO_"))
}
/// Build base environment, then overlay config.toml + ~/.hcom/env (these win).
///
/// This makes the new-window/runner-script path behave like the PTY path
/// (`Command::new` inherits parent env by default). The runner script
/// already `unset`s TOOL_MARKER_VARS + HCOM_IDENTITY_VARS before exec,
/// so those categories are safe to include here (they're cleared in-script).
pub fn build_launch_env(
hcom_config: &HcomConfig,
regime: LaunchEnvRegime,
) -> HashMap<String, String> {
build_launch_env_with_resolver(hcom_config, regime, crate::shell_env::resolved_shell_env)
}
/// Apply the launcher's inherited `HCOM_NOTES` to a child instance env as a
/// fallback only.
///
/// `instance_env` (via `base_env`) already carries any notes resolved from the
/// explicit sources — config.toml, `~/.hcom/env`, and `LaunchParams.env` — and
/// those must win. The inherited parent value only fills the gap for a nested
/// launch where no explicit notes were configured, so it must not clobber a
/// value already present (including an intentional empty string used to clear
/// notes).
fn apply_inherited_notes(instance_env: &mut HashMap<String, String>, inherited: Option<String>) {
if let Some(val) = inherited {
instance_env.entry("HCOM_NOTES".to_string()).or_insert(val);
}
}
/// Start a new Grok conversation under an explicit session id.
///
/// Without one the TUI opens on its welcome screen over a hidden "home"
/// session, and never draws turns another client (hcom's queue) runs there.
/// `--session-id` opens the conversation view directly. Resume/continue
/// already open a conversation.
fn ensure_grok_session_id(args: &mut Vec<String>) {
let opens_conversation = args.iter().take_while(|arg| *arg != "--").any(|arg| {
let flag = arg.split('=').next().unwrap_or(arg);
matches!(
flag,
"-r" | "--resume" | "-c" | "--continue" | "-s" | "--session-id"
)
});
if !opens_conversation {
args.insert(0, "--session-id".to_string());
args.insert(1, uuid::Uuid::new_v4().to_string());
}
}
/// Prepend `extra` to Grok's `--rules` (text appended to its system prompt).
fn inject_grok_rules(args: &mut Vec<String>, extra: &str) {
if extra.is_empty() {
return;
}
let mut i = 0;
// Flags only: after `--` it is the prompt, whatever it looks like.
while i < args.len() && args[i] != "--" {
let token = &args[i];
if token == "--rules" {
if i + 1 < args.len() && !args[i + 1].starts_with('-') {
args[i + 1] = format!("{}\n\n{}", extra, args[i + 1]);
} else {
args.insert(i + 1, extra.to_string());
}
return;
}
if let Some(rest) = token.strip_prefix("--rules=") {
args[i] = format!("--rules={}\n\n{}", extra, rest);
return;
}
i += 1;
}
args.insert(0, "--rules".to_string());
args.insert(1, extra.to_string());
}
fn build_codex_bootstrap(
db: &HcomDb,
hcom_dir: &Path,
instance_name: &str,
background: bool,
instance_env: &HashMap<String, String>,
) -> String {
build_launch_bootstrap(
db,
hcom_dir,
instance_name,
"codex",
background,
instance_env,
)
}
fn build_grok_bootstrap(
db: &HcomDb,
hcom_dir: &Path,
instance_name: &str,
background: bool,
instance_env: &HashMap<String, String>,
) -> String {
build_launch_bootstrap(
db,
hcom_dir,
instance_name,
"grok",
background,
instance_env,
)
}
fn build_launch_bootstrap(
db: &HcomDb,
hcom_dir: &Path,
instance_name: &str,
tool: &str,
background: bool,
instance_env: &HashMap<String, String>,
) -> String {
// Codex and Grok take their bootstrap at launch, so render it from the env
// the instance will run with. HCOM_BACKGROUND is only added to the runner
// env later, hence the explicit override.
let cwd = std::env::current_dir().unwrap_or_default();
let mut ctx = crate::shared::HcomContext::from_env(instance_env, cwd);
ctx.hcom_dir = hcom_dir.to_path_buf();
ctx.is_launched = true;
ctx.is_background = background;
crate::bootstrap::get_bootstrap(db, &ctx, instance_name, tool)
}
fn build_launch_env_with_resolver<F>(
hcom_config: &HcomConfig,
regime: LaunchEnvRegime,
resolved_shell_env: F,
) -> HashMap<String, String>
where
F: Fn() -> Option<HashMap<String, String>>,
{
let base: HashMap<String, String> = match regime {
LaunchEnvRegime::HumanShell | LaunchEnvRegime::RunHere => std::env::vars().collect(),
LaunchEnvRegime::ContaminatedParent => {
resolved_shell_env().unwrap_or_else(|| std::env::vars().collect())
}
};
let strip = match regime {
LaunchEnvRegime::RunHere => run_here_env_strip_set(),
LaunchEnvRegime::HumanShell | LaunchEnvRegime::ContaminatedParent => env_strip_set(),
};
let mut env: HashMap<String, String> = base
.into_iter()
.filter(|(k, _)| !strip.contains(k.as_str()))
.collect();
// HCOM_* settings from config.toml
for (key, value) in hcom_config.to_env_dict() {
if !value.is_empty() {
insert_effective_env(&mut env, key, value, cfg!(windows));
}
}
// Passthrough vars from env file (these win over everything)
let env_path = paths::hcom_path(&["env"]);
for (key, value) in config::load_env_extras(&env_path) {
if !value.is_empty() {
insert_effective_env(&mut env, key, value, cfg!(windows));
}
}
env
}
/// Build the set of env var names to strip from inherited env.
///
/// Three closed categories (owned by hcom):
/// 1. HCOM_IDENTITY_VARS
/// 2. TOOL_MARKER_VARS
/// 3. TERMINAL_CONTEXT_VARS
///
/// Per-tool instance-state vars are NOT in the initial strip — they are
/// stripped per-instance later via `strip_instance_state_vars` so that
/// cross-tool nesting doesn't strip vars the child tool doesn't own.
fn env_strip_set() -> std::collections::HashSet<String> {
let mut strip: std::collections::HashSet<String> = std::collections::HashSet::new();
strip.extend(run_here_env_strip_set());
for v in crate::terminal::TERMINAL_CONTEXT_VARS {
strip.insert((*v).to_string());
}
strip
}
fn run_here_env_strip_set() -> std::collections::HashSet<String> {
let mut strip: std::collections::HashSet<String> = std::collections::HashSet::new();
for v in crate::shared::constants::HCOM_IDENTITY_VARS {
strip.insert((*v).to_string());
}
for v in tool_marker_vars() {
strip.insert((*v).to_string());
}
strip.insert("HCOM_LAUNCHED_PRESET".to_string());
// A new plugin host must claim ownership itself; an inherited marker would
// make hcom's OpenCode/Kilo plugin stay inert in the process hcom launched.
strip.insert(crate::hooks::runtime::PLUGIN_HOST_PID_ENV.to_string());
strip
}
/// Insert an environment override using the target platform's key semantics.
/// Windows environment names are case-insensitive, while `HashMap` keys are
/// not; remove an earlier spelling so the child receives one authoritative
/// value instead of an order-dependent pair.
fn insert_effective_env(
env: &mut HashMap<String, String>,
key: String,
value: String,
case_insensitive: bool,
) {
if case_insensitive {
env.retain(|existing, _| !existing.eq_ignore_ascii_case(&key));
}
env.insert(key, value);
}
fn effective_env_value<'a>(
env: &'a HashMap<String, String>,
key: &str,
case_insensitive: bool,
) -> Option<&'a str> {
if case_insensitive {
env.iter()
.find(|(existing, _)| existing.eq_ignore_ascii_case(key))
.map(|(_, value)| value.as_str())
} else {
env.get(key).map(String::as_str)
}
}
/// Make the tool config directory explicit in the child environment.
///
/// Some launch backends clear the inherited environment while others do not.
/// Copying an ambient override into the effective launch map keeps preflight,
/// hook setup, and the child process on the same directory in both cases.
fn ensure_tool_config_env(tool: &LaunchTool, env: &mut HashMap<String, String>) {
let Some(env_var) = tool.spec().launch.config_dir_env else {
return;
};
let case_insensitive = cfg!(windows);
if let Some(value) = effective_env_value(env, env_var, case_insensitive).map(str::to_owned) {
insert_effective_env(env, env_var.to_string(), value, case_insensitive);
return;
}
if let Some(value) = std::env::var(env_var)
.ok()
.filter(|value| !value.is_empty())
{
insert_effective_env(env, env_var.to_string(), value, case_insensitive);
}
}
/// Get system prompt file path for Gemini/Codex.
fn get_system_prompt_path(tool: &str) -> std::path::PathBuf {
let prompts_dir = paths::hcom_path(&["system-prompts"]);
fs::create_dir_all(&prompts_dir).ok();
prompts_dir.join(format!("{}.md", tool))
}
/// Write system prompt to file (only if content differs).
fn write_system_prompt_file(system_prompt: &str, tool: &str) -> String {
let filepath = get_system_prompt_path(tool);
// Only write if content differs
if let Ok(existing) = fs::read_to_string(&filepath)
&& existing == system_prompt
{
return filepath.to_string_lossy().to_string();
}
if let Err(e) = fs::write(&filepath, system_prompt) {
eprintln!(
"[hcom] warn: failed to write system prompt to {}: {e}",
filepath.display()
);
}
filepath.to_string_lossy().to_string()
}
/// Generate a UUID v4-like process ID string.
fn generate_process_id() -> String {
let mut rng = rand::rng();
let a: u32 = rng.random();
let b: u16 = rng.random();
let c: u16 = (rng.random::<u16>() & 0x0FFF) | 0x4000; // version 4
let d: u16 = (rng.random::<u16>() & 0x3FFF) | 0x8000; // variant 1
let e: u64 = rng.random::<u64>() & 0xFFFFFFFFFFFF; // 48 bits
format!("{:08x}-{:04x}-{:04x}-{:04x}-{:012x}", a, b, c, d, e)
}
fn install_diag_context(tool: &LaunchTool, paths: &[(&str, std::path::PathBuf)]) -> String {
use std::fmt::Write as _;
let mut out = String::new();
let _ = writeln!(out, "Diagnostic context:");
for (label, p) in paths {
let _ = writeln!(out, " resolved {label}={}", p.display());
}
let _ = writeln!(
out,
" HCOM_DIR={}",
std::env::var("HCOM_DIR").unwrap_or_else(|_| "<unset>".into())
);
let tool_env_var = tool.spec().launch.config_dir_env;
if let Some(env_var) = tool_env_var {
let _ = writeln!(
out,
" {env_var}={}",
std::env::var(env_var).unwrap_or_else(|_| "<unset>".into())
);
}
let _ = writeln!(
out,
" cwd={}",
std::env::current_dir()
.map(|p| p.display().to_string())
.unwrap_or_else(|_| "<unknown>".into())
);
out
}
/// Verify hooks are installed for the target tool, auto-install if needed.
///
/// Uses verify-first pattern: read-only check first, only write if needed.
/// Strict gate: refuses to launch if hooks can't be installed.
fn ensure_hooks_installed(tool: &LaunchTool, include_permissions: bool) -> Result<()> {
match tool {
LaunchTool::Claude | LaunchTool::ClaudePty => unreachable!("Claude uses per-run hooks"),
LaunchTool::Gemini => {
if !crate::hooks::gemini::is_gemini_version_supported() {
if let Some(ver) = crate::hooks::gemini::get_gemini_version() {
bail!(
"Gemini CLI version {}.{}.{} is too old. Update: npm i -g @google/gemini-cli@latest",
ver.0,
ver.1,
ver.2
);
} else {
eprintln!("Warning: Could not detect Gemini CLI version");
}
}
if crate::hooks::gemini::verify_gemini_hooks_installed(include_permissions) {
return Ok(());
}
if let Err(e) = crate::hooks::gemini::try_setup_gemini_hooks(include_permissions) {
let diag = install_diag_context(
tool,
&[(
"settings_path",
crate::hooks::gemini::get_gemini_settings_path(),
)],
);
bail!(
"Failed to setup Gemini hooks: {e}\n\
Run: hcom hooks add gemini\n\
{diag}"
);
}
Ok(())
}
LaunchTool::Codex => unreachable!("Codex uses per-run hooks"),
LaunchTool::OpenCode => unreachable!("OpenCode uses per-run hooks"),
LaunchTool::Kilo => unreachable!("Kilo uses per-run hooks"),
LaunchTool::Pi => unreachable!("Pi uses per-run hooks"),
LaunchTool::Omp => unreachable!("OMP uses per-run hooks"),
LaunchTool::Antigravity => {
if crate::hooks::antigravity::verify_antigravity_hooks_installed(include_permissions) {
return Ok(());
}
if let Err(e) =
crate::hooks::antigravity::try_setup_antigravity_hooks(include_permissions)
{
let diag = install_diag_context(
tool,
&[(
"hooks_path",
crate::hooks::antigravity::get_antigravity_hooks_path(),
)],
);
bail!(
"Failed to setup Antigravity hooks: {e}\n\
Run: hcom hooks add antigravity\n\
{diag}"
);
}
Ok(())
}
LaunchTool::Cursor => {
if crate::hooks::cursor::verify_cursor_hooks_installed(include_permissions) {
return Ok(());
}
if let Err(e) = crate::hooks::cursor::try_setup_cursor_hooks(include_permissions) {
let diag = install_diag_context(
tool,
&[("hooks_path", crate::hooks::cursor::get_cursor_hooks_path())],
);
bail!(
"Failed to setup Cursor hooks: {e}\n\
Run: hcom hooks add cursor\n\
{diag}"
);
}
Ok(())
}
LaunchTool::Kimi => {
if crate::hooks::kimi::verify_kimi_hooks_installed(include_permissions) {
return Ok(());
}
if let Err(e) = crate::hooks::kimi::try_setup_kimi_hooks(include_permissions) {
let diag = install_diag_context(
tool,
&[("hooks_path", crate::hooks::kimi::get_kimi_settings_path())],
);
bail!(
"Failed to setup Kimi hooks: {e}\n\
Run: hcom hooks add kimi\n\
{diag}"
);
}
Ok(())
}
LaunchTool::Copilot => unreachable!("Copilot uses per-run hooks"),
LaunchTool::Qoder => unreachable!("Qoder uses per-run hooks"),
LaunchTool::Grok => unreachable!("Grok has no hooks"),
}
}
/// Build a command string for Claude (non-PTY mode). Quoting matches the
/// shell that will run the resulting script: PowerShell on Windows, POSIX
/// shell elsewhere (see `launch_terminal`'s `create_powershell_script` /
/// `create_bash_script` split).
fn build_claude_command(args: &[String]) -> String {
let mut parts = vec!["claude".to_string()];
for arg in args {
if cfg!(windows) {
parts.push(terminal::ps_quote(arg));
} else {
parts.push(crate::tools::args_common::shell_quote(arg));
}
}
parts.join(" ")
}
/// Tool-specific extra environment variables for PTY mode.
fn tool_extra_env(tool: &str) -> HashMap<String, String> {
let mut m = HashMap::new();
// Claude is driven by the PTY wrapper (ConPTY on Windows, openpty on Unix),
// which handles injection; HCOM_PTY_MODE tells the Stop hook to defer to it.
if tool == "claude" {
m.insert("HCOM_PTY_MODE".to_string(), "1".to_string());
}
if tool == "antigravity" {
m.insert("ANTIGRAVITY_AGENT".to_string(), "1".to_string());
}
m
}
fn background_runner_env(
tool: &str,
env: &HashMap<String, String>,
instance_name: &str,
) -> HashMap<String, String> {
let mut runner_env = env.clone();
runner_env.insert("HCOM_INSTANCE_NAME".to_string(), instance_name.to_string());
// Default HCOM_TOOL when the caller didn't already set it (most callers
// come from `launch()` which inserts it; this keeps the standalone PTY
// and headless paths consistent so `{tool}` template substitution and
// delivery-loop label formatting see the right value).
runner_env
.entry("HCOM_TOOL".to_string())
.or_insert_with(|| tool.to_string());
runner_env.extend(tool_extra_env(tool));
runner_env
}
/// Non-HCOM ambient env to forward through the sidecar, with marker/identity/
/// instance-state/terminal-color vars stripped. On Windows env names are
/// case-insensitive (and the paired PowerShell `Remove-Item Env:` folds case),
/// so `case_insensitive` folds case for the match; Unix keeps exact-case.
fn sidecar_ambient_env<'a>(
env: &HashMap<String, String>,
strip_vars: impl Iterator<Item = &'a str>,
case_insensitive: bool,
) -> HashMap<String, String> {
let norm = |k: &str| {
if case_insensitive {
k.to_ascii_lowercase()
} else {
k.to_string()
}
};
let strip: std::collections::HashSet<String> = strip_vars.map(&norm).collect();
env.iter()
.filter(|(k, _)| !k.starts_with("HCOM_") && !strip.contains(&norm(k)))
.map(|(k, v)| (k.clone(), v.clone()))
.collect()
}
struct RunnerBinaries {
path_dirs: Vec<String>,
tool_path: Option<String>,
}
/// Resolve the executables needed by generated runners and order their directories.
///
/// The selected Node runtime must precede every other prepended directory: tool,
/// hcom, and Python directories can all contain an older `node`/`npx`. The tool is
/// resolved before PATH changes and passed explicitly to `hcom pty`, so moving its
/// directory after Node does not change which tool executable is launched.
fn resolve_runner_binaries(
initial_dirs: Vec<String>,
tool_bin: &str,
mut which_bin: impl FnMut(&str) -> Option<String>,
) -> RunnerBinaries {
let tool_path = which_bin(tool_bin);
let hcom_path = which_bin("hcom");
let node_path = which_bin("node");
let python_path = which_bin("python3");
let mut path_dirs = Vec::new();
fn append_binary_dir(path_dirs: &mut Vec<String>, path: &str) {
if let Some(dir) = Path::new(path).parent() {
let dir = dir.to_string_lossy().into_owned();
if !path_dirs.contains(&dir) {
path_dirs.push(dir);
}
}
}
for path in node_path.iter() {
append_binary_dir(&mut path_dirs, path);
}
for dir in initial_dirs {
if !path_dirs.contains(&dir) {
path_dirs.push(dir);
}
}
for path in tool_path
.iter()
.chain(hcom_path.iter())
.chain(python_path.iter())
{
append_binary_dir(&mut path_dirs, path);
}
RunnerBinaries {
path_dirs,
tool_path,
}
}
/// Windows runner: a PowerShell script that launches the tool through the hcom
/// ConPTY wrapper (`hcom pty <tool>`), mirroring the Unix bash runner. The
/// wrapper runs the delivery loop so idle agents can be woken. Mirrors the bash
/// runner's env scrubbing, HCOM env, secret sidecar, and PATH setup.
fn create_runner_script_windows(
tool: &str,
cwd: &str,
instance_name: &str,
env: &HashMap<String, String>,
tool_args: &[String],
run_here: bool,
) -> Result<String> {
let tool_spec = tool.parse::<crate::tool::Tool>().map(|t| t.spec()).ok();
let instance_state_env: &[&str] = tool_spec.map(|s| s.instance_state_env).unwrap_or(&[]);
let launch_dir = paths::hcom_path(&[paths::LAUNCH_DIR]);
fs::create_dir_all(&launch_dir).ok();
let script_file = launch_dir.join(format!(
"{}_{}_{}_{}.ps1",
tool,
instance_name,
std::process::id(),
rand::random::<u16>() % 9000 + 1000
));
// Visible HCOM_* env, plus the managed-launch marker so hooks engage.
let mut hcom_env: HashMap<String, String> = env
.iter()
.filter(|(k, _)| k.starts_with("HCOM_"))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
hcom_env.insert("HCOM_LAUNCHED".to_string(), "1".to_string());
let env_block = terminal::build_env_string(&hcom_env, "powershell");
// Non-HCOM ambient env (may carry secrets) goes through a private sidecar
// that is dot-sourced then deleted, matching the bash runner.
let pane_identity_vars = if run_here {
std::collections::HashSet::new()
} else {
crate::config::pane_identity_env_vars()
};
let ambient_env = sidecar_ambient_env(
env,
tool_marker_vars()
.iter()
.chain(HCOM_IDENTITY_VARS.iter())
.chain(instance_state_env.iter())
.chain(crate::terminal::TERMINAL_COLOR_VARS.iter())
.copied()
.chain(pane_identity_vars.iter().map(String::as_str)),
true,
);
let sidecar_source = if ambient_env.is_empty() {
String::new()
} else {
let env_file = launch_dir.join(format!(
"{}_{}_{}_{}.ps1",
tool,
instance_name,
std::process::id(),
rand::random::<u16>() % 9000 + 1000
));
let mut file = crate::sys::fs::create_private_new(&env_file)?;
// Windows PowerShell 5.1 reads BOM-less files using the legacy ANSI
// code page, corrupting non-ASCII env values; a UTF-8 BOM forces it
// to read as UTF-8.
file.write_all(b"\xEF\xBB\xBF")?;
writeln!(
file,
"{}",
terminal::build_env_string(&ambient_env, "powershell")
)?;
let q = terminal::ps_quote(&env_file.to_string_lossy());
format!("if (Test-Path {q}) {{ . {q}; Remove-Item -Force {q} }}")
};
// Scrub inherited tool markers / identity / instance-state vars.
let unset_names: Vec<String> = tool_marker_vars()
.iter()
.chain(HCOM_IDENTITY_VARS.iter())
.chain(instance_state_env.iter())
.map(|v| format!("Env:{v}"))
.collect();
let unset_line = if unset_names.is_empty() {
String::new()
} else {
format!(
"Remove-Item {} -ErrorAction SilentlyContinue",
unset_names.join(",")
)
};
// Resolve binary directories for minimal PATH environments.
let mut path_dirs: Vec<String> = Vec::new();
if let Ok(dev_root) = std::env::var("HCOM_DEV_ROOT")
&& let Some(bin) = crate::shared::dev_root_binary(Path::new(&dev_root))
&& let Some(dir) = bin.parent()
{
path_dirs.push(dir.to_string_lossy().into_owned());
}
// Ensure the launched tool (and its hooks) can call back to *this* hcom by
// name — a dev binary may not be on the global PATH.
if let Ok(exe) = std::env::current_exe()
&& let Some(dir) = exe.parent()
{
let d = dir.to_string_lossy().to_string();
if !path_dirs.contains(&d) {
path_dirs.push(d);
}
}
let tool_bin = tool
.parse::<crate::tool::Tool>()
.map(|t| t.spec().cli_binary)
.unwrap_or(tool);
let binaries = resolve_runner_binaries(path_dirs, tool_bin, terminal::which_bin);
let path_dirs = binaries.path_dirs;
let path_line = if path_dirs.is_empty() {
String::new()
} else {
format!(
"$env:PATH = {} + $env:PATH",
terminal::ps_quote(&format!("{};", path_dirs.join(";")))
)
};