use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
use incurs::cli::Cli;
use incurs::command::{McpAnnotations, McpCommandOptions, TypedContext, TypedResult};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tokio::sync::Mutex;
use crate::benchmark::{ProcessBenchmark, process_benchmark};
use crate::daemon::{Daemon, DaemonClient, DaemonStatus};
use crate::history::{
active_invocation_id, active_store, invocation_middleware, invocation_purpose,
invocation_scope, tracked_typed,
};
use crate::model::{
ActionReceipt, AgentSession, CausalEvent, ConnectorConfig, ConnectorKind, EnvironmentView,
Execution, ExecutionBudget, ExecutionListPage, ExecutionProgram, ExecutionSpec,
ExecutionStatus, HistoryPatternOutput, HistoryQueryOutput, InvocationPage,
InvocationPatternQuery, InvocationQuery, InvocationRecord, InvocationScopeKind,
InvocationSource, InvocationStatus, InvocationSurface, InvocationTimelinePage, IoMode, Lease,
LeaseOwnerKind, OperationReceipt, PollCondition, PollIteration, PollIterationPage,
PollSchedule, PollTarget, PortInfo, ProcessDossier, ProcessEvent, ProcessEventQuery,
ProcessFile, ProcessInfo, ProcessInsight, ProcessProbe, ProcessQuery, ProcessSample,
ProcessSelection, ProcessWait, Recipe, RecipeSuggestion, 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(Serialize, Deserialize, incurs::Options)]
struct ListOptions {
selector: Option<String>,
#[incurs(default = "cpu")]
sort: String,
#[incurs(alias = "n", default = 50)]
limit: usize,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct TargetArgs {
target: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct QueryArgs {
query: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct SignalArgs {
target: String,
signal: String,
}
#[derive(Serialize, 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(Serialize, Deserialize, incurs::Options)]
struct MutationOptions {
idempotency_key: Option<String>,
#[serde(default)]
allow_empty: bool,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct PortArgs {
port: u16,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct PortOptions {
protocol: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct SocketOptions {
protocol: Option<String>,
#[serde(default)]
listening: bool,
#[incurs(default = 1000)]
limit: usize,
}
#[derive(Serialize, 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(Serialize, Deserialize, incurs::Options)]
struct ProcessWaitOptions {
#[incurs(default = "exit")]
condition: String,
#[incurs(default = 50)]
interval_ms: u64,
#[incurs(default = 30000)]
timeout_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ProcessContextOptions {
#[incurs(default = 50)]
events: usize,
}
#[derive(Serialize, 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(Serialize, 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(Serialize, Deserialize, incurs::Args)]
struct RunArgv {
executable: String,
arg: Option<Vec<String>>,
}
#[derive(Serialize, 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>>,
#[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>,
}
macro_rules! poll_options {
($name:ident { $($extra:tt)* }) => {
#[derive(Serialize, Deserialize, incurs::Options)]
struct $name {
$($extra)*
/// Interval policy: fixed-delay, backoff, or fixed-rate.
#[incurs(default = "fixed-delay")]
interval_mode: String,
interval_ms: Option<u64>,
initial_interval_ms: Option<u64>,
multiplier: Option<f64>,
max_interval_ms: Option<u64>,
until_exit_code: Option<Vec<i32>>,
until_stdout_regex: Option<String>,
until_stderr_regex: Option<String>,
until_json_pointer: Option<String>,
until_json_equals: Option<String>,
until_js: Option<String>,
max_iterations: Option<u64>,
duration_ms: Option<u64>,
iteration_timeout_ms: Option<u64>,
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>>,
#[incurs(default = "persistent")]
owner: String,
session: Option<String>,
parent: Option<String>,
artifact_bytes: Option<u64>,
}
};
}
poll_options!(PollCommandOptions {
#[serde(default)]
shell: bool,
});
poll_options!(PollApocOptions {
#[incurs(default = "{}")]
arguments: String,
});
#[derive(Serialize, Deserialize, incurs::Args)]
struct PollMethodArgs {
method: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct PollIterationArgs {
id: String,
iteration: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct PollIterationListOptions {
#[incurs(default = 20)]
limit: usize,
cursor: Option<String>,
}
#[derive(Serialize, 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(Serialize, 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(Serialize, Deserialize, incurs::Args)]
struct RunIdArgs {
id: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RunSignalArgs {
id: String,
signal: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RunInputArgs {
id: String,
data: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RunStopOptions {
#[incurs(default = 5000)]
timeout_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RunLogsOptions {
#[incurs(default = 65536)]
tail_bytes: usize,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ExecutionListOptions {
#[incurs(default = 20)]
limit: usize,
cursor: Option<String>,
status: Option<ExecutionStatus>,
}
#[derive(Serialize, 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(Serialize, Deserialize, incurs::Options)]
struct SessionOpenOptions {
actor: Option<String>,
label: Option<Vec<String>>,
#[incurs(default = 60000)]
ttl_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct SessionHeartbeatOptions {
#[incurs(default = 60000)]
ttl_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ActiveOptions {
#[serde(default)]
active: bool,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct LeaseRenewOptions {
#[incurs(default = 60000)]
ttl_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct ReservationAcquireArgs {
kind: String,
key: String,
lease: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ReservationOptions {
ttl_ms: Option<u64>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct EventQueryOptions {
#[incurs(default = 0)]
after: u64,
#[incurs(default = 100)]
limit: usize,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct HistoryOptions {
#[serde(default)]
global: bool,
cwd: Option<String>,
#[incurs(default = 50)]
limit: usize,
cursor: Option<String>,
source: Option<String>,
surface: Option<String>,
command: Option<String>,
status: Option<String>,
actor: Option<String>,
execution: Option<String>,
since_ms: Option<u64>,
until_ms: Option<u64>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct HistoryTimelineOptions {
#[serde(default)]
global: bool,
cwd: Option<String>,
#[incurs(default = 100)]
limit: usize,
cursor: Option<String>,
source: Option<String>,
surface: Option<String>,
command: Option<String>,
status: Option<String>,
actor: Option<String>,
execution: Option<String>,
since_ms: Option<u64>,
until_ms: Option<u64>,
}
impl From<HistoryTimelineOptions> for HistoryOptions {
fn from(options: HistoryTimelineOptions) -> Self {
Self {
global: options.global,
cwd: options.cwd,
limit: options.limit,
cursor: options.cursor,
source: options.source,
surface: options.surface,
command: options.command,
status: options.status,
actor: options.actor,
execution: options.execution,
since_ms: options.since_ms,
until_ms: options.until_ms,
}
}
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct HistoryPatternOptions {
#[serde(default)]
global: bool,
cwd: Option<String>,
#[incurs(default = 3)]
min_count: usize,
#[incurs(default = 50)]
limit: usize,
source: Option<String>,
command: Option<String>,
since_ms: Option<u64>,
until_ms: Option<u64>,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct HistorySearchArgs {
query: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct HistoryGetArgs {
id: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct HistoryQueryArgs {
sql: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct HistoryQueryOptions {
#[serde(default)]
global: bool,
cwd: Option<String>,
#[incurs(default = 20)]
limit: usize,
}
#[derive(Serialize, Deserialize, JsonSchema)]
struct HistoryImportOutput {
source_rows: usize,
imported: usize,
skipped: usize,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct EventWatchOptions {
#[incurs(default = 0)]
after: u64,
#[incurs(default = 100)]
limit: usize,
#[incurs(default = 30000)]
timeout_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct PayloadArgs {
id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct PayloadPinOptions {
#[serde(default)]
unpin: bool,
}
#[derive(Serialize, 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(Serialize, Deserialize, incurs::Options)]
struct SkillInstallOptions {
prefix: Option<String>,
#[serde(default)]
force: bool,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct SkillStatusOptions {
prefix: Option<String>,
}
pub fn build_cli() -> Cli {
build_agent_cli()
.group(daemon_cli())
.group(code_cli())
.group(env_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"))
.use_middleware(invocation_middleware(store))
.group(process)
.group(benchmark_cli(manager))
.group(execution_cli())
.group(poll_cli())
.group(session_cli())
.group(lease_cli())
.group(reservation_cli())
.group(history_cli())
.group(event_cli())
.command(
"version",
tracked_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",
tracked_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",
tracked_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",
tracked_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(Serialize, Deserialize, incurs::Args)]
struct CodeArgs {
code: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct CodeIdArgs {
id: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct ArtifactArgs {
execution: String,
artifact: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct CodeRunOptions {
#[incurs(default = 300000)]
timeout_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct SearchArgs {
query: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ReceiptListOptions {
#[incurs(default = 100)]
limit: usize,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct ProviderActionArgs {
provider: String,
method: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ProviderActionOptions {
input: Option<String>,
#[incurs(default = 300000)]
timeout_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct EnvironmentSetArgs {
assignment: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct EnvironmentSecretArgs {
name: String,
reference: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct EnvironmentNameArgs {
name: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct EnvironmentMutationOptions {
#[serde(default)]
global: bool,
cwd: Option<String>,
idempotency_key: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct EnvironmentLookupOptions {
#[serde(default)]
global: bool,
cwd: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecipePutArgs {
name: String,
code: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecipePutOptions {
description: Option<String>,
input_schema: Option<String>,
output_schema: Option<String>,
#[serde(default)]
dependency: Vec<String>,
#[serde(default)]
require_env: Vec<String>,
#[serde(default)]
read_only: bool,
#[serde(default)]
destructive: bool,
#[serde(default)]
idempotent: bool,
#[serde(default)]
open_world: bool,
ttl_ms: Option<u64>,
#[serde(default)]
global: bool,
cwd: Option<String>,
idempotency_key: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecipeSuggestOptions {
description: Option<String>,
input_schema: Option<String>,
output_schema: Option<String>,
#[serde(default)]
dependency: Vec<String>,
#[serde(default)]
require_env: Vec<String>,
#[serde(default)]
read_only: bool,
#[serde(default)]
destructive: bool,
#[serde(default)]
idempotent: bool,
#[serde(default)]
open_world: bool,
#[serde(default)]
positive: Vec<String>,
#[serde(default)]
counterexample: Vec<String>,
rationale: String,
#[serde(default)]
global: bool,
cwd: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecipeSuggestionArgs {
id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecipeAdoptOptions {
ttl_ms: Option<u64>,
#[serde(default)]
replace: bool,
idempotency_key: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct NameArgs {
name: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecipeRunOptions {
#[incurs(default = 300000)]
timeout_ms: u64,
input: Option<String>,
#[serde(default)]
global: bool,
cwd: Option<String>,
idempotency_key: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecipeLookupOptions {
#[serde(default)]
global: bool,
cwd: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecipeListOptions {
prefix: Option<String>,
#[serde(default)]
include_expired: bool,
#[serde(default)]
global: bool,
cwd: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecipeMutationOptions {
#[serde(default)]
global: bool,
cwd: Option<String>,
idempotency_key: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecipeExportArgs {
prefix: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecipeExportOptions {
file: String,
#[serde(default)]
global: bool,
cwd: Option<String>,
#[serde(default)]
replace: bool,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecipeImportArgs {
file: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecipeImportOptions {
#[serde(default)]
global: bool,
cwd: Option<String>,
ttl_ms: Option<u64>,
#[serde(default)]
replace: bool,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct HttpProviderArgs {
name: String,
url: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct StdioProviderArgs {
name: String,
command: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct HttpProviderOptions {
header: Option<Vec<String>>,
instructions: Option<String>,
base_url: Option<String>,
secret_header: Option<Vec<String>>,
}
#[derive(Serialize, 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",
tracked_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,
"purpose": invocation_purpose(&context.globals),
}),
)
.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",
tracked_typed::<CodeArgs, (), (), serde_json::Value, _, _>(
"start",
|context: TypedContext<CodeArgs, (), ()>| async move {
match DaemonClient
.call(
"code.start",
serde_json::json!({
"code": context.args.code,
"purpose": invocation_purpose(&context.globals),
}),
)
.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",
tracked_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",
tracked_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",
tracked_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",
tracked_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 history_query_scope(
global: bool,
cwd: Option<String>,
agent: bool,
) -> Result<(Option<InvocationScopeKind>, Option<String>), String> {
if global && cwd.is_some() {
return Err("--global and --cwd cannot be used together".to_string());
}
let controller = controller(agent);
let cwd = match cwd {
Some(cwd) if std::path::Path::new(&cwd).is_absolute() => Some(cwd),
Some(cwd) => controller.cwd.as_deref().map(|base| {
std::path::Path::new(base)
.join(cwd)
.to_string_lossy()
.into_owned()
}),
None => controller.cwd,
};
let scope = (!global).then(|| invocation_scope(cwd.as_deref()));
Ok((
scope.as_ref().map(|scope| scope.kind),
scope.and_then(|scope| scope.key),
))
}
fn receipt_cli() -> Cli {
Cli::create("receipt")
.description("Inspect durable intent and outcome records for provider actions.")
.command(
"list",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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 env_cli() -> Cli {
Cli::create("env")
.description("Manage durable scoped environment values and secret references.")
.command(
"set",
tracked_typed::<EnvironmentSetArgs, EnvironmentMutationOptions, (), EnvironmentView, _, _>(
"set",
|context: TypedContext<EnvironmentSetArgs, EnvironmentMutationOptions, ()>| async move {
let Some((name, value)) = context.args.assignment.split_once('=') else {
return TypedResult::error("INVALID_ENV", "Expected NAME=VALUE");
};
match DaemonClient.call("env.set", serde_json::json!({
"name": name,
"value": value,
"secret": null,
"global": context.options.global,
"cwd": context.options.cwd,
"idempotency_key": context.options.idempotency_key,
})).await {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("ENV_SET_FAILED", error),
}
},
)
.description("Set one literal value in the implicit durable environment.")
.mcp(destructive(true))
.done(),
)
.command(
"secret",
tracked_typed::<EnvironmentSecretArgs, EnvironmentMutationOptions, (), EnvironmentView, _, _>(
"secret",
|context: TypedContext<EnvironmentSecretArgs, EnvironmentMutationOptions, ()>| async move {
let Some((provider, reference)) = context.args.reference.split_once(':') else {
return TypedResult::error(
"INVALID_SECRET_REFERENCE",
"Expected PROVIDER:REFERENCE",
);
};
if provider.is_empty() || reference.is_empty() {
return TypedResult::error(
"INVALID_SECRET_REFERENCE",
"Secret provider and reference cannot be empty",
);
}
match DaemonClient.call("env.secret", serde_json::json!({
"name": context.args.name,
"value": null,
"secret": {
"provider": provider,
"reference": reference,
"version": null
},
"global": context.options.global,
"cwd": context.options.cwd,
"idempotency_key": context.options.idempotency_key,
})).await {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("ENV_SECRET_FAILED", error),
}
},
)
.description("Store one unresolved secret reference without persisting its value.")
.mcp(destructive(true))
.done(),
)
.command(
"unset",
tracked_typed::<EnvironmentNameArgs, EnvironmentMutationOptions, (), EnvironmentView, _, _>(
"unset",
|context: TypedContext<EnvironmentNameArgs, EnvironmentMutationOptions, ()>| async move {
match DaemonClient.call("env.unset", serde_json::json!({
"name": context.args.name,
"value": null,
"secret": null,
"global": context.options.global,
"cwd": context.options.cwd,
"idempotency_key": context.options.idempotency_key,
})).await {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("ENV_UNSET_FAILED", error),
}
},
)
.description("Remove one value from the selected durable environment.")
.mcp(destructive(true))
.done(),
)
.command(
"clear",
tracked_typed::<(), EnvironmentMutationOptions, (), EnvironmentView, _, _>(
"clear",
|context: TypedContext<(), EnvironmentMutationOptions, ()>| async move {
match DaemonClient.call("env.clear", serde_json::json!({
"name": null,
"value": null,
"secret": null,
"global": context.options.global,
"cwd": context.options.cwd,
"idempotency_key": context.options.idempotency_key,
})).await {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("ENV_CLEAR_FAILED", error),
}
},
)
.description("Clear the selected implicit durable environment.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"list",
tracked_typed::<(), EnvironmentLookupOptions, (), EnvironmentView, _, _>(
"list",
|context: TypedContext<(), EnvironmentLookupOptions, ()>| async move {
match DaemonClient.call("env.list", serde_json::json!({
"global": context.options.global,
"cwd": context.options.cwd,
})).await {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("ENV_LIST_FAILED", error),
}
},
)
.description("List effective environment names without secret values or references.")
.mcp(read_only())
.done(),
)
.command(
"doctor",
tracked_typed::<(), EnvironmentLookupOptions, (), EnvironmentView, _, _>(
"doctor",
|context: TypedContext<(), EnvironmentLookupOptions, ()>| async move {
match DaemonClient.call("env.doctor", serde_json::json!({
"global": context.options.global,
"cwd": context.options.cwd,
})).await {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("ENV_DOCTOR_FAILED", error),
}
},
)
.description("Check whether effective literal and secret values can resolve.")
.mcp(read_only())
.done(),
)
}
fn recipe_cli() -> Cli {
Cli::create("recipe")
.description("Save and rerun durable JavaScript orchestration.")
.command(
"suggest",
tracked_typed::<RecipePutArgs, RecipeSuggestOptions, (), RecipeSuggestion, _, _>(
"suggest",
|context: TypedContext<RecipePutArgs, RecipeSuggestOptions, ()>| 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,
};
let output_schema = match context.options.output_schema {
Some(value) => match serde_json::from_str::<serde_json::Value>(&value) {
Ok(value) => Some(value),
Err(error) => {
return TypedResult::error(
"INVALID_OUTPUT_SCHEMA",
error.to_string(),
);
}
},
None => None,
};
match DaemonClient
.call(
"recipe.suggest",
serde_json::json!({
"name": context.args.name,
"description": context.options.description.unwrap_or_default(),
"code": context.args.code,
"input_schema": input_schema,
"output_schema": output_schema,
"dependencies": context.options.dependency,
"required_env": context.options.require_env,
"annotations": {
"read_only": context.options.read_only.then_some(true),
"destructive": context.options.destructive.then_some(true),
"idempotent": context.options.idempotent.then_some(true),
"open_world": context.options.open_world.then_some(true)
},
"positive": context.options.positive,
"counterexample": context.options.counterexample,
"rationale": context.options.rationale,
"global": context.options.global,
"cwd": context.options.cwd,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECIPE_SUGGEST_FAILED", error),
}
},
)
.description("Store an immutable non-executable recipe candidate with exact evidence.")
.mcp(destructive(true))
.done(),
)
.command(
"suggestions",
tracked_typed::<(), (), (), Vec<RecipeSuggestion>, _, _>(
"suggestions",
|_| async move {
match DaemonClient
.call("recipe.suggestions", serde_json::json!({}))
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECIPE_SUGGESTIONS_FAILED", error),
}
},
)
.description("List immutable recipe suggestions separately from executable recipes.")
.mcp(read_only())
.done(),
)
.command(
"suggestion",
tracked_typed::<RecipeSuggestionArgs, (), (), RecipeSuggestion, _, _>(
"suggestion",
|context: TypedContext<RecipeSuggestionArgs, (), ()>| async move {
match DaemonClient
.call(
"recipe.suggestion",
serde_json::json!({
"id": context.args.id,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECIPE_SUGGESTION_FAILED", error),
}
},
)
.description("Get one recipe suggestion and its exact evidence identifiers.")
.mcp(read_only())
.done(),
)
.command(
"adopt",
tracked_typed::<RecipeSuggestionArgs, RecipeAdoptOptions, (), Recipe, _, _>(
"adopt",
|context: TypedContext<RecipeSuggestionArgs, RecipeAdoptOptions, ()>| async move {
match DaemonClient
.call(
"recipe.adopt",
serde_json::json!({
"id": context.args.id,
"ttl_ms": context.options.ttl_ms,
"replace": context.options.replace,
"idempotency_key": context.options.idempotency_key,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECIPE_ADOPT_FAILED", error),
}
},
)
.description("Atomically adopt one exact suggestion as a short-lived recipe.")
.mcp(destructive(true))
.done(),
)
.command(
"put",
tracked_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,
};
let output_schema = match context.options.output_schema {
Some(value) => match serde_json::from_str::<serde_json::Value>(&value) {
Ok(value) => Some(value),
Err(error) => {
return TypedResult::error(
"INVALID_OUTPUT_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,
"output_schema": output_schema,
"dependencies": context.options.dependency,
"required_env": context.options.require_env,
"annotations": {
"read_only": context.options.read_only.then_some(true),
"destructive": context.options.destructive.then_some(true),
"idempotent": context.options.idempotent.then_some(true),
"open_world": context.options.open_world.then_some(true)
},
"ttl_ms": context.options.ttl_ms,
"global": context.options.global,
"cwd": context.options.cwd,
"idempotency_key": context.options.idempotency_key
}),
)
.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",
tracked_typed::<(), RecipeListOptions, (), Vec<Recipe>, _, _>(
"list",
|context: TypedContext<(), RecipeListOptions, ()>| async move {
match DaemonClient
.call(
"recipe.list",
serde_json::json!({
"prefix": context.options.prefix,
"include_expired": context.options.include_expired,
"global": context.options.global,
"cwd": context.options.cwd
}),
)
.await
{
Ok(recipes) => TypedResult::ok(recipes),
Err(error) => TypedResult::error("RECIPE_LIST_FAILED", error),
}
},
)
.description("List saved recipes.")
.mcp(read_only())
.done(),
)
.command(
"get",
tracked_typed::<NameArgs, RecipeLookupOptions, (), Recipe, _, _>(
"get",
|context: TypedContext<NameArgs, RecipeLookupOptions, ()>| async move {
match DaemonClient
.call(
"recipe.get",
serde_json::json!({
"name": context.args.name,
"global": context.options.global,
"cwd": context.options.cwd
}),
)
.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",
tracked_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,
"global": context.options.global,
"cwd": context.options.cwd,
"idempotency_key": context.options.idempotency_key
}),
)
.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",
tracked_typed::<NameArgs, RecipeMutationOptions, (), RemoveOutput, _, _>(
"remove",
|context: TypedContext<NameArgs, RecipeMutationOptions, ()>| async move {
match DaemonClient
.call(
"recipe.remove",
serde_json::json!({
"name": context.args.name,
"global": context.options.global,
"cwd": context.options.cwd,
"idempotency_key": context.options.idempotency_key
}),
)
.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(),
)
.command(
"pin",
tracked_typed::<NameArgs, RecipeMutationOptions, (), Recipe, _, _>(
"pin",
|context: TypedContext<NameArgs, RecipeMutationOptions, ()>| async move {
match DaemonClient
.call(
"recipe.pin",
serde_json::json!({
"name": context.args.name,
"global": context.options.global,
"cwd": context.options.cwd,
"idempotency_key": context.options.idempotency_key
}),
)
.await
{
Ok(recipe) => TypedResult::ok(recipe),
Err(error) => TypedResult::error("RECIPE_PIN_FAILED", error),
}
},
)
.description("Clear one recipe's expiry timestamp.")
.mcp(destructive(true))
.done(),
)
.command(
"prune",
tracked_typed::<(), RecipeMutationOptions, (), serde_json::Value, _, _>(
"prune",
|context: TypedContext<(), RecipeMutationOptions, ()>| async move {
match DaemonClient
.call(
"recipe.prune",
serde_json::json!({
"global": context.options.global,
"cwd": context.options.cwd,
"idempotency_key": context.options.idempotency_key
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECIPE_PRUNE_FAILED", error),
}
},
)
.description("Delete expired recipes in one explicit scope.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"export",
tracked_typed::<RecipeExportArgs, RecipeExportOptions, (), serde_json::Value, _, _>(
"export",
|context: TypedContext<RecipeExportArgs, RecipeExportOptions, ()>| async move {
match DaemonClient
.call(
"recipe.export",
serde_json::json!({
"prefix": context.args.prefix,
"file": context.options.file,
"global": context.options.global,
"cwd": context.options.cwd,
"replace": context.options.replace,
"idempotency_key": context.options.idempotency_key
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECIPE_EXPORT_FAILED", error),
}
},
)
.description("Write a portable namespace and its transitive dependencies to JSON.")
.mcp(destructive(true))
.done(),
)
.command(
"import",
tracked_typed::<RecipeImportArgs, RecipeImportOptions, (), serde_json::Value, _, _>(
"import",
|context: TypedContext<RecipeImportArgs, RecipeImportOptions, ()>| async move {
match DaemonClient
.call(
"recipe.import",
serde_json::json!({
"file": context.args.file,
"global": context.options.global,
"cwd": context.options.cwd,
"ttl_ms": context.options.ttl_ms,
"replace": context.options.replace,
"idempotency_key": context.options.idempotency_key
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECIPE_IMPORT_FAILED", error),
}
},
)
.description("Validate and import one portable RecipeBundleV1 JSON file.")
.mcp(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,
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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(args.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,
environment_generations: Vec::new(),
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 PollSpecOptions {
interval_mode: String,
interval_ms: Option<u64>,
initial_interval_ms: Option<u64>,
multiplier: Option<f64>,
max_interval_ms: Option<u64>,
until_exit_code: Option<Vec<i32>>,
until_stdout_regex: Option<String>,
until_stderr_regex: Option<String>,
until_json_pointer: Option<String>,
until_json_equals: Option<String>,
until_js: Option<String>,
max_iterations: Option<u64>,
duration_ms: Option<u64>,
iteration_timeout_ms: Option<u64>,
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>>,
owner: String,
session: Option<String>,
parent: Option<String>,
artifact_bytes: Option<u64>,
}
fn poll_command_spec(
args: RunArgv,
options: PollCommandOptions,
) -> Result<(ExecutionSpec, Option<String>, Option<String>), String> {
let mut argv = vec![args.executable];
argv.extend(args.arg.unwrap_or_default());
poll_execution_spec(
PollTarget::Command {
argv,
shell: options.shell,
},
PollSpecOptions {
interval_mode: options.interval_mode,
interval_ms: options.interval_ms,
initial_interval_ms: options.initial_interval_ms,
multiplier: options.multiplier,
max_interval_ms: options.max_interval_ms,
until_exit_code: options.until_exit_code,
until_stdout_regex: options.until_stdout_regex,
until_stderr_regex: options.until_stderr_regex,
until_json_pointer: options.until_json_pointer,
until_json_equals: options.until_json_equals,
until_js: options.until_js,
max_iterations: options.max_iterations,
duration_ms: options.duration_ms,
iteration_timeout_ms: options.iteration_timeout_ms,
idempotency_key: options.idempotency_key,
name: options.name,
purpose: options.purpose,
label: options.label,
cwd: options.cwd,
env: options.env,
secret_env: options.secret_env,
owner: options.owner,
session: options.session,
parent: options.parent,
artifact_bytes: options.artifact_bytes,
},
)
}
fn poll_apoc_spec(
args: PollMethodArgs,
options: PollApocOptions,
) -> Result<(ExecutionSpec, Option<String>, Option<String>), String> {
let arguments = serde_json::from_str::<serde_json::Value>(&options.arguments)
.map_err(|error| format!("Invalid --arguments JSON: {error}"))?;
poll_execution_spec(
PollTarget::ApocCall {
method: args.method,
arguments,
},
PollSpecOptions {
interval_mode: options.interval_mode,
interval_ms: options.interval_ms,
initial_interval_ms: options.initial_interval_ms,
multiplier: options.multiplier,
max_interval_ms: options.max_interval_ms,
until_exit_code: options.until_exit_code,
until_stdout_regex: options.until_stdout_regex,
until_stderr_regex: options.until_stderr_regex,
until_json_pointer: options.until_json_pointer,
until_json_equals: options.until_json_equals,
until_js: options.until_js,
max_iterations: options.max_iterations,
duration_ms: options.duration_ms,
iteration_timeout_ms: options.iteration_timeout_ms,
idempotency_key: options.idempotency_key,
name: options.name,
purpose: options.purpose,
label: options.label,
cwd: options.cwd,
env: options.env,
secret_env: options.secret_env,
owner: options.owner,
session: options.session,
parent: options.parent,
artifact_bytes: options.artifact_bytes,
},
)
}
fn poll_execution_spec(
target: PollTarget,
options: PollSpecOptions,
) -> Result<(ExecutionSpec, Option<String>, Option<String>), String> {
let schedule = match options.interval_mode.as_str() {
"fixed-delay" => {
if options.initial_interval_ms.is_some()
|| options.multiplier.is_some()
|| options.max_interval_ms.is_some()
{
return Err(
"Backoff interval arguments require --interval-mode backoff".to_string()
);
}
PollSchedule::FixedDelay {
interval_ms: options.interval_ms.unwrap_or(1000),
}
}
"fixed-rate" => {
if options.initial_interval_ms.is_some()
|| options.multiplier.is_some()
|| options.max_interval_ms.is_some()
{
return Err(
"Backoff interval arguments require --interval-mode backoff".to_string()
);
}
PollSchedule::FixedRate {
interval_ms: options.interval_ms.unwrap_or(1000),
}
}
"backoff" => {
if options.interval_ms.is_some() {
return Err(
"Use --initial-interval-ms and --max-interval-ms for backoff".to_string(),
);
}
PollSchedule::Backoff {
initial_interval_ms: options.initial_interval_ms.unwrap_or(1000),
multiplier: options.multiplier.unwrap_or(2.0),
max_interval_ms: options.max_interval_ms.unwrap_or(30_000),
}
}
value => return Err(format!("Unknown interval mode \"{value}\"")),
};
if options.until_json_pointer.is_some() != options.until_json_equals.is_some() {
return Err(
"--until-json-pointer and --until-json-equals must be supplied together".to_string(),
);
}
let mut conditions = Vec::new();
if let Some(codes) = options.until_exit_code {
conditions.push(PollCondition::ExitCode { codes });
}
if let Some(pattern) = options.until_stdout_regex {
conditions.push(PollCondition::StdoutRegex { pattern });
}
if let Some(pattern) = options.until_stderr_regex {
conditions.push(PollCondition::StderrRegex { pattern });
}
if let (Some(pointer), Some(value)) = (options.until_json_pointer, options.until_json_equals) {
conditions.push(PollCondition::JsonEquals {
pointer,
value: serde_json::from_str(&value)
.map_err(|error| format!("Invalid --until-json-equals JSON: {error}"))?,
});
}
if let Some(expression) = options.until_js {
conditions.push(PollCondition::Javascript { expression });
}
if conditions.len() > 1 {
return Err("Choose exactly one poll condition family".to_string());
}
let condition = conditions.pop();
let labels = parse_labels(options.label.as_deref().unwrap_or_default())?;
let env = parse_env(options.env.as_deref().unwrap_or_default())?;
let secrets = parse_execution_secrets(options.secret_env.as_deref().unwrap_or_default())?;
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 polls require --session".to_string());
}
let parent_id = options.parent;
let session_id = options.session;
let owner_id = match owner_kind {
LeaseOwnerKind::Execution => parent_id.clone(),
LeaseOwnerKind::Session => session_id.clone(),
LeaseOwnerKind::Persistent => None,
};
let default_name = match &target {
PollTarget::Command { argv, .. } => argv
.first()
.map(|value| format!("poll {value}"))
.unwrap_or_else(|| "poll command".to_string()),
PollTarget::ApocCall { method, .. } => format!("poll {method}"),
};
Ok((
ExecutionSpec {
schema_version: SCHEMA_VERSION,
idempotency_key: options.idempotency_key,
name: options.name.unwrap_or(default_name),
purpose: options.purpose,
labels,
program: ExecutionProgram::Poll {
target,
schedule,
condition,
max_iterations: options.max_iterations,
duration_ms: options.duration_ms,
iteration_timeout_ms: options.iteration_timeout_ms,
},
workspace: WorkspaceContext {
cwd: options.cwd,
..WorkspaceContext::default()
},
env,
secrets,
environment_generations: Vec::new(),
io: IoMode::Pipes,
owner_kind,
owner_id,
expires_at: None,
retry: RetryPolicy::default(),
budget: ExecutionBudget {
artifact_bytes: options.artifact_bytes,
..ExecutionBudget::default()
},
},
parent_id,
session_id,
))
}
fn parse_execution_secrets(values: &[String]) -> Result<BTreeMap<String, SecretRef>, String> {
let mut secrets = 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}\""
));
}
secrets.insert(
name.to_string(),
SecretRef {
provider: provider.to_string(),
reference: reference.to_string(),
version: None,
},
);
}
Ok(secrets)
}
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(),
environment_generations: Vec::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(|| "Expected secret NAME=PROVIDER:REFERENCE".to_string())?;
let (provider, reference) = reference
.split_once(':')
.ok_or_else(|| format!("Expected secret {name}=PROVIDER:REFERENCE"))?;
if name.is_empty() || provider.is_empty() || reference.is_empty() {
return Err("Secret name, provider, and reference cannot be empty".to_string());
}
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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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 poll_cli() -> Cli {
Cli::create("poll")
.description(
"Repeatedly evaluate exact commands or typed apoc operations under a durable execution.",
)
.group(poll_mode_cli("run", "poll.run", true))
.group(poll_mode_cli("start", "poll.start", false))
.command(
"iterations",
tracked_typed::<RunIdArgs, PollIterationListOptions, (), PollIterationPage, _, _>(
"iterations",
|context: TypedContext<RunIdArgs, PollIterationListOptions, ()>| async move {
match DaemonClient
.call(
"poll.iterations",
serde_json::json!({
"id": context.args.id,
"limit": context.options.limit,
"cursor": context.options.cursor
}),
)
.await
{
Ok(page) => TypedResult::ok(page),
Err(error) => TypedResult::error("POLL_ITERATIONS_FAILED", error),
}
},
)
.description(
"List compact durable poll iterations newest-first in a bounded cursor page.",
)
.mcp(read_only())
.done(),
)
.command(
"iteration",
tracked_typed::<PollIterationArgs, (), (), PollIteration, _, _>(
"iteration",
|context: TypedContext<PollIterationArgs, (), ()>| async move {
match DaemonClient
.call(
"poll.iteration",
serde_json::json!({
"id": context.args.id,
"iteration": context.args.iteration
}),
)
.await
{
Ok(iteration) => TypedResult::ok(iteration),
Err(error) => TypedResult::error("POLL_ITERATION_FAILED", error),
}
},
)
.description(
"Get one detailed poll observation and its child execution or retained payload link.",
)
.mcp(read_only())
.done(),
)
}
fn poll_mode_cli(name: &'static str, rpc: &'static str, wait: bool) -> Cli {
Cli::create(name)
.description(if wait {
"Run a durable poll until it reaches a terminal outcome."
} else {
"Start a durable poll and return after ownership is recorded."
})
.command(
"command",
tracked_typed::<RunArgv, PollCommandOptions, (), ExecutionInvocation, _, _>(
"command",
move |context: TypedContext<RunArgv, PollCommandOptions, ()>| async move {
let (spec, parent_id, session_id) =
match poll_command_spec(context.args, context.options) {
Ok(value) => value,
Err(error) => return TypedResult::error("INVALID_POLL", error),
};
match DaemonClient
.call(
rpc,
serde_json::json!({
"spec": spec,
"parent_id": parent_id,
"session_id": session_id
}),
)
.await
{
Ok(invocation) if wait => invocation_result(invocation),
Ok(invocation) => TypedResult::ok(invocation),
Err(error) => TypedResult::error("POLL_COMMAND_FAILED", error),
}
},
)
.description(if wait {
"Poll an exact-argv command to a match or configured bound and return its terminal execution."
} else {
"Start polling an exact-argv command and return its durable execution immediately."
})
.mcp(destructive(false))
.done(),
)
.command(
"apoc",
tracked_typed::<PollMethodArgs, PollApocOptions, (), ExecutionInvocation, _, _>(
"apoc",
move |context: TypedContext<PollMethodArgs, PollApocOptions, ()>| async move {
let (spec, parent_id, session_id) =
match poll_apoc_spec(context.args, context.options) {
Ok(value) => value,
Err(error) => return TypedResult::error("INVALID_POLL", error),
};
match DaemonClient
.call(
rpc,
serde_json::json!({
"spec": spec,
"parent_id": parent_id,
"session_id": session_id
}),
)
.await
{
Ok(invocation) if wait => invocation_result(invocation),
Ok(invocation) => TypedResult::ok(invocation),
Err(error) => TypedResult::error("POLL_APOC_FAILED", error),
}
},
)
.description(if wait {
"Poll a schema-validated typed apoc operation without spawning a nested CLI process."
} else {
"Start polling a schema-validated typed apoc operation and return immediately."
})
.mcp(destructive(false))
.done(),
)
}
fn session_cli() -> Cli {
Cli::create("session")
.description("Own related executions and resources with a durable agent heartbeat.")
.command(
"open",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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 history_cli() -> Cli {
Cli::create("history")
.description(
"Search durable apoc command invocations in the current workspace or globally.",
)
.command(
"list",
tracked_typed::<(), HistoryOptions, (), InvocationPage, _, _>(
"list",
|context: TypedContext<(), HistoryOptions, ()>| async move {
match query_history(context.options, None, context.agent) {
Ok(page) => TypedResult::ok(page),
Err(error) => TypedResult::error("HISTORY_QUERY_FAILED", error),
}
},
)
.description("List recent invocations. Local workspace scope is the default.")
.mcp(read_only())
.done(),
)
.command(
"timeline",
tracked_typed::<(), HistoryTimelineOptions, (), InvocationTimelinePage, _, _>(
"timeline",
|context: TypedContext<(), HistoryTimelineOptions, ()>| async move {
match build_history_query(context.options.into(), None, context.agent)
.and_then(|query| history_store()?.timeline_invocations(&query))
{
Ok(page) => TypedResult::ok(page),
Err(error) => TypedResult::error("HISTORY_TIMELINE_FAILED", error),
}
},
)
.description("Read complete sanitized invocations oldest-first in a stable snapshot.")
.mcp(read_only())
.done(),
)
.command(
"search",
tracked_typed::<HistorySearchArgs, HistoryOptions, (), InvocationPage, _, _>(
"search",
|context: TypedContext<HistorySearchArgs, HistoryOptions, ()>| async move {
match query_history(context.options, Some(context.args.query), context.agent) {
Ok(page) => TypedResult::ok(page),
Err(error) => TypedResult::error("HISTORY_QUERY_FAILED", error),
}
},
)
.description("Search literal normalized invocation text in local or global history.")
.mcp(read_only())
.done(),
)
.command(
"query",
tracked_typed::<HistoryQueryArgs, HistoryQueryOptions, (), HistoryQueryOutput, _, _>(
"query",
|context: TypedContext<HistoryQueryArgs, HistoryQueryOptions, ()>| async move {
match history_query_scope(
context.options.global,
context.options.cwd,
context.agent,
)
.and_then(|(scope_kind, scope_key)| {
history_store()?.query_invocation_purposes_sql(
&context.args.sql,
context.options.limit,
scope_kind,
scope_key,
active_invocation_id(),
)
}) {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("HISTORY_SQL_FAILED", error),
}
},
)
.description("Run bounded read-only SQL over invocation ids and purposes.")
.mcp(read_only())
.done(),
)
.command(
"get",
tracked_typed::<HistoryGetArgs, (), (), InvocationRecord, _, _>(
"get",
|context: TypedContext<HistoryGetArgs, (), ()>| async move {
let store = match history_store() {
Ok(store) => store,
Err(error) => {
return TypedResult::error("HISTORY_STORE_FAILED", error);
}
};
match store.get_invocation(&context.args.id) {
Ok(Some(invocation)) => TypedResult::ok(invocation),
Ok(None) => TypedResult::error(
"HISTORY_NOT_FOUND",
format!("Invocation \"{}\" not found", context.args.id),
),
Err(error) => TypedResult::error("HISTORY_QUERY_FAILED", error),
}
},
)
.description("Get one complete invocation record by identifier.")
.mcp(read_only())
.done(),
)
.command(
"patterns",
tracked_typed::<(), HistoryPatternOptions, (), HistoryPatternOutput, _, _>(
"patterns",
|context: TypedContext<(), HistoryPatternOptions, ()>| async move {
match query_history_patterns(context.options, context.agent) {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("HISTORY_PATTERN_QUERY_FAILED", error),
}
},
)
.description("Group repeated normalized invocations without creating recipes.")
.mcp(read_only())
.done(),
)
.command(
"import-devsql",
tracked_typed::<(), (), (), HistoryImportOutput, _, _>(
"import-devsql",
|_| async move {
match import_devsql_history().await {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("HISTORY_IMPORT_FAILED", error),
}
},
)
.description("Explicitly import historical apoc command observations from DevSQL.")
.mcp(destructive(true))
.done(),
)
}
fn query_history_patterns(
options: HistoryPatternOptions,
agent: bool,
) -> Result<HistoryPatternOutput, String> {
if options.global && options.cwd.is_some() {
return Err("--global and --cwd cannot be used together".to_string());
}
let controller = controller(agent);
let cwd = match options.cwd {
Some(cwd) if std::path::Path::new(&cwd).is_absolute() => Some(cwd),
Some(cwd) => controller.cwd.as_deref().map(|base| {
std::path::Path::new(base)
.join(cwd)
.to_string_lossy()
.into_owned()
}),
None => controller.cwd,
};
let scope = (!options.global).then(|| invocation_scope(cwd.as_deref()));
let source = options
.source
.as_deref()
.map(parse_invocation_source)
.transpose()?;
history_store()?.query_invocation_patterns(&InvocationPatternQuery {
min_count: options.min_count,
limit: options.limit,
exclude_id: active_invocation_id(),
scope_kind: scope.as_ref().map(|scope| scope.kind),
scope_key: scope.and_then(|scope| scope.key),
source,
command_path: options.command,
since_ms: options.since_ms,
until_ms: options.until_ms,
})
}
fn query_history(
options: HistoryOptions,
search: Option<String>,
agent: bool,
) -> Result<InvocationPage, String> {
let query = build_history_query(options, search, agent)?;
history_store()?.query_invocations(&query)
}
fn build_history_query(
options: HistoryOptions,
search: Option<String>,
agent: bool,
) -> Result<InvocationQuery, String> {
if options.global && options.cwd.is_some() {
return Err("--global and --cwd cannot be used together".to_string());
}
let controller = controller(agent);
let cwd = match options.cwd {
Some(cwd) if std::path::Path::new(&cwd).is_absolute() => Some(cwd),
Some(cwd) => controller.cwd.as_deref().map(|base| {
std::path::Path::new(base)
.join(cwd)
.to_string_lossy()
.into_owned()
}),
None => controller.cwd,
};
let scope = (!options.global).then(|| invocation_scope(cwd.as_deref()));
let source = options
.source
.as_deref()
.map(parse_invocation_source)
.transpose()?;
let surface = options
.surface
.as_deref()
.map(parse_invocation_surface)
.transpose()?;
let status = options
.status
.as_deref()
.map(parse_invocation_status)
.transpose()?;
Ok(InvocationQuery {
limit: options.limit,
cursor: options.cursor,
exclude_id: active_invocation_id(),
search,
scope_kind: scope.as_ref().map(|scope| scope.kind),
scope_key: scope.and_then(|scope| scope.key),
source,
surface,
command_path: options.command,
status,
actor: options.actor,
execution_id: options.execution,
since_ms: options.since_ms,
until_ms: options.until_ms,
})
}
fn history_store() -> Result<Arc<crate::store::Store>, String> {
active_store()
.map(Ok)
.unwrap_or_else(|| crate::store::Store::open_default().map(Arc::new))
}
fn parse_invocation_source(value: &str) -> Result<InvocationSource, String> {
match value {
"native" => Ok(InvocationSource::Native),
"devsql" => Ok(InvocationSource::Devsql),
_ => Err(format!("Unknown invocation source \"{value}\"")),
}
}
fn parse_invocation_surface(value: &str) -> Result<InvocationSurface, String> {
match value {
"cli" => Ok(InvocationSurface::Cli),
"mcp" => Ok(InvocationSurface::Mcp),
"code" => Ok(InvocationSurface::Code),
_ => Err(format!("Unknown invocation surface \"{value}\"")),
}
}
fn parse_invocation_status(value: &str) -> Result<InvocationStatus, String> {
match value {
"running" => Ok(InvocationStatus::Running),
"succeeded" => Ok(InvocationStatus::Succeeded),
"failed" => Ok(InvocationStatus::Failed),
"incomplete" => Ok(InvocationStatus::Incomplete),
_ => Err(format!("Unknown invocation status \"{value}\"")),
}
}
async fn import_devsql_history() -> Result<HistoryImportOutput, String> {
const QUERY: &str = "SELECT source, source_id, source_order, channel, actor, \
provenance_quality, command, cwd, source_path, \
CAST(unixepoch(timestamp) * 1000 AS INTEGER) AS at, duration_ms, exit_code \
FROM command_events WHERE lower(command) LIKE '%apoc%' ORDER BY timestamp, source_order";
let output = tokio::process::Command::new("devsql")
.args([QUERY, "--format", "json"])
.output()
.await
.map_err(|error| format!("Could not run devsql: {error}"))?;
if !output.status.success() {
return Err(format!(
"DevSQL query failed with {}: {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
));
}
let rows = serde_json::from_slice::<Vec<serde_json::Value>>(&output.stdout)
.map_err(|error| format!("DevSQL returned invalid JSON: {error}"))?;
let store = history_store()?;
let pattern = regex::Regex::new(
r"(?m)(?:^|(?:&&|\|\||[;|&\n])\s*)(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+\s+)*(?:(?:g?timeout)\s+[^\s]+\s+)?(?:(?:[^\s;&|]+/)?apoc)(?P<tail>(?:\s+[^;\n|&]*)?)",
)
.expect("static apoc invocation expression");
let source_rows = rows.len();
let mut imported = 0;
let mut skipped = 0;
for row in rows {
let command = row
.get("command")
.and_then(serde_json::Value::as_str)
.unwrap_or_default();
let matches = pattern.captures_iter(command).collect::<Vec<_>>();
if matches.is_empty() {
skipped += 1;
continue;
}
for (occurrence, matched) in matches.into_iter().enumerate() {
let at = row
.get("at")
.and_then(serde_json::Value::as_u64)
.unwrap_or_else(now_ms);
let source = row
.get("source")
.and_then(serde_json::Value::as_str)
.unwrap_or("unknown");
let source_id = row.get("source_id").and_then(serde_json::Value::as_str);
let source_order = row.get("source_order").and_then(serde_json::Value::as_i64);
let source_path = row.get("source_path").and_then(serde_json::Value::as_str);
let identity = format!(
"{source}\u{0}{}\u{0}{}\u{0}{}\u{0}{at}\u{0}{command}\u{0}{occurrence}",
source_id.unwrap_or_default(),
source_order.unwrap_or_default(),
source_path.unwrap_or_default()
);
let id = format!("devsql_{:x}", Sha256::digest(identity));
if store.get_invocation(&id)?.is_some() {
skipped += 1;
continue;
}
let cwd = row.get("cwd").and_then(serde_json::Value::as_str);
let scope = if cwd.is_some_and(|cwd| std::path::Path::new(cwd).is_dir()) {
invocation_scope(cwd)
} else {
crate::history::InvocationScope {
cwd: cwd.map(ToString::to_string),
kind: crate::model::InvocationScopeKind::Unknown,
key: None,
}
};
let duration = row.get("duration_ms").and_then(serde_json::Value::as_u64);
let exit_code = row
.get("exit_code")
.and_then(serde_json::Value::as_i64)
.and_then(|value| i32::try_from(value).ok());
let status = match exit_code {
Some(0) => InvocationStatus::Succeeded,
Some(_) => InvocationStatus::Failed,
None => InvocationStatus::Incomplete,
};
let actor = row
.get("actor")
.and_then(serde_json::Value::as_str)
.map(ToString::to_string);
let command_path = imported_command_path(
matched
.name("tail")
.map(|value| value.as_str())
.unwrap_or_default(),
);
let completed_at = duration.map(|duration| at.saturating_add(duration));
let sanitized_command = sanitize_imported_command(command);
let invocation = InvocationRecord {
id,
parent_id: None,
execution_id: None,
source: InvocationSource::Devsql,
source_id: source_id.map(ToString::to_string),
source_order,
source_path: source_path.map(ToString::to_string),
accepted_sequence: 0,
surface: InvocationSurface::Cli,
actor: actor.clone(),
agent: actor.as_deref() == Some("agent"),
command_path,
purpose: None,
normalized_input: serde_json::json!({
"command": sanitized_command,
"channel": row.get("channel"),
"provenance_quality": row.get("provenance_quality")
}),
search_text: sanitized_command,
pattern_signature: String::new(),
variable_paths: Vec::new(),
cwd: scope.cwd,
scope_kind: scope.kind,
scope_key: scope.key,
started_at: at,
completed_at,
updated_at: completed_at.unwrap_or(at),
status,
exit_code,
error_code: None,
error: None,
};
store.insert_invocation(&invocation)?;
imported += 1;
}
}
Ok(HistoryImportOutput {
source_rows,
imported,
skipped,
})
}
fn imported_command_path(tail: &str) -> String {
let words = tail.split_whitespace().collect::<Vec<_>>();
let Some(root) = words.first().filter(|word| !word.starts_with('-')) else {
return "apoc".to_string();
};
let grouped = matches!(
*root,
"action"
| "benchmark"
| "capability"
| "code"
| "connector"
| "daemon"
| "event"
| "execution"
| "history"
| "lease"
| "process"
| "provider"
| "receipt"
| "recipe"
| "reservation"
| "session"
| "skill"
);
if grouped && let Some(command) = words.get(1).filter(|word| !word.starts_with('-')) {
return format!("{root} {command}");
}
(*root).to_string()
}
fn sanitize_imported_command(command: &str) -> String {
let secret_flag =
regex::Regex::new(r"(?P<prefix>--secret-(?:env|header)(?:=|\s+))(?P<value>[^\s;&|]+)")
.expect("static secret flag expression");
let command = secret_flag.replace_all(command, |captures: ®ex::Captures<'_>| {
let value = captures.name("value").map_or("", |value| value.as_str());
let name = value.split_once('=').map_or(value, |(name, _)| name);
format!("{}{}=[REDACTED]", &captures["prefix"], name)
});
let env_secret =
regex::Regex::new(r"(?P<prefix>\bapoc\s+env\s+secret\s+[^\s;&|]+\s+)[^\s;&|]+")
.expect("static env secret expression");
env_secret
.replace_all(&command, "${prefix}[REDACTED]")
.into_owned()
}
fn event_cli() -> Cli {
Cli::create("event")
.description("Query the compact causal journal and retained payloads.")
.command(
"query",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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,
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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",
tracked_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,
tracked_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()
}
}
#[cfg(test)]
mod tests {
use super::*;
use incurs::command::RequestContext;
use incurs::tool::{ToolCallOptions, ToolCallOutcome};
#[tokio::test]
async fn records_structured_mcp_dispatch_as_one_invocation() {
let directory = tempfile::tempdir().unwrap();
let store =
Arc::new(crate::store::Store::open(directory.path().join("apoc.sqlite3")).unwrap());
let catalog = build_agent_cli_with_store(Some(store.clone())).tool_catalog();
let mut arguments = BTreeMap::new();
arguments.insert(
"purpose".to_string(),
serde_json::json!("Checking the structured MCP version contract."),
);
let outcome = catalog
.call(
"version",
arguments,
ToolCallOptions {
request: Some(RequestContext {
headers: std::collections::HashMap::new(),
method: "tools/call".to_string(),
path: "version".to_string(),
}),
..ToolCallOptions::default()
},
)
.await;
assert!(matches!(outcome, ToolCallOutcome::Ok { .. }));
let page = store
.query_invocations(&InvocationQuery {
limit: 10,
surface: Some(InvocationSurface::Mcp),
..InvocationQuery::default()
})
.unwrap();
assert_eq!(page.invocations.len(), 1);
assert_eq!(page.invocations[0].command_path, "version");
assert_eq!(
page.invocations[0].purpose.as_deref(),
Some("Checking the structured MCP version contract.")
);
assert_eq!(page.invocations[0].status, InvocationStatus::Succeeded);
}
}