-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.rs
More file actions
1635 lines (1508 loc) · 52.7 KB
/
Copy pathmain.rs
File metadata and controls
1635 lines (1508 loc) · 52.7 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
use clap::{Args, CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::{generate, Shell};
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
mod host_adapter;
mod journal_sink;
mod run_output;
mod serve;
#[derive(Debug, Parser)]
#[command(
name = "altai-cli",
version,
about = "ALTAI terminal product",
long_about = "The ALTAI terminal product. Use `altai agent` for the interactive TUI, `altai run` for one-shot headless sessions, and `altai acp` for Agent Client Protocol (ACP) over stdio."
)]
struct Cli {
#[command(subcommand)]
command: Option<Commands>,
}
#[derive(Debug, Subcommand)]
enum Commands {
/// Start the interactive ALTAI terminal experience.
Agent(AgentArgs),
/// Run one prompt without starting an interactive terminal session.
Run(RunArgs),
/// Speak the Agent Client Protocol (ACP) over stdio for editors such as Zed.
Acp(AcpArgs),
/// Start the machine-facing ALTAI agent-host stdio protocol.
Serve(ServeArgs),
/// Print release and dependency information.
Version {
/// Include terminal-contract metadata.
#[arg(long)]
verbose: bool,
},
/// Generate shell completion definitions.
Completion {
#[arg(value_enum)]
shell: Shell,
},
/// Inspect the local terminal-product foundation.
Doctor {
/// Print machine-readable JSON.
#[arg(long)]
json: bool,
},
/// Inspect configuration locations for an ALTAI workspace.
Config {
#[command(subcommand)]
command: ConfigCommands,
},
/// Inspect the model selected for an ALTAI workspace.
Models {
#[command(subcommand)]
command: ModelsCommands,
},
/// Launch ALTAI Desktop. This router is safe to exercise with --dry-run.
Open(OpenArgs),
/// Inspect the durable agent event journal shared with ALTAI Desktop.
Journal {
#[command(subcommand)]
command: JournalCommands,
},
}
#[derive(Debug, Args)]
struct ServeArgs {
/// Required guard that prevents accidentally treating a terminal as a protocol transport.
#[arg(long)]
stdio: bool,
/// Agent-host protocol version to serve.
#[arg(long, default_value_t = 1)]
protocol: u8,
/// Canonical workspace root for this host process.
#[arg(long)]
workspace: PathBuf,
}
#[derive(Debug, Subcommand)]
enum JournalCommands {
/// List incomplete runs and, optionally, the latest run for one chat.
Summary(JournalSummaryArgs),
/// Fetch journal events for one run after a sequence number.
Fetch(JournalFetchArgs),
}
#[derive(Debug, Args)]
struct JournalSummaryArgs {
/// Workspace path. Defaults to the current directory.
path: Option<PathBuf>,
/// Restrict the latest-run lookup to one chat.
#[arg(long)]
chat: Option<String>,
/// Print machine-readable JSON.
#[arg(long)]
json: bool,
}
#[derive(Debug, Args)]
struct JournalFetchArgs {
/// Workspace path. Defaults to the current directory.
path: Option<PathBuf>,
/// Run identifier to fetch events for.
#[arg(long)]
run: String,
/// Only return events with sequence greater than this value.
#[arg(long, default_value_t = 0)]
after: u64,
/// Maximum number of events to return.
#[arg(long, default_value_t = 200)]
limit: usize,
/// Print machine-readable JSON.
#[arg(long)]
json: bool,
}
#[derive(Debug, Clone, ValueEnum, PartialEq, Eq)]
enum PermissionMode {
/// Prompt before protected shell commands and file edits.
Ask,
/// Apply file edits automatically while retaining protected shell prompts.
AutoEdit,
/// Read-only planning mode.
Plan,
/// Use the guarded bypass policy. This always requires an explicit flag.
Bypass,
}
impl PermissionMode {
const fn as_str(&self) -> &'static str {
match self {
Self::Ask => "ask",
Self::AutoEdit => "auto-edit",
Self::Plan => "plan",
Self::Bypass => "bypass",
}
}
}
#[derive(Debug, Clone, Copy, ValueEnum, PartialEq, Eq)]
enum ThemeMode {
/// Select an ALTAI terminal theme from terminal capabilities.
Auto,
/// Use the ALTAI near-black IDE theme.
Dark,
/// Use the ALTAI light theme.
Light,
/// Preserve terminal structure without ANSI foreground colors.
NoColor,
}
impl ThemeMode {
const fn as_str(&self) -> &'static str {
match self {
Self::Auto => "auto",
Self::Dark => "dark",
Self::Light => "light",
Self::NoColor => "no-color",
}
}
}
#[derive(Debug, Clone, ValueEnum, PartialEq, Eq)]
enum OutputMode {
/// Interactive human-oriented output.
Pretty,
/// Line-oriented human output.
Plain,
/// Print only the terminal assistant result.
Final,
/// Emit one structured JSON object for the final result.
Json,
/// Emit the versioned ALTAI JSONL event stream.
Jsonl,
}
impl OutputMode {
const fn as_str(&self) -> &'static str {
match self {
Self::Pretty => "pretty",
Self::Plain => "plain",
Self::Final => "final",
Self::Json => "json",
Self::Jsonl => "jsonl",
}
}
}
#[derive(Debug, Args)]
struct AgentOptions {
/// Explicit workspace root. Defaults to PATH or the current directory.
#[arg(short, long)]
workspace: Option<PathBuf>,
/// Provider/model identifier such as anthropic/claude-sonnet-4-6.
#[arg(long)]
model: Option<String>,
/// Fallback provider/model identifier.
#[arg(long)]
fallback_model: Option<String>,
/// Permission behavior for this process.
#[arg(long, value_enum)]
permission: Option<PermissionMode>,
/// Terminal theme selection.
#[arg(long, value_enum, default_value_t = ThemeMode::Auto)]
theme: ThemeMode,
/// Resume this durable ALTAI chat.
#[arg(long)]
resume: Option<String>,
/// Attach a local file to the next prompt. May be repeated.
#[arg(long = "file")]
files: Vec<PathBuf>,
/// Disable between-turn auto-compaction (manual `/compact` still works).
#[arg(long)]
no_auto_compact: bool,
/// Token threshold that triggers auto-compaction when auto is enabled.
#[arg(long)]
compact_threshold: Option<usize>,
/// Number of recent summaries / tail turns retained after compaction.
#[arg(long)]
compact_tail: Option<usize>,
}
#[derive(Debug, Args)]
struct AgentArgs {
/// Workspace path. Defaults to the current directory.
path: Option<PathBuf>,
/// Use an accessible line-oriented REPL instead of the IsanAgent TUI.
#[arg(long)]
no_tui: bool,
/// Describe the resolved terminal session without starting the host.
#[arg(long)]
dry_run: bool,
#[command(flatten)]
options: AgentOptions,
}
#[derive(Debug, Args)]
struct AcpArgs {
/// Workspace path. Defaults to the current directory.
path: Option<PathBuf>,
/// Describe the resolved ACP host without starting it.
#[arg(long)]
dry_run: bool,
#[command(flatten)]
options: AgentOptions,
}
#[derive(Debug, Args)]
struct RunArgs {
/// Workspace path. Defaults to the current directory.
path: Option<PathBuf>,
/// Prompt text. Use `-` to read the prompt from standard input.
#[arg(short, long)]
prompt: String,
/// Output contract for the foreground run.
#[arg(long, value_enum, default_value_t = OutputMode::Pretty)]
output: OutputMode,
/// Alias for `--output jsonl`.
#[arg(long, conflicts_with = "output")]
json: bool,
/// Complete foreground-run timeout, for example `10m`.
#[arg(long)]
timeout: Option<String>,
/// Suppress non-error diagnostic output.
#[arg(long)]
quiet: bool,
/// Describe the resolved foreground run without starting the host.
#[arg(long)]
dry_run: bool,
#[command(flatten)]
options: AgentOptions,
}
#[derive(Debug, Args)]
struct OpenArgs {
/// File or folder to open in ALTAI Desktop.
path: Option<PathBuf>,
/// Describe the desktop command without spawning it.
#[arg(long)]
dry_run: bool,
}
#[derive(Debug, Subcommand)]
enum ConfigCommands {
/// Print the project-local ALTAI and IsanAgent configuration paths.
Path(ConfigPathArgs),
/// Resolve non-secret agent settings and optionally report their origins.
List(ConfigListArgs),
}
#[derive(Debug, Args)]
struct ConfigPathArgs {
/// Workspace path. Defaults to the current directory.
path: Option<PathBuf>,
/// Print machine-readable JSON.
#[arg(long)]
json: bool,
}
#[derive(Debug, Args)]
struct ConfigListArgs {
/// Workspace path. Defaults to the current directory.
path: Option<PathBuf>,
/// Resolve the effective settings using ALTAI's documented precedence.
#[arg(long)]
resolved: bool,
/// Include the source that supplied each effective setting.
#[arg(long, requires = "resolved")]
show_origin: bool,
/// Print machine-readable JSON.
#[arg(long)]
json: bool,
}
#[derive(Debug, Subcommand)]
enum ModelsCommands {
/// Print the resolved primary and fallback model selections.
Current(ModelsCurrentArgs),
}
#[derive(Debug, Args)]
struct ModelsCurrentArgs {
/// Workspace path. Defaults to the current directory.
path: Option<PathBuf>,
/// Include the source that supplied each selection.
#[arg(long)]
show_origin: bool,
/// Print machine-readable JSON.
#[arg(long)]
json: bool,
}
#[derive(Debug)]
enum CliError {
Message(String),
#[allow(dead_code)] // Reserved for commands that still lack a host integration.
HostUnavailable {
command: &'static str,
},
RunFailed {
code: run_output::RunExitCode,
message: String,
},
}
impl CliError {
fn exit_code(&self) -> u8 {
match self {
// Exit code 10 is reserved by the public contract for an internal
// error. A missing host integration must never masquerade as an
// approval, provider, or workspace failure.
Self::HostUnavailable { .. } => 10,
Self::RunFailed { code, .. } => (*code).into(),
Self::Message(_) => 1,
}
}
}
impl std::fmt::Display for CliError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Message(message) => f.write_str(message),
Self::HostUnavailable { command } => write!(
f,
"`altai-cli {command}` is declared but cannot run yet: the ALTAI adapter needs the reusable IsanAgent host API. Use `altai-cli doctor` to inspect the installed foundation."
),
Self::RunFailed { message, .. } => f.write_str(message),
}
}
}
fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("altai-cli: {error}");
ExitCode::from(error.exit_code())
}
}
}
fn run() -> Result<(), CliError> {
let cli = Cli::parse();
match cli.command {
None => {
Cli::command()
.print_help()
.map_err(|error| CliError::Message(error.to_string()))?;
println!();
Ok(())
}
Some(Commands::Agent(args)) => agent(args),
Some(Commands::Run(args)) => run_prompt(args),
Some(Commands::Acp(args)) => acp(args),
Some(Commands::Serve(args)) => serve_command(args),
Some(Commands::Version { verbose }) => print_version(verbose),
Some(Commands::Completion { shell }) => {
let mut command = Cli::command();
let name = command.get_name().to_string();
generate(shell, &mut command, name, &mut io::stdout());
Ok(())
}
Some(Commands::Doctor { json }) => doctor(json),
Some(Commands::Config { command }) => config(command),
Some(Commands::Models { command }) => models(command),
Some(Commands::Open(args)) => open_desktop(args),
Some(Commands::Journal { command }) => journal(command),
}
}
fn serve_command(args: ServeArgs) -> Result<(), CliError> {
if !args.stdio || args.protocol != altai_protocol::PROTOCOL_VERSION {
return Err(CliError::Message(
"serve requires --stdio --protocol 1".into(),
));
}
let workspace = altai_core::resolve_workspace(Some(&args.workspace))
.map_err(|error| CliError::Message(error.to_string()))?;
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.map_err(|error| CliError::Message(format!("could not start serve runtime: {error}")))?
.block_on(serve::run(workspace))
.map_err(CliError::Message)
}
fn journal(command: JournalCommands) -> Result<(), CliError> {
match command {
JournalCommands::Summary(args) => journal_summary(args),
JournalCommands::Fetch(args) => journal_fetch(args),
}
}
fn open_workspace_journal(
path: Option<&Path>,
) -> Result<(altai_core::WorkspacePaths, altai_core::EventJournal), CliError> {
let workspace = altai_core::resolve_workspace(path)
.map_err(|error| CliError::Message(error.to_string()))?;
let journal = altai_core::EventJournal::open(workspace.agent_event_journal_db())
.map_err(|error| CliError::Message(format!("could not open event journal: {error}")))?;
Ok((workspace, journal))
}
fn journal_summary(args: JournalSummaryArgs) -> Result<(), CliError> {
let (workspace, journal) = open_workspace_journal(args.path.as_deref())?;
let incomplete = journal
.incomplete_run_summaries()
.map_err(|error| CliError::Message(error.to_string()))?;
let latest = match &args.chat {
Some(chat_id) => journal
.latest_run_summary_for_chat(chat_id)
.map_err(|error| CliError::Message(error.to_string()))?,
None => None,
};
if args.json {
return print_preview(serde_json::json!({
"workspace": workspace.root,
"incomplete_runs": incomplete.iter().map(run_summary_json).collect::<Vec<_>>(),
"latest_run": latest.as_ref().map(run_summary_json),
}));
}
println!("Workspace: {}", workspace.root.display());
if incomplete.is_empty() {
println!("Incomplete runs: none");
} else {
println!("Incomplete runs:");
for summary in &incomplete {
println!(
" {} (chat {}, last_seq {})",
summary.run_id, summary.chat_id, summary.last_seq
);
}
}
if let Some(chat_id) = &args.chat {
match latest {
Some(summary) => println!(
"Latest run for {chat_id}: {} (last_seq {}, terminal {})",
summary.run_id,
summary.last_seq,
summary.terminal_kind.as_deref().unwrap_or("pending")
),
None => println!("Latest run for {chat_id}: none"),
}
}
Ok(())
}
fn journal_fetch(args: JournalFetchArgs) -> Result<(), CliError> {
let (_workspace, journal) = open_workspace_journal(args.path.as_deref())?;
let events = journal
.fetch_after(&args.run, args.after, args.limit)
.map_err(|error| CliError::Message(error.to_string()))?;
if args.json {
return print_preview(serde_json::json!({
"run_id": args.run,
"events": events.iter().map(journal_event_json).collect::<Vec<_>>(),
}));
}
for event in &events {
println!(
"{:>6} {} {}",
event.seq,
event.kind,
serde_json::to_string(&event.payload).unwrap_or_default()
);
}
Ok(())
}
fn run_summary_json(summary: &altai_core::RunJournalSummary) -> serde_json::Value {
serde_json::json!({
"run_id": summary.run_id,
"chat_id": summary.chat_id,
"last_seq": summary.last_seq,
"terminal_seq": summary.terminal_seq,
"terminal_kind": summary.terminal_kind,
"terminal_payload": summary.terminal_payload,
})
}
fn journal_event_json(event: &altai_core::JournalEvent) -> serde_json::Value {
serde_json::json!({
"version": event.version,
"run_id": event.run_id,
"seq": event.seq,
"chat_id": event.chat_id,
"recorded_at_ms": event.recorded_at_ms,
"kind": event.kind,
"payload": event.payload,
})
}
fn models(command: ModelsCommands) -> Result<(), CliError> {
match command {
ModelsCommands::Current(args) => models_current(args),
}
}
fn models_current(args: ModelsCurrentArgs) -> Result<(), CliError> {
let workspace = altai_core::resolve_workspace(args.path.as_deref())
.map_err(|error| CliError::Message(error.to_string()))?;
let resolved = load_workspace_agent_config(&workspace)?;
if args.json {
return print_preview(serde_json::json!({
"workspace": workspace.root,
"model": config_value(resolved.model.as_ref(), args.show_origin),
"fallback_model": config_value(resolved.fallback_model.as_ref(), args.show_origin),
}));
}
print_config_field("model", resolved.model.as_ref(), args.show_origin);
print_config_field(
"fallback_model",
resolved.fallback_model.as_ref(),
args.show_origin,
);
Ok(())
}
fn config(command: ConfigCommands) -> Result<(), CliError> {
match command {
ConfigCommands::Path(args) => config_path(args),
ConfigCommands::List(args) => config_list(args),
}
}
fn config_list(args: ConfigListArgs) -> Result<(), CliError> {
if !args.resolved {
return Err(CliError::Message(
"only resolved configuration is available in this build; pass --resolved".into(),
));
}
let workspace = altai_core::resolve_workspace(args.path.as_deref())
.map_err(|error| CliError::Message(error.to_string()))?;
let resolved = load_workspace_agent_config(&workspace)?;
let values = [
("model", resolved.model.as_ref()),
("fallback_model", resolved.fallback_model.as_ref()),
("provider", resolved.provider.as_ref()),
("base_url", resolved.base_url.as_ref()),
];
if args.json {
let values = values
.into_iter()
.map(|(name, value)| (name.to_string(), config_value(value, args.show_origin)))
.collect::<serde_json::Map<String, serde_json::Value>>();
return print_preview(serde_json::json!({
"workspace": workspace.root,
"values": values,
}));
}
for (name, value) in values {
print_config_field(name, value, args.show_origin);
}
Ok(())
}
fn load_workspace_agent_config(
workspace: &altai_core::WorkspacePaths,
) -> Result<altai_core::ResolvedAgentConfig, CliError> {
altai_core::load_agent_config(
&workspace.root.join(".altai/config.toml"),
&workspace.isanagent_state.join("config.toml"),
)
.map_err(|error| CliError::Message(error.to_string()))
}
fn print_config_field(
name: &str,
value: Option<&altai_core::ResolvedConfig<String>>,
show_origin: bool,
) {
match (value, show_origin) {
(Some(value), true) => println!("{name}: {} ({})", value.value, value.source.label()),
(Some(value), false) => println!("{name}: {}", value.value),
(None, true) => println!("{name}: <unset> (default)"),
(None, false) => println!("{name}: <unset>"),
}
}
fn config_value(
value: Option<&altai_core::ResolvedConfig<String>>,
show_origin: bool,
) -> serde_json::Value {
match (value, show_origin) {
(Some(value), true) => serde_json::json!({
"value": value.value.clone(),
"source": value.source.label(),
}),
(Some(value), false) => serde_json::Value::String(value.value.clone()),
(None, true) => serde_json::json!({ "value": null, "source": "default" }),
(None, false) => serde_json::Value::Null,
}
}
fn config_path(args: ConfigPathArgs) -> Result<(), CliError> {
let workspace = altai_core::resolve_workspace(args.path.as_deref())
.map_err(|error| CliError::Message(error.to_string()))?;
let altai_config = workspace.root.join(".altai/config.toml");
let isanagent_config = workspace.isanagent_state.join("config.toml");
let workspace_display = workspace.root.display().to_string();
let altai_config_display = altai_config.display().to_string();
let isanagent_config_display = isanagent_config.display().to_string();
let value = serde_json::json!({
"workspace": workspace.root,
"altai_config": altai_config,
"isanagent_config": isanagent_config,
});
if args.json {
return print_preview(value);
}
println!("Workspace: {workspace_display}");
println!("ALTAI config: {altai_config_display}");
println!("IsanAgent config: {isanagent_config_display}");
Ok(())
}
fn agent(args: AgentArgs) -> Result<(), CliError> {
let workspace =
resolve_command_workspace(args.options.workspace.as_deref(), args.path.as_deref())?;
let appearance = resolve_cli_theme(args.options.theme);
let mut host = host_adapter::host_config_for_workspace(&workspace);
host.model = args.options.model.clone();
host.fallback_model = args.options.fallback_model.clone();
host.permission = args.options.permission.as_ref().map(host_permission_mode);
host.no_color = appearance == altai_core::EffectiveTerminalAppearance::NoColor;
host.theme = host_theme_mode(appearance);
host.resume = args.options.resume.clone();
host.files = args.options.files.clone();
host.line_mode = args.no_tui;
apply_compaction_overrides(&mut host, &args.options);
if !args.dry_run {
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.map_err(|error| {
CliError::Message(format!("could not start the host runtime: {error}"))
})?;
return runtime
.block_on(isanagent::host::start_host(host))
.map_err(|error| {
CliError::Message(format!("IsanAgent host exited with an error: {error}"))
});
}
let value = serde_json::json!({
"kind": "agent",
"workspace": workspace.root,
"isanagent_state": workspace.isanagent_state,
"host": {
"state": host.workspace,
"config": host.config,
"sandbox": host.sandbox,
},
"tui": !args.no_tui,
"model": args.options.model,
"fallback_model": args.options.fallback_model,
"permission": args.options.permission.as_ref().map(PermissionMode::as_str),
"theme": args.options.theme.as_str(),
"effective_theme": appearance.as_str(),
"resume": args.options.resume,
"files": args.options.files,
"compaction": resolved_compaction_preview(&args.options),
});
print_preview(value)
}
fn acp(args: AcpArgs) -> Result<(), CliError> {
let workspace =
resolve_command_workspace(args.options.workspace.as_deref(), args.path.as_deref())?;
let appearance = resolve_cli_theme(args.options.theme);
let mut host = host_adapter::acp_host_config(&workspace);
host.model = args.options.model.clone();
host.fallback_model = args.options.fallback_model.clone();
host.permission = args.options.permission.as_ref().map(host_permission_mode);
host.no_color = appearance == altai_core::EffectiveTerminalAppearance::NoColor;
host.theme = host_theme_mode(appearance);
host.resume = args.options.resume.clone();
host.files = args.options.files.clone();
apply_compaction_overrides(&mut host, &args.options);
if !args.dry_run {
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.map_err(|error| {
CliError::Message(format!("could not start the host runtime: {error}"))
})?;
return runtime
.block_on(isanagent::host::start_host(host))
.map_err(|error| {
CliError::Message(format!("IsanAgent ACP host exited with an error: {error}"))
});
}
let value = serde_json::json!({
"kind": "acp",
"protocol": "agent-client-protocol",
"transport": "stdio",
"workspace": workspace.root,
"isanagent_state": workspace.isanagent_state,
"host": {
"state": host.workspace,
"config": host.config,
"sandbox": host.sandbox,
"acp_mode": host.acp_mode,
},
"model": args.options.model,
"fallback_model": args.options.fallback_model,
"permission": args.options.permission.as_ref().map(PermissionMode::as_str),
"theme": args.options.theme.as_str(),
"effective_theme": appearance.as_str(),
"resume": args.options.resume,
"files": args.options.files,
"compaction": resolved_compaction_preview(&args.options),
});
print_preview(value)
}
fn apply_compaction_overrides(host: &mut isanagent::host::HostConfig, options: &AgentOptions) {
apply_compaction_fields(
host,
options.no_auto_compact,
options.compact_threshold,
options.compact_tail,
);
}
fn apply_compaction_fields(
host: &mut isanagent::host::HostConfig,
no_auto_compact: bool,
compact_threshold: Option<usize>,
compact_tail: Option<usize>,
) {
let prefs = altai_core::resolve_compaction_prefs(altai_core::CompactionOverrides {
auto: if no_auto_compact { Some(false) } else { None },
threshold_tokens: compact_threshold,
tail_turns: compact_tail,
});
let logic = prefs.to_logic_params();
host.compact_auto = Some(prefs.auto);
host.compact_threshold_tokens = Some(logic.short_term_threshold_tokens);
host.compact_tail_turns = Some(logic.max_recent_summaries);
}
fn resolved_compaction_preview(options: &AgentOptions) -> serde_json::Value {
let prefs = altai_core::resolve_compaction_prefs(altai_core::CompactionOverrides {
auto: if options.no_auto_compact {
Some(false)
} else {
None
},
threshold_tokens: options.compact_threshold,
tail_turns: options.compact_tail,
});
let logic = prefs.to_logic_params();
serde_json::json!({
"auto": prefs.auto,
"threshold_tokens": prefs.threshold_tokens,
"tail_turns": prefs.tail_turns,
"logic": {
"max_recent_summaries": logic.max_recent_summaries,
"short_term_threshold_turns": logic.short_term_threshold_turns,
"short_term_threshold_tokens": logic.short_term_threshold_tokens,
}
})
}
fn resolve_cli_theme(theme: ThemeMode) -> altai_core::EffectiveTerminalAppearance {
let cli = match theme {
ThemeMode::Auto => altai_core::TerminalThemeMode::Auto,
ThemeMode::Dark => altai_core::TerminalThemeMode::Dark,
ThemeMode::Light => altai_core::TerminalThemeMode::Light,
ThemeMode::NoColor => altai_core::TerminalThemeMode::NoColor,
};
altai_core::resolve_terminal_appearance_from_env(cli)
}
const fn host_theme_mode(
appearance: altai_core::EffectiveTerminalAppearance,
) -> isanagent::host::HostThemeMode {
match appearance {
altai_core::EffectiveTerminalAppearance::Dark => isanagent::host::HostThemeMode::Dark,
altai_core::EffectiveTerminalAppearance::Light => isanagent::host::HostThemeMode::Light,
altai_core::EffectiveTerminalAppearance::NoColor => isanagent::host::HostThemeMode::NoColor,
}
}
const fn host_permission_mode(permission: &PermissionMode) -> isanagent::host::HostPermissionMode {
match permission {
PermissionMode::Ask => isanagent::host::HostPermissionMode::Ask,
PermissionMode::AutoEdit => isanagent::host::HostPermissionMode::AutoEdit,
PermissionMode::Plan => isanagent::host::HostPermissionMode::Plan,
PermissionMode::Bypass => isanagent::host::HostPermissionMode::Bypass,
}
}
fn run_prompt(args: RunArgs) -> Result<(), CliError> {
let output = if args.json {
OutputMode::Jsonl
} else {
args.output.clone()
};
let prompt = resolve_prompt(&args.prompt)?;
let workspace =
resolve_command_workspace(args.options.workspace.as_deref(), args.path.as_deref())?;
if args.dry_run {
let value = serde_json::json!({
"kind": "run",
"workspace": workspace.root,
"isanagent_state": workspace.isanagent_state,
"prompt": prompt,
"output": output.as_str(),
"timeout": args.timeout,
"quiet": args.quiet,
"model": args.options.model,
"fallback_model": args.options.fallback_model,
"permission": args.options.permission.as_ref().map(PermissionMode::as_str),
"theme": args.options.theme.as_str(),
"resume": args.options.resume,
"files": args.options.files,
"compaction": resolved_compaction_preview(&args.options),
});
return print_preview(value);
}
let permission = resolve_run_permission(args.options.permission.clone())?;
let timeout = args
.timeout
.as_deref()
.map(run_output::parse_timeout)
.transpose()
.map_err(CliError::Message)?;
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.map_err(|error| CliError::Message(format!("could not start the host runtime: {error}")))?;
runtime.block_on(async_run_prompt(AsyncRunRequest {
workspace,
prompt,
output,
timeout,
quiet: args.quiet,
model: args.options.model,
fallback_model: args.options.fallback_model,
permission,
no_color: args.options.theme == ThemeMode::NoColor
|| std::env::var_os("NO_COLOR").is_some(),
resume: args.options.resume,
files: args.options.files,
no_auto_compact: args.options.no_auto_compact,
compact_threshold: args.options.compact_threshold,
compact_tail: args.options.compact_tail,
}))
}
struct AsyncRunRequest {
workspace: altai_core::WorkspacePaths,
prompt: String,
output: OutputMode,
timeout: Option<std::time::Duration>,
quiet: bool,
model: Option<String>,
fallback_model: Option<String>,
permission: PermissionMode,
no_color: bool,
resume: Option<String>,
files: Vec<PathBuf>,
no_auto_compact: bool,
compact_threshold: Option<usize>,
compact_tail: Option<usize>,
}
async fn async_run_prompt(request: AsyncRunRequest) -> Result<(), CliError> {
use isanagent::host::{OneshotOutcome, OneshotResult};
use std::io::{self, Write};
let (observe_tx, mut observe_rx) = tokio::sync::mpsc::unbounded_channel();
let mut host = host_adapter::oneshot_host_config(
&request.workspace,
request.prompt.clone(),
Some(observe_tx),
);
host.model = request.model.clone();
host.fallback_model = request.fallback_model.clone();
host.permission = Some(host_permission_mode(&request.permission));
host.no_color = request.no_color;
host.resume = request.resume.clone();
host.files = request.files.clone();
apply_compaction_fields(
&mut host,
request.no_auto_compact,
request.compact_threshold,
request.compact_tail,
);
let workspace_display = request.workspace.root.display().to_string();
let output_mode = request.output.clone();
let quiet = request.quiet;
let journal_sink = std::sync::Arc::new(tokio::sync::Mutex::new(
journal_sink::JournalSink::open(&request.workspace),
));
let journal_sink_for_observer = journal_sink.clone();
let observer = tokio::spawn(async move {
let mut emitter = run_output::JsonlEmitter::new(workspace_display);
let mut stdout = io::stdout();
let mut stderr = io::stderr();
while let Some(message) = observe_rx.recv().await {
if let Some(sink) = journal_sink_for_observer.lock().await.as_mut() {
sink.observe_bus_message(&message);
}
match output_mode {
OutputMode::Jsonl => {
if let Err(error) = emitter.observe_bus_message(&message, &mut stdout) {
let _ = writeln!(stderr, "altai-cli: failed to emit JSONL: {error}");
}
}
OutputMode::Pretty | OutputMode::Plain if !quiet => {
if let isanagent::bus::BusMessage::Telemetry(
isanagent::bus::TelemetryEvent::ToolCallStarted { tool_name, .. },
) = &message
{
let _ = writeln!(stderr, "tool: {tool_name}");
}
}
_ => {}
}
}
});
let mut oneshot_task = tokio::spawn(isanagent::host::run_oneshot(host));
let result = tokio::select! {
joined = &mut oneshot_task => {
match joined {
Ok(Ok(result)) => result,
Ok(Err(error)) => {
return Err(CliError::RunFailed {
code: run_output::RunExitCode::Internal,
message: format!("IsanAgent oneshot host failed: {error}"),
});
}
Err(error) => {