ilo 26.5.0

ilo - the token-minimal programming language AI agents write
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
//! WASM HTTP backend — routes `get` and `pst` through a `fetch` host import.
//!
//! ## Architecture
//!
//! Three concrete implementations exist for the `HttpBackend` trait:
//!
//! * [`NativeHttpBackend`] — uses `minreq` (the existing path, native builds).
//! * [`WasmFetchBackend`] — calls into a host-provided `fetch` import
//!   (`wasm32-wasi` / `wasm32-unknown-unknown`).
//! * [`StubHttpBackend`] — returns `Err("http not available")` immediately;
//!   used when neither `http` feature nor WASM fetch is compiled in.
//!
//! The interpreter selects the right backend via `cfg` at compile time;
//! the `HttpBackend` trait normalises the call-site so the dispatch arms stay
//! identical.
//!
//! ## WASM host import contract (`wasm32` targets)
//!
//! The host must export two functions under the module name `ilo_http`:
//!
//! ```text
//! (func $ilo_http_get
//!   (import "ilo_http" "get")
//!   (param $url_ptr i32) (param $url_len i32)
//!   (param $hdr_ptr i32) (param $hdr_len i32)
//!   (result i32))   ; returns a handle
//!
//! (func $ilo_http_post
//!   (import "ilo_http" "post")
//!   (param $url_ptr i32) (param $url_len i32)
//!   (param $body_ptr i32) (param $body_len i32)
//!   (param $hdr_ptr i32) (param $hdr_len i32)
//!   (result i32))   ; returns a handle
//!
//! (func $ilo_http_response_status
//!   (import "ilo_http" "response_status")
//!   (param $handle i32)
//!   (result i32))
//!
//! (func $ilo_http_response_body_len
//!   (import "ilo_http" "response_body_len")
//!   (param $handle i32)
//!   (result i32))
//!
//! (func $ilo_http_response_body_read
//!   (import "ilo_http" "response_body_read")
//!   (param $handle i32) (param $buf_ptr i32) (param $buf_len i32)
//!   (result i32))   ; bytes written
//!
//! (func $ilo_http_response_free
//!   (import "ilo_http" "response_free")
//!   (param $handle i32))
//! ```
//!
//! **Headers format** (`hdr_ptr`/`hdr_len`): a UTF-8 string of
//! `"key1\x00value1\x00key2\x00value2\x00"` — null-byte delimited key/value
//! pairs, terminated by an extra null byte.  An empty header block is a
//! zero-length string (pass a valid pointer with `hdr_len = 0`).
//!
//! A handle of `0` signals transport failure; the body of handle `0` is
//! an ASCII error message.  Status `0` also means transport failure (not
//! an HTTP status code).
//!
//! ## WASI Preview 2 transition path
//!
//! When the `wasi:http/outgoing-handler` interface stabilises in the Rust
//! toolchain, this module will be replaced with a WIT-bound implementation.
//! The `HttpBackend` trait ensures the interpreter dispatch arms need zero
//! changes at that point — only this file and `Cargo.toml` change.

use std::sync::Arc;

use super::{MapKey, Value};

// ── Trait ─────────────────────────────────────────────────────────────────────

/// Synchronous HTTP backend abstraction.
///
/// Both `get` and `post` are synchronous from the caller's perspective even on
/// WASM; the WASM implementation drives the host's async `fetch` via a
/// blocking adapter (spin-loop on the handle until the host resolves it, or a
/// host-provided blocking call — host implementors should use the latter).
pub trait HttpBackend {
    /// Perform an HTTP GET.  Returns `Ok(body_text)` or `Err(message)`.
    fn get(&self, url: &str, headers: &[(String, String)]) -> Result<String, String>;

    /// Perform an HTTP POST with a text body.  Returns `Ok(body_text)` or
    /// `Err(message)`.
    fn post(&self, url: &str, body: &str, headers: &[(String, String)]) -> Result<String, String>;

