lean-ctx 3.12.2

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
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
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
// SPDX-License-Identifier: Apache-2.0

//! Explicit local-host boundary: credentials arrive only on operator-owned stdin.

use std::{
    io::{BufRead, Read},
    path::{Path, PathBuf},
};

use lean_ctx_protocol::{ExecutionPlanV1, TaskEnvelopeV1};
use serde::Deserialize;
use zeroize::Zeroizing;

#[cfg(test)]
use lean_ctx::core::engine_interface::execute_transport_context_view_with_budget;

use super::{EngineCliError, SemanticVersion};
use lean_ctx::core::{
    engine_interface::{
        CAPABILITY_ID, CAPABILITY_VERSION, ENGINE_TRANSPORT_POLICY_REF,
        MAX_TRANSPORT_BUDGET_TOKENS, execute_transport_context_view_with_plan,
    },
    execution_ledger::host::{HostReceiptAuthority, digest, parse_key},
};

const REQUEST_LIMIT: usize = 1024 * 1024;

mod outcome;
mod sources;

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HostRequest {
    schema_version: u32,
    transport_version: u32,
    engine_interface_version: SemanticVersion,
    path: String,
    mode: String,
    task: TaskEnvelopeV1,
    plan: ExecutionPlanV1,
}

/// Operator settings are at most this long, as a document or as the first
/// line of a framed input.
const SETTINGS_LIMIT: usize = 16 * 1024;

/// Whether `args` name an operation of this module.
pub(super) fn is_host_operation(args: &[String]) -> bool {
    matches!(
        args.first().map(String::as_str),
        Some(
            "context-view-receipt"
                | "context-sources-receipt"
                | "context-sources-receipt-v2"
                | "context-outcome"
                | "context-outcome-receipt"
                | "context-checkpoint"
                | "context-checkpoint-resume"
                | "context-checkpoint-package"
                | "context-checkpoint-import"
                | "context-checkpoint-continue"
                | "context-checkpoint-sources"
                | "signer-info"
        )
    )
}

/// Everything a host operation will read from stdin, read ONCE: the project
/// it works on is learned from these bytes ([`project_root`]) before it
/// runs, and the same bytes are then handed to [`run`].
///
/// Bounded by what any operation accepts — a settings line and one request,
/// each one byte over its own limit — so an operation's own bound still
/// sees an oversized input as oversized. Only an invocation that names
/// stdin (`--host-stdin`, `--key-stdin`) is read; every other one is a
/// usage error that reads nothing. A read that fails hands on what was
/// read, and the operation refuses the truncated input with its own code.
/// The bytes carry operator credentials and are wiped when dropped.
pub(super) fn read_input(args: &[String], input: &mut impl Read) -> Zeroizing<Vec<u8>> {
    let mut bytes = Zeroizing::new(Vec::new());
    if args
        .iter()
        .any(|arg| matches!(arg.as_str(), "--host-stdin" | "--key-stdin"))
    {
        let request = REQUEST_LIMIT.max(lean_ctx_protocol::MAX_ENGINE_OUTCOME_REQUEST_BYTES);
        let limit = (SETTINGS_LIMIT + 1 + request + 1) as u64;
        let _ = input.take(limit).read_to_end(&mut bytes);
    }
    bytes
}

/// The root-bearing fields of the operator settings and nothing else of
/// them: the signing key and every other field are skipped, never loaded.
#[derive(Deserialize)]
struct ScopeSettings {
    #[serde(default)]
    checkpoint_resume: Option<ScopeRoot>,
    #[serde(default)]
    checkpoint_import: Option<ReceivingScope>,
}

#[derive(Deserialize)]
struct ScopeRoot {
    project_root: PathBuf,
}

#[derive(Deserialize)]
struct ReceivingScope {
    receiving: ScopeRoot,
}

