outlayer-cli 0.2.5

CLI for deploying, running, and managing OutLayer agents
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
use anyhow::{Context, Result};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};

use crate::api::{ApiClient, HttpsCallRequest, SecretsRef};
use crate::config::{self, NetworkConfig};
use crate::near::{ContractCaller, NearClient};

// ── Source types ──────────────────────────────────────────────────────

pub enum RunSource {
    Project {
        project_id: String,
        version: Option<String>,
    },
    WasmUrl {
        url: String,
        hash: Option<String>,
    },
}

impl RunSource {
    /// Build contract-format JSON for request_execution
    async fn to_contract_json(&self, build_target: &str) -> Result<Value> {
        match self {
            RunSource::Project { project_id, version } => Ok(json!({
                "Project": {
                    "project_id": project_id,
                    "version_key": version
                }
            })),
            RunSource::WasmUrl { url, hash } => {
                let hash = match hash.as_deref() {
                    Some(h) => h.to_string(),
                    None => {
                        eprintln!("Downloading WASM to compute hash...");
                        compute_wasm_hash(url).await?
                    }
                };
                Ok(json!({
                    "WasmUrl": {
                        "url": url,
                        "hash": hash,
                        "build_target": build_target
                    }
                }))
            }
        }
    }

    fn label(&self) -> String {
        match self {
            RunSource::Project { project_id, .. } => project_id.clone(),
            RunSource::WasmUrl { url, .. } => format!("wasm:{url}"),
        }
    }
}

// ── Run ──────────────────────────────────────────────────────────────

/// `outlayer run` — execute agent from a project or a wasm url
#[allow(clippy::too_many_arguments)]
pub async fn run(
    network: &NetworkConfig,
    source: RunSource,
    input: Option<String>,
    input_file: Option<String>,
    is_async: bool,
    deposit: Option<String>,
    compute_limit: Option<u64>,
    build_target: &str,
    secrets_ref: Option<SecretsRef>,
    attach_near: Option<String>,
) -> Result<()> {
    let input_value = parse_input(input, input_file)?;
    let attach_yocto = attach_near.as_deref().map(parse_near).transpose()?;

    // HTTPS API only works for Project source with payment key
    if let RunSource::Project { ref project_id, ref version } = source {
        if let Ok(payment_key) = find_payment_key() {
            anyhow::ensure!(
                attach_yocto.is_none(),
                "--attach-near is for on-chain runs; this one goes over HTTPS with your payment key"
            );
            return run_https(
                network,
                project_id,
                &payment_key,
                input_value,
                is_async,
                deposit,
                version.clone(),
                compute_limit,
                secrets_ref,
            )
            .await;
        }
    }

    // On-chain for all source types
    if is_async {
        anyhow::bail!("--async is only supported with payment key (HTTPS API)");
    }

    eprintln!("Executing on-chain with NEAR deposit.\n");
    run_on_chain(network, &source, input_value, compute_limit, build_target, secrets_ref, attach_yocto).await
}

/// Execute via HTTPS API (Project source + payment key)
async fn run_https(
    network: &NetworkConfig,
    project_id: &str,
    payment_key: &str,
    input_value: Value,
    is_async: bool,
    deposit: Option<String>,
    version: Option<String>,
    compute_limit: Option<u64>,
    secrets_ref: Option<SecretsRef>,
) -> Result<()> {
    let (owner, project) = split_project(project_id)?;

    let api = ApiClient::new(network);
    let body = HttpsCallRequest {
        input: input_value,
        is_async,
        version_key: version,
        secrets_ref,
    };

    eprintln!("Running {owner}/{project}...");

    let response = api
        .call_project(
            owner,
            project,
            payment_key,
            &body,
            compute_limit,
            deposit.as_deref(),
        )
        .await?;

    if is_async {
        eprintln!("Call ID: {}", response.call_id);
        eprintln!("Status:  {}", response.status);
        if let Some(poll_url) = &response.poll_url {
            eprintln!("Poll:    {poll_url}");
        }
    } else {
        print_sync_result(&response)?;
    }

    Ok(())
}