    /// Stream an HTTP GET response as lines (ILO-46 client side). Returns a
    /// boxed `Iterator<Item = Result<String, String>>` that drains the body
    /// one line at a time as bytes arrive — never buffers the full response.
    /// Each `Ok(line)` is one chunk-line (newline stripped, trailing `\r`
    /// trimmed for `\r\n` chunked encoding). Transport / I/O errors surface
    /// as `Err(msg)` from the iterator; the outer `Result` only fails when
    /// the initial connection can't be opened.
    fn get_stream(
        &self,
        url: &str,
        headers: &[(String, String)],
    ) -> Result<Box<dyn Iterator<Item = std::result::Result<String, std::io::Error>> + Send>, String>;

    /// Stream an HTTP POST response as lines. Same semantics as `get_stream`.
    fn post_stream(
        &self,
        url: &str,
        body: &str,
        headers: &[(String, String)],
    ) -> Result<Box<dyn Iterator<Item = std::result::Result<String, std::io::Error>> + Send>, String>;
}

// ── Native backend (minreq) ───────────────────────────────────────────────────

/// Native HTTP backend that uses `minreq`.  Present on non-WASM builds when
/// the `http` feature is enabled.
#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
pub struct NativeHttpBackend;

#[cfg(all(feature = "http", not(target_arch = "wasm32")))]
impl HttpBackend for NativeHttpBackend {
    fn get(&self, url: &str, headers: &[(String, String)]) -> Result<String, String> {
        let mut req = minreq::get(url);
        for (k, v) in headers {
            req = req.with_header(k.as_str(), v.as_str());
        }
        req.send()
            .map_err(|e| e.to_string())
            .and_then(|r| r.as_str().map(|s| s.to_owned()).map_err(|e| e.to_string()))
    }

    fn post(&self, url: &str, body: &str, headers: &[(String, String)]) -> Result<String, String> {
        let mut req = minreq::post(url).with_body(body);
        for (k, v) in headers {
            req = req.with_header(k.as_str(), v.as_str());
        }
        req.send()
            .map_err(|e| e.to_string())
            .and_then(|r| r.as_str().map(|s| s.to_owned()).map_err(|e| e.to_string()))
    }

    fn get_stream(
        &self,
        url: &str,
        headers: &[(String, String)],
    ) -> Result<Box<dyn Iterator<Item = std::result::Result<String, std::io::Error>> + Send>, String>
    {
        let mut req = minreq::get(url);
        for (k, v) in headers {
            req = req.with_header(k.as_str(), v.as_str());
        }
        let resp = req.send_lazy().map_err(|e| e.to_string())?;
        // BufReader's `lines()` strips both `\n` and the trailing `\r` for
        // `\r\n` chunked encoding, which is exactly what we want for SSE-
        // style line consumption.
        use std::io::BufRead;
        let reader = std::io::BufReader::new(resp);
        Ok(Box::new(reader.lines()))
    }

    fn post_stream(
        &self,
        url: &str,
        body: &str,
        headers: &[(String, String)],
    ) -> Result<Box<dyn Iterator<Item = std::result::Result<String, std::io::Error>> + Send>, String>
    {
        let mut req = minreq::post(url).with_body(body);
        for (k, v) in headers {
            req = req.with_header(k.as_str(), v.as_str());
        }
        let resp = req.send_lazy().map_err(|e| e.to_string())?;
        use std::io::BufRead;
        let reader = std::io::BufReader::new(resp);
        Ok(Box::new(reader.lines()))
    }
}

// ── WASM fetch backend ────────────────────────────────────────────────────────

/// WASM HTTP backend that routes requests through a host-provided `fetch`
/// import.  See module-level docs for the host import contract.
#[cfg(target_arch = "wasm32")]
pub struct WasmFetchBackend;