/// The project a host operation works on, learned from what it will execute
/// — before it runs, so that its request scope and its gateway receipt are
/// that project's:
///
/// - `context-view-receipt`, `context-sources-receipt[-v2]`: the
///   `--project-root` argument;
/// - `context-checkpoint-package`: the working directory, which is the
///   project that operation selects itself;
/// - `context-checkpoint-resume`: the operator's `checkpoint_resume` target;
/// - `context-checkpoint-import`, `-continue`, `-sources`: the operator's
///   `checkpoint_import.receiving` scope;
/// - `context-checkpoint`, `context-outcome`, `context-outcome-receipt`,
///   `signer-info`: none — they work on the host ledger, the Engine's
///   artifact store, or a key, and name no project.
///
/// The root is resolved as the operations resolve it
/// (`std::fs::canonicalize`); they compare the request scope with exactly
/// that path. A root that is absent, unreadable, not a directory or too
/// broad to be a project yields `None`: the operation then runs unscoped
/// and refuses the root itself.
pub(super) fn project_root(args: &[String], input: &[u8]) -> Option<PathBuf> {
    let settings = || -> Option<ScopeSettings> {
        // A framed invocation (`<operation> --host-stdin`) carries the
        // settings as its first line; every other one as the whole input.
        let document = if args.len() == 2 {
            input.split_inclusive(|byte| *byte == b'\n').next()?
        } else {
            input
        };
        serde_json::from_slice(document).ok()
    };
    let configured = match args.first().map(String::as_str)? {
        "context-view-receipt" | "context-sources-receipt" | "context-sources-receipt-v2" => args
            .windows(2)
            .find(|pair| pair[0] == "--project-root")
            .map(|pair| PathBuf::from(&pair[1]))?,
        "context-checkpoint-package" => std::env::current_dir().ok()?,
        "context-checkpoint-resume" => settings()?.checkpoint_resume?.project_root,
        "context-checkpoint-import"
        | "context-checkpoint-continue"
        | "context-checkpoint-sources" => settings()?.checkpoint_import?.receiving.project_root,
        _ => return None,
    };
    let root = std::fs::canonicalize(configured).ok()?;
    (root.is_dir() && !lean_ctx::core::pathutil::is_broad_or_unsafe_root(&root)).then_some(root)
}

