neosian 2.12.1

The state layer for LLM agents, as one static binary: the record, memory and the state process
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
//! `setup`: wire the selected clients once per machine (§22.6, §30.3).

use super::{
    cache_install, codex_skills,
    context::{CLIENTS, Context},
    diagnostics, files, hooks, mcp, runner, settings, setup_check, targets,
};
use clap::Args;
use serde_json::{Value, json};
use std::io::{self, IsTerminal, Write};

#[derive(Args)]
pub struct Setup {
    #[arg(long, value_parser = CLIENTS)]
    client: Vec<String>,
    #[arg(long)]
    write: bool,
    /// Check saved registrations and probe this binary with temporary MCP/file storage.
    #[arg(long, conflicts_with = "write")]
    check: bool,
    #[arg(long)]
    json: bool,
    #[arg(long, default_value = "user", value_parser = ["user", "project"])]
    pub level: String,
    #[arg(long)]
    binary: Option<String>,
    #[arg(long, value_name = "CLIENT=DIR")]
    at: Vec<String>,
    #[arg(long)]
    yes: bool,
    #[arg(long)]
    pub root: Option<String>,
    #[arg(long)]
    pub url: Option<String>,
    #[arg(long)]
    pub profile: Option<String>,
    /// Install idle cache maintenance for Claude Code, or disable it and restore its prior statusline.
    #[arg(long, default_value = "auto", value_parser = ["auto", "off"])]
    claude_cache: String,
    /// Install Codex's upkeep skill, preserve an opt-out, explicitly enable it, or remove it.
    #[arg(long, default_value = "auto", value_parser = ["auto", "on", "off"])]
    codex_skills: String,
}

fn discovery(context: &Context, clients: &[String]) -> Vec<Value> {
    clients
        .iter()
        .map(|client| {
            let directory = context.directory(client);
            json!({"client": client, "directory": directory, "installed": directory.is_dir()})
        })
        .collect()
}

fn discovery_text(rows: &[Value]) -> String {
    rows.iter()
        .filter(|r| r["installed"] == false)
        .map(|r| {
            format!(
                "  {}: not found; searched {}\n",
                text(r, "client"),
                text(r, "directory")
            )
        })
        .collect()
}

fn text<'a>(value: &'a Value, key: &str) -> &'a str {
    value[key].as_str().unwrap_or("-")
}

fn applied(mut envelope: Value) -> Value {
    if envelope.get("client").is_some() {
        envelope["applied"] = json!(envelope["written"] == true);
    }
    envelope
}