// Raw host imports.  The host (browser, Deno, Cloudflare Workers, a custom
// wasmtime host) must provide these under module `"ilo_http"`.
#[cfg(target_arch = "wasm32")]
#[link(wasm_import_module = "ilo_http")]
unsafe extern "C" {
    /// Issue an HTTP GET.  Returns a response handle (0 = transport error).
    fn ilo_http_get(url_ptr: *const u8, url_len: usize, hdr_ptr: *const u8, hdr_len: usize) -> u32;

    /// Issue an HTTP POST.  Returns a response handle (0 = transport error).
    fn ilo_http_post(
        url_ptr: *const u8,
        url_len: usize,
        body_ptr: *const u8,
        body_len: usize,
        hdr_ptr: *const u8,
        hdr_len: usize,
    ) -> u32;

    /// HTTP status code for `handle`.  Returns 0 on transport error.
    fn ilo_http_response_status(handle: u32) -> u32;

    /// Byte length of the response body for `handle`.
    fn ilo_http_response_body_len(handle: u32) -> u32;

    /// Read up to `buf_len` bytes of the response body into `buf_ptr`.
    /// Returns the number of bytes written.
    fn ilo_http_response_body_read(handle: u32, buf_ptr: *mut u8, buf_len: usize) -> u32;

    /// Release host-side resources for `handle`.
    fn ilo_http_response_free(handle: u32);
}

/// Encode a `&[(String, String)]` header slice into the null-delimited wire
/// format expected by the host import.
#[cfg(target_arch = "wasm32")]
fn encode_headers(headers: &[(String, String)]) -> Vec<u8> {
    let mut buf = Vec::new();
    for (k, v) in headers {
        buf.extend_from_slice(k.as_bytes());
        buf.push(0);
        buf.extend_from_slice(v.as_bytes());
        buf.push(0);
    }
    buf
}

#[cfg(target_arch = "wasm32")]
impl HttpBackend for WasmFetchBackend {
    fn get(&self, url: &str, headers: &[(String, String)]) -> Result<String, String> {
        let hdr_buf = encode_headers(headers);
        let handle =
            unsafe { ilo_http_get(url.as_ptr(), url.len(), hdr_buf.as_ptr(), hdr_buf.len()) };
        read_response(handle)
    }

    fn post(&self, url: &str, body: &str, headers: &[(String, String)]) -> Result<String, String> {
        let hdr_buf = encode_headers(headers);
        let handle = unsafe {
            ilo_http_post(
                url.as_ptr(),
                url.len(),
                body.as_ptr(),
                body.len(),
                hdr_buf.as_ptr(),
                hdr_buf.len(),
            )
        };
        read_response(handle)
    }

    fn get_stream(
        &self,
        _url: &str,
        _headers: &[(String, String)],
    ) -> Result<Box<dyn Iterator<Item = std::result::Result<String, std::io::Error>> + Send>, String>
    {
        Err("HTTP streaming not supported on this build".to_string())
    }

    fn post_stream(
        &self,
        _url: &str,
        _body: &str,
        _headers: &[(String, String)],
    ) -> Result<Box<dyn Iterator<Item = std::result::Result<String, std::io::Error>> + Send>, String>
    {
        Err("HTTP streaming not supported on this build".to_string())
    }
}

/// Read the body from a response handle, then free it.
///
/// A handle of `0` signals transport failure; the body bytes of handle `0`
/// contain an error message from the host.
#[cfg(target_arch = "wasm32")]
fn read_response(handle: u32) -> Result<String, String> {
    let body_len = unsafe { ilo_http_response_body_len(handle) } as usize;
    let mut buf = vec![0u8; body_len];
    if body_len > 0 {
        unsafe { ilo_http_response_body_read(handle, buf.as_mut_ptr(), buf.len()) };
    }
    let status = unsafe { ilo_http_response_status(handle) };
    unsafe { ilo_http_response_free(handle) };

    let text = String::from_utf8(buf).map_err(|e| format!("response is not valid UTF-8: {e}"))?;

    if handle == 0 || status == 0 {
        Err(text)
    } else {
        Ok(text)
    }
}

// ── Stub backend ──────────────────────────────────────────────────────────────

