use anyhow::{Result, anyhow};
use onlyne_config::Spec;
use onlyne_config::layout::{RoleWorkspace, ServerRoot, detect_legacy};
use onlyne_net::KeyPair;
use std::path::{Path, PathBuf};
const PLACEMENT_COMMENTS: &str = "\
# Where this machine displays the role's runtime: orca | zellij |
# headless | external. An absent value probes orca, zellij in that order
# and falls back to headless; a nonempty ONLYNE_BACKEND wins over this key.
# placement = \"headless\"
";
const ACP_COMMENTS: &str = "\
# ACP options, read only when the role's `[client.runtime] drive` is `acp`.
# `mode`, `model`,
# and `reasoning_effort` name the agent's own configuration values: the agent
# validates them, and an empty one keeps the agent's default. `permission` is
# this machine's answer to a permission request from the agent: `deny` (the
# default, it refuses and records a fault) or `allow`.
# [acp]
# mode = \"\"
# model = \"\"
# reasoning_effort = \"\"
# permission = \"deny\"
";
#[derive(Debug, Clone)]
pub struct InitArgs {
pub workspace: PathBuf,
pub role: String,
pub server_root: PathBuf,
pub prose: String,
}
#[derive(Debug)]
pub struct LegacyWorkspace;
impl std::fmt::Display for LegacyWorkspace {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("legacy workspace")
}
}
impl std::error::Error for LegacyWorkspace {}
const RECONNECT_COMMENTS: &str = "\
# Seconds a dropped plugin connection may stay away before this client retires
# the session it left behind. A session with a task bound goes with it: an
# unsettled task ends `failed`, the delivery that session still held is refused
# with reason `session_dead`, and the session's own exit is published. An agent
# that reconnects inside the window keeps its session; a connection that returns
# after a newer session took the task is held read-only, and what it sends rides
# that session's closing handoff. 0 disables the sweep.
# reconnect_grace_secs = 60
";
fn role_key(path: &Path) -> Result<KeyPair> {
if path.exists() {
return KeyPair::load(path).map_err(|error| anyhow!(error.to_string()));
}
let key = KeyPair::generate();
key.save(path).map_err(|error| anyhow!(error.to_string()))?;
Ok(key)
}
fn server_section(root: &Path) -> Result<(String, String, String)> {
let layout = ServerRoot::resolve(root);
let spec = Spec::load(layout.spec_path())?;
Ok((spec.server.listen, spec.server.cert_pin, spec.server.name))
}
pub async fn init(args: InitArgs) -> Result<String> {
if let Some(reason) = detect_legacy(&args.workspace) {
eprintln!(
"{}",
onlyne_proto::legacy_workspace_message(&[reason.to_string()])
);
return Err(anyhow::Error::new(LegacyWorkspace));
}
let workspace = RoleWorkspace::resolve(&args.workspace);
workspace.bootstrap()?;
let key = role_key(&workspace.key_path())?;
let (listen, cert_pin, _server_name) = server_section(&args.server_root)?;
let (host, port) = listen
.rsplit_once(':')
.map(|(h, p)| (h.to_string(), p.parse::<u16>().unwrap_or(0)))
.unwrap_or((listen, 0));
let config = format!(
"role = {role:?}\ncert_pin = {pin:?}\nkey_path = {key_path:?}\nplugins = []\n\n{PLACEMENT_COMMENTS}\n{RECONNECT_COMMENTS}\n[server]\nhost = {host:?}\nport = {port}\n\n{ACP_COMMENTS}",
role = args.role,
pin = cert_pin,
key_path = workspace.key_path().display().to_string(),
host = host,
port = port,
);
std::fs::write(workspace.config_path(), config)?;
Ok(fragment(&args.role, &key.public_str(), &args.prose))
}
const SEED_RUNTIME: &str = "\
[client.runtime]\n\
drive = \"plugin\"\n\
command = [\"pi\", \"--session-id\", \"{session}\", \"--session-dir\", \".pi/sessions\", \"-ns\"]";
pub fn fragment(role: &str, public_key: &str, prose: &str) -> String {
let role = toml_string(role);
let key = toml_string(public_key);
let prose = toml_string(prose);
format!(
"[[client]]\nrole = {role}\nkey = {key}\nadmin = false\nmax_sessions = 1\nallowed_senders = [\"*\", {role}]\nallowed_targets = [{role}]\nprose = {prose}\n{KNOB_COMMENTS}\n{runtime}\n",
runtime = SEED_RUNTIME,
)
}
const KNOB_COMMENTS: &str = "\
# timeout = { ready_ms = 30000, idle_ms = 60000 }
# Per-session budgets in milliseconds; the server projects them into the hello
# reply as `timeout_ready_ms` and `timeout_idle_ms`.
# intent = { attempts = 3, backoff_ms = [1000, 2000, 4000] }
# Retry policy for one intent: total attempts, then the per-retry waits in
# milliseconds; a longer list repeats its last entry.
# aggregate = \"\"
# The child-cluster name this role stands for. It is an annotation only: no
# delivery decision reads it, and a plain role leaves it empty.
# The [client.runtime] table below is the drive and the argv a session runs.
# `drive` names how the client talks to the runtime: plugin (the default)
# starts it and lets its plugin dial back, acp runs the agent as a child over
# stdio (placement headless only), and exec runs the command and reads its exit
# code. `command` is the argv, with {session} and {task} substituted; any other
# brace is refused.
";
pub fn toml_string(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for character in text.chars() {
match character {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
other => out.push(other),
}
}
out.push('"');
out
}
pub fn legacy_error_code() -> i32 {
2
}