Skip to main content

harn_cli/
lib.rs

1#![recursion_limit = "256"]
2
3pub mod acp;
4mod bootstrap;
5pub mod cli;
6mod cli_bytecode;
7pub mod commands;
8mod compiler_context;
9#[doc(hidden)]
10pub mod dispatch;
11mod entrypoint;
12pub mod env_guard;
13mod eval_cli;
14mod exit;
15pub mod format;
16pub mod json_envelope;
17pub use commands::check::{
18    decode_lint_envelope, decode_lint_json, lint_json_schema, DecodedLintEnvelope, LintDecodeError,
19    LintDecodeOptions, LintReportWire,
20};
21mod net;
22pub mod package;
23mod provider_bootstrap;
24mod provider_info;
25mod run_records;
26mod runtime;
27pub mod skill_loader;
28pub mod skill_provenance;
29mod source_exec;
30pub mod test_report;
31pub mod test_runner;
32pub mod test_timing;
33#[doc(hidden)]
34pub mod tests;
35mod typecheck_imports;
36pub use commands::dispatch_explain::DISPATCH_AUDIT_SCHEMA_VERSION;
37pub(crate) use compiler_context::{
38    compiler_for_source, compiler_with_imported_enum_candidates,
39    ensure_builtin_signatures_installed, imported_enum_candidates_for_source,
40};
41pub use harn_skills::{get_embedded_skill, list_embedded_skills, EmbeddedSkill, SkillFrontmatter};
42// Items that used to live directly in this file. A bare item at the crate
43// root is visible crate-wide, so re-exporting the modules' `pub(crate)` items
44// here keeps every existing `crate::<item>` path resolving unchanged.
45pub(crate) use self::entrypoint::*;
46pub(crate) use self::eval_cli::*;
47pub(crate) use self::exit::*;
48pub(crate) use self::provider_info::*;
49pub(crate) use self::run_records::*;
50pub(crate) use self::source_exec::*;
51
52use clap::{error::ErrorKind, CommandFactory, Parser as ClapParser};
53use std::path::{Path, PathBuf};
54use std::sync::{Arc, Once};
55use std::{env, fs, panic, process, thread};
56
57use cli::{
58    Cli, Command, CompletionShell, EvalCommand, GuardCommand, MergeCaptainCommand,
59    MergeCaptainMockCommand, ModelInfoArgs, PackageArtifactsCommand, PackageCacheCommand,
60    PackageCommand, PackageScaffoldCommand, PgCommand, ProviderCommand, SkillCommand,
61    SkillKeyCommand, SkillTrustCommand, TimeCommand, ToolCommand,
62};
63use harn_lexer::Lexer;
64use harn_modules::project_config;
65use harn_parser::{DiagnosticSeverity, Parser, TypeChecker};
66use runtime::{build_cli_runtime, cli_runtime_mode, CliRuntimeMode};
67pub const CLI_RUNTIME_STACK_SIZE: usize = 16 * 1024 * 1024;
68static BROKEN_PIPE_PANIC_HOOK: Once = Once::new();
69
70#[cfg(feature = "hostlib")]
71pub(crate) fn install_default_hostlib(vm: &mut harn_vm::Vm) {
72    let _ = harn_hostlib::install_default(vm);
73    // The `rules` capability lives in its own crate (it depends on
74    // `harn-rules`, which depends on `harn-hostlib`, so it can't ship inside
75    // `install_default`). Wire it in alongside the defaults.
76    harn_rules_hostlib::install(vm);
77}
78
79#[cfg(not(feature = "hostlib"))]
80pub(crate) fn install_default_hostlib(_vm: &mut harn_vm::Vm) {}
81
82/// Entry point used by `src/main.rs`. Hosts the CLI runtime thread and
83/// drives the async dispatcher in `async_main`.
84pub fn run() {
85    install_broken_pipe_panic_hook();
86    harn_vm::initialize_runtime_assets();
87    let raw_args = normalize_serve_args(bootstrap::args_after_pre_runtime_command());
88    // Defeat rlib dead-code stripping of `#[harn_builtin]`-emitted statics
89    // (linkme issue #36). Without this touch the linker can drop every
90    // builtin's distributed-slice entry, leaving `ALL_BUILTIN_DEFS` empty
91    // and surfacing as a swarm of `HARN-NAM-002` errors at first call.
92    harn_vm::stdlib::force_link();
93
94    ensure_builtin_signatures_installed();
95
96    let runtime_mode = cli_runtime_mode(&raw_args);
97
98    let handle = thread::Builder::new()
99        .name("harn-cli".to_string())
100        .stack_size(CLI_RUNTIME_STACK_SIZE)
101        .spawn(move || {
102            let runtime = build_cli_runtime(runtime_mode);
103            runtime.block_on(async_main(raw_args, runtime_mode));
104            // Drain any queued OTLP exports while the tokio runtime
105            // is still alive. The auto-registered `OtelSink` uses a
106            // batch processor with `runtime::Tokio`; if we let the
107            // runtime drop before this call, in-flight spans never
108            // reach the configured collector. No-op when OTel is not
109            // configured.
110            if let Err(error) = harn_vm::events::shutdown_otel_sink() {
111                eprintln!("[harn] OTel exporter shutdown failed: {error}");
112            }
113        })
114        .unwrap_or_else(|error| {
115            eprintln!("failed to start CLI runtime thread: {error}");
116            process::exit(1);
117        });
118
119    if let Err(payload) = handle.join() {
120        if runtime::is_broken_pipe_panic_payload(payload.as_ref()) {
121            process::exit(0);
122        }
123        std::panic::resume_unwind(payload);
124    }
125}
126
127fn install_broken_pipe_panic_hook() {
128    BROKEN_PIPE_PANIC_HOOK.call_once(|| {
129        let previous = panic::take_hook();
130        panic::set_hook(Box::new(move |info| {
131            if runtime::is_broken_pipe_panic_payload(info.payload()) {
132                return;
133            }
134            previous(info);
135        }));
136    });
137}