harn-vm 0.10.162

Async bytecode virtual machine for the Harn programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Which provider and model a selector resolves to, and the options a call
//! against that route inherits.

use crate::llm_config;
use crate::stdlib::json_to_vm_value;
use crate::stdlib::macros::harn_builtin;
use crate::value::{VmDictExt, VmError, VmValue};

use super::batch_projection::string_list_to_vm_value;
use super::catalog_projection::toml_value_to_vm_value;
use super::model_projection::{
    model_def_to_vm_value, model_info_to_vm_value, resolved_model_to_vm_value,
};

/// Infer the configured provider name for a model identifier.
#[harn_builtin(
    exposure = "harness.llm.infer_provider",
    effects = ["llm.read@arg0"],
    sig = "llm_infer_provider(model_id: string) -> string",
    category = "llm.config"
)]
fn llm_infer_provider_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let model_id = args.first().map(|a| a.display()).unwrap_or_default();
    Ok(VmValue::String(arcstr::ArcStr::from(
        llm_config::infer_provider(&model_id),
    )))
}

/// Return the configured capability tier for a model identifier.
#[harn_builtin(
    exposure = "harness.llm.model_tier",
    effects = ["llm.read@arg0"],
    sig = "llm_model_tier(model_id: string) -> string",
    category = "llm.config"
)]
fn llm_model_tier_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let model_id = args.first().map(|a| a.display()).unwrap_or_default();
    Ok(VmValue::String(arcstr::ArcStr::from(
        llm_config::model_tier(&model_id),
    )))
}

/// Resolve a model alias or selector to full model metadata.
#[harn_builtin(
    exposure = "harness.llm.resolve_model",
    effects = ["llm.read@arg0"],
    sig = "llm_resolve_model(alias: string) -> dict",
    category = "llm.config"
)]
fn llm_resolve_model_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let alias = args.first().map(|a| a.display()).unwrap_or_default();
    Ok(resolved_model_to_vm_value(&llm_config::resolve_model_info(
        &alias,
    )))
}

/// Return catalog metadata for a resolved model selector.
#[harn_builtin(
    exposure = "harness.llm.model_info",
    effects = ["llm.read@arg0"],
    sig = "llm_model_info(selector: string) -> dict",
    category = "llm.config"
)]
fn llm_model_info_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let selector = args.first().map(|a| a.display()).unwrap_or_default();
    let resolved = llm_config::resolve_model_info(&selector);
    Ok(model_info_to_vm_value(&resolved))
}

/// List configured model alias names.
#[harn_builtin(
    exposure = "harness.llm.known_models",
    effects = ["llm.read@const=model-catalog"],
    sig = "llm_known_models() -> list", category = "llm.config"
)]
fn llm_known_models_builtin(_args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    Ok(string_list_to_vm_value(llm_config::known_model_names()))
}

/// Return the configured cheap QC/repair model for a provider.
#[harn_builtin(
    exposure = "harness.llm.qc_default_model",
    effects = ["llm.read@arg0"],
    sig = "llm_qc_default_model(provider: string) -> string|nil",
    category = "llm.config"
)]
fn llm_qc_default_model_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let provider = args.first().map(|a| a.display()).unwrap_or_default();
    if provider.is_empty() {
        return Err(VmError::Runtime(
            "llm_qc_default_model: provider name is required".to_string(),
        ));
    }
    Ok(llm_config::qc_default_model(&provider)
        .map(|model| VmValue::String(arcstr::ArcStr::from(model)))
        .unwrap_or(VmValue::Nil))
}