/// A synchronous call's answer. `pending` here means the API restarted while the call ran: it was
/// not resent and is still running (a resend would run and charge it twice), so this fails with
/// where its result is instead of printing nothing.
fn print_sync_result(response: &crate::api::HttpsCallResponse) -> Result<()> {
    if response.status == "pending" {
        anyhow::bail!(
            "The OutLayer API restarted while this call ran. The call is still running and was not resent \
             (do not run it again, it would be charged twice).\nGet its result with: outlayer status {}",
            response.call_id
        );
    }
    if let Some(output) = &response.output {
        println!(
            "{}",
            serde_json::to_string_pretty(output).unwrap_or_else(|_| output.to_string())
        );
    }
    if let Some(error) = &response.error {
        eprintln!("Error: {error}");
    }
    if let Some(cost) = &response.compute_cost {
        eprintln!("Cost: {cost}");
    }
    if let Some(time_ms) = response.time_ms {
        eprintln!("Time: {time_ms}ms");
    }
    Ok(())
}

#[cfg(test)]
mod sync_result_tests {
    #[test]
    fn a_near_amount_is_read_exactly() {
        assert_eq!(super::parse_near("0.5").unwrap(), 5 * 10u128.pow(23));
        assert_eq!(super::parse_near("2").unwrap(), 2 * 10u128.pow(24));
        assert_eq!(super::parse_near(".000001").unwrap(), 10u128.pow(18));
        assert_eq!(super::parse_near("0.000000000000000000000001").unwrap(), 1);
        assert!(super::parse_near("0.0000000000000000000000001").is_err(), "below one yocto");
        assert!(super::parse_near("1e3").is_err());
        assert!(super::parse_near("").is_err());
        assert!(super::parse_near("-1").is_err());
        assert_eq!(super::near_str(5 * 10u128.pow(23)), "0.5");
        assert_eq!(super::near_str(13_000_200_000_000_000_000_000), "0.0130002");
    }

    use super::print_sync_result;
    use crate::api::HttpsCallResponse;

    fn response(status: &str) -> HttpsCallResponse {
        serde_json::from_value(serde_json::json!({
            "call_id": "6f1c0e2a-1111-2222-3333-444455556666",
            "status": status,
            "output": if status == "completed" { serde_json::json!({"ok": true}) } else { serde_json::Value::Null },
            "poll_url": if status == "pending" { serde_json::json!("/calls/6f1c0e2a-1111-2222-3333-444455556666") } else { serde_json::Value::Null },
        }))
        .unwrap()
    }

    #[test]
    fn a_pending_sync_answer_fails_and_names_the_call() {
        let err = print_sync_result(&response("pending")).unwrap_err().to_string();
        assert!(err.contains("restarted"), "{err}");
        assert!(err.contains("outlayer status 6f1c0e2a-1111-2222-3333-444455556666"), "{err}");
    }

    #[test]
    fn a_finished_sync_answer_succeeds() {
        assert!(print_sync_result(&response("completed")).is_ok());
        assert!(print_sync_result(&response("failed")).is_ok());
    }
}

/// A NEAR amount ("0.5", "2", "0.000001") in yoctoNEAR, exactly.
fn parse_near(s: &str) -> Result<u128> {
    let s = s.trim();
    let (whole, frac) = s.split_once('.').unwrap_or((s, ""));
    anyhow::ensure!(
        !(whole.is_empty() && frac.is_empty())
            && whole.chars().all(|c| c.is_ascii_digit())
            && frac.chars().all(|c| c.is_ascii_digit())
            && frac.len() <= 24,
        "not a NEAR amount: {s:?} (e.g. 0.5)"
    );
    let whole: u128 = if whole.is_empty() { 0 } else { whole.parse()? };
    let frac: u128 = format!("{frac:0<24}").parse()?;
    whole
        .checked_mul(10u128.pow(24))
        .and_then(|w| w.checked_add(frac))
        .ok_or_else(|| anyhow::anyhow!("NEAR amount too large: {s}"))
}

/// yoctoNEAR as NEAR, for messages.
fn near_str(yocto: u128) -> String {
    let whole = yocto / 10u128.pow(24);
    let frac = format!("{:024}", yocto % 10u128.pow(24));
    let frac = frac.trim_end_matches('0');
    if frac.is_empty() { whole.to_string() } else { format!("{whole}.{frac}") }
}

