use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
use incurs::cli::Cli;
use incurs::command::{CommandDef, McpAnnotations, McpCommandOptions, TypedContext, TypedResult};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use crate::benchmark::{ProcessBenchmark, process_benchmark};
use crate::daemon::{Daemon, DaemonClient, DaemonStatus};
use crate::model::{
ActionReceipt, AgentSession, CausalEvent, ConnectorConfig, ConnectorKind, Execution,
ExecutionBudget, ExecutionListPage, ExecutionProgram, ExecutionSpec, ExecutionStatus, IoMode,
Lease, LeaseOwnerKind, OperationReceipt, PortInfo, ProcessDossier, ProcessEvent,
ProcessEventQuery, ProcessFile, ProcessInfo, ProcessInsight, ProcessProbe, ProcessQuery,
ProcessSample, ProcessSelection, ProcessWait, Recipe, Reservation, RetryPolicy, SCHEMA_VERSION,
SecretRef, WorkspaceContext, now_ms, valid_provider_name,
};
use crate::process::{ProcessManager, controller, parse_signal, port_owners, sockets, wait_for};
use crate::run::{InputReceipt, RunLogs};
use crate::skill::{
SkillError, SkillStatus, install, install_with_prefix, status, status_with_prefix,
};
#[derive(Deserialize, incurs::Options)]
struct ListOptions {
selector: Option<String>,
#[incurs(default = "cpu")]
sort: String,
#[incurs(alias = "n", default = 50)]
limit: usize,
}
#[derive(Deserialize, incurs::Args)]
struct TargetArgs {
target: String,
}
#[derive(Deserialize, incurs::Args)]
struct QueryArgs {
query: String,
}
#[derive(Deserialize, incurs::Args)]
struct SignalArgs {
target: String,
signal: String,
}
#[derive(Deserialize, incurs::Options)]
struct StopOptions {
#[incurs(default = 5000)]
timeout_ms: u64,
#[serde(default)]
force: bool,
idempotency_key: Option<String>,
#[serde(default)]
allow_empty: bool,
}
#[derive(Deserialize, incurs::Options)]
struct MutationOptions {
idempotency_key: Option<String>,
#[serde(default)]
allow_empty: bool,
}
#[derive(Deserialize, incurs::Args)]
struct PortArgs {
port: u16,
}
#[derive(Deserialize, incurs::Options)]
struct PortOptions {
protocol: Option<String>,
}
#[derive(Deserialize, incurs::Options)]
struct SocketOptions {
protocol: Option<String>,
#[serde(default)]
listening: bool,
#[incurs(default = 1000)]
limit: usize,
}
#[derive(Deserialize, incurs::Options)]
struct SampleOptions {
selector: Option<String>,
#[incurs(default = "cpu")]
sort: String,
#[incurs(default = 50)]
limit: usize,
#[incurs(default = 1000)]
interval_ms: u64,
#[incurs(default = 2)]
count: usize,
}
#[derive(Deserialize, incurs::Options)]
struct ProcessWaitOptions {
#[incurs(default = "exit")]
condition: String,
#[incurs(default = 50)]
interval_ms: u64,
#[incurs(default = 30000)]
timeout_ms: u64,
}
#[derive(Deserialize, incurs::Options)]
struct ProcessContextOptions {
#[incurs(default = 50)]
events: usize,
}
#[derive(Deserialize, incurs::Options)]
struct ProcessHistoryOptions {
#[incurs(default = 100)]
limit: usize,
process_key: Option<String>,
pid: Option<u32>,
operation: Option<String>,
phase: Option<String>,
actor: Option<String>,
controller_execution_id: Option<String>,
execution_id: Option<String>,
since_ms: Option<u64>,
until_ms: Option<u64>,
}
#[derive(Deserialize, incurs::Options)]
struct BenchmarkOptions {
#[incurs(default = 10)]
iterations: usize,
#[incurs(default = 2)]
warmup: usize,
}
#[derive(Serialize, JsonSchema)]
struct VersionOutput {
version: String,
name: String,
execution_schema_version: u32,
}
#[derive(Deserialize, incurs::Args)]
struct RunArgv {
executable: String,
}
#[derive(Deserialize, incurs::Options)]
struct ExecutionOptions {
idempotency_key: Option<String>,
name: Option<String>,
purpose: Option<String>,
label: Option<Vec<String>>,
cwd: Option<String>,
env: Option<Vec<String>>,
secret_env: Option<Vec<String>>,
arg: Option<Vec<String>>,
#[serde(default)]
shell: bool,
#[serde(default)]
pty: bool,
#[incurs(default = "persistent")]
owner: String,
session: Option<String>,
parent: Option<String>,
#[incurs(default = 1)]
max_attempts: u32,
#[incurs(default = 500)]
retry_backoff_ms: u64,
#[incurs(default = 30000)]
retry_max_backoff_ms: u64,
timeout_ms: Option<u64>,
progress_timeout_ms: Option<u64>,
#[serde(default)]
cancel_on_stall: bool,
child_processes: Option<u32>,
artifact_bytes: Option<u64>,
expires_at: Option<u64>,
}
#[derive(Deserialize, incurs::Options)]
struct BatchOptions {
file: Option<String>,
commands: Option<Vec<crate::model::CommandUnit>>,
name: Option<String>,
purpose: Option<String>,
idempotency_key: Option<String>,
cwd: Option<String>,
session: Option<String>,
parent: Option<String>,
max_parallel: Option<u32>,
#[serde(default)]
fail_fast: bool,
}
#[derive(Deserialize, incurs::Options)]
struct PipelineOptions {
file: Option<String>,
commands: Option<Vec<crate::model::CommandUnit>>,
name: Option<String>,
purpose: Option<String>,
idempotency_key: Option<String>,
cwd: Option<String>,
session: Option<String>,
parent: Option<String>,
#[incurs(default = true)]
pipefail: bool,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum CommandGroupFile {
Commands(Vec<crate::model::CommandUnit>),
Object {
commands: Vec<crate::model::CommandUnit>,
max_parallel: Option<u32>,
fail_fast: Option<bool>,
pipefail: Option<bool>,
},
}
#[derive(Deserialize, incurs::Args)]
struct RunIdArgs {
id: String,
}
#[derive(Deserialize, incurs::Args)]
struct RunSignalArgs {
id: String,
signal: String,
}
#[derive(Deserialize, incurs::Args)]
struct RunInputArgs {
id: String,
data: String,
}
#[derive(Deserialize, incurs::Options)]
struct RunStopOptions {
#[incurs(default = 5000)]
timeout_ms: u64,
}
#[derive(Deserialize, incurs::Options)]
struct RunLogsOptions {
#[incurs(default = 65536)]
tail_bytes: usize,
}
#[derive(Deserialize, incurs::Options)]
struct ExecutionListOptions {
#[incurs(default = 20)]
limit: usize,
cursor: Option<String>,
status: Option<ExecutionStatus>,
}
#[derive(Deserialize, incurs::Options)]
struct RunWaitOptions {
timeout_ms: Option<u64>,
}
#[derive(Serialize, Deserialize, JsonSchema)]
struct RemoveOutput {
id: String,
removed: bool,
}
#[derive(Serialize, Deserialize, JsonSchema)]
struct ExecutionAttachment {
execution: Execution,
logs: RunLogs,
live_io: bool,
}
#[derive(Serialize, Deserialize, JsonSchema)]
struct ExecutionInvocation {
execution: Execution,
replayed: bool,
logs: Option<RunLogs>,
}
fn invocation_result(value: ExecutionInvocation) -> TypedResult<ExecutionInvocation> {
let code = value
.execution
.result
.as_ref()
.and_then(|result| result.get("exit_code"))
.and_then(serde_json::Value::as_i64)
.and_then(|code| i32::try_from(code).ok())
.or_else(|| {
value
.execution
.attempts
.last()
.and_then(|attempt| attempt.exit_code)
})
.unwrap_or(match value.execution.status {
ExecutionStatus::Completed => 0,
ExecutionStatus::Canceled => 128,
_ => 1,
});
TypedResult::ok_with_exit_code(value, code)
}
#[derive(Serialize, Deserialize, JsonSchema)]
struct DetachOutput {
id: String,
detached: bool,
}
#[derive(Deserialize, incurs::Options)]
struct SessionOpenOptions {
actor: Option<String>,
label: Option<Vec<String>>,
#[incurs(default = 60000)]
ttl_ms: u64,
}
#[derive(Deserialize, incurs::Options)]
struct SessionHeartbeatOptions {
#[incurs(default = 60000)]
ttl_ms: u64,
}
#[derive(Deserialize, incurs::Options)]
struct ActiveOptions {
#[serde(default)]
active: bool,
}
#[derive(Deserialize, incurs::Options)]
struct LeaseRenewOptions {
#[incurs(default = 60000)]
ttl_ms: u64,
}
#[derive(Deserialize, incurs::Args)]
struct ReservationAcquireArgs {
kind: String,
key: String,
lease: String,
}
#[derive(Deserialize, incurs::Options)]
struct ReservationOptions {
ttl_ms: Option<u64>,
}
#[derive(Deserialize, incurs::Options)]
struct EventQueryOptions {
#[incurs(default = 0)]
after: u64,
#[incurs(default = 100)]
limit: usize,
}
#[derive(Deserialize, incurs::Options)]
struct EventWatchOptions {
#[incurs(default = 0)]
after: u64,
#[incurs(default = 100)]
limit: usize,
#[incurs(default = 30000)]
timeout_ms: u64,
}
#[derive(Deserialize, incurs::Args)]
struct PayloadArgs {
id: String,
}
#[derive(Deserialize, incurs::Options)]
struct PayloadPinOptions {
#[serde(default)]
unpin: bool,
}
#[derive(Deserialize, incurs::Options)]
struct PayloadPruneOptions {
#[incurs(default = 2592000000_u64)]
max_age_ms: u64,
}
#[derive(Serialize, Deserialize, JsonSchema)]
struct ReleaseOutput {
id: String,
released: bool,
}
#[derive(Serialize, Deserialize, JsonSchema)]
struct PayloadOutput {
id: String,
value: serde_json::Value,
}
#[derive(Serialize, Deserialize, JsonSchema)]
struct PayloadPinOutput {
id: String,
pinned: bool,
updated: bool,
}
#[derive(Serialize, Deserialize, JsonSchema)]
struct PayloadPruneOutput {
pruned: usize,
before: u64,
}
#[derive(Serialize, Deserialize, JsonSchema)]
struct DaemonStopOutput {
stopping: bool,
}
#[derive(Deserialize, incurs::Options)]
struct SkillInstallOptions {
prefix: Option<String>,
#[serde(default)]
force: bool,
}
#[derive(Deserialize, incurs::Options)]
struct SkillStatusOptions {
prefix: Option<String>,
}
pub fn build_cli() -> Cli {
build_agent_cli()
.group(daemon_cli())
.group(code_cli())
.group(recipe_cli())
.group(receipt_cli())
.group(capability_cli())
.group(action_cli())
.group(provider_cli())
.group(connector_cli())
.group(skill_cli())
}
pub(crate) fn build_agent_cli() -> Cli {
build_agent_cli_with_store(None)
}
pub(crate) fn build_agent_cli_with_store(store: Option<Arc<crate::store::Store>>) -> Cli {
let manager = Arc::new(Mutex::new(match &store {
Some(store) => ProcessManager::with_store(store.clone()),
None => ProcessManager::new(),
}));
let process = process_cli(Arc::clone(&manager), store.clone());
Cli::create("apoc")
.description("apoc: unrestricted process control for LLMs")
.version(env!("CARGO_PKG_VERSION"))
.group(process)
.group(benchmark_cli(manager))
.group(execution_cli())
.group(session_cli())
.group(lease_cli())
.group(reservation_cli())
.group(event_cli())
.command(
"version",
CommandDef::typed::<(), (), (), VersionOutput, _, _>("version", |_| async move {
TypedResult::ok(VersionOutput {
version: env!("CARGO_PKG_VERSION").to_string(),
name: "apoc".to_string(),
execution_schema_version: SCHEMA_VERSION,
})
})
.description("Return the apoc build version.")
.mcp(read_only())
.done(),
)
}
fn skill_cli() -> Cli {
Cli::create("skill")
.description("Install and inspect the embedded apoc skill.")
.command(
"install",
CommandDef::typed::<(), SkillInstallOptions, (), SkillStatus, _, _>(
"install",
|context: TypedContext<(), SkillInstallOptions, ()>| async move {
let result = match context.options.prefix {
Some(prefix) => install_with_prefix(prefix, context.options.force),
None => install(context.options.force),
};
match result {
Ok(status) => TypedResult::ok(status),
Err(SkillError::Conflict(error)) => {
TypedResult::error("SKILL_CONFLICT", error)
}
Err(error) => TypedResult::error("SKILL_INSTALL_FAILED", error.to_string()),
}
},
)
.description("Install the embedded apoc skill into local agent skill roots.")
.mcp(destructive(false))
.done(),
)
.command(
"status",
CommandDef::typed::<(), SkillStatusOptions, (), SkillStatus, _, _>(
"status",
|context: TypedContext<(), SkillStatusOptions, ()>| async move {
let result = match context.options.prefix {
Some(prefix) => status_with_prefix(prefix),
None => status(),
};
match result {
Ok(status) => TypedResult::ok(status),
Err(error) => TypedResult::error("SKILL_STATUS_FAILED", error.to_string()),
}
},
)
.description("Return the embedded apoc skill installation status.")
.mcp(read_only())
.done(),
)
}
fn benchmark_cli(manager: Arc<Mutex<ProcessManager>>) -> Cli {
Cli::create("benchmark")
.description("Measure representative persistent agent workflows against shell tools.")
.command(
"process",
CommandDef::typed::<(), BenchmarkOptions, (), ProcessBenchmark, _, _>(
"process",
move |context: TypedContext<(), BenchmarkOptions, ()>| {
let manager = Arc::clone(&manager);
async move {
match process_benchmark(
manager,
context.options.iterations,
context.options.warmup,
controller(context.agent),
)
.await
{
Ok(report) => TypedResult::ok(report),
Err(error) => TypedResult::error("PROCESS_BENCHMARK_FAILED", error),
}
}
},
)
.description("Compare context-recording apoc inventory and lookup with spawned ps.")
.mcp(read_only())
.done(),
)
}
#[derive(Deserialize, incurs::Args)]
struct CodeArgs {
code: String,
}
#[derive(Deserialize, incurs::Args)]
struct CodeIdArgs {
id: String,
}
#[derive(Deserialize, incurs::Args)]
struct ArtifactArgs {
execution: String,
artifact: String,
}
#[derive(Deserialize, incurs::Options)]
struct CodeRunOptions {
#[incurs(default = 300000)]
timeout_ms: u64,
}
#[derive(Deserialize, incurs::Args)]
struct SearchArgs {
query: String,
}
#[derive(Deserialize, incurs::Options)]
struct ReceiptListOptions {
#[incurs(default = 100)]
limit: usize,
}
#[derive(Deserialize, incurs::Args)]
struct ProviderActionArgs {
provider: String,
method: String,
}
#[derive(Deserialize, incurs::Options)]
struct ProviderActionOptions {
input: Option<String>,
#[incurs(default = 300000)]
timeout_ms: u64,
}
#[derive(Deserialize, incurs::Args)]
struct RecipePutArgs {
name: String,
code: String,
}
#[derive(Deserialize, incurs::Options)]
struct RecipePutOptions {
description: Option<String>,
input_schema: Option<String>,
}
#[derive(Deserialize, incurs::Args)]
struct NameArgs {
name: String,
}
#[derive(Deserialize, incurs::Options)]
struct RecipeRunOptions {
#[incurs(default = 300000)]
timeout_ms: u64,
input: Option<String>,
}
#[derive(Deserialize, incurs::Args)]
struct HttpProviderArgs {
name: String,
url: String,
}
#[derive(Deserialize, incurs::Args)]
struct StdioProviderArgs {
name: String,
command: String,
}
#[derive(Deserialize, incurs::Options)]
struct HttpProviderOptions {
header: Option<Vec<String>>,
instructions: Option<String>,
base_url: Option<String>,
secret_header: Option<Vec<String>>,
}
#[derive(Deserialize, incurs::Options)]
struct StdioProviderOptions {
instructions: Option<String>,
arg: Option<Vec<String>>,
cwd: Option<String>,
env: Option<Vec<String>>,
secret_env: Option<Vec<String>>,
}
fn code_cli() -> Cli {
Cli::create("code")
.description("Execute durable JavaScript orchestration over the apoc tool graph.")
.command(
"run",
CommandDef::typed::<CodeArgs, CodeRunOptions, (), serde_json::Value, _, _>(
"run",
|context: TypedContext<CodeArgs, CodeRunOptions, ()>| async move {
match DaemonClient
.call(
"code.run",
serde_json::json!({
"code": context.args.code,
"timeout_ms": context.options.timeout_ms
}),
)
.await
{
Ok(state) => TypedResult::ok(state),
Err(error) => TypedResult::error("CODE_RUN_FAILED", error),
}
},
)
.description("Execute JavaScript through all replay passes and return durable state.")
.mcp(destructive(false))
.done(),
)
.command(
"start",
CommandDef::typed::<CodeArgs, (), (), serde_json::Value, _, _>(
"start",
|context: TypedContext<CodeArgs, (), ()>| async move {
match DaemonClient
.call(
"code.start",
serde_json::json!({ "code": context.args.code }),
)
.await
{
Ok(state) => TypedResult::ok(state),
Err(error) => TypedResult::error("CODE_START_FAILED", error),
}
},
)
.description("Start JavaScript and return its durable running state immediately.")
.mcp(destructive(false))
.done(),
)
.command(
"get",
CommandDef::typed::<CodeIdArgs, (), (), serde_json::Value, _, _>(
"get",
|context: TypedContext<CodeIdArgs, (), ()>| async move {
match DaemonClient
.call("code.get", serde_json::json!({ "id": context.args.id }))
.await
{
Ok(state) => TypedResult::ok(state),
Err(error) => TypedResult::error("CODE_GET_FAILED", error),
}
},
)
.description("Return one durable Code Mode execution snapshot.")
.mcp(read_only())
.done(),
)
.command(
"cancel",
CommandDef::typed::<CodeIdArgs, (), (), serde_json::Value, _, _>(
"cancel",
|context: TypedContext<CodeIdArgs, (), ()>| async move {
match DaemonClient
.call("code.cancel", serde_json::json!({ "id": context.args.id }))
.await
{
Ok(state) => TypedResult::ok(state),
Err(error) => TypedResult::error("CODE_CANCEL_FAILED", error),
}
},
)
.description("Cancel one active Code Mode execution and its active tool calls.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"search",
CommandDef::typed::<SearchArgs, (), (), serde_json::Value, _, _>(
"search",
|context: TypedContext<SearchArgs, (), ()>| async move {
match DaemonClient
.call(
"code.search",
serde_json::json!({ "query": context.args.query }),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("CODE_SEARCH_FAILED", error),
}
},
)
.description("Search current Code Mode methods, schemas, and snippets.")
.mcp(read_only())
.done(),
)
.command(
"artifact",
CommandDef::typed::<ArtifactArgs, (), (), serde_json::Value, _, _>(
"artifact",
|context: TypedContext<ArtifactArgs, (), ()>| async move {
match DaemonClient
.call(
"code.artifact",
serde_json::json!({
"execution": context.args.execution,
"artifact": context.args.artifact
}),
)
.await
{
Ok(value) => TypedResult::ok(value),
Err(error) => TypedResult::error("CODE_ARTIFACT_FAILED", error),
}
},
)
.description("Load one oversized value owned by a durable execution.")
.mcp(read_only())
.done(),
)
}
fn receipt_cli() -> Cli {
Cli::create("receipt")
.description("Inspect durable intent and outcome records for provider actions.")
.command(
"list",
CommandDef::typed::<(), ReceiptListOptions, (), Vec<OperationReceipt>, _, _>(
"list",
|context: TypedContext<(), ReceiptListOptions, ()>| async move {
match DaemonClient
.call(
"receipt.list",
serde_json::json!({"limit": context.options.limit}),
)
.await
{
Ok(receipts) => TypedResult::ok(receipts),
Err(error) => TypedResult::error("RECEIPT_LIST_FAILED", error),
}
},
)
.description("List recent provider action receipts.")
.mcp(read_only())
.done(),
)
.command(
"get",
CommandDef::typed::<CodeIdArgs, (), (), OperationReceipt, _, _>(
"get",
|context: TypedContext<CodeIdArgs, (), ()>| async move {
match DaemonClient
.call("receipt.get", serde_json::json!({"id": context.args.id}))
.await
{
Ok(receipt) => TypedResult::ok(receipt),
Err(error) => TypedResult::error("RECEIPT_GET_FAILED", error),
}
},
)
.description("Get one receipt by receipt or idempotency identifier.")
.mcp(read_only())
.done(),
)
}
fn capability_cli() -> Cli {
Cli::create("capability")
.description("Discover the smallest relevant slice of the live capability graph.")
.command(
"search",
CommandDef::typed::<SearchArgs, (), (), serde_json::Value, _, _>(
"search",
|context: TypedContext<SearchArgs, (), ()>| async move {
match DaemonClient
.call(
"code.search",
serde_json::json!({"query": context.args.query}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("CAPABILITY_SEARCH_FAILED", error),
}
},
)
.description("Search provider methods, schemas, and usage guidance.")
.mcp(read_only())
.done(),
)
}
fn action_cli() -> Cli {
Cli::create("action")
.description("Invoke one provider capability through durable Code Mode.")
.command(
"run",
CommandDef::typed::<
ProviderActionArgs,
ProviderActionOptions,
(),
serde_json::Value,
_,
_,
>(
"run",
|context: TypedContext<ProviderActionArgs, ProviderActionOptions, ()>| async move {
let code = match provider_action_code(
&context.args.provider,
&context.args.method,
context.options.input.as_deref(),
) {
Ok(code) => code,
Err(error) => return TypedResult::error("INVALID_ACTION_INPUT", error),
};
match DaemonClient
.call(
"code.run",
serde_json::json!({
"code": code,
"timeout_ms": context.options.timeout_ms
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("ACTION_FAILED", error),
}
},
)
.description("Invoke one capability and wait for its durable terminal state.")
.mcp(destructive(false))
.done(),
)
.command(
"start",
CommandDef::typed::<
ProviderActionArgs,
ProviderActionOptions,
(),
serde_json::Value,
_,
_,
>(
"start",
|context: TypedContext<ProviderActionArgs, ProviderActionOptions, ()>| async move {
let code = match provider_action_code(
&context.args.provider,
&context.args.method,
context.options.input.as_deref(),
) {
Ok(code) => code,
Err(error) => return TypedResult::error("INVALID_ACTION_INPUT", error),
};
match DaemonClient
.call("code.start", serde_json::json!({"code": code}))
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("ACTION_START_FAILED", error),
}
},
)
.description("Start one capability call and return its durable running state.")
.mcp(destructive(false))
.done(),
)
}
fn provider_action_code(
provider: &str,
method: &str,
input: Option<&str>,
) -> Result<String, String> {
if !valid_provider_name(provider) {
return Err(format!(
"Provider \"{provider}\" is not a valid JavaScript namespace"
));
}
let input = input
.map(serde_json::from_str::<serde_json::Value>)
.transpose()
.map_err(|error| error.to_string())?
.unwrap_or_else(|| serde_json::json!({}));
Ok(format!(
"return await {provider}[{}]({});",
serde_json::to_string(method).map_err(|error| error.to_string())?,
serde_json::to_string(&input).map_err(|error| error.to_string())?
))
}
fn recipe_cli() -> Cli {
Cli::create("recipe")
.description("Save and rerun durable JavaScript orchestration.")
.command(
"put",
CommandDef::typed::<RecipePutArgs, RecipePutOptions, (), Recipe, _, _>(
"put",
|context: TypedContext<RecipePutArgs, RecipePutOptions, ()>| async move {
let input_schema = match context.options.input_schema {
Some(value) => match serde_json::from_str::<serde_json::Value>(&value) {
Ok(value) => Some(value),
Err(error) => {
return TypedResult::error(
"INVALID_INPUT_SCHEMA",
error.to_string(),
);
}
},
None => None,
};
match DaemonClient
.call(
"recipe.put",
serde_json::json!({
"name": context.args.name,
"description": context.options.description.unwrap_or_default(),
"code": context.args.code,
"input_schema": input_schema
}),
)
.await
{
Ok(recipe) => TypedResult::ok(recipe),
Err(error) => TypedResult::error("RECIPE_PUT_FAILED", error),
}
},
)
.description("Create or replace one named JavaScript recipe.")
.mcp(destructive(true))
.done(),
)
.command(
"list",
CommandDef::typed::<(), (), (), Vec<Recipe>, _, _>("list", |_| async move {
match DaemonClient
.call("recipe.list", serde_json::json!({}))
.await
{
Ok(recipes) => TypedResult::ok(recipes),
Err(error) => TypedResult::error("RECIPE_LIST_FAILED", error),
}
})
.description("List saved recipes.")
.mcp(read_only())
.done(),
)
.command(
"get",
CommandDef::typed::<NameArgs, (), (), Recipe, _, _>(
"get",
|context: TypedContext<NameArgs, (), ()>| async move {
match DaemonClient
.call("recipe.get", serde_json::json!({ "id": context.args.name }))
.await
{
Ok(recipe) => TypedResult::ok(recipe),
Err(error) => TypedResult::error("RECIPE_GET_FAILED", error),
}
},
)
.description("Get one saved recipe.")
.mcp(read_only())
.done(),
)
.command(
"run",
CommandDef::typed::<NameArgs, RecipeRunOptions, (), serde_json::Value, _, _>(
"run",
|context: TypedContext<NameArgs, RecipeRunOptions, ()>| async move {
let input = match context.options.input {
Some(value) => match serde_json::from_str::<serde_json::Value>(&value) {
Ok(value) => value,
Err(error) => {
return TypedResult::error("INVALID_INPUT", error.to_string());
}
},
None => serde_json::Value::Null,
};
match DaemonClient
.call(
"recipe.run",
serde_json::json!({
"name": context.args.name,
"timeout_ms": context.options.timeout_ms,
"input": input
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECIPE_RUN_FAILED", error),
}
},
)
.description("Execute a saved recipe through durable Code Mode.")
.mcp(destructive(false))
.done(),
)
.command(
"remove",
CommandDef::typed::<NameArgs, (), (), RemoveOutput, _, _>(
"remove",
|context: TypedContext<NameArgs, (), ()>| async move {
match DaemonClient
.call(
"recipe.remove",
serde_json::json!({ "id": context.args.name }),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECIPE_REMOVE_FAILED", error),
}
},
)
.description("Delete one saved recipe.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn provider_cli() -> Cli {
external_provider_cli("provider", false)
}
fn connector_cli() -> Cli {
external_provider_cli("connector", true)
}
fn external_provider_cli(group: &'static str, legacy: bool) -> Cli {
let mut cli = Cli::create(group).description(if legacy {
"Deprecated alias for provider management."
} else {
"Register capability providers for immediate Code Mode composition."
});
for (name, description, kind) in [
(
if legacy { "add-mcp" } else { "add-mcp-http" },
"Register or replace one Streamable HTTP MCP server.",
ConnectorKind::McpHttp,
),
(
"add-openapi",
"Register or replace one OpenAPI document and request base URL.",
ConnectorKind::OpenApi,
),
] {
cli = cli.command(
name,
CommandDef::typed::<HttpProviderArgs, HttpProviderOptions, (), ConnectorConfig, _, _>(
name,
move |context: TypedContext<HttpProviderArgs, HttpProviderOptions, ()>| async move {
let headers =
match parse_env(context.options.header.as_deref().unwrap_or_default()) {
Ok(headers) => headers,
Err(error) => {
return TypedResult::error("INVALID_HEADER", error);
}
};
let secret_headers = match parse_secret_refs(
context.options.secret_header.as_deref().unwrap_or_default(),
) {
Ok(headers) => headers,
Err(error) => return TypedResult::error("INVALID_SECRET_HEADER", error),
};
if kind == ConnectorKind::OpenApi && context.options.base_url.is_none() {
return TypedResult::error(
"BASE_URL_REQUIRED",
"OpenAPI connectors require --base-url".to_string(),
);
}
let now = now_ms();
match DaemonClient
.call(
"connector.put",
ConnectorConfig {
name: context.args.name,
kind,
url: Some(context.args.url),
base_url: context.options.base_url,
command: None,
args: Vec::new(),
cwd: None,
env: BTreeMap::new(),
secret_env: BTreeMap::new(),
headers,
secret_headers,
instructions: context.options.instructions,
enabled: true,
generation: format!("config/{now}"),
created_at: now,
updated_at: now,
},
)
.await
{
Ok(config) => TypedResult::ok(config),
Err(error) => TypedResult::error("CONNECTOR_PUT_FAILED", error),
}
},
)
.description(description)
.mcp(destructive(true))
.done(),
);
}
cli = cli.command(
"add-mcp-stdio",
CommandDef::typed::<StdioProviderArgs, StdioProviderOptions, (), ConnectorConfig, _, _>(
"add-mcp-stdio",
|context: TypedContext<StdioProviderArgs, StdioProviderOptions, ()>| async move {
let env = match parse_env(context.options.env.as_deref().unwrap_or_default()) {
Ok(env) => env,
Err(error) => return TypedResult::error("INVALID_ENV", error),
};
let secret_env = match parse_secret_refs(
context.options.secret_env.as_deref().unwrap_or_default(),
) {
Ok(env) => env,
Err(error) => return TypedResult::error("INVALID_SECRET_ENV", error),
};
let now = now_ms();
match DaemonClient
.call(
"provider.put",
ConnectorConfig {
name: context.args.name,
kind: ConnectorKind::McpStdio,
url: None,
base_url: None,
command: Some(context.args.command),
args: context.options.arg.unwrap_or_default(),
cwd: context.options.cwd,
env,
secret_env,
headers: BTreeMap::new(),
secret_headers: BTreeMap::new(),
instructions: context.options.instructions,
enabled: true,
generation: format!("config/{now}"),
created_at: now,
updated_at: now,
},
)
.await
{
Ok(config) => TypedResult::ok(config),
Err(error) => TypedResult::error("PROVIDER_PUT_FAILED", error),
}
},
)
.description("Register or replace one supervised MCP stdio provider.")
.mcp(destructive(true))
.done(),
);
cli.command(
"list",
CommandDef::typed::<(), (), (), Vec<ConnectorConfig>, _, _>("list", |_| async move {
match DaemonClient
.call("provider.list", serde_json::json!({}))
.await
{
Ok(connectors) => TypedResult::ok(connectors),
Err(error) => TypedResult::error("CONNECTOR_LIST_FAILED", error),
}
})
.description("List registered capability providers.")
.mcp(read_only())
.done(),
)
.command(
"get",
CommandDef::typed::<NameArgs, (), (), ConnectorConfig, _, _>(
"get",
|context: TypedContext<NameArgs, (), ()>| async move {
match DaemonClient
.call(
"provider.get",
serde_json::json!({ "id": context.args.name }),
)
.await
{
Ok(config) => TypedResult::ok(config),
Err(error) => TypedResult::error("CONNECTOR_GET_FAILED", error),
}
},
)
.description("Get one capability-provider configuration.")
.mcp(read_only())
.done(),
)
.command(
"doctor",
CommandDef::typed::<NameArgs, (), (), serde_json::Value, _, _>(
"doctor",
|context: TypedContext<NameArgs, (), ()>| async move {
match DaemonClient
.call(
"provider.doctor",
serde_json::json!({ "id": context.args.name }),
)
.await
{
Ok(description) => TypedResult::ok(description),
Err(error) => TypedResult::error("PROVIDER_DOCTOR_FAILED", error),
}
},
)
.description("Connect to one provider and return its live capability description.")
.mcp(read_only())
.done(),
)
.command(
"refresh",
CommandDef::typed::<NameArgs, (), (), serde_json::Value, _, _>(
"refresh",
|context: TypedContext<NameArgs, (), ()>| async move {
match DaemonClient
.call(
"provider.refresh",
serde_json::json!({ "id": context.args.name }),
)
.await
{
Ok(description) => TypedResult::ok(description),
Err(error) => TypedResult::error("PROVIDER_REFRESH_FAILED", error),
}
},
)
.description("Discover capabilities and persist their immutable generation digest.")
.mcp(destructive(true))
.done(),
)
.command(
"remove",
CommandDef::typed::<NameArgs, (), (), RemoveOutput, _, _>(
"remove",
|context: TypedContext<NameArgs, (), ()>| async move {
match DaemonClient
.call(
"provider.remove",
serde_json::json!({ "id": context.args.name }),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("CONNECTOR_REMOVE_FAILED", error),
}
},
)
.description("Remove a provider and rebuild the Code Mode actor immediately.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn execution_spec(
args: RunArgv,
options: ExecutionOptions,
) -> Result<(ExecutionSpec, Option<String>, Option<String>), String> {
let labels = parse_labels(options.label.as_deref().unwrap_or_default())?;
let env = parse_env(options.env.as_deref().unwrap_or_default())?;
let mut secrets = std::collections::BTreeMap::new();
for value in options.secret_env.as_deref().unwrap_or_default() {
let (name, reference) = value
.split_once('=')
.ok_or_else(|| format!("Expected NAME=PROVIDER:REFERENCE, got \"{value}\""))?;
let (provider, reference) = reference
.split_once(':')
.ok_or_else(|| format!("Expected NAME=PROVIDER:REFERENCE, got \"{value}\""))?;
if name.is_empty() || provider.is_empty() || reference.is_empty() {
return Err(format!(
"Expected non-empty NAME=PROVIDER:REFERENCE, got \"{value}\""
));
}
secrets.insert(
name.to_string(),
SecretRef {
provider: provider.to_string(),
reference: reference.to_string(),
version: None,
},
);
}
let owner_kind = match options.owner.as_str() {
"execution" => LeaseOwnerKind::Execution,
"session" => LeaseOwnerKind::Session,
"persistent" => LeaseOwnerKind::Persistent,
value => return Err(format!("Unknown lease owner \"{value}\"")),
};
if owner_kind == LeaseOwnerKind::Session && options.session.is_none() {
return Err("Session-owned executions require --session".to_string());
}
let mut argv = vec![args.executable];
argv.extend(options.arg.unwrap_or_default());
let name = options.name.unwrap_or_else(|| {
argv.first()
.cloned()
.unwrap_or_else(|| "execution".to_string())
});
let owner_id = match owner_kind {
LeaseOwnerKind::Execution => options.parent.clone(),
LeaseOwnerKind::Session => options.session.clone(),
LeaseOwnerKind::Persistent => None,
};
let parent_id = options.parent;
let session_id = options.session;
Ok((
ExecutionSpec {
schema_version: SCHEMA_VERSION,
idempotency_key: options.idempotency_key,
name,
purpose: options.purpose,
labels,
program: ExecutionProgram::Command {
argv,
shell: options.shell,
},
workspace: WorkspaceContext {
cwd: options.cwd,
..WorkspaceContext::default()
},
env,
secrets,
io: if options.pty {
IoMode::Pty
} else {
IoMode::Pipes
},
owner_kind,
owner_id,
expires_at: options.expires_at,
retry: RetryPolicy {
max_attempts: options.max_attempts,
backoff_ms: options.retry_backoff_ms,
max_backoff_ms: options.retry_max_backoff_ms,
},
budget: ExecutionBudget {
wall_time_ms: options.timeout_ms,
child_processes: options.child_processes,
artifact_bytes: options.artifact_bytes,
progress_timeout_ms: options.progress_timeout_ms,
cancel_on_stall: options.cancel_on_stall,
},
},
parent_id,
session_id,
))
}
struct CommandGroupInput {
file: Option<String>,
commands: Option<Vec<crate::model::CommandUnit>>,
name: Option<String>,
purpose: Option<String>,
idempotency_key: Option<String>,
cwd: Option<String>,
session: Option<String>,
parent: Option<String>,
topology: crate::model::CommandTopology,
}
fn command_group_spec(
options: CommandGroupInput,
) -> Result<(ExecutionSpec, Option<String>, Option<String>), String> {
if options.file.is_some() && options.commands.is_some() {
return Err("Use either file or commands, not both".to_string());
}
let file = options
.file
.as_deref()
.map(|path| {
let bytes = std::fs::read(path)
.map_err(|error| format!("Could not read command file \"{path}\": {error}"))?;
serde_json::from_slice::<CommandGroupFile>(&bytes)
.map_err(|error| format!("Invalid command file \"{path}\": {error}"))
})
.transpose()?;
let (commands, file_max_parallel, file_fail_fast, file_pipefail) = match file {
Some(CommandGroupFile::Commands(commands)) => (commands, None, None, None),
Some(CommandGroupFile::Object {
commands,
max_parallel,
fail_fast,
pipefail,
}) => (commands, max_parallel, fail_fast, pipefail),
None => (
options
.commands
.ok_or_else(|| "Supply --file or structured commands".to_string())?,
None,
None,
None,
),
};
let topology = match options.topology {
crate::model::CommandTopology::Parallel {
max_parallel,
fail_fast,
} => crate::model::CommandTopology::Parallel {
max_parallel: file_max_parallel.unwrap_or(max_parallel),
fail_fast: file_fail_fast.unwrap_or(fail_fast),
},
crate::model::CommandTopology::Pipeline { pipefail } => {
crate::model::CommandTopology::Pipeline {
pipefail: file_pipefail.unwrap_or(pipefail),
}
}
};
let name = options.name.unwrap_or_else(|| match &topology {
crate::model::CommandTopology::Parallel { .. } => "batch".to_string(),
crate::model::CommandTopology::Pipeline { .. } => "pipeline".to_string(),
});
let owner_kind = if options.session.is_some() {
LeaseOwnerKind::Session
} else if options.parent.is_some() {
LeaseOwnerKind::Execution
} else {
LeaseOwnerKind::Persistent
};
let owner_id = options.session.clone().or_else(|| options.parent.clone());
Ok((
ExecutionSpec {
schema_version: SCHEMA_VERSION,
idempotency_key: options.idempotency_key,
name,
purpose: options.purpose,
labels: BTreeMap::new(),
program: ExecutionProgram::Commands { commands, topology },
workspace: WorkspaceContext {
cwd: options.cwd,
..WorkspaceContext::default()
},
env: BTreeMap::new(),
secrets: BTreeMap::new(),
io: IoMode::Pipes,
owner_kind,
owner_id,
expires_at: None,
retry: RetryPolicy::default(),
budget: ExecutionBudget::default(),
},
options.parent,
options.session,
))
}
fn parse_env(values: &[String]) -> Result<std::collections::BTreeMap<String, String>, String> {
parse_pairs(values, "environment")
}
fn parse_secret_refs(values: &[String]) -> Result<BTreeMap<String, SecretRef>, String> {
let mut refs = BTreeMap::new();
for value in values {
let (name, reference) = value
.split_once('=')
.ok_or_else(|| format!("Expected NAME=PROVIDER:REFERENCE, got \"{value}\""))?;
let (provider, reference) = reference
.split_once(':')
.ok_or_else(|| format!("Expected NAME=PROVIDER:REFERENCE, got \"{value}\""))?;
if name.is_empty() || provider.is_empty() || reference.is_empty() {
return Err(format!(
"Expected non-empty NAME=PROVIDER:REFERENCE, got \"{value}\""
));
}
refs.insert(
name.to_string(),
SecretRef {
provider: provider.to_string(),
reference: reference.to_string(),
version: None,
},
);
}
Ok(refs)
}
fn parse_labels(values: &[String]) -> Result<std::collections::BTreeMap<String, String>, String> {
parse_pairs(values, "label")
}
fn parse_pairs(
values: &[String],
kind: &str,
) -> Result<std::collections::BTreeMap<String, String>, String> {
values
.iter()
.map(|value| {
let (name, value) = value
.split_once('=')
.ok_or_else(|| format!("Expected {kind} NAME=VALUE, got \"{value}\""))?;
if name.is_empty() {
return Err(format!("{kind} names cannot be empty"));
}
Ok((name.to_string(), value.to_string()))
})
.collect()
}
fn daemon_cli() -> Cli {
Cli::create("daemon")
.description("Operate the private per-user apoc daemon.")
.command(
"start",
CommandDef::typed::<(), (), (), DaemonStatus, _, _>("start", |_| async move {
match DaemonClient
.call("daemon.status", serde_json::json!({}))
.await
{
Ok(status) => TypedResult::ok(status),
Err(error) => TypedResult::error("DAEMON_START_FAILED", error),
}
})
.description("Start the daemon if needed and return its status.")
.mcp(destructive(false))
.done(),
)
.command(
"status",
CommandDef::typed::<(), (), (), DaemonStatus, _, _>("status", |_| async move {
match DaemonClient
.call_existing("daemon.status", serde_json::json!({}))
.await
{
Ok(status) => TypedResult::ok(status),
Err(error) => TypedResult::error("DAEMON_STATUS_FAILED", error),
}
})
.description("Return status without starting a missing daemon.")
.mcp(read_only())
.done(),
)
.command(
"serve",
CommandDef::typed::<(), (), (), DaemonStopOutput, _, _>("serve", |_| async move {
let daemon = match Daemon::open_default() {
Ok(daemon) => daemon,
Err(error) => return TypedResult::error("DAEMON_OPEN_FAILED", error),
};
match daemon.serve().await {
Ok(()) => TypedResult::ok(DaemonStopOutput { stopping: true }),
Err(error) => TypedResult::error("DAEMON_SERVE_FAILED", error),
}
})
.description("Serve the daemon in the current process.")
.mcp(destructive(false))
.done(),
)
.command(
"stop",
CommandDef::typed::<(), (), (), DaemonStopOutput, _, _>("stop", |_| async move {
match DaemonClient
.call_existing("daemon.shutdown", serde_json::json!({}))
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("DAEMON_STOP_FAILED", error),
}
})
.description("Request a clean daemon shutdown.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn execution_cli() -> Cli {
let mut cli = Cli::create("execution")
.description(
"Start, coordinate, inspect, and cancel durable agent executions. Omitted cwd inherits the invoking process directory.",
);
cli = cli.command(
"start",
CommandDef::typed::<RunArgv, ExecutionOptions, (), ExecutionInvocation, _, _>(
"start",
|context: TypedContext<RunArgv, ExecutionOptions, ()>| async move {
let (spec, parent_id, session_id) =
match execution_spec(context.args, context.options) {
Ok(value) => value,
Err(error) => return TypedResult::error("INVALID_EXECUTION", error),
};
match DaemonClient
.call(
"execution.start",
serde_json::json!({
"spec": spec,
"parent_id": parent_id,
"session_id": session_id
}),
)
.await
{
Ok(execution) => TypedResult::ok(execution),
Err(error) => TypedResult::error("EXECUTION_START_FAILED", error),
}
},
)
.description(
"Start a durable exact-argv command and return after ownership is recorded; use an idempotency key for safe retries.",
)
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"command",
CommandDef::typed::<RunArgv, ExecutionOptions, (), ExecutionInvocation, _, _>(
"command",
|context: TypedContext<RunArgv, ExecutionOptions, ()>| async move {
let (spec, parent_id, session_id) =
match execution_spec(context.args, context.options) {
Ok(value) => value,
Err(error) => return TypedResult::error("INVALID_EXECUTION", error),
};
match DaemonClient
.call(
"execution.command",
serde_json::json!({
"spec": spec,
"parent_id": parent_id,
"session_id": session_id
}),
)
.await
{
Ok(execution) => invocation_result(execution),
Err(error) => TypedResult::error("EXECUTION_COMMAND_FAILED", error),
}
},
)
.description(
"Run an exact-argv command to completion; return bounded logs and the managed exit status, with idempotent replay when keyed.",
)
.command_aliases(vec!["exec".to_string()])
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"batch",
CommandDef::typed::<(), BatchOptions, (), ExecutionInvocation, _, _>(
"batch",
|context: TypedContext<(), BatchOptions, ()>| async move {
let options = context.options;
let max_parallel = options.max_parallel.unwrap_or_else(|| {
std::thread::available_parallelism()
.map(|value| value.get().min(256) as u32)
.unwrap_or(1)
});
let (spec, parent_id, session_id) = match command_group_spec(CommandGroupInput {
file: options.file,
commands: options.commands,
name: options.name,
purpose: options.purpose,
idempotency_key: options.idempotency_key,
cwd: options.cwd,
session: options.session,
parent: options.parent,
topology: crate::model::CommandTopology::Parallel {
max_parallel,
fail_fast: options.fail_fast,
},
}) {
Ok(value) => value,
Err(error) => return TypedResult::error("INVALID_BATCH", error),
};
match DaemonClient
.call(
"execution.command",
serde_json::json!({
"spec": spec,
"parent_id": parent_id,
"session_id": session_id
}),
)
.await
{
Ok(execution) => invocation_result(execution),
Err(error) => TypedResult::error("EXECUTION_BATCH_FAILED", error),
}
},
)
.description(
"Run exact-argv commands concurrently with bounded logs, managed exit status, and optional idempotent replay.",
)
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"pipeline",
CommandDef::typed::<(), PipelineOptions, (), ExecutionInvocation, _, _>(
"pipeline",
|context: TypedContext<(), PipelineOptions, ()>| async move {
let options = context.options;
let (spec, parent_id, session_id) = match command_group_spec(CommandGroupInput {
file: options.file,
commands: options.commands,
name: options.name,
purpose: options.purpose,
idempotency_key: options.idempotency_key,
cwd: options.cwd,
session: options.session,
parent: options.parent,
topology: crate::model::CommandTopology::Pipeline {
pipefail: options.pipefail,
},
}) {
Ok(value) => value,
Err(error) => return TypedResult::error("INVALID_PIPELINE", error),
};
match DaemonClient
.call(
"execution.command",
serde_json::json!({
"spec": spec,
"parent_id": parent_id,
"session_id": session_id
}),
)
.await
{
Ok(execution) => invocation_result(execution),
Err(error) => TypedResult::error("EXECUTION_PIPELINE_FAILED", error),
}
},
)
.description(
"Run an exact-argv native pipeline with pipefail, bounded logs, managed exit status, and optional idempotent replay.",
)
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"list",
CommandDef::typed::<(), ExecutionListOptions, (), ExecutionListPage, _, _>(
"list",
|context: TypedContext<(), ExecutionListOptions, ()>| async move {
match DaemonClient
.call(
"execution.list",
serde_json::json!({
"limit": context.options.limit,
"cursor": context.options.cursor,
"status": context.options.status
}),
)
.await
{
Ok(executions) => TypedResult::ok(executions),
Err(error) => TypedResult::error("EXECUTION_LIST_FAILED", error),
}
},
)
.description(
"List compact durable execution summaries in a bounded cursor page; use get for a full record.",
)
.command_aliases(vec!["ls".to_string()])
.mcp(read_only())
.done(),
);
cli = cli.command(
"get",
CommandDef::typed::<RunIdArgs, (), (), Execution, _, _>(
"get",
|context: TypedContext<RunIdArgs, (), ()>| async move {
match DaemonClient
.call(
"execution.get",
serde_json::json!({ "id": context.args.id }),
)
.await
{
Ok(execution) => TypedResult::ok(execution),
Err(error) => TypedResult::error("EXECUTION_GET_FAILED", error),
}
},
)
.description("Get one durable execution with its passes and attempts.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"logs",
CommandDef::typed::<RunIdArgs, RunLogsOptions, (), RunLogs, _, _>(
"logs",
|context: TypedContext<RunIdArgs, RunLogsOptions, ()>| async move {
match DaemonClient
.call(
"execution.logs",
serde_json::json!({
"id": context.args.id,
"tail_bytes": context.options.tail_bytes
}),
)
.await
{
Ok(logs) => TypedResult::ok(logs),
Err(error) => TypedResult::error("EXECUTION_LOGS_FAILED", error),
}
},
)
.description("Read bounded stdout and stderr tails.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"attach",
CommandDef::typed::<RunIdArgs, RunLogsOptions, (), ExecutionAttachment, _, _>(
"attach",
|context: TypedContext<RunIdArgs, RunLogsOptions, ()>| async move {
match DaemonClient
.call(
"execution.attach",
serde_json::json!({
"id": context.args.id,
"tail_bytes": context.options.tail_bytes
}),
)
.await
{
Ok(attachment) => TypedResult::ok(attachment),
Err(error) => TypedResult::error("EXECUTION_ATTACH_FAILED", error),
}
},
)
.description(
"Attach to current execution state, bounded output, and live-I/O availability.",
)
.mcp(read_only())
.done(),
);
cli = cli.command(
"detach",
CommandDef::typed::<RunIdArgs, (), (), DetachOutput, _, _>(
"detach",
|context: TypedContext<RunIdArgs, (), ()>| async move {
TypedResult::ok(DetachOutput {
id: context.args.id,
detached: true,
})
},
)
.description("Detach this client without changing durable execution ownership.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"input",
CommandDef::typed::<RunInputArgs, (), (), InputReceipt, _, _>(
"input",
|context: TypedContext<RunInputArgs, (), ()>| async move {
match DaemonClient
.call(
"execution.input",
serde_json::json!({
"id": context.args.id,
"data": context.args.data
}),
)
.await
{
Ok(receipt) => TypedResult::ok(receipt),
Err(error) => TypedResult::error("EXECUTION_INPUT_FAILED", error),
}
},
)
.description("Write UTF-8 bytes to the active pipe or PTY.")
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"wait",
CommandDef::typed::<RunIdArgs, RunWaitOptions, (), Execution, _, _>(
"wait",
|context: TypedContext<RunIdArgs, RunWaitOptions, ()>| async move {
match DaemonClient
.call(
"execution.wait",
serde_json::json!({
"id": context.args.id,
"timeout_ms": context.options.timeout_ms
}),
)
.await
{
Ok(execution) => TypedResult::ok(execution),
Err(error) => TypedResult::error("EXECUTION_WAIT_FAILED", error),
}
},
)
.description("Wait for an execution to complete, fail, or cancel.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"signal",
CommandDef::typed::<RunSignalArgs, (), (), Execution, _, _>(
"signal",
|context: TypedContext<RunSignalArgs, (), ()>| async move {
match DaemonClient
.call(
"execution.signal",
serde_json::json!({
"id": context.args.id,
"signal": context.args.signal
}),
)
.await
{
Ok(execution) => TypedResult::ok(execution),
Err(error) => TypedResult::error("EXECUTION_SIGNAL_FAILED", error),
}
},
)
.description("Signal the active execution process group.")
.mcp(destructive(false))
.destructive(true)
.done(),
);
cli = cli.command(
"cancel",
CommandDef::typed::<RunIdArgs, RunStopOptions, (), Execution, _, _>(
"cancel",
|context: TypedContext<RunIdArgs, RunStopOptions, ()>| async move {
match DaemonClient
.call(
"execution.cancel",
serde_json::json!({
"id": context.args.id,
"timeout_ms": context.options.timeout_ms
}),
)
.await
{
Ok(execution) => TypedResult::ok(execution),
Err(error) => TypedResult::error("EXECUTION_CANCEL_FAILED", error),
}
},
)
.description("Cancel an execution and cascade cancellation to owned children.")
.command_aliases(vec!["stop".to_string()])
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli.command(
"remove",
CommandDef::typed::<RunIdArgs, (), (), RemoveOutput, _, _>(
"remove",
|context: TypedContext<RunIdArgs, (), ()>| async move {
match DaemonClient
.call::<RemoveOutput>(
"execution.remove",
serde_json::json!({ "id": context.args.id }),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("EXECUTION_REMOVE_FAILED", error),
}
},
)
.description("Remove one terminal execution's durable metadata.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn session_cli() -> Cli {
Cli::create("session")
.description("Own related executions and resources with a durable agent heartbeat.")
.command(
"open",
CommandDef::typed::<(), SessionOpenOptions, (), AgentSession, _, _>(
"open",
|context: TypedContext<(), SessionOpenOptions, ()>| async move {
let labels =
match parse_labels(context.options.label.as_deref().unwrap_or_default()) {
Ok(labels) => labels,
Err(error) => return TypedResult::error("INVALID_LABEL", error),
};
match DaemonClient
.call(
"session.open",
serde_json::json!({
"actor": context.options.actor,
"labels": labels,
"ttl_ms": context.options.ttl_ms
}),
)
.await
{
Ok(session) => TypedResult::ok(session),
Err(error) => TypedResult::error("SESSION_OPEN_FAILED", error),
}
},
)
.description("Open an agent session and its root resource lease.")
.mcp(destructive(false))
.done(),
)
.command(
"heartbeat",
CommandDef::typed::<RunIdArgs, SessionHeartbeatOptions, (), AgentSession, _, _>(
"heartbeat",
|context: TypedContext<RunIdArgs, SessionHeartbeatOptions, ()>| async move {
match DaemonClient
.call(
"session.heartbeat",
serde_json::json!({
"id": context.args.id,
"ttl_ms": context.options.ttl_ms
}),
)
.await
{
Ok(session) => TypedResult::ok(session),
Err(error) => TypedResult::error("SESSION_HEARTBEAT_FAILED", error),
}
},
)
.description("Renew one agent session and its root lease.")
.mcp(destructive(true))
.done(),
)
.command(
"get",
CommandDef::typed::<RunIdArgs, (), (), AgentSession, _, _>(
"get",
|context: TypedContext<RunIdArgs, (), ()>| async move {
match DaemonClient
.call("session.get", serde_json::json!({ "id": context.args.id }))
.await
{
Ok(session) => TypedResult::ok(session),
Err(error) => TypedResult::error("SESSION_GET_FAILED", error),
}
},
)
.description("Get one durable agent session.")
.mcp(read_only())
.done(),
)
.command(
"list",
CommandDef::typed::<(), ActiveOptions, (), Vec<AgentSession>, _, _>(
"list",
|context: TypedContext<(), ActiveOptions, ()>| async move {
match DaemonClient
.call(
"session.list",
serde_json::json!({ "active": context.options.active }),
)
.await
{
Ok(sessions) => TypedResult::ok(sessions),
Err(error) => TypedResult::error("SESSION_LIST_FAILED", error),
}
},
)
.description("List agent sessions by most recent heartbeat.")
.command_aliases(vec!["ls".to_string()])
.mcp(read_only())
.done(),
)
.command(
"close",
CommandDef::typed::<RunIdArgs, RunStopOptions, (), AgentSession, _, _>(
"close",
|context: TypedContext<RunIdArgs, RunStopOptions, ()>| async move {
match DaemonClient
.call(
"session.close",
serde_json::json!({
"id": context.args.id,
"timeout_ms": context.options.timeout_ms
}),
)
.await
{
Ok(session) => TypedResult::ok(session),
Err(error) => TypedResult::error("SESSION_CLOSE_FAILED", error),
}
},
)
.description("Close a session and cancel executions and reservations that it owns.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn lease_cli() -> Cli {
Cli::create("lease")
.description("Inspect, renew, release, and clean durable ownership leases.")
.command(
"get",
CommandDef::typed::<RunIdArgs, (), (), Lease, _, _>(
"get",
|context: TypedContext<RunIdArgs, (), ()>| async move {
match DaemonClient
.call("lease.get", serde_json::json!({ "id": context.args.id }))
.await
{
Ok(lease) => TypedResult::ok(lease),
Err(error) => TypedResult::error("LEASE_GET_FAILED", error),
}
},
)
.description("Get one ownership lease.")
.mcp(read_only())
.done(),
)
.command(
"list",
CommandDef::typed::<(), ActiveOptions, (), Vec<Lease>, _, _>(
"list",
|context: TypedContext<(), ActiveOptions, ()>| async move {
match DaemonClient
.call(
"lease.list",
serde_json::json!({ "active": context.options.active }),
)
.await
{
Ok(leases) => TypedResult::ok(leases),
Err(error) => TypedResult::error("LEASE_LIST_FAILED", error),
}
},
)
.description("List durable ownership leases.")
.command_aliases(vec!["ls".to_string()])
.mcp(read_only())
.done(),
)
.command(
"renew",
CommandDef::typed::<RunIdArgs, LeaseRenewOptions, (), Lease, _, _>(
"renew",
|context: TypedContext<RunIdArgs, LeaseRenewOptions, ()>| async move {
match DaemonClient
.call(
"lease.renew",
serde_json::json!({
"id": context.args.id,
"ttl_ms": context.options.ttl_ms
}),
)
.await
{
Ok(lease) => TypedResult::ok(lease),
Err(error) => TypedResult::error("LEASE_RENEW_FAILED", error),
}
},
)
.description("Renew one expiring lease.")
.mcp(destructive(true))
.done(),
)
.command(
"release",
CommandDef::typed::<RunIdArgs, RunStopOptions, (), ReleaseOutput, _, _>(
"release",
|context: TypedContext<RunIdArgs, RunStopOptions, ()>| async move {
match DaemonClient
.call(
"lease.release",
serde_json::json!({
"id": context.args.id,
"timeout_ms": context.options.timeout_ms
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("LEASE_RELEASE_FAILED", error),
}
},
)
.description("Release a lease and cancel any active execution that it directly owns.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"cleanup",
CommandDef::typed::<(), RunStopOptions, (), Vec<Lease>, _, _>(
"cleanup",
|context: TypedContext<(), RunStopOptions, ()>| async move {
match DaemonClient
.call(
"lease.cleanup",
serde_json::json!({ "timeout_ms": context.options.timeout_ms }),
)
.await
{
Ok(leases) => TypedResult::ok(leases),
Err(error) => TypedResult::error("LEASE_CLEANUP_FAILED", error),
}
},
)
.description("Release expired leases and clean their executions and reservations.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn reservation_cli() -> Cli {
Cli::create("reservation")
.description(
"Coordinate apoc-local ownership of ports, paths, processes, devices, and custom keys.",
)
.command(
"acquire",
CommandDef::typed::<ReservationAcquireArgs, ReservationOptions, (), Reservation, _, _>(
"acquire",
|context: TypedContext<ReservationAcquireArgs, ReservationOptions, ()>| async move {
match DaemonClient
.call(
"reservation.acquire",
serde_json::json!({
"kind": context.args.kind,
"key": context.args.key,
"lease_id": context.args.lease,
"ttl_ms": context.options.ttl_ms
}),
)
.await
{
Ok(reservation) => TypedResult::ok(reservation),
Err(error) => TypedResult::error("RESERVATION_ACQUIRE_FAILED", error),
}
},
)
.description("Atomically acquire one apoc-local coordination key.")
.mcp(destructive(false))
.done(),
)
.command(
"get",
CommandDef::typed::<RunIdArgs, (), (), Reservation, _, _>(
"get",
|context: TypedContext<RunIdArgs, (), ()>| async move {
match DaemonClient
.call(
"reservation.get",
serde_json::json!({ "id": context.args.id }),
)
.await
{
Ok(reservation) => TypedResult::ok(reservation),
Err(error) => TypedResult::error("RESERVATION_GET_FAILED", error),
}
},
)
.description("Get one resource reservation.")
.mcp(read_only())
.done(),
)
.command(
"list",
CommandDef::typed::<(), ActiveOptions, (), Vec<Reservation>, _, _>(
"list",
|context: TypedContext<(), ActiveOptions, ()>| async move {
match DaemonClient
.call(
"reservation.list",
serde_json::json!({ "active": context.options.active }),
)
.await
{
Ok(reservations) => TypedResult::ok(reservations),
Err(error) => TypedResult::error("RESERVATION_LIST_FAILED", error),
}
},
)
.description("List resource reservations.")
.command_aliases(vec!["ls".to_string()])
.mcp(read_only())
.done(),
)
.command(
"wait",
CommandDef::typed::<ReservationAcquireArgs, ReservationOptions, (), Reservation, _, _>(
"wait",
|context: TypedContext<ReservationAcquireArgs, ReservationOptions, ()>| async move {
match DaemonClient
.call(
"reservation.wait",
serde_json::json!({
"kind": context.args.kind,
"key": context.args.key,
"lease_id": context.args.lease,
"ttl_ms": context.options.ttl_ms
}),
)
.await
{
Ok(reservation) => TypedResult::ok(reservation),
Err(error) => TypedResult::error("RESERVATION_WAIT_FAILED", error),
}
},
)
.description("Wait up to 30 seconds to acquire one coordination key.")
.mcp(destructive(false))
.done(),
)
.command(
"release",
CommandDef::typed::<RunIdArgs, (), (), ReleaseOutput, _, _>(
"release",
|context: TypedContext<RunIdArgs, (), ()>| async move {
match DaemonClient
.call(
"reservation.release",
serde_json::json!({ "id": context.args.id }),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RESERVATION_RELEASE_FAILED", error),
}
},
)
.description("Release one resource reservation.")
.mcp(destructive(true))
.done(),
)
}
fn event_cli() -> Cli {
Cli::create("event")
.description("Query the compact causal journal and retained payloads.")
.command(
"query",
CommandDef::typed::<(), EventQueryOptions, (), Vec<CausalEvent>, _, _>(
"query",
|context: TypedContext<(), EventQueryOptions, ()>| async move {
match DaemonClient
.call(
"event.query",
serde_json::json!({
"after": context.options.after,
"limit": context.options.limit
}),
)
.await
{
Ok(events) => TypedResult::ok(events),
Err(error) => TypedResult::error("EVENT_QUERY_FAILED", error),
}
},
)
.description("Query causal events after an exclusive durable cursor.")
.mcp(read_only())
.done(),
)
.command(
"watch",
CommandDef::typed::<(), EventWatchOptions, (), Vec<CausalEvent>, _, _>(
"watch",
|context: TypedContext<(), EventWatchOptions, ()>| async move {
match DaemonClient
.call(
"event.watch",
serde_json::json!({
"after": context.options.after,
"limit": context.options.limit,
"timeout_ms": context.options.timeout_ms
}),
)
.await
{
Ok(events) => TypedResult::ok(events),
Err(error) => TypedResult::error("EVENT_WATCH_FAILED", error),
}
},
)
.description("Wait for causal events after an exclusive durable cursor.")
.mcp(read_only())
.done(),
)
.command(
"export",
CommandDef::typed::<(), EventQueryOptions, (), Vec<CausalEvent>, _, _>(
"export",
|context: TypedContext<(), EventQueryOptions, ()>| async move {
match DaemonClient
.call(
"event.query",
serde_json::json!({
"after": context.options.after,
"limit": context.options.limit
}),
)
.await
{
Ok(events) => TypedResult::ok(events),
Err(error) => TypedResult::error("EVENT_EXPORT_FAILED", error),
}
},
)
.description("Export causal events through the selected CLI output format.")
.mcp(read_only())
.done(),
)
.command(
"payload",
CommandDef::typed::<PayloadArgs, (), (), PayloadOutput, _, _>(
"payload",
|context: TypedContext<PayloadArgs, (), ()>| async move {
match DaemonClient
.call(
"event.payload",
serde_json::json!({ "id": context.args.id }),
)
.await
{
Ok(payload) => TypedResult::ok(payload),
Err(error) => TypedResult::error("EVENT_PAYLOAD_FAILED", error),
}
},
)
.description("Load one retained content-addressed payload.")
.mcp(read_only())
.done(),
)
.command(
"pin",
CommandDef::typed::<PayloadArgs, PayloadPinOptions, (), PayloadPinOutput, _, _>(
"pin",
|context: TypedContext<PayloadArgs, PayloadPinOptions, ()>| async move {
match DaemonClient
.call(
"event.pin",
serde_json::json!({
"id": context.args.id,
"pinned": !context.options.unpin
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("EVENT_PIN_FAILED", error),
}
},
)
.description("Pin or unpin a retained payload body.")
.mcp(destructive(true))
.done(),
)
.command(
"prune-payloads",
CommandDef::typed::<(), PayloadPruneOptions, (), PayloadPruneOutput, _, _>(
"prune-payloads",
|context: TypedContext<(), PayloadPruneOptions, ()>| async move {
match DaemonClient
.call(
"event.prune-payloads",
serde_json::json!({ "max_age_ms": context.options.max_age_ms }),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("EVENT_PRUNE_FAILED", error),
}
},
)
.description("Prune expired unpinned payload bodies while preserving causal metadata.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn process_cli(
manager: Arc<Mutex<ProcessManager>>,
store: Option<Arc<crate::store::Store>>,
) -> Cli {
let mut cli = Cli::create("process").description("Discover and control host processes.");
let backend = Arc::clone(&manager);
cli = cli.command(
"list",
CommandDef::typed::<(), ListOptions, (), Vec<ProcessInfo>, _, _>(
"list",
move |context: TypedContext<(), ListOptions, ()>| {
let backend = Arc::clone(&backend);
async move {
let selector = context.options.selector.as_deref();
let mut backend = backend.lock().await;
match backend.list(selector, &context.options.sort, context.options.limit) {
Ok(processes) => match backend.record(
&processes,
"process.list",
"observed",
selector,
context.agent,
"observed",
None,
&serde_json::json!({
"sort": context.options.sort,
"limit": context.options.limit
}),
) {
Ok(_) => TypedResult::ok(processes),
Err(error) => {
TypedResult::error("PROCESS_CONTEXT_RECORD_FAILED", error)
}
},
Err(error) => TypedResult::error("PROCESS_LIST_FAILED", error),
}
}
},
)
.description("List processes using one native process-table snapshot.")
.command_aliases(vec!["ls".to_string(), "ps".to_string()])
.mcp(read_only())
.done(),
);
let backend = Arc::clone(&manager);
cli = cli.command(
"query",
CommandDef::typed::<QueryArgs, (), (), Vec<ProcessInfo>, _, _>(
"query",
move |context: TypedContext<QueryArgs, (), ()>| {
let backend = Arc::clone(&backend);
async move {
let query = match serde_json::from_str::<ProcessQuery>(&context.args.query) {
Ok(query) => query,
Err(error) => {
return TypedResult::error("INVALID_PROCESS_QUERY", error.to_string());
}
};
match backend.lock().await.query(&query, context.agent) {
Ok(processes) => TypedResult::ok(processes),
Err(error) => TypedResult::error("PROCESS_QUERY_FAILED", error),
}
}
},
)
.description("Execute a structured boolean ProcessQuery JSON document.")
.mcp(read_only())
.done(),
);
let backend = Arc::clone(&manager);
cli = cli.command(
"probe",
CommandDef::typed::<TargetArgs, (), (), ProcessProbe, _, _>(
"probe",
move |context: TypedContext<TargetArgs, (), ()>| {
let backend = Arc::clone(&backend);
async move {
match backend
.lock()
.await
.probe(&context.args.target, context.agent)
{
Ok(probe) => TypedResult::ok(probe),
Err(error) => TypedResult::error("PROCESS_PROBE_FAILED", error),
}
}
},
)
.description("Probe whether a selector or exact process identity still exists.")
.mcp(read_only())
.done(),
);
let backend = Arc::clone(&manager);
cli = cli.command(
"files",
CommandDef::typed::<TargetArgs, (), (), Vec<ProcessFile>, _, _>(
"files",
move |context: TypedContext<TargetArgs, (), ()>| {
let backend = Arc::clone(&backend);
async move {
match backend
.lock()
.await
.files(&context.args.target, context.agent)
{
Ok(files) => TypedResult::ok(files),
Err(error) => TypedResult::error("PROCESS_FILES_FAILED", error),
}
}
},
)
.description("List vnode-backed open files without invoking lsof.")
.mcp(read_only())
.done(),
);
for (name, description) in [
(
"why",
"Explain the recorded cause and launch lineage for a process target.",
),
(
"impact",
"Return known descendants, executions, leases, and reservations affected by a process target.",
),
(
"owner",
"Return the recorded execution, session, lease, and actor ownership for a process target.",
),
(
"related",
"Return recorded process-tree, execution, workspace, lease, and resource relationships.",
),
(
"changed",
"Return recorded causal changes for a process target.",
),
] {
let backend = Arc::clone(&manager);
cli = cli.command(
name,
CommandDef::typed::<TargetArgs, ProcessContextOptions, (), ProcessInsight, _, _>(
name,
move |context: TypedContext<TargetArgs, ProcessContextOptions, ()>| {
let backend = Arc::clone(&backend);
async move {
match backend.lock().await.insight(
name,
&context.args.target,
context.options.events,
context.agent,
) {
Ok(insight) => TypedResult::ok(insight),
Err(error) => TypedResult::error("PROCESS_INSIGHT_FAILED", error),
}
}
},
)
.description(description)
.mcp(read_only())
.done(),
);
}
let backend = Arc::clone(&manager);
cli = cli.command(
"select",
CommandDef::typed::<TargetArgs, (), (), ProcessSelection, _, _>(
"select",
move |context: TypedContext<TargetArgs, (), ()>| {
let backend = Arc::clone(&backend);
async move {
let mut backend = backend.lock().await;
match backend.select(&context.args.target) {
Ok(selection) => {
let snapshots = backend.snapshots(&selection.processes);
match backend.record(
&snapshots,
"process.select",
"observed",
Some(&context.args.target),
context.agent,
"observed",
None,
&serde_json::json!({ "selection_id": selection.id }),
) {
Ok(_) => TypedResult::ok(selection),
Err(error) => {
TypedResult::error("PROCESS_CONTEXT_RECORD_FAILED", error)
}
}
}
Err(error) => TypedResult::error("PROCESS_SELECT_FAILED", error),
}
}
},
)
.description("Resolve a selector to immutable PID and start-time identities.")
.mcp(read_only())
.done(),
);
let backend = Arc::clone(&manager);
cli = cli.command(
"get",
CommandDef::typed::<TargetArgs, (), (), ProcessInfo, _, _>(
"get",
move |context: TypedContext<TargetArgs, (), ()>| {
let backend = Arc::clone(&backend);
async move {
let mut backend = backend.lock().await;
match backend.get(&context.args.target) {
Ok(process) => match backend.record(
std::slice::from_ref(&process),
"process.get",
"observed",
Some(&context.args.target),
context.agent,
"observed",
None,
&serde_json::json!({}),
) {
Ok(_) => TypedResult::ok(process),
Err(error) => {
TypedResult::error("PROCESS_CONTEXT_RECORD_FAILED", error)
}
},
Err(error) => TypedResult::error("PROCESS_GET_FAILED", error),
}
}
},
)
.description("Inspect exactly one process.")
.command_aliases(vec!["show".to_string(), "inspect".to_string()])
.mcp(read_only())
.done(),
);
let backend = Arc::clone(&manager);
cli = cli.command(
"tree",
CommandDef::typed::<TargetArgs, (), (), Vec<ProcessInfo>, _, _>(
"tree",
move |context: TypedContext<TargetArgs, (), ()>| {
let backend = Arc::clone(&backend);
async move {
let mut backend = backend.lock().await;
match backend.tree(&context.args.target) {
Ok(processes) => match backend.record(
&processes,
"process.tree",
"observed",
Some(&context.args.target),
context.agent,
"observed",
None,
&serde_json::json!({}),
) {
Ok(_) => TypedResult::ok(processes),
Err(error) => {
TypedResult::error("PROCESS_CONTEXT_RECORD_FAILED", error)
}
},
Err(error) => TypedResult::error("PROCESS_TREE_FAILED", error),
}
}
},
)
.description("Return selected processes and every descendant in parent-first order.")
.mcp(read_only())
.done(),
);
let backend = Arc::clone(&manager);
cli = cli.command(
"ports",
CommandDef::typed::<PortArgs, PortOptions, (), Vec<PortInfo>, _, _>(
"ports",
move |context: TypedContext<PortArgs, PortOptions, ()>| {
let backend = Arc::clone(&backend);
async move {
match port_owners(context.args.port, context.options.protocol.as_deref()) {
Ok(ports) => {
let pids = ports
.iter()
.flat_map(|port| port.pids.iter().copied())
.collect::<Vec<_>>();
let mut backend = backend.lock().await;
let snapshots = backend.snapshots_for_pids(&pids);
match backend.record(
&snapshots,
"process.ports",
"observed",
Some(&format!("port:{}", context.args.port)),
context.agent,
"observed",
None,
&serde_json::to_value(&ports)
.unwrap_or_else(|_| serde_json::json!({})),
) {
Ok(_) => TypedResult::ok(ports),
Err(error) => {
TypedResult::error("PROCESS_CONTEXT_RECORD_FAILED", error)
}
}
}
Err(error) => TypedResult::error("PORT_LOOKUP_FAILED", error),
}
}
},
)
.description("Return native socket ownership for one local port.")
.mcp(read_only())
.done(),
);
let backend = Arc::clone(&manager);
cli = cli.command(
"sockets",
CommandDef::typed::<(), SocketOptions, (), Vec<PortInfo>, _, _>(
"sockets",
move |context: TypedContext<(), SocketOptions, ()>| {
let backend = Arc::clone(&backend);
async move {
match sockets(
context.options.protocol.as_deref(),
context.options.listening,
context.options.limit,
) {
Ok(sockets) => {
let pids = sockets
.iter()
.flat_map(|socket| socket.pids.iter().copied())
.collect::<Vec<_>>();
let mut backend = backend.lock().await;
let snapshots = backend.snapshots_for_pids(&pids);
match backend.record(
&snapshots,
"process.sockets",
"observed",
None,
context.agent,
"observed",
None,
&serde_json::json!({
"protocol": context.options.protocol,
"listening": context.options.listening,
"limit": context.options.limit
}),
) {
Ok(_) => TypedResult::ok(sockets),
Err(error) => {
TypedResult::error("PROCESS_CONTEXT_RECORD_FAILED", error)
}
}
}
Err(error) => TypedResult::error("SOCKET_LIST_FAILED", error),
}
}
},
)
.description("List native socket ownership without invoking lsof or netstat.")
.mcp(read_only())
.done(),
);
let backend = Arc::clone(&manager);
cli = cli.command(
"sample",
CommandDef::typed::<(), SampleOptions, (), Vec<ProcessSample>, _, _>(
"sample",
move |context: TypedContext<(), SampleOptions, ()>| {
let backend = Arc::clone(&backend);
async move {
if context.options.count > 1000 {
return TypedResult::error(
"SAMPLE_LIMIT",
"Sample count cannot exceed 1000".to_string(),
);
}
let mut samples = Vec::with_capacity(context.options.count);
for index in 0..context.options.count {
let delay = if index == 0 {
sysinfo::MINIMUM_CPU_UPDATE_INTERVAL
} else {
Duration::from_millis(context.options.interval_ms)
};
tokio::time::sleep(delay).await;
let processes = match backend.lock().await.list(
context.options.selector.as_deref(),
&context.options.sort,
context.options.limit,
) {
Ok(processes) => processes,
Err(error) => {
return TypedResult::error("PROCESS_SAMPLE_FAILED", error);
}
};
if let Err(error) = backend.lock().await.record(
&processes,
"process.sample",
"observed",
context.options.selector.as_deref(),
context.agent,
"observed",
None,
&serde_json::json!({
"sample": index,
"interval_ms": context.options.interval_ms
}),
) {
return TypedResult::error("PROCESS_CONTEXT_RECORD_FAILED", error);
}
samples.push(ProcessSample {
at: now_ms(),
processes,
});
}
TypedResult::ok(samples)
}
},
)
.description("Collect bounded timestamped process snapshots.")
.command_aliases(vec!["watch".to_string(), "top".to_string()])
.mcp(read_only())
.done(),
);
cli = cli.command(
"wait",
CommandDef::typed::<TargetArgs, ProcessWaitOptions, (), ProcessWait, _, _>(
"wait",
|context: TypedContext<TargetArgs, ProcessWaitOptions, ()>| async move {
match wait_for(
&context.args.target,
&context.options.condition,
Duration::from_millis(context.options.interval_ms),
Duration::from_millis(context.options.timeout_ms),
context.agent,
)
.await
{
Ok(wait) => TypedResult::ok(wait),
Err(error) => TypedResult::error("PROCESS_WAIT_FAILED", error),
}
},
)
.description("Wait for a selector to exist or for its initial identities to exit.")
.mcp(read_only())
.done(),
);
let backend = Arc::clone(&manager);
cli = cli.command(
"context",
CommandDef::typed::<TargetArgs, ProcessContextOptions, (), Vec<ProcessDossier>, _, _>(
"context",
move |context: TypedContext<TargetArgs, ProcessContextOptions, ()>| {
let backend = Arc::clone(&backend);
async move {
match backend.lock().await.dossiers(
&context.args.target,
context.options.events,
context.agent,
) {
Ok(dossiers) => TypedResult::ok(dossiers),
Err(error) => TypedResult::error("PROCESS_CONTEXT_FAILED", error),
}
}
},
)
.description("Return durable context and event history for current or exited processes.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"history",
CommandDef::typed::<(), ProcessHistoryOptions, (), Vec<ProcessEvent>, _, _>(
"history",
|context: TypedContext<(), ProcessHistoryOptions, ()>| async move {
let query = ProcessEventQuery {
limit: context.options.limit,
process_key: context.options.process_key,
pid: context.options.pid,
operation: context.options.operation,
phase: context.options.phase,
actor: context.options.actor,
controller_execution_id: context.options.controller_execution_id,
execution_id: context.options.execution_id,
since_ms: context.options.since_ms,
until_ms: context.options.until_ms,
};
match crate::store::Store::open_default()
.and_then(|store| store.query_process_events(&query))
{
Ok(events) => TypedResult::ok(events),
Err(error) => TypedResult::error("PROCESS_HISTORY_FAILED", error),
}
},
)
.description("List the durable cross-process interaction ledger.")
.mcp(read_only())
.done(),
);
let mutation_store = store.clone();
cli = cli.command(
"signal",
CommandDef::typed::<SignalArgs, MutationOptions, (), ActionReceipt, _, _>(
"signal",
move |context: TypedContext<SignalArgs, MutationOptions, ()>| {
let mutation_store = mutation_store.clone();
async move {
let signal = match parse_signal(&context.args.signal) {
Ok(signal) => signal,
Err(error) => return TypedResult::error("INVALID_SIGNAL", error),
};
let mut backend = process_manager(mutation_store);
match backend
.signal(
&context.args.target,
signal,
context.agent,
context.options.idempotency_key.as_deref(),
context.options.allow_empty,
)
.await
{
Ok(receipt) => TypedResult::ok(receipt),
Err(error) => TypedResult::error("SIGNAL_FAILED", error),
}
}
},
)
.description("Send an arbitrary supported signal to every selected process.")
.mcp(destructive(false))
.destructive(true)
.done(),
);
let mutation_store = store.clone();
cli = cli.command(
"stop",
CommandDef::typed::<TargetArgs, StopOptions, (), ActionReceipt, _, _>(
"stop",
move |context: TypedContext<TargetArgs, StopOptions, ()>| {
let mutation_store = mutation_store.clone();
async move {
let mut backend = process_manager(mutation_store);
match backend
.stop(
&context.args.target,
Duration::from_millis(context.options.timeout_ms),
context.options.force,
context.agent,
context.options.idempotency_key.as_deref(),
context.options.allow_empty,
)
.await
{
Ok(receipt) => TypedResult::ok(receipt),
Err(error) => TypedResult::error("STOP_FAILED", error),
}
}
},
)
.description("Send SIGTERM, wait, and optionally escalate to SIGKILL.")
.mcp(destructive(false))
.destructive(true)
.done(),
);
for (name, description, signal) in [
("kill", "Send SIGKILL to every selected process.", "KILL"),
("pause", "Send SIGSTOP to every selected process.", "STOP"),
("resume", "Send SIGCONT to every selected process.", "CONT"),
] {
let mutation_store = store.clone();
cli = cli.command(
name,
CommandDef::typed::<TargetArgs, MutationOptions, (), ActionReceipt, _, _>(
name,
move |context: TypedContext<TargetArgs, MutationOptions, ()>| {
let mutation_store = mutation_store.clone();
async move {
let signal = parse_signal(signal).expect("static signal");
let mut backend = process_manager(mutation_store);
match backend
.signal(
&context.args.target,
signal,
context.agent,
context.options.idempotency_key.as_deref(),
context.options.allow_empty,
)
.await
{
Ok(receipt) => TypedResult::ok(receipt),
Err(error) => TypedResult::error("PROCESS_CONTROL_FAILED", error),
}
}
},
)
.description(description)
.mcp(destructive(name == "resume"))
.destructive(name != "resume")
.done(),
);
}
cli
}
fn process_manager(store: Option<Arc<crate::store::Store>>) -> ProcessManager {
store.map(ProcessManager::with_store).unwrap_or_default()
}
fn read_only() -> McpCommandOptions {
McpCommandOptions {
annotations: Some(McpAnnotations {
read_only_hint: Some(true),
idempotent_hint: Some(true),
..McpAnnotations::default()
}),
..McpCommandOptions::default()
}
}
fn destructive(idempotent: bool) -> McpCommandOptions {
McpCommandOptions {
destructive: true,
annotations: Some(McpAnnotations {
read_only_hint: Some(false),
destructive_hint: Some(true),
idempotent_hint: Some(idempotent),
open_world_hint: Some(false),
..McpAnnotations::default()
}),
..McpCommandOptions::default()
}
}