/// Return one named catalog model ladder, including its ordered route steps.
#[harn_builtin(
    exposure = "harness.llm.model_ladder",
    effects = ["llm.read@arg0"],
    sig = "llm_model_ladder(name: string) -> dict|nil",
    category = "llm.config"
)]
pub(super) fn llm_model_ladder_builtin(
    args: &[VmValue],
    _out: &mut String,
) -> Result<VmValue, VmError> {
    let name = args.first().map(VmValue::display).unwrap_or_default();
    if name.trim().is_empty() {
        return Err(VmError::Runtime(
            "llm_model_ladder: ladder name is required".to_string(),
        ));
    }
    let Some(ladder) = llm_config::model_ladder(&name) else {
        return Ok(VmValue::Nil);
    };
    let value = serde_json::to_value(ladder).map_err(|error| {
        VmError::Runtime(format!(
            "llm_model_ladder: failed to project catalog row: {error}"
        ))
    })?;
    Ok(crate::stdlib::json_to_vm_value(&value))
}

/// Return logical- and route-merged model defaults for `model_id`.
#[harn_builtin(
    exposure = "harness.llm.model_defaults",
    effects = ["llm.read@arg0"],
    sig = "llm_model_defaults(model_id: string) -> dict",
    category = "llm.config"
)]
pub(super) fn llm_model_defaults_builtin(
    args: &[VmValue],
    _out: &mut String,
) -> Result<VmValue, VmError> {
    let model_id = args.first().map(|a| a.display()).unwrap_or_default();
    if model_id.is_empty() {
        return Err(VmError::Runtime(
            "llm_model_defaults: model_id is required".to_string(),
        ));
    }
    let resolved = llm_config::resolve_model_info(&model_id);
    let params = llm_config::model_params_for_route(&resolved.provider, &resolved.id);
    let mut dict = crate::value::DictMap::new();
    for (k, v) in &params {
        dict.insert(crate::value::intern_key(k), toml_value_to_vm_value(v));
    }
    Ok(VmValue::dict(dict))
}

/// Return merged call options. An omitted model uses normal dispatch defaults.
#[harn_builtin(
    exposure = "harness.llm.resolved_options",
    effects = ["llm.read@dynamic"],
    sig = "llm_resolved_options(opts: dict) -> dict",
    category = "llm.config"
)]
pub(super) fn llm_resolved_options_builtin(
    args: &[VmValue],
    _out: &mut String,
) -> Result<VmValue, VmError> {
    let opts = args
        .first()
        .and_then(|a| a.as_dict())
        .ok_or_else(|| VmError::Runtime("llm_resolved_options: opts must be a dict".to_string()))?;
    let model = opts
        .get("model")
        .map(|v| v.display())
        .filter(|s| !s.is_empty());
    let user_provider = opts
        .get("provider")
        .map(|v| v.display())
        .filter(|s| !s.is_empty());
    let (resolved_id, final_provider) = if let Some(model) = model {
        let (resolved_id, provider_from_alias) = llm_config::resolve_model(&model);
        let provider = user_provider.unwrap_or_else(|| {
            provider_from_alias.unwrap_or_else(|| llm_config::infer_provider(&resolved_id))
        });
        (resolved_id, provider)
    } else {
        let mut defaults_options = opts.clone();
        defaults_options.remove("model");
        if user_provider.is_none() {
            defaults_options.remove("provider");
        }
        let options = Some(defaults_options);
        let provider = crate::llm::helpers::vm_resolve_provider(&options);
        let model = crate::llm::helpers::vm_resolve_model(&options, &provider)?;
        (model, provider)
    };
    let defaults = llm_config::model_params_for_route(&final_provider, &resolved_id);
    let mut out = opts.clone();
    for (k, v) in &defaults {
        if !out.contains_key(k.as_str()) {
            out.insert(crate::value::intern_key(k), toml_value_to_vm_value(v));
        }
    }
    out.put_str("provider", final_provider);
    out.put_str("model", resolved_id);
    Ok(VmValue::dict(out))
}