/// Execute on-chain via request_execution (any source type)
async fn run_on_chain(
    network: &NetworkConfig,
    source: &RunSource,
    input_value: Value,
    compute_limit: Option<u64>,
    build_target: &str,
    secrets_ref: Option<SecretsRef>,
    attach_yocto: Option<u128>,
) -> Result<()> {
    let creds = config::load_credentials(network)?;
    let near = NearClient::new(network);
    let caller = ContractCaller::from_credentials(&creds, network)?;

    let resource_limits = json!({
        "max_instructions": compute_limit.unwrap_or(1_000_000_000),
        "max_memory_mb": 128,
        "max_execution_seconds": 10
    });

    let input_data = serde_json::to_string(&input_value)?;

    // Estimate cost
    let cost_str: String = near
        .estimate_execution_cost(Some(resource_limits.clone()), input_data.len(), 0)
        .await?;
    let cost_yocto: u128 = cost_str
        .trim_matches('"')
        .parse()
        .context("Failed to parse execution cost")?;

    // The estimate covers compute and the input; a stored output (1 KB or more) needs more,
    // which --attach-near provides. Whatever the run does not use is refunded.
    let deposit_yocto = match attach_yocto {
        Some(attach) if attach < cost_yocto => anyhow::bail!(
            "--attach-near is {} NEAR; this request needs at least {} NEAR (compute and input)",
            near_str(attach),
            near_str(cost_yocto)
        ),
        Some(attach) => attach,
        None => cost_yocto,
    };
    let label = source.label();
    eprintln!(
        "Running {label} (on-chain, attaching {} NEAR; what the run does not use is refunded)...",
        near_str(deposit_yocto)
    );

    let source_json = source.to_contract_json(build_target).await?;
    let gas = 300_000_000_000_000u64; // 300 TGas

    let secrets_ref_json = secrets_ref
        .map(|sr| json!({"profile": sr.profile, "account_id": sr.account_id}))
        .unwrap_or(Value::Null);

    let result = caller
        .call_contract(
            "request_execution",
            json!({
                "source": source_json,
                "resource_limits": resource_limits,
                "input_data": input_data,
                "secrets_ref": secrets_ref_json,
                "response_format": "Json",
                "payer_account_id": null,
                "params": null
            }),
            gas,
            deposit_yocto,
        )
        .await
        .context("On-chain execution failed")?;

    if let Some(hash) = &result.tx_hash {
        eprintln!("Tx: {hash}");
    }

    // Print result
    if let Some(value) = &result.value {
        if !value.is_null() {
            println!(
                "{}",
                serde_json::to_string_pretty(value)
                    .unwrap_or_else(|_| value.to_string())
            );
        }
    }

    Ok(())
}

// ── Helpers ────────────────────────────────────────────────────────────

fn split_project(project_id: &str) -> Result<(&str, &str)> {
    project_id
        .split_once('/')
        .context("Project must be in format owner/name (e.g. alice.near/my-agent)")
}

async fn compute_wasm_hash(url: &str) -> Result<String> {
    let client = reqwest::Client::new();
    let resp = client
        .get(url)
        .send()
        .await
        .with_context(|| format!("Failed to download WASM from {url}"))?;

    if !resp.status().is_success() {
        anyhow::bail!("Failed to download WASM: HTTP {}", resp.status());
    }

    let bytes = resp.bytes().await.context("Failed to read WASM body")?;
    let hash = hex::encode(Sha256::digest(&bytes));
    eprintln!("Hash: {hash} ({} bytes)", bytes.len());
    Ok(hash)
}

fn find_payment_key() -> Result<String> {
    if let Ok(key) = std::env::var("PAYMENT_KEY") {
        return Ok(key);
    }

    let cwd = std::env::current_dir()?;
    let env_path = cwd.join(".env");
    if env_path.exists() {
        let content = std::fs::read_to_string(&env_path)?;
        for line in content.lines() {
            if let Some(val) = line.strip_prefix("PAYMENT_KEY=") {
                return Ok(val.to_string());
            }
        }
    }

    anyhow::bail!("No payment key found")
}

fn parse_input(input: Option<String>, input_file: Option<String>) -> Result<Value> {
    if let Some(file) = input_file {
        let data = std::fs::read_to_string(&file)
            .with_context(|| format!("Failed to read input file: {file}"))?;
        serde_json::from_str(&data).with_context(|| format!("Invalid JSON in {file}"))
    } else if let Some(json_str) = input {
        serde_json::from_str(&json_str).context("Invalid JSON input")
    } else if std::io::IsTerminal::is_terminal(&std::io::stdin()) {
        Ok(Value::Object(serde_json::Map::new()))
    } else {
        let mut buf = String::new();
        std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)?;
        if buf.trim().is_empty() {
            Ok(Value::Object(serde_json::Map::new()))
        } else {
            serde_json::from_str(&buf).context("Invalid JSON from stdin")
        }
    }
}