fn install_pair(args: &Setup, context: &Context, client: &str) -> Value {
    let target = targets::mcp(client, context, &args.level);
    let hook = targets::hooks(client, context, &args.level);
    let settings = settings::resolve_profile(
        args.root.as_deref().filter(|v| !v.is_empty()),
        args.url.as_deref().filter(|v| !v.is_empty()),
        args.profile.as_deref(),
        false,
        context,
    )
    .and_then(|mut settings| {
        if settings.profile.is_none() {
            settings.mounts = settings::mount_argv(
                &settings::mounts(&args.level, context).map_err(settings::refusal)?,
            );
        }
        Ok(settings)
    });
    let grammar = |message: String| json!({"success": false, "error": message, "hint": null});
    let incompatible = (target.level != args.level).then(|| {
        format!(
            "--level {}: {} keeps one file for every project ({}); it registers at the user level",
            args.level,
            target.label,
            target.path.display()
        )
    });
    let settings = match settings {
        Ok(s) => s,
        Err(message) => {
            return json!({"client": client, "label": target.label,
            "mcp": grammar(incompatible.unwrap_or_else(|| message.clone())), "hooks": grammar(message)});
        }
    };
    if client == "codex" && args.level == "user" {
        let skills = codex_skills::install(context, &args.codex_skills, false);
        if skills["success"] != true {
            return json!({"client":client,"label":target.label,
                "mcp":applied(mcp::install(&target, context, &settings, false)),
                "hooks":applied(hooks::install(&hook, context, &settings, false)),"skills":skills});
        }
    }
    if args.write && ["claude-code", "codex", "muse-code", "cursor", "pi"].contains(&client) {
        let mcp = applied(match &incompatible {
            Some(message) => grammar(message.clone()),
            None => mcp::install(&target, context, &settings, false),
        });
        let hooks = applied(hooks::install(&hook, context, &settings, false));
        if mcp["success"] != true || hooks["success"] != true {
            return json!({"client": client, "label": target.label, "mcp": mcp, "hooks": hooks});
        }
        if client == "claude-code" && args.claude_cache == "auto" {
            let cache = cache_install::install(context, &args.level, false);
            if cache["success"] != true {
                return json!({"client":client,"label":target.label,"mcp":mcp,"hooks":hooks,"cache":cache});
            }
        }
    }
    let mut mcp = applied(match incompatible {
        Some(message) => grammar(message),
        None => mcp::install(
            &target,
            context,
            &settings,
            args.write && target.cli.is_none(),
        ),
    });
    if args.write && mcp["apply"].is_string() {
        let argv = mcp::apply_argv(&target, &mcp["entry"]);
        let mut result = runner::run(&argv, &context.env);
        if result.as_ref().is_some_and(|(ok, _)| !ok) {
            let mut remove = vec![argv[0].clone(), "mcp".into(), "remove".into()];
            if target.cli == Some("claude") {
                remove.extend(["--scope".into(), "user".into()]);
            }
            remove.push(targets::SERVER.into());
            runner::run(&remove, &context.env);
            result = runner::run(&argv, &context.env);
        }
        mcp["applied"] = json!(result.as_ref().is_some_and(|(ok, _)| *ok));
        mcp["apply_error"] = result
            .filter(|(ok, _)| !ok)
            .map_or(Value::Null, |(_, err)| json!(err));
        let project = targets::mcp(client, context, "project");
        if mcp["applied"] == true
            && project.path != target.path
            && let Err(e) = mcp::displace(&project, true)
        {
            mcp["apply_error"] = json!(e.message);
        }
    }
    let hooks = applied(hooks::install(&hook, context, &settings, args.write));
    let mut row = json!({"client": client, "label": target.label, "mcp": mcp, "hooks": hooks});
    if client == "codex" && args.level == "user" {
        let ready = row["mcp"]["success"] == true
            && row["mcp"]["applied"] == true
            && row["hooks"]["success"] == true
            && row["hooks"]["applied"] == true;
        row["skills"] = codex_skills::install(context, &args.codex_skills, args.write && ready);
    }
    if client == "claude-code" {
        row["cache"] = if args.claude_cache == "off" {
            cache_install::disable(context, &args.level, args.write)
        } else {
            cache_install::install(context, &args.level, args.write)
        };
    }
    if let Some(profile) = settings.profile {
        row["profile"] = profile;
        row["profile_support"] = settings::support(client);
    }
    row
}

fn line(kind: &str, envelope: &Value, write: bool) -> String {
    let prefix = format!("  {kind:<6}{}  ", text(envelope, "config_path"));
    let result = if envelope["success"] != true {
        format!("refused: {}", text(envelope, "error"))
    } else if let Some(apply) = envelope["apply"].as_str() {
        if !write {
            format!("would run: {apply}")
        } else if envelope["applied"] == true {
            format!("applied: {apply}")
        } else {
            let why = envelope["apply_error"]
                .as_str()
                .map(str::to_owned)
                .unwrap_or_else(|| format!("{} is not on PATH", shlex::split(apply).unwrap()[0]));
            format!("not applied ({why}); run: {apply}")
        }
    } else if let Some(action) = envelope["action"]
        .as_str()
        .filter(|_| !write || envelope["applied"] == true)
    {
        format!("{}{}", if write { "applied: " } else { "would " }, action)
    } else if write {
        if envelope["applied"] != true {
            "not applied (preflight failed)".into()
        } else if envelope["created"] == true {
            "created".into()
        } else {
            "updated".into()
        }
    } else {
        "would write".into()
    };
    prefix + &result
}