/// Apply Harn's provider-aware reasoning-policy and effort defaults to an `llm_call` option dict.
#[harn_builtin(
    exposure = "harness.llm.apply_reasoning_policy",
    effects = ["llm.read@dynamic"],
    sig = "llm_apply_reasoning_policy(opts: dict) -> dict",
    category = "llm.config"
)]
fn llm_apply_reasoning_policy_builtin(
    args: &[VmValue],
    _out: &mut String,
) -> Result<VmValue, VmError> {
    let opts = args.first().and_then(|a| a.as_dict()).ok_or_else(|| {
        VmError::Runtime("llm_apply_reasoning_policy: opts must be a dict".to_string())
    })?;
    let out = crate::llm::reasoning_policy::apply_policy_to_vm_options(opts)?;
    Ok(VmValue::dict(out))
}

/// Resolve the canonical reasoning-channel output budget (tokens) for an effort
/// level, mirroring the policy used when materializing a `thinking` budget. This
/// is the single source of truth for the effort -> token mapping so callers
/// (e.g. the `std/llm/safe` structured-floor fallback) do not re-hardcode it.
/// An unknown/empty level resolves to the medium default.
#[harn_builtin(
    exposure = "harness.llm.reasoning_effort_budget",
    effects = ["llm.read@arg0"],
    sig = "llm_reasoning_effort_budget(level: string) -> int",
    category = "llm.config"
)]
pub(super) fn llm_reasoning_effort_budget_builtin(
    args: &[VmValue],
    _out: &mut String,
) -> Result<VmValue, VmError> {
    let level = args.first().map(|a| a.display()).unwrap_or_default();
    let budget = crate::llm::reasoning_policy::budget_for_reasoning_level(level.trim());
    Ok(VmValue::Int(i64::from(budget)))
}

/// Resolve a model alias or tier to an `{id, provider, tier}` dict.
#[harn_builtin(
    exposure = "harness.llm.pick_model",
    effects = ["llm.read@dynamic"],
    sig = "llm_pick_model(target: string, options?: dict|nil) -> dict",
    category = "llm.config"
)]
fn llm_pick_model_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let target = args.first().map(|a| a.display()).unwrap_or_default();
    let options = args.get(1).and_then(|v| v.as_dict());
    let preferred_provider = options.and_then(|d| d.get("provider")).map(|v| v.display());

    let (id, provider) = if let Some((id, provider)) =
        llm_config::resolve_tier_model(&target, preferred_provider.as_deref())
    {
        (id, provider)
    } else {
        let (id, provider) = llm_config::resolve_model(&target);
        (
            id.clone(),
            provider.unwrap_or_else(|| llm_config::infer_provider(&id)),
        )
    };

    let mut dict = crate::value::DictMap::new();
    dict.put_str("id", id.clone());
    dict.put_str("provider", provider);
    dict.put_str("tier", llm_config::model_tier(&id));
    Ok(VmValue::dict(dict))
}

/// Pick a different-family reviewer model for review, critique, or plan review.
#[harn_builtin(
    exposure = "harness.llm.complementary_reviewer",
    effects = ["llm.read@dynamic"],
    sig = "llm_complementary_reviewer(options: dict) -> dict",
    category = "llm.config"
)]
fn llm_complementary_reviewer_builtin(
    args: &[VmValue],
    _out: &mut String,
) -> Result<VmValue, VmError> {
    let options = parse_complementary_reviewer_options(args.first())?;
    let selection = llm_config::pick_complementary_reviewer(options);
    let json = serde_json::to_value(selection).map_err(|error| {
        VmError::Runtime(format!(
            "llm_complementary_reviewer: serialize result: {error}"
        ))
    })?;
    Ok(json_to_vm_value(&json))
}