pub(super) fn run(args: &[String], input: &mut impl Read) -> Result<String, EngineCliError> {
    if args == ["context-checkpoint-continue", "--host-stdin"] {
        let mut reader = std::io::BufReader::new(input);
        let authority = read_framed_authority(&mut reader, None)?;
        let bytes = read_bounded(&mut reader, REQUEST_LIMIT, "invalid_host_request")?;
        let request = serde_json::from_slice::<
            lean_ctx::core::execution_ledger::host::HostCheckpointImportRequest,
        >(&bytes)
        .map_err(|_| host_error("invalid_host_request"))?;
        return authority
            .continue_checkpoint(&request)
            .map(|value| value.to_string())
            .map_err(|_| host_error("host_checkpoint_continuation_rejected"));
    }
    if args.first().map(String::as_str) == Some("context-outcome-receipt") {
        return outcome::run(args, input);
    }
    if matches!(
        args.first().map(String::as_str),
        Some("context-sources-receipt" | "context-sources-receipt-v2")
    ) {
        return sources::run(args, input);
    }
    if args.first().map(String::as_str) == Some("context-checkpoint-resume") {
        if args.len() != 4 || args[1] != "--json" || args[3] != "--host-stdin" {
            return Err(EngineCliError::Usage);
        }
        let request = read_request::<
            lean_ctx::core::execution_ledger::host::HostCheckpointResumeRequest,
        >(Path::new(&args[2]))?;
        let authority = HostReceiptAuthority::from_reader(input).map_err(EngineCliError::Host)?;
        return authority
            .resume_checkpoint(&request)
            .map(|value| value.to_string())
            .map_err(|_| host_error("host_checkpoint_resume_rejected"));
    }
    if args.first().map(String::as_str) == Some("context-checkpoint-package") {
        if args.len() != 4 || args[1] != "--json" || args[3] != "--host-stdin" {
            return Err(EngineCliError::Usage);
        }
        let request = read_request::<
            lean_ctx::core::execution_ledger::host::HostCheckpointPackageRequest,
        >(Path::new(&args[2]))?;
        let authority = HostReceiptAuthority::from_reader(input).map_err(EngineCliError::Host)?;
        return authority
            .package_checkpoint(&request)
            .map(|value| value.to_string())
            .map_err(|_| host_error("host_checkpoint_package_rejected"));
    }
    if args.first().map(String::as_str) == Some("context-checkpoint-sources") {
        if args.len() != 4 || args[1] != "--json" || args[3] != "--host-stdin" {
            return Err(EngineCliError::Usage);
        }
        let request = read_request::<
            lean_ctx::core::execution_ledger::host::HostCheckpointImportRequest,
        >(Path::new(&args[2]))?;
        let authority = HostReceiptAuthority::from_reader(input).map_err(EngineCliError::Host)?;
        return authority
            .recheck_checkpoint_sources(&request)
            .map(|value| value.to_string())
            .map_err(|_| host_error("host_checkpoint_sources_rejected"));
    }
    if matches!(
        args.first().map(String::as_str),
        Some("context-checkpoint-import" | "context-checkpoint-continue")
    ) {
        if args.len() != 4 || args[1] != "--json" || args[3] != "--host-stdin" {
            return Err(EngineCliError::Usage);
        }
        let request = read_request::<
            lean_ctx::core::execution_ledger::host::HostCheckpointImportRequest,
        >(Path::new(&args[2]))?;
        let authority = HostReceiptAuthority::from_reader(input).map_err(EngineCliError::Host)?;
        if args[0] == "context-checkpoint-continue" {
            return authority
                .continue_checkpoint(&request)
                .map(|value| value.to_string())
                .map_err(|_| host_error("host_checkpoint_continuation_rejected"));
        }
        return authority
            .import_checkpoint(&request)
            .map(|value| value.to_string())
            .map_err(|_| host_error("host_checkpoint_import_rejected"));
    }
    if args.first().map(String::as_str) == Some("context-checkpoint") {
        if args.len() != 4 || args[1] != "--json" || args[3] != "--host-stdin" {
            return Err(EngineCliError::Usage);
        }
        let request = read_request::<lean_ctx::core::execution_ledger::host::HostCheckpointRequest>(
            Path::new(&args[2]),
        )?;
        let authority = HostReceiptAuthority::from_reader(input).map_err(EngineCliError::Host)?;
        return authority
            .export_checkpoint(&request)
            .map(|value| value.to_string())
            .map_err(|_| host_error("host_checkpoint_rejected"));
    }
    if args.first().map(String::as_str) == Some("context-outcome") {
        if args.len() != 4 || args[1] != "--json" || args[3] != "--host-stdin" {
            return Err(EngineCliError::Usage);
        }
        let request = read_request::<lean_ctx::core::execution_ledger::host::HostOutcomeRequest>(
            Path::new(&args[2]),
        )?;
        let authority = HostReceiptAuthority::from_reader(input).map_err(EngineCliError::Host)?;
        return authority
            .observe_outcome(&request)
            .map(|value| value.to_string())
            .map_err(|_| host_error("host_outcome_rejected"));
    }
    if args == ["signer-info", "--key-stdin"] {
        let bytes = read_bounded(input, 66, "invalid_signing_key")?;
        let text = std::str::from_utf8(&bytes).map_err(|_| host_error("invalid_signing_key"))?;
        let key = parse_key(text.trim()).map_err(EngineCliError::Host)?;
        return Ok(serde_json::json!({
            "schema_version":1, "algorithm":"ed25519",
            "public_key_hex":lean_ctx::core::agent_identity::hex_encode(key.verifying_key().as_bytes()),
            "public_key_digest":digest(key.verifying_key().as_bytes()).map_err(EngineCliError::Host)?.as_str(),
        }).to_string());
    }
    if args.first().map(String::as_str) != Some("context-view-receipt")
        || args
            .iter()
            .filter(|arg| arg.as_str() == "--host-stdin")
            .count()
            != 1
    {
        return Err(EngineCliError::Usage);
    }
    let mut view_args: Vec<String> = args
        .iter()
        .filter(|arg| arg.as_str() != "--host-stdin")
        .cloned()
        .collect();
    view_args[0] = "context-view".into();
    let cli = super::parse_cli_args(&view_args)?;
    let request: HostRequest = read_request(&cli.json_file)?;
    let authority = HostReceiptAuthority::from_reader(input).map_err(EngineCliError::Host)?;
    validate_request(&request)?;
    let attempt = authority
        .begin(&request.task, &request.plan)
        .map_err(EngineCliError::Host)?;
    let result = execute_transport_context_view_with_plan(
        &cli.project_root,
        &request.path,
        &request.task,
        &request.plan,
    )
    .map_err(EngineCliError::Engine)?;
    let invocation = result
        .invocation
        .as_ref()
        .ok_or_else(|| host_error("host_engine_evidence_unavailable"))?;
    let observation = result
        .observation
        .as_ref()
        .ok_or_else(|| host_error("host_engine_evidence_unavailable"))?;
    let published = authority
        .publish(&attempt, invocation, observation, &result.view.text)
        .map_err(EngineCliError::Host)?;
    let view: serde_json::Value = serde_json::from_str(&super::encode_response(result)?)
        .map_err(|_| host_error("host_response_unavailable"))?;
    Ok(serde_json::json!({
        "schema_version":1, "engine":view,
        "canonical_receipt":{
            "receipt_id":published.receipt_id, "receipt_ref":published.receipt_ref,
            "receipt_digest":published.receipt_digest, "outcome":"unknown",
        },
    })
    .to_string())
}