pub fn run(args: &Setup, out: &mut impl Write, err: &mut impl Write) -> io::Result<u8> {
    let mut context = Context::new()?;
    if let Err(message) = context
        .locations(&args.at)
        .and_then(|()| context.binary(args.binary.as_deref()))
    {
        return crate::cli::usage(args.json, &message, out, err);
    }
    let tty = io::stdin().is_terminal() && io::stdout().is_terminal();
    if args.write && args.client.is_empty() && !args.yes && (args.json || !tty) {
        return crate::cli::usage(
            args.json,
            "unattended --write requires --yes or --client",
            out,
            err,
        );
    }
    let searched_clients = if args.client.is_empty() {
        CLIENTS.map(str::to_owned).to_vec()
    } else {
        args.client.clone()
    };
    let searched = discovery(&context, &searched_clients);
    let mut clients = Vec::new();
    for client in &searched_clients {
        if !clients.contains(client)
            && (!args.client.is_empty() || context.directory(client).is_dir())
        {
            clients.push(client.clone());
        }
    }
    let installation = diagnostics::installation(&context);
    let storage = diagnostics::selection(
        args.root.as_deref(),
        args.url.as_deref(),
        args.profile.as_deref(),
        &context,
    );
    if args.check {
        return setup_check::run(
            &context,
            &clients,
            storage,
            args.root.is_some() || args.url.is_some() || args.profile.is_some(),
            args.json,
            out,
        );
    }
    if clients.is_empty() {
        let message = format!(
            "no client found: none of {} is installed",
            CLIENTS.join(", ")
        );
        if args.json {
            writeln!(
                out,
                "{}",
                json!({"error": message, "hint": null, "searched": searched})
            )?;
        }
        writeln!(err, "error: {message}")?;
        write!(err, "{}", discovery_text(&searched))?;
        return Ok(1);
    }
    if args.write && args.client.is_empty() && !args.yes {
        let labels: Vec<_> = clients
            .iter()
            .map(|c| targets::mcp(c, &context, "user").label)
            .collect();
        let Some(selected) = super::selection::select(&labels, &mut io::stdin().lock(), out)?
        else {
            writeln!(err, "setup cancelled; nothing written")?;
            return Ok(1);
        };
        clients = clients
            .into_iter()
            .enumerate()
            .filter_map(|(i, c)| selected.contains(&i).then_some(c))
            .collect();
        if clients.is_empty() {
            writeln!(out, "No clients selected; nothing written.")?;
            return Ok(0);
        }
    }

    let rows: Vec<_> = clients
        .iter()
        .map(|client| install_pair(args, &context, client))
        .collect();
    let failed = rows.iter().any(|row| {
        ["mcp", "hooks", "cache", "skills"].iter().any(|k| {
            !row[k].is_null()
                && (row[k]["success"] != true || (args.write && row[k]["applied"] != true))
        })
    });
    if args.json {
        writeln!(
            out,
            "{}",
            json!({"written": args.write, "level": args.level, "clients": rows, "searched": searched,
                "installation":installation,"storage":storage})
        )?;
    } else {
        setup_check::render_installation(&installation, out)?;
        setup_check::render_storage(&storage, out)?;
        for row in &rows {
            writeln!(out, "{}", text(row, "label"))?;
            if row["profile"].is_object() {
                writeln!(
                    out,
                    "  profile {}  capture {}  context {}",
                    text(&row["profile"], "profile"),
                    text(&row["profile"], "capture"),
                    text(&row["profile_support"], "context")
                )?;
                writeln!(
                    out,
                    "  capture fields {}  history source {}  support {}",
                    row["profile"]["definition"]["capture"]["fields"],
                    text(&row["profile"]["definition"]["history"], "source"),
                    text(&row["profile_support"], "capture")
                )?;
            }
            for kind in ["mcp", "hooks"] {
                writeln!(out, "{}", line(kind, &row[kind], args.write))?;
            }
            if let Some(skills) = row.get("skills") {
                writeln!(out, "{}", line("skills", skills, args.write))?;
            }
            if let Some(cache) = row.get("cache") {
                writeln!(out, "{}", line("cache", cache, args.write))?;
                if let Some(note) = cache["note"].as_str() {
                    writeln!(out, "  note  {note}")?;
                }
                if !args.write
                    && let Some(commands) = cache["commands"].as_array()
                {
                    for argv in commands {
                        let argv: Vec<_> = argv
                            .as_array()
                            .unwrap()
                            .iter()
                            .filter_map(Value::as_str)
                            .map(str::to_owned)
                            .collect();
                        writeln!(out, "    {}", super::context::shell_join(&argv))?;
                    }
                }
            }
            for note in [&row["mcp"]["note"], &row["hooks"]["trust_hint"]]
                .into_iter()
                .filter_map(Value::as_str)
            {
                writeln!(out, "  note  {note}")?;
            }
            if let Some(shadow) = row["mcp"]["mcp_shadowed_by"].as_str() {
                writeln!(
                    err,
                    "note: preserved shared {shadow}; it overrides Muse's user registration"
                )?;
            }
            if let Some(files) = row["hooks"].get("files")
                && !args.write
            {
                write!(out, "{}", files::pretty(files))?;
            }
        }
        if !args.write {
            writeln!(err, "hint: re-run with --write to apply")?;
        }
        if args.write && !failed {
            writeln!(
                out,
                "Registrations saved. Run this executable with setup --check, then restart the client and review hook trust."
            )?;
        }
        write!(out, "{}", discovery_text(&searched))?;
    }
    if args.url.as_ref().is_some_and(|value| !value.is_empty()) {
        writeln!(
            err,
            "hint: set NEOSIAN_CLIENT_TOKEN in each client's own environment: the token is never written into a registration or a hook line"
        )?;
    }
    Ok(u8::from(failed))
}