pub(super) fn parse_complementary_reviewer_options(
    value: Option<&VmValue>,
) -> Result<llm_config::ComplementaryReviewerOptions, VmError> {
    let dict = value.and_then(|value| value.as_dict()).ok_or_else(|| {
        VmError::Runtime("llm_complementary_reviewer: options must be a dict".to_string())
    })?;
    let author_model = dict
        .get("author_model")
        .or_else(|| dict.get("model"))
        .map(|value| value.display())
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
        .ok_or_else(|| {
            VmError::Runtime(
                "llm_complementary_reviewer: options.author_model is required".to_string(),
            )
        })?;
    let author_provider = dict
        .get("author_provider")
        .or_else(|| dict.get("provider"))
        .map(|value| value.display())
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty());
    let intent = dict
        .get("intent")
        .map(|value| value.display())
        .unwrap_or_else(|| "review".to_string());
    let intent =
        llm_config::ComplementaryReviewerIntent::parse(intent.trim()).ok_or_else(|| {
            VmError::Runtime(
                "llm_complementary_reviewer: intent must be review, critique, or plan_review"
                    .to_string(),
            )
        })?;
    let max_price_multiplier = dict
        .get("max_price_multiplier")
        .map(|value| vm_value_as_f64(value, "max_price_multiplier"))
        .transpose()?;
    if max_price_multiplier.is_some_and(|value| !value.is_finite() || value <= 0.0) {
        return Err(VmError::Runtime(
            "llm_complementary_reviewer: max_price_multiplier must be positive".to_string(),
        ));
    }
    let min_price_cap_per_mtok = dict
        .get("min_price_cap_per_mtok")
        .map(|value| vm_value_as_f64(value, "min_price_cap_per_mtok"))
        .transpose()?;
    let max_price_cap_per_mtok = dict
        .get("max_price_cap_per_mtok")
        .map(|value| vm_value_as_f64(value, "max_price_cap_per_mtok"))
        .transpose()?;
    if min_price_cap_per_mtok.is_some_and(|value| !value.is_finite() || value <= 0.0) {
        return Err(VmError::Runtime(
            "llm_complementary_reviewer: min_price_cap_per_mtok must be positive".to_string(),
        ));
    }
    if max_price_cap_per_mtok.is_some_and(|value| !value.is_finite() || value <= 0.0) {
        return Err(VmError::Runtime(
            "llm_complementary_reviewer: max_price_cap_per_mtok must be positive".to_string(),
        ));
    }
    if min_price_cap_per_mtok
        .zip(max_price_cap_per_mtok)
        .is_some_and(|(floor, ceiling)| floor > ceiling)
    {
        return Err(VmError::Runtime(
            "llm_complementary_reviewer: min_price_cap_per_mtok must not exceed max_price_cap_per_mtok".to_string(),
        ));
    }
    Ok(llm_config::ComplementaryReviewerOptions {
        author_model,
        author_provider,
        intent,
        max_price_multiplier,
        min_price_cap_per_mtok,
        max_price_cap_per_mtok,
    })
}

fn vm_value_as_f64(value: &VmValue, field: &str) -> Result<f64, VmError> {
    match value {
        VmValue::Float(value) => Ok(*value),
        VmValue::Int(value) => Ok(*value as f64),
        other => Err(VmError::Runtime(format!(
            "llm_complementary_reviewer: {field} must be numeric, got {}",
            other.type_name(),
        ))),
    }
}

/// Return same-logical-model routes suitable for explicit failover or
/// experiment comparison. The result intentionally excludes the selected
/// source route and only includes non-deprecated, non-dedicated catalog rows
/// with compatible context/tool/structured-output capabilities.
#[harn_builtin(
    exposure = "harness.llm.equivalent_models",
    effects = ["llm.read@arg0"],
    sig = "llm_equivalent_models(selector: string) -> list",
    category = "llm.config"
)]
fn llm_equivalent_models_builtin(args: &[VmValue], _out: &mut String) -> Result<VmValue, VmError> {
    let selector = args
        .first()
        .map(|value| value.display())
        .unwrap_or_default();
    if selector.trim().is_empty() {
        return Err(VmError::Runtime(
            "llm_equivalent_models: selector is required".to_string(),
        ));
    }
    let entries = llm_config::equivalent_model_catalog_entries(selector.trim())
        .into_iter()
        .map(|(id, model)| model_def_to_vm_value(&id, &model))
        .collect();
    Ok(VmValue::List(std::sync::Arc::new(entries)))
}