/// Fallback backend returned when neither `http` nor WASM fetch is available.
pub struct StubHttpBackend;

impl HttpBackend for StubHttpBackend {
    fn get(&self, _url: &str, _headers: &[(String, String)]) -> Result<String, String> {
        Err("http feature not enabled".to_string())
    }

    fn post(
        &self,
        _url: &str,
        _body: &str,
        _headers: &[(String, String)],
    ) -> Result<String, String> {
        Err("http feature not enabled".to_string())
    }

    fn get_stream(
        &self,
        _url: &str,
        _headers: &[(String, String)],
    ) -> Result<Box<dyn Iterator<Item = std::result::Result<String, std::io::Error>> + Send>, String>
    {
        Err("HTTP streaming not supported on this build".to_string())
    }

    fn post_stream(
        &self,
        _url: &str,
        _body: &str,
        _headers: &[(String, String)],
    ) -> Result<Box<dyn Iterator<Item = std::result::Result<String, std::io::Error>> + Send>, String>
    {
        Err("HTTP streaming not supported on this build".to_string())
    }
}

// ── Factory ───────────────────────────────────────────────────────────────────

/// Return a boxed backend appropriate for the current compile target and
/// feature flags.
///
/// Selection order:
/// 1. WASM target → `WasmFetchBackend` (regardless of `http` feature).
/// 2. Non-WASM + `http` feature → `NativeHttpBackend`.
/// 3. Otherwise → `StubHttpBackend`.
pub fn default_backend() -> Box<dyn HttpBackend> {
    #[cfg(target_arch = "wasm32")]
    {
        Box::new(WasmFetchBackend)
    }
    #[cfg(all(feature = "http", not(target_arch = "wasm32")))]
    {
        Box::new(NativeHttpBackend)
    }
    #[cfg(all(not(feature = "http"), not(target_arch = "wasm32")))]
    {
        Box::new(StubHttpBackend)
    }
}

// ── Value helpers ─────────────────────────────────────────────────────────────

/// Convert a backend `Result<String, String>` to an ilo `R t t` value.
pub fn result_to_value(r: Result<String, String>) -> Value {
    match r {
        Ok(body) => Value::Ok(Box::new(Value::Text(Arc::new(body)))),
        Err(msg) => Value::Err(Box::new(Value::Text(Arc::new(msg)))),
    }
}

/// Extract headers from an ilo `M t t` value into a `Vec<(String, String)>`.
pub fn map_to_headers(map: &std::collections::HashMap<MapKey, Value>) -> Vec<(String, String)> {
    map.iter()
        .map(|(k, v)| {
            let key = k.to_display_string();
            let val = match v {
                Value::Text(s) => (**s).clone(),
                other => format!("{other:?}"),
            };
            (key, val)
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn stub_get_returns_err() {
        let b = StubHttpBackend;
        let r = b.get("https://example.com", &[]);
        assert!(r.is_err());
        assert!(r.unwrap_err().contains("http feature not enabled"));
    }

    #[test]
    fn stub_post_returns_err() {
        let b = StubHttpBackend;
        let r = b.post("https://example.com", "body", &[]);
        assert!(r.is_err());
    }

    #[test]
    fn result_to_value_ok() {
        let v = result_to_value(Ok("hello".to_string()));
        assert!(matches!(v, Value::Ok(_)));
    }

    #[test]
    fn result_to_value_err() {
        let v = result_to_value(Err("boom".to_string()));
        assert!(matches!(v, Value::Err(_)));
    }

    #[cfg(target_arch = "wasm32")]
    #[test]
    fn encode_headers_empty() {
        assert!(encode_headers(&[]).is_empty());
    }

    #[cfg(target_arch = "wasm32")]
    #[test]
    fn encode_headers_one_pair() {
        let enc = encode_headers(&[("Content-Type".to_string(), "application/json".to_string())]);
        // key \0 value \0
        let expected = b"Content-Type\x00application/json\x00";
        assert_eq!(&enc, expected);
    }
}