fn validate_request(request: &HostRequest) -> Result<(), EngineCliError> {
    super::validate_header(
        request.schema_version,
        request.transport_version,
        &request.engine_interface_version,
    )?;
    request
        .task
        .validate()
        .map_err(|_| host_error("invalid_host_task"))?;
    request
        .plan
        .validate()
        .map_err(|_| host_error("invalid_host_plan"))?;
    if request.path.trim().is_empty()
        || request.mode != "aggressive"
        || request.plan.task_id != request.task.task_id
        || request.plan.model != "local-native"
        || request.plan.provider != "local-native"
        || request.plan.context_plan_id.is_some()
        || request
            .plan
            .context_token_limit()
            .is_none_or(|limit| limit == 0 || limit > MAX_TRANSPORT_BUDGET_TOKENS)
        || !request
            .plan
            .capability_ids
            .iter()
            .any(|id| id.as_str() == CAPABILITY_ID)
        || request.plan.policy_decision_ref.as_deref() != Some(ENGINE_TRANSPORT_POLICY_REF)
        || request.plan.capability_bindings.iter().any(|binding| {
            binding.capability_id.as_str() == CAPABILITY_ID && binding.version != CAPABILITY_VERSION
        })
    {
        return Err(host_error("invalid_host_plan"));
    }
    lean_ctx::core::engine_interface::planning::validate_native_plan(
        &request.task,
        &request.plan,
        &lean_ctx_protocol::EnginePolicyAdmissionV1 {
            policy_ref: lean_ctx_protocol::ProtocolReference::new(ENGINE_TRANSPORT_POLICY_REF)
                .map_err(|_| host_error("invalid_host_plan"))?,
            decision: lean_ctx_protocol::EnginePolicyDecisionV1::Admitted,
        },
    )
    .map_err(|_| host_error("invalid_host_plan"))?;
    Ok(())
}

fn read_framed_authority(
    reader: &mut impl BufRead,
    ledger_root: Option<&Path>,
) -> Result<HostReceiptAuthority, EngineCliError> {
    // Compact settings are operator-owned, bounded even without a newline,
    // zeroized after loading and never part of the untrusted request DTO.
    let mut settings = Zeroizing::new(Vec::new());
    reader
        .by_ref()
        .take(16 * 1024 + 1)
        .read_until(b'\n', &mut settings)
        .map_err(|_| host_error("invalid_host_configuration"))?;
    if settings.len() > 16 * 1024 || !settings.ends_with(b"\n") {
        return Err(host_error("invalid_host_configuration"));
    }
    HostReceiptAuthority::from_reader_scoped(&mut settings.as_slice(), ledger_root)
        .map_err(EngineCliError::Host)
}

fn read_request<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T, EngineCliError> {
    let mut options = std::fs::OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
    }
    let mut file = options
        .open(path)
        .map_err(|_| host_error("host_request_unavailable"))?;
    if !file
        .metadata()
        .map_err(|_| host_error("host_request_unavailable"))?
        .is_file()
    {
        return Err(host_error("host_request_unavailable"));
    }
    serde_json::from_slice(&read_bounded(
        &mut file,
        REQUEST_LIMIT,
        "host_request_unavailable",
    )?)
    .map_err(|_| host_error("invalid_host_request"))
}

fn read_bounded(
    input: &mut impl Read,
    limit: usize,
    code: &'static str,
) -> Result<Zeroizing<Vec<u8>>, EngineCliError> {
    let mut bytes = Zeroizing::new(Vec::new());
    input
        .take(limit as u64 + 1)
        .read_to_end(&mut bytes)
        .map_err(|_| host_error(code))?;
    if bytes.len() > limit {
        return Err(host_error(code));
    }
    Ok(bytes)
}

fn host_error(code: &'static str) -> EngineCliError {
    EngineCliError::Host(code)
}

#[cfg(test)]
mod tests;
#[cfg(test)]
mod transfer_tests;