mod observe;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
use incurs::cli::Cli;
use incurs::command::{McpAnnotations, McpCommandOptions, TypedContext, TypedResult};
use regex::Regex;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use tokio::sync::Mutex;
use crate::benchmark::{ProcessBenchmark, process_benchmark};
use crate::daemon::{Daemon, DaemonClient, DaemonStatus};
use crate::debugger::{
AppleAttachResolution, AppleAttachResult, AppleDeviceApp, AppleDeviceTarget, BrowserCookie,
BrowserCoverageSnapshot, BrowserDomNode, BrowserInteraction, BrowserMetric, BrowserMockRule,
BrowserNavigation, BrowserNetworkBody, BrowserNetworkRequest, BrowserPageEvent,
BrowserScreenshot, BrowserStorageEntry, BrowserStyle, BrowserWebSocketFrame, DapInstruction,
DapMemory, DapModule, DapRegister, DapSessionState, DapSignal, DapThread, DapWatchpoint,
DebuggerAfter, DebuggerBreakpoint, DebuggerBrowserState, DebuggerCapture, DebuggerConsoleEntry,
DebuggerEvaluation, DebuggerEvent, DebuggerEvidenceTrace, DebuggerEvidenceTraceView,
DebuggerExceptionEntry, DebuggerFlow, DebuggerFlowRun, DebuggerFlowView, DebuggerFrame,
DebuggerHealth, DebuggerListener, DebuggerMark, DebuggerProperty, DebuggerPrototype,
DebuggerRecording, DebuggerRecordingStart, DebuggerReplay, DebuggerRunResult, DebuggerScope,
DebuggerScript, DebuggerSelection, DebuggerSessionRecord, DebuggerSessionView, DebuggerSource,
DebuggerTap, DebuggerTapHit, DebuggerTarget, DebuggerTimeline, DebuggerTraceCursor,
DebuggerTraceEntry, DebuggerTraceExport, DebuggerTraceGc, DebuggerTraceImport,
DebuggerTraceReplayResult, DebuggerVariable, DebuggerWatch, DebuggerWatchHit, DebuggerWhy,
ExtensionAttachResult, ExtensionCdpResult, ExtensionDoctor, ExtensionEvaluation,
ExtensionEvent, ExtensionHostInstallation, ExtensionObserveResult, ExtensionSnapshotResult,
ExtensionStatusView, ExtensionTab, LegacyDebuggerIndexStatus, LegacyDebuggerMigration,
LegacyDebuggerQuery, RrBackend, RrExecutionResult, RrProcessStatus, RrTrace,
};
use crate::history::{
active_invocation_id, active_store, discovery_typed, invocation_middleware, invocation_purpose,
invocation_scope, tracked_typed,
};
use crate::hook::{Hook, HookDelivery};
use crate::image::{VerificationReport, VerificationStatus, verify_reference};
use crate::model::{
ActionReceipt, AgentSession, CausalEvent, ConnectorConfig, ConnectorKind,
DEFAULT_TELEMETRY_INTERVAL_MS, DEFAULT_TELEMETRY_MAX_BYTES, Execution, ExecutionBackendSpec,
ExecutionBudget, ExecutionExportSpec, ExecutionListPage, ExecutionOutcome, ExecutionProgram,
ExecutionSpec, ExecutionStatus, ExecutionTree, ExecutionVerdict, HistoryPatternOutput,
HistoryQueryOutput, ImageImportResponse, InvocationPage, InvocationPatternQuery,
InvocationQuery, InvocationRecord, InvocationScopeKind, InvocationSource, InvocationStatus,
InvocationSurface, InvocationTimelinePage, IoMode, IsolatedExecutionSpec,
IsolatedNetworkPolicy, IsolatedWorkspaceMode, IsolationMutationResponse, IsolationStatus,
Lease, LeaseOwnerKind, OperationReceipt, PollCondition, PollIteration, PollIterationPage,
PollSchedule, PollTarget, PortInfo, ProcessDossier, ProcessEvent, ProcessEventQuery,
ProcessFile, ProcessInfo, ProcessInsight, ProcessProbe, ProcessQuery, ProcessSample,
ProcessSelection, ProcessWait, ProfileMode, ProfileResolution, ProfileView, Recipe,
RecipeSuggestion, Recording, RecordingDetail, RecordingStopOutput, Reservation, RetryPolicy,
SCHEMA_VERSION, SecretRef, TelemetryCapture, TelemetryPolicy, TelemetrySlice, TelemetrySummary,
Verbosity, WorkspaceContext, now_ms, valid_provider_name,
};
use crate::operation::{
AppleAppsOperation, AppleAttachOperation, AppleDevicesOperation, AppleResolveOperation,
DaemonOperation, DapAttachOperation, DapDisassembleOperation, DapLaunchOperation,
DapMemoryOperation, DapModulesOperation, DapRegistersOperation, DapRequestOperation,
DapSignalsOperation, DapStateOperation, DapThreadsOperation, DapWatchpointsOperation,
DebuggerBreakpointDeleteOperation, DebuggerBreakpointListOperation,
DebuggerBreakpointSetOperation, DebuggerBrowserClickOperation, DebuggerBrowserCookiesOperation,
DebuggerBrowserCoverageOperation, DebuggerBrowserDomOperation, DebuggerBrowserEmulateOperation,
DebuggerBrowserMockOperation, DebuggerBrowserNavigateOperation,
DebuggerBrowserNetworkBodyOperation, DebuggerBrowserNetworkOperation,
DebuggerBrowserPageEventsOperation, DebuggerBrowserPerformanceOperation,
DebuggerBrowserScreenshotOperation, DebuggerBrowserSelectOperation,
DebuggerBrowserStateOperation, DebuggerBrowserStorageOperation, DebuggerBrowserStylesOperation,
DebuggerBrowserThrottleOperation, DebuggerBrowserTypeOperation, DebuggerBrowserUnmockOperation,
DebuggerBrowserWebSocketsOperation, DebuggerCloseOperation, DebuggerConsoleOperation,
DebuggerContinueOperation, DebuggerEvaluateOperation, DebuggerEventsOperation,
DebuggerEvidenceTraceCursorOperation, DebuggerEvidenceTraceExportOperation,
DebuggerEvidenceTraceGcOperation, DebuggerEvidenceTraceImportOperation,
DebuggerEvidenceTraceJumpOperation, DebuggerEvidenceTraceListOperation,
DebuggerEvidenceTraceMoveOperation, DebuggerEvidenceTraceReplayOperation,
DebuggerEvidenceTraceShowOperation, DebuggerEvidenceTraceStartOperation,
DebuggerEvidenceTraceStopOperation, DebuggerEvidenceTraceUseOperation,
DebuggerExceptionsOperation, DebuggerExtensionAttachOperation,
DebuggerExtensionBridgeOperation, DebuggerExtensionCdpOperation,
DebuggerExtensionDetachOperation, DebuggerExtensionDoctorOperation,
DebuggerExtensionEvaluateOperation, DebuggerExtensionEventsOperation,
DebuggerExtensionInstallHostOperation, DebuggerExtensionObserveOperation,
DebuggerExtensionSnapshotOperation, DebuggerExtensionStatusOperation,
DebuggerExtensionTabsOperation, DebuggerExtensionUnobserveOperation, DebuggerFlowListOperation,
DebuggerFlowRecordOperation, DebuggerFlowRunOperation, DebuggerFlowShowOperation,
DebuggerFlowStopOperation, DebuggerHealthOperation, DebuggerLegacyImportOperation,
DebuggerLegacyQueryOperation, DebuggerLegacyStatusOperation, DebuggerListOperation,
DebuggerListenersOperation, DebuggerOpenOperation, DebuggerPauseOperation,
DebuggerPropertiesOperation, DebuggerPrototypesOperation, DebuggerReconnectOperation,
DebuggerRecordingAfterGetOperation, DebuggerRecordingAfterOperation,
DebuggerRecordingAftersOperation, DebuggerRecordingCaptureOperation,
DebuggerRecordingCapturesOperation, DebuggerRecordingCorrelateOperation,
DebuggerRecordingListOperation, DebuggerRecordingMarkOperation,
DebuggerRecordingMarksOperation, DebuggerRecordingReplayOperation,
DebuggerRecordingShootOperation, DebuggerRecordingStartOperation,
DebuggerRecordingStatusOperation, DebuggerRecordingStopOperation,
DebuggerRecordingTimelineOperation, DebuggerRecordingWhyOperation, DebuggerRestartOperation,
DebuggerResumeOperation, DebuggerRunOperation, DebuggerScopesOperation,
DebuggerScriptsOperation, DebuggerSelectOperation, DebuggerSelectedOperation,
DebuggerSourceOperation, DebuggerStackOperation, DebuggerStatusOperation,
DebuggerStepOperation, DebuggerTapAddOperation, DebuggerTapHitsOperation,
DebuggerTapListOperation, DebuggerTapRemoveOperation, DebuggerTargetsOperation,
DebuggerThisOperation, DebuggerTraceOperation, DebuggerVariablesOperation,
DebuggerWatchAddOperation, DebuggerWatchHitsOperation, DebuggerWatchListOperation,
DebuggerWatchRemoveOperation, ImageImportOperation, RrImportOperation, RrListOperation,
RrProcessStatusOperation, RrRecordOperation, RrReplayOperation, RrShowOperation,
};
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,
};
const EXACT_ARGV_RECOVERY: &str = "Child command arguments must follow the `--` separator. Put apoc options before `--`, then pass exact child argv after it, for example: `apoc execution command git --purpose 'Create the isolated worktree.' -- worktree add -b BRANCH PATH BASE`. The CLI has no `--arg` option; Code Mode uses `arg: []`.";
const BOOLEAN_FLAG_VALUE_RECOVERY: &str = "Boolean apoc flags do not take values. Use `--cancel-on-stall`, `--pty`, or `--shell` without a following `true` or `false`; place only child argv after `--`.";
pub fn exact_argv_cli_error(argv: &[String]) -> Option<&'static str> {
let executable_index = match argv {
[group, command, ..]
if group == "execution" && matches!(command.as_str(), "command" | "start") =>
{
2
}
[group, action, target, ..]
if group == "poll"
&& matches!(action.as_str(), "run" | "start")
&& target == "command" =>
{
3
}
_ => return None,
};
if argv.len() <= executable_index + 1 {
return None;
}
let options_end = argv
.iter()
.position(|value| value == "--")
.unwrap_or(argv.len());
let mut index = executable_index + 1;
let mut saw_child_argument = false;
while index < options_end {
let token = &argv[index];
let option = token
.split_once('=')
.map_or(token.as_str(), |(name, _)| name);
let inline_value = token.contains('=');
let takes_value = matches!(
option,
"--artifact-bytes"
| "--child-processes"
| "--cpu-percent"
| "--cpu-time-ms"
| "--cwd"
| "--duration-ms"
| "--env"
| "--expires-at"
| "--filter-output"
| "--format"
| "--idempotency-key"
| "--initial-interval-ms"
| "--interval-mode"
| "--interval-ms"
| "--iteration-timeout-ms"
| "--label"
| "--max-attempts"
| "--max-interval-ms"
| "--max-iterations"
| "--memory-limit-mb"
| "--multiplier"
| "--name"
| "--owner"
| "--parent"
| "--progress-timeout-ms"
| "--purpose"
| "--retry-backoff-ms"
| "--retry-max-backoff-ms"
| "--secret-env"
| "--session"
| "--timeout-ms"
| "--telemetry-interval-ms"
| "--telemetry-max-bytes"
| "--token-limit"
| "--token-offset"
| "--until-exit-code"
| "--until-js"
| "--until-json-equals"
| "--until-json-pointer"
| "--until-stderr-regex"
| "--until-stdout-regex"
);
let boolean = matches!(
option,
"--cancel-on-stall" | "--pty" | "--shell" | "--telemetry"
);
if boolean {
let has_inline_value = matches!(token.split_once('='), Some((_, "true" | "false")));
let has_separate_value =
index + 1 < options_end && matches!(argv[index + 1].as_str(), "true" | "false");
if has_inline_value || has_separate_value {
return Some(BOOLEAN_FLAG_VALUE_RECOVERY);
}
index += 1;
continue;
}
if takes_value {
index += usize::from(!inline_value) + 1;
continue;
}
if option == "--arg" || option.starts_with("--arg=") {
return Some(EXACT_ARGV_RECOVERY);
}
if token.starts_with("--") {
return saw_child_argument.then_some(EXACT_ARGV_RECOVERY);
}
if token.starts_with('-') {
return Some(EXACT_ARGV_RECOVERY);
}
saw_child_argument = true;
index += 1;
}
saw_child_argument.then_some(EXACT_ARGV_RECOVERY)
}
#[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::Options)]
struct ExecutionMutationOptions {
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct PortArgs {
port: u16,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerOpenArgs {
port: u16,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerOpenOptions {
#[incurs(default = "s0")]
id: String,
#[incurs(default = "127.0.0.1")]
host: String,
target_id: Option<String>,
execution_id: Option<String>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerTargetsOptions {
#[incurs(default = "127.0.0.1")]
host: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerRunOptions {
#[incurs(default = "s0")]
id: String,
#[incurs(default = "127.0.0.1")]
host: String,
#[incurs(default = 9229)]
port: u16,
cwd: Option<String>,
env: Option<Vec<String>>,
#[incurs(default = 30000)]
timeout_ms: u64,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerSessionArgs {
id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerMutationOptions {
idempotency_key: String,
#[incurs(default = 30000)]
timeout_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct LegacyDebuggerImportArgs {
source: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct LegacyDebuggerImportOptions {
index: Option<String>,
artifact: Option<Vec<String>>,
#[serde(default)]
replace: bool,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct LegacyDebuggerQueryArgs {
sql: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct LegacyDebuggerQueryOptions {
index: Option<String>,
#[incurs(default = 100)]
limit: usize,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct LegacyDebuggerStatusOptions {
index: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct ExtensionTabArgs {
tab_id: u64,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ExtensionInstallHostOptions {
extension_id: String,
#[incurs(default = "chrome")]
browser: String,
#[incurs(default = "com.douglance.apoc")]
host_name: String,
host_path: Option<String>,
home: Option<String>,
user_data_dir: Option<String>,
#[serde(default)]
dry_run: bool,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ExtensionDoctorOptions {
#[incurs(default = "chrome")]
browser: String,
#[incurs(default = "com.douglance.apoc")]
host_name: String,
host_path: Option<String>,
home: Option<String>,
user_data_dir: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ExtensionDetachOptions {
tab_id: Option<u64>,
idempotency_key: String,
#[incurs(default = 30000)]
timeout_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct ExtensionEvaluateArgs {
expression: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ExtensionEvaluateOptions {
tab_id: Option<u64>,
#[incurs(default = "page")]
world: String,
idempotency_key: String,
#[incurs(default = 30000)]
timeout_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct ExtensionCdpArgs {
method: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ExtensionCdpOptions {
tab_id: Option<u64>,
#[incurs(default = "{}")]
params: String,
idempotency_key: String,
#[incurs(default = 30000)]
timeout_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ExtensionSnapshotOptions {
tab_id: Option<u64>,
#[incurs(default = true)]
dom: bool,
#[incurs(default = true)]
state: bool,
#[incurs(default = true)]
storage: bool,
#[incurs(default = true)]
react: bool,
idempotency_key: String,
#[incurs(default = 30000)]
timeout_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct ExtensionObserveArgs {
kinds: Vec<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ExtensionObserveOptions {
tab_id: Option<u64>,
idempotency_key: String,
#[incurs(default = 30000)]
timeout_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ExtensionEventsOptions {
#[incurs(default = 0)]
after: u64,
#[incurs(default = 100)]
limit: usize,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerStepArgs {
id: String,
kind: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerBreakpointArgs {
id: String,
file: String,
line: u64,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerBreakpointOptions {
condition: Option<String>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerBreakpointIdArgs {
id: String,
breakpoint_id: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerTapAddArgs {
id: String,
file: String,
line: u64,
expression: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerTapAddOptions {
url_regex: Option<String>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerTapIdArgs {
id: String,
tap_id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerHitOptions {
#[incurs(default = 100)]
limit: usize,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerIdempotencyOptions {
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerWatchAddArgs {
id: String,
target: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerWatchAddOptions {
expression: Option<String>,
#[incurs(default = "write")]
access: String,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerWatchIdArgs {
id: String,
watch_id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerEventsOptions {
#[incurs(default = 0)]
after: u64,
#[incurs(default = 100)]
limit: usize,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerFrameArgs {
id: String,
frame: usize,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerObjectArgs {
id: String,
object_id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerPrototypeOptions {
#[incurs(default = 8)]
limit: usize,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerSourceOptions {
script_id: Option<String>,
file: Option<String>,
from_line: Option<u64>,
to_line: Option<u64>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerTraceOptions {
#[incurs(default = 0)]
after: u64,
#[incurs(default = 100)]
limit: usize,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerEvaluateArgs {
id: String,
expression: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerEvaluateOptions {
#[incurs(default = 0)]
frame: usize,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct BrowserNavigateArgs {
id: String,
action: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct BrowserNavigateOptions {
target: Option<String>,
#[incurs(default = 30000)]
timeout_ms: u64,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct BrowserSelectorArgs {
id: String,
selector: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct BrowserMutationOptions {
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct BrowserValueArgs {
id: String,
selector: String,
value: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct BrowserScreenshotArgs {
id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct BrowserScreenshotOptions {
selector: Option<String>,
state: Option<String>,
#[serde(default)]
full_page: bool,
width: Option<u64>,
height: Option<u64>,
#[serde(default)]
inline: bool,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct BrowserStorageArgs {
id: String,
kind: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct BrowserRequestArgs {
id: String,
request_id: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct BrowserPresetArgs {
id: String,
preset: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct BrowserMockArgs {
id: String,
pattern: String,
body: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct BrowserMockOptions {
#[incurs(default = 200)]
status: u16,
header: Option<Vec<String>>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct BrowserUnmockArgs {
id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct BrowserUnmockOptions {
pattern: Option<String>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DebuggerRecordingStartOptions {
#[incurs(default = 200)]
max_frames: usize,
#[incurs(default = 104857600_u64)]
max_bytes: u64,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecordingCaptureOptions {
#[incurs(default = "manual")]
reason: String,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecordingMarkArgs {
id: String,
name: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecordingCorrelateArgs {
id: String,
kind: String,
reference: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecordingCorrelateOptions {
path: Option<String>,
at: Option<u64>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecordingAfterOptions {
at: Option<String>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecordingAfterIdArgs {
id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecordingTimelineOptions {
#[incurs(default = 100)]
limit: usize,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecordingWhyArgs {
id: String,
substring: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecordingWhyOptions {
#[incurs(default = 300000)]
window_ms: u64,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct FlowNameArgs {
id: String,
name: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct FlowRecordOptions {
url: Option<String>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct FlowRunOptions {
#[incurs(default = 5000)]
step_timeout_ms: u64,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct EvidenceTraceStartArgs {
id: String,
name: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct EvidenceTraceStopArgs {
id: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct EvidenceTraceIdArgs {
trace_id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct EvidenceTraceReplayOptions {
at: Option<String>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct EvidenceTraceImportArgs {
path: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct EvidenceTraceGcOptions {
#[incurs(default = 10)]
keep: usize,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct EvidenceTraceCursorOptions {
trace_id: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct EvidenceTraceMoveArgs {
direction: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct EvidenceTraceMoveOptions {
#[incurs(default = 1)]
count: usize,
kind: Option<String>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct EvidenceTraceJumpArgs {
direction: String,
kind: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RrRecordOptions {
#[incurs(default = "rr-trace")]
name: String,
#[incurs(default = "rr")]
rr_executable: String,
backend: Option<String>,
image: Option<String>,
cwd: Option<String>,
env: Option<Vec<String>>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RrTraceArgs {
trace_id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RrReplayOptions {
#[incurs(default = "rr")]
rr_executable: String,
backend: Option<String>,
image: Option<String>,
event: Option<u64>,
pid: Option<u32>,
#[incurs(default = false)]
end: bool,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RrProcessStatusOptions {
#[incurs(default = "rr")]
rr_executable: String,
backend: Option<String>,
image: Option<String>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RrImportArgs {
path: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RrImportOptions {
name: Option<String>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DapLaunchOptions {
#[incurs(default = "native")]
id: String,
#[incurs(default = "lldb-dap")]
adapter: String,
adapter_arg: Option<Vec<String>>,
cwd: Option<String>,
env: Option<Vec<String>>,
#[incurs(default = 45000)]
timeout_ms: u64,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct AppleDevicesOptions {
#[incurs(default = "auto")]
platform: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct AppleAppsArgs {
device_id: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct AppleResolveArgs {
bundle_id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct AppleResolveOptions {
#[incurs(default = "auto")]
platform: String,
device: Option<String>,
pid: Option<u32>,
#[serde(default)]
launch: bool,
#[incurs(default = "auto")]
attach_strategy: String,
#[incurs(default = 45000)]
attach_timeout_ms: u64,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct AppleAttachOptions {
#[incurs(default = "apple")]
id: String,
#[incurs(default = "auto")]
platform: String,
device: Option<String>,
pid: Option<u32>,
#[serde(default)]
launch: bool,
#[incurs(default = "auto")]
attach_strategy: String,
#[incurs(default = "lldb-dap")]
adapter: String,
adapter_arg: Option<Vec<String>>,
cwd: Option<String>,
env: Option<Vec<String>>,
#[incurs(default = 45000)]
timeout_ms: u64,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DapAttachArgs {
pid: u32,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DapAttachOptions {
#[incurs(default = "native")]
id: String,
#[incurs(default = "lldb-dap")]
adapter: String,
adapter_arg: Option<Vec<String>>,
#[incurs(default = false)]
wait_for: bool,
attach_command: Option<Vec<String>>,
#[incurs(default = false)]
started_stopped: bool,
cwd: Option<String>,
env: Option<Vec<String>>,
#[incurs(default = 45000)]
timeout_ms: u64,
idempotency_key: String,
}
fn dap_adapter_argv(adapter: String, adapter_args: Option<Vec<String>>) -> Vec<String> {
let mut argv = if cfg!(target_os = "macos") && adapter == "lldb-dap" {
vec!["/usr/bin/xcrun".to_string(), adapter]
} else {
vec![adapter]
};
argv.extend(adapter_args.unwrap_or_default());
argv
}
fn dap_request_arguments(arguments: Option<Value>) -> Result<Value, String> {
let Some(arguments) = arguments else {
return Ok(serde_json::json!({}));
};
let parsed = match &arguments {
Value::String(text) if text.trim().is_empty() => serde_json::json!({}),
Value::String(text) => serde_json::from_str::<Value>(text)
.map_err(|error| format!("DAP request arguments must be a JSON object: {error}"))?,
other => other.clone(),
};
if !parsed.is_object() {
return Err("DAP request arguments must be a JSON object".to_string());
}
Ok(parsed)
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DapRequestArgs {
id: String,
command: String,
arguments: Option<Value>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DapRequestOptions {
#[incurs(default = 15000)]
timeout_ms: u64,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DapMemoryArgs {
id: String,
address: String,
count: u64,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DapDisassembleArgs {
id: String,
address: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DapDisassembleOptions {
#[incurs(default = 32)]
count: u64,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DebuggerRecordingIdArgs {
recording_id: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecordingReplayArgs {
id: String,
capture_id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecordingReplayOptions {
#[incurs(default = 30000)]
timeout_ms: u64,
idempotency_key: String,
}
#[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,
}
const MAX_WAIT_MS: u64 = 60_000;
#[derive(Serialize, Deserialize, incurs::Options)]
struct WaitOptions {
#[incurs(default = 1000)]
ms: u64,
}
#[derive(Serialize, JsonSchema)]
struct WaitOutput {
waited_ms: u64,
}
#[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::Args)]
struct ImageVerifyArgs {
image: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct ImageImportArgs {
source: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ImageImportOptions {
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct IsolationWarmupOptions {
idempotency_key: String,
#[incurs(default = 60_000)]
timeout_ms: u64,
vm_bundle: Option<String>,
pool_size: Option<u64>,
idle_drain_seconds: Option<u64>,
max_pool_memory_mb: Option<u64>,
#[serde(default)]
snapshot_restore: bool,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct IsolationMutationOptions {
idempotency_key: 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>,
profile: Option<String>,
env: Option<Vec<String>>,
secret_env: Option<Vec<String>>,
#[serde(default)]
shell: bool,
provider: Option<String>,
provider_generation: Option<String>,
provider_options: Option<String>,
#[serde(default)]
isolated: bool,
image: Option<String>,
workspace_mode: Option<String>,
guest_cwd: Option<String>,
memory_mb: Option<u64>,
cpu_count: Option<u32>,
pids_max: Option<u32>,
network: Option<String>,
#[serde(default, deserialize_with = "deserialize_execution_exports")]
export: Option<Vec<ExecutionExportSpec>>,
#[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>,
memory_limit_mb: Option<u64>,
cpu_percent: Option<f32>,
cpu_time_ms: Option<u64>,
progress_timeout_ms: Option<u64>,
#[serde(default)]
cancel_on_stall: bool,
child_processes: Option<u32>,
artifact_bytes: Option<u64>,
#[serde(default)]
telemetry: bool,
telemetry_interval_ms: Option<u64>,
telemetry_max_bytes: Option<u64>,
expires_at: Option<u64>,
#[serde(default)]
keep_alive: bool,
lifetime_ms: Option<u64>,
expect_exit_code: Option<Vec<i32>>,
expect_stdout_regex: Option<String>,
expect_stderr_regex: Option<String>,
expect_json_pointer: Option<String>,
expect_json_equals: Option<String>,
expect_js: Option<String>,
verbosity: Option<String>,
#[incurs(alias = "v", count)]
#[serde(default)]
verbose: u32,
#[incurs(alias = "q", count)]
#[serde(default)]
quiet: u32,
#[incurs(deprecated)]
view: Option<String>,
}
type ExecutionRequest = (
ExecutionSpec,
Option<String>,
Option<String>,
Option<String>,
);
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>,
profile: 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>,
#[serde(default)]
telemetry: bool,
telemetry_interval_ms: Option<u64>,
telemetry_max_bytes: Option<u64>,
verbosity: Option<String>,
#[incurs(alias = "v", count)]
#[serde(default)]
verbose: u32,
#[incurs(alias = "q", count)]
#[serde(default)]
quiet: u32,
#[incurs(deprecated)]
view: Option<String>,
}
};
}
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>,
#[serde(default, deserialize_with = "deserialize_command_units")]
commands: Option<Vec<crate::model::CommandUnit>>,
name: Option<String>,
purpose: Option<String>,
idempotency_key: Option<String>,
cwd: Option<String>,
profile: Option<String>,
session: Option<String>,
parent: Option<String>,
#[serde(default)]
telemetry: bool,
telemetry_interval_ms: Option<u64>,
telemetry_max_bytes: Option<u64>,
max_parallel: Option<u32>,
#[serde(default)]
fail_fast: bool,
verbosity: Option<String>,
#[incurs(alias = "v", count)]
#[serde(default)]
verbose: u32,
#[incurs(alias = "q", count)]
#[serde(default)]
quiet: u32,
#[incurs(deprecated)]
view: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct PipelineOptions {
file: Option<String>,
#[serde(default, deserialize_with = "deserialize_command_units")]
commands: Option<Vec<crate::model::CommandUnit>>,
name: Option<String>,
purpose: Option<String>,
idempotency_key: Option<String>,
cwd: Option<String>,
profile: Option<String>,
session: Option<String>,
parent: Option<String>,
#[serde(default)]
telemetry: bool,
telemetry_interval_ms: Option<u64>,
telemetry_max_bytes: Option<u64>,
#[incurs(default = true)]
pipefail: bool,
verbosity: Option<String>,
#[incurs(alias = "v", count)]
#[serde(default)]
verbose: u32,
#[incurs(alias = "q", count)]
#[serde(default)]
quiet: u32,
#[incurs(deprecated)]
view: Option<String>,
}
#[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>,
},
}
fn deserialize_command_units<'de, D>(
deserializer: D,
) -> Result<Option<Vec<crate::model::CommandUnit>>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = Option::<serde_json::Value>::deserialize(deserializer)?;
value
.map(command_units_from_value)
.transpose()
.map_err(serde::de::Error::custom)
}
fn deserialize_execution_exports<'de, D>(
deserializer: D,
) -> Result<Option<Vec<ExecutionExportSpec>>, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = Option::<serde_json::Value>::deserialize(deserializer)?;
value
.map(execution_exports_from_value)
.transpose()
.map_err(serde::de::Error::custom)
}
fn execution_exports_from_value(
value: serde_json::Value,
) -> Result<Vec<ExecutionExportSpec>, String> {
match value {
serde_json::Value::String(json) => {
let value = serde_json::from_str(&json)
.map_err(|error| format!("Invalid export JSON: {error}"))?;
execution_exports_from_value(value)
}
serde_json::Value::Array(values) => {
let mut exports = Vec::new();
for value in values {
match value {
serde_json::Value::String(_) | serde_json::Value::Array(_) => {
exports.extend(execution_exports_from_value(value)?);
}
value => exports.push(
serde_json::from_value(value)
.map_err(|error| format!("Invalid export: {error}"))?,
),
}
}
Ok(exports)
}
value => serde_json::from_value(value)
.map(|export| vec![export])
.map_err(|error| format!("Invalid export: {error}")),
}
}
fn command_units_from_value(
value: serde_json::Value,
) -> Result<Vec<crate::model::CommandUnit>, String> {
match value {
serde_json::Value::String(json) => {
let value = serde_json::from_str(&json)
.map_err(|error| format!("Invalid commands JSON: {error}"))?;
command_units_from_value(value)
}
serde_json::Value::Array(values) => {
let mut commands = Vec::new();
for value in values {
match value {
serde_json::Value::String(_) | serde_json::Value::Array(_) => {
commands.extend(command_units_from_value(value)?);
}
value => commands.push(
serde_json::from_value(value)
.map_err(|error| format!("Invalid command: {error}"))?,
),
}
}
Ok(commands)
}
serde_json::Value::Object(object) if object.contains_key("commands") => {
match serde_json::from_value::<CommandGroupFile>(serde_json::Value::Object(object))
.map_err(|error| format!("Invalid commands object: {error}"))?
{
CommandGroupFile::Commands(commands)
| CommandGroupFile::Object { commands, .. } => Ok(commands),
}
}
value => serde_json::from_value(value)
.map(|command| vec![command])
.map_err(|error| format!("Invalid command: {error}")),
}
}
#[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,
verbosity: Option<String>,
#[incurs(alias = "v", count)]
#[serde(default)]
verbose: u32,
#[incurs(alias = "q", count)]
#[serde(default)]
quiet: u32,
#[incurs(deprecated)]
view: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ExecutionCancelOptions {
idempotency_key: String,
#[incurs(default = 5000)]
timeout_ms: u64,
verbosity: Option<String>,
#[incurs(alias = "v", count)]
#[serde(default)]
verbose: u32,
#[incurs(alias = "q", count)]
#[serde(default)]
quiet: u32,
#[incurs(deprecated)]
view: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ExecutionViewOptions {
verbosity: Option<String>,
#[incurs(alias = "v", count)]
#[serde(default)]
verbose: u32,
#[incurs(alias = "q", count)]
#[serde(default)]
quiet: u32,
#[incurs(deprecated)]
view: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RunLogsOptions {
#[incurs(default = 65536)]
tail_bytes: usize,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct LogQueryOptions {
#[incurs(default = 65536)]
tail_bytes: usize,
grep: Option<String>,
#[incurs(default = 2)]
context: usize,
#[incurs(default = 20)]
max_matches: usize,
lines: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct TelemetryStartOptions {
idempotency_key: String,
#[incurs(default = 250)]
interval_ms: u64,
#[incurs(default = 67108864)]
max_bytes: u64,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct TelemetryGetOptions {
grep: Option<String>,
#[incurs(default = 2)]
context: usize,
#[incurs(default = 20)]
max_matches: usize,
lines: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct TelemetryStopOptions {
idempotency_key: String,
}
#[derive(Serialize, JsonSchema)]
#[serde(untagged)]
enum TelemetryResponse {
Summary(Box<TelemetrySummary>),
Slice(TelemetrySlice),
}
#[derive(Serialize, JsonSchema)]
#[serde(untagged)]
enum LogResponse {
Tail(RunLogs),
Slice(crate::run::LogSlice),
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ExecutionListOptions {
#[incurs(default = 20)]
limit: usize,
cursor: Option<String>,
status: Option<ExecutionStatus>,
error_code: Option<String>,
parent: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RunWaitOptions {
timeout_ms: Option<u64>,
verbosity: Option<String>,
#[incurs(alias = "v", count)]
#[serde(default)]
verbose: u32,
#[incurs(alias = "q", count)]
#[serde(default)]
quiet: u32,
#[incurs(deprecated)]
view: Option<String>,
}
#[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>,
}
#[derive(Serialize, JsonSchema)]
struct SilentResponse {}
#[derive(Serialize, JsonSchema)]
struct ExecutionDetail {
outcome: ExecutionVerdict,
#[serde(flatten)]
execution: Box<Execution>,
}
#[derive(Serialize, JsonSchema)]
struct ExecutionInvocationDetail {
outcome: ExecutionVerdict,
#[serde(flatten)]
invocation: Box<ExecutionInvocation>,
}
#[derive(Serialize, JsonSchema)]
#[serde(untagged)]
enum ExecutionResponse {
Detail(Box<ExecutionDetail>),
Outcome(ExecutionOutcome),
Silent(SilentResponse),
}
#[derive(Serialize, JsonSchema)]
#[serde(untagged)]
enum ExecutionInvocationResponse {
Detail(Box<ExecutionInvocationDetail>),
Outcome(ExecutionOutcome),
Silent(SilentResponse),
}
struct VerbosityRequest<'a> {
level: Option<&'a str>,
view: Option<&'a str>,
verbose: u32,
quiet: u32,
}
macro_rules! verbosity_request {
($options:expr) => {
VerbosityRequest {
level: $options.verbosity.as_deref(),
view: $options.view.as_deref(),
verbose: $options.verbose,
quiet: $options.quiet,
}
};
}
fn verbosity<Output>(request: VerbosityRequest<'_>) -> Result<Verbosity, TypedResult<Output>> {
let base = if let Some(level) = request.level {
Verbosity::parse(level).map_err(|error| TypedResult::error("INVALID_VERBOSITY", error))?
} else if let Some(view) = request.view {
Verbosity::parse_view(view).map_err(|error| TypedResult::error("INVALID_VIEW", error))?
} else if let Some(context) = crate::process::request_verbosity() {
Verbosity::parse(&context)
.map_err(|error| TypedResult::error("INVALID_VERBOSITY", error))?
} else {
match Verbosity::from_env() {
Some(level) => level.map_err(|error| TypedResult::error("INVALID_VERBOSITY", error))?,
None => Verbosity::DEFAULT,
}
};
Ok(base.shift(request.verbose as i32 - request.quiet as i32))
}
fn invocation_exit_code(execution: &Execution) -> i32 {
execution.exit_code().unwrap_or(match execution.status {
ExecutionStatus::Completed => 0,
ExecutionStatus::Canceled => 128,
_ => 1,
})
}
fn execution_outcome(
execution: &Execution,
logs: Option<&RunLogs>,
replayed: bool,
level: Verbosity,
) -> ExecutionOutcome {
let id = execution.id.clone();
let exit_code = execution.exit_code();
let mut outcome = ExecutionOutcome {
id: id.clone(),
outcome: ExecutionVerdict::of_execution(execution),
status: None,
exit_code: None,
error_code: None,
replayed: None,
stdout_bytes: None,
stderr_bytes: None,
truncated: None,
inspect: Vec::new(),
logs: None,
};
if level <= Verbosity::Error {
return outcome;
}
let stdout_bytes = logs.map(|logs| logs.stdout.len());
let stderr_bytes = logs.map(|logs| logs.stderr.len());
let truncated = logs.map(|logs| logs.stdout_truncated || logs.stderr_truncated);
outcome.error_code = execution.recorded_error_code().map(ToString::to_string);
outcome.replayed = replayed.then_some(true);
outcome.truncated = truncated.filter(|truncated| *truncated);
if level == Verbosity::Warn {
return outcome;
}
outcome.status = Some(execution.status);
outcome.exit_code = exit_code;
outcome.replayed = Some(replayed);
outcome.stdout_bytes = stdout_bytes;
outcome.stderr_bytes = stderr_bytes;
outcome.truncated = truncated;
outcome.inspect = inspect_reads(execution, stdout_bytes, stderr_bytes);
if level == Verbosity::Info {
return outcome;
}
outcome.logs = logs.cloned();
outcome
}
fn inspect_reads(
execution: &Execution,
stdout_bytes: Option<usize>,
stderr_bytes: Option<usize>,
) -> Vec<String> {
let id = &execution.id;
let terminal = matches!(
execution.status,
ExecutionStatus::Completed | ExecutionStatus::Failed | ExecutionStatus::Canceled
);
let readable_logs = stdout_bytes.unwrap_or(1) > 0 || stderr_bytes.unwrap_or(1) > 0 || !terminal;
let mut inspect = Vec::new();
match execution.spec.program {
ExecutionProgram::Command { .. } if readable_logs => {
inspect.push(format!("apoc execution logs {id}"));
}
ExecutionProgram::Commands { .. } => {
if readable_logs {
inspect.push(format!("apoc execution logs {id}"));
}
inspect.push(format!("apoc execution list --parent {id}"));
}
ExecutionProgram::Poll { .. } => inspect.push(format!("apoc poll iterations {id}")),
ExecutionProgram::Command { .. } | ExecutionProgram::Javascript { .. } => {}
}
if inspect.is_empty() {
inspect.push(format!("apoc execution get {id}"));
}
inspect
}
fn execution_response(execution: Execution, level: Verbosity) -> ExecutionResponse {
match level {
Verbosity::Off => ExecutionResponse::Silent(SilentResponse {}),
Verbosity::Trace => ExecutionResponse::Detail(Box::new(ExecutionDetail {
outcome: ExecutionVerdict::of_execution(&execution),
execution: Box::new(execution),
})),
level => ExecutionResponse::Outcome(execution_outcome(&execution, None, false, level)),
}
}
fn invocation_response(
invocation: ExecutionInvocation,
level: Verbosity,
) -> ExecutionInvocationResponse {
match level {
Verbosity::Off => ExecutionInvocationResponse::Silent(SilentResponse {}),
Verbosity::Trace => {
ExecutionInvocationResponse::Detail(Box::new(ExecutionInvocationDetail {
outcome: ExecutionVerdict::of_execution(&invocation.execution),
invocation: Box::new(invocation),
}))
}
level => ExecutionInvocationResponse::Outcome(execution_outcome(
&invocation.execution,
invocation.logs.as_ref(),
invocation.replayed,
level,
)),
}
}
fn verdict_exit_code(execution: &Execution) -> i32 {
match (
ExecutionVerdict::of_execution(execution),
invocation_exit_code(execution),
) {
(ExecutionVerdict::Passed | ExecutionVerdict::Pending | ExecutionVerdict::Skipped, _) => 0,
(ExecutionVerdict::Failed, 0) => 1,
(_, code) => code,
}
}
fn invocation_result(
invocation: ExecutionInvocation,
level: Verbosity,
) -> TypedResult<ExecutionInvocationResponse> {
let code = verdict_exit_code(&invocation.execution);
TypedResult::ok_with_exit_code(invocation_response(invocation, level), 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>,
error_code: 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>,
error_code: 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,
error_code: options.error_code,
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, incurs::Options)]
struct GcOptions {
#[serde(default)]
apply: bool,
idempotency_key: Option<String>,
max_batches: Option<usize>,
}
#[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>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum CommandSurface {
Public,
CodeMode,
}
#[cfg(test)]
const CODE_MODE_EXCLUDED_GROUPS: &[&str] = &[
"daemon_",
"mcp_",
"code_",
"profile_",
"env_",
"recipe_",
"recording_",
"receipt_",
"capability_",
"action_",
"provider_",
"connector_",
"skill_",
"decider_",
];
pub fn build_cli() -> Cli {
build_cli_for_surface(CommandSurface::Public, None)
}
pub(crate) fn build_agent_cli_with_store(store: Option<Arc<crate::store::Store>>) -> Cli {
build_cli_for_surface(CommandSurface::CodeMode, store)
}
fn build_cli_for_surface(surface: CommandSurface, 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());
let cli = 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(debugger_cli())
.group(evidence_trace_cli())
.group(rr_cli())
.group(execution_cli())
.group(poll_cli())
.group(session_cli())
.group(lease_cli())
.group(reservation_cli())
.group(history_cli())
.group(event_cli())
.group(observe::observe_cli())
.group(hook_cli())
.group(intent_cli())
.command(
"wait",
tracked_typed::<(), WaitOptions, (), WaitOutput, _, _>(
"wait",
|context: TypedContext<(), WaitOptions, ()>| async move {
let ms = context.options.ms;
if ms > MAX_WAIT_MS {
return TypedResult::error(
"WAIT_LIMIT",
format!("Wait duration cannot exceed {MAX_WAIT_MS} ms"),
);
}
tokio::time::sleep(Duration::from_millis(ms)).await;
TypedResult::ok(WaitOutput { waited_ms: ms })
},
)
.description("Wait for a bounded duration on the host runtime.")
.mcp(read_only())
.done(),
)
.command(
"gc",
tracked_typed::<(), GcOptions, (), crate::daemon::GcReport, _, _>(
"gc",
|context: TypedContext<(), GcOptions, ()>| async move {
match DaemonClient
.call(
"gc.collect",
serde_json::json!({
"apply": context.options.apply,
"idempotency_key": context.options.idempotency_key,
"max_batches": context.options.max_batches
}),
)
.await
{
Ok(report) => TypedResult::ok(report),
Err(error) => TypedResult::error("GC_FAILED", error),
}
},
)
.description(
"Close orphaned executions, list or stop unowned background work past its lifetime, and delete terminal history past retention. Reports counts and a bounded sample without changing anything unless --apply is given.",
)
.mcp(destructive(true))
.destructive(true)
.done(),
)
.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(),
);
if surface == CommandSurface::CodeMode {
return cli;
}
cli.group(daemon_cli())
.group(code_cli())
.group(profile_cli())
.group(env_cli())
.group(recipe_cli())
.group(recording_cli())
.group(receipt_cli())
.group(capability_cli())
.group(action_cli())
.group(provider_cli())
.group(connector_cli())
.group(skill_cli())
.group(mcp_cli())
.group(decider_cli())
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct DeciderPutArgs {
name: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct DeciderPutOptions {
program: String,
verb: Option<Vec<String>>,
on_unavailable: String,
#[incurs(default = 2000)]
timeout_ms: u64,
#[serde(default)]
disabled: bool,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct IntentListOptions {
#[incurs(default = 50)]
limit: usize,
}
fn decider_cli() -> Cli {
Cli::create("decider")
.description("Register programs that answer what apoc is about to do. apoc ships none.")
.command(
"put",
tracked_typed::<DeciderPutArgs, DeciderPutOptions, (), crate::intent::Decider, _, _>(
"put",
|context: TypedContext<DeciderPutArgs, DeciderPutOptions, ()>| async move {
let on_unavailable = match context.options.on_unavailable.as_str() {
"allow" | "refuse" => context.options.on_unavailable.clone(),
other => {
return TypedResult::error(
"DECIDER_INVALID",
format!("--on-unavailable must be allow or refuse, not {other}"),
);
}
};
match DaemonClient
.call(
"decider.put",
serde_json::json!({
"name": context.args.name,
"program": context.options.program,
"verbs": context.options.verb.clone().unwrap_or_default(),
"timeout_ms": context.options.timeout_ms,
"on_unavailable": on_unavailable,
"enabled": !context.options.disabled,
}),
)
.await
{
Ok(decider) => TypedResult::ok(decider),
Err(error) => TypedResult::error("DECIDER_PUT_FAILED", error),
}
},
)
.description("Create or replace one decider.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"list",
tracked_typed::<(), (), (), Vec<crate::intent::Decider>, _, _>(
"list",
|_context: TypedContext<(), (), ()>| async move {
match DaemonClient
.call("decider.list", serde_json::json!({}))
.await
{
Ok(deciders) => TypedResult::ok(deciders),
Err(error) => TypedResult::error("DECIDER_LIST_FAILED", error),
}
},
)
.description("List registered deciders.")
.mcp(read_only())
.done(),
)
.command(
"remove",
tracked_typed::<NameArgs, (), (), RemoveOutput, _, _>(
"remove",
|context: TypedContext<NameArgs, (), ()>| async move {
match DaemonClient
.call(
"decider.remove",
serde_json::json!({"name": context.args.name}),
)
.await
{
Ok(removed) => TypedResult::ok(removed),
Err(error) => TypedResult::error("DECIDER_REMOVE_FAILED", error),
}
},
)
.description("Remove one decider.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn intent_cli() -> Cli {
Cli::create("intent")
.description("Read what deciders were asked about, and what happened.")
.command(
"list",
tracked_typed::<(), IntentListOptions, (), Vec<crate::intent::IntentRecord>, _, _>(
"list",
|context: TypedContext<(), IntentListOptions, ()>| async move {
match DaemonClient
.call(
"intent.list",
serde_json::json!({"limit": context.options.limit}),
)
.await
{
Ok(records) => TypedResult::ok(records),
Err(error) => TypedResult::error("INTENT_LIST_FAILED", error),
}
},
)
.description(
"List intents deciders were asked about, newest first. An unchecked intent is one no decider ruled on.",
)
.mcp(read_only())
.done(),
)
}
fn mcp_cli() -> Cli {
Cli::create("mcp")
.description("Inspect the MCP servers configured elsewhere on this machine.")
.command(
"check",
tracked_typed::<(), (), (), crate::code::McpCheckOutput, _, _>(
"check",
|_context: TypedContext<(), (), ()>| async move {
match crate::code::mcp_check() {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("MCP_CHECK_FAILED", error),
}
},
)
.description("Report every discovered MCP server without starting any of them. Discovery is unconditional; APOC_MCP_ROOT treats one directory as the whole machine, which is how a sandboxed run isolates itself.")
.mcp(read_only())
.done(),
)
.command(
"refresh",
tracked_typed::<(), (), (), crate::code::McpRefreshOutput, _, _>(
"refresh",
|_context: TypedContext<(), (), ()>| async move {
match crate::code::mcp_refresh().await {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("MCP_REFRESH_FAILED", error),
}
},
)
.description("Contact every discovered MCP server and cache its tool schema. This is the only command that deliberately starts downstream servers.")
.mcp(destructive(false))
.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 {
verbosity: Option<String>,
#[incurs(alias = "v", count)]
#[serde(default)]
verbose: u32,
#[incurs(alias = "q", count)]
#[serde(default)]
quiet: u32,
#[incurs(deprecated)]
view: Option<String>,
#[incurs(default = 300000)]
timeout_ms: u64,
profile: Option<String>,
#[serde(default)]
telemetry: bool,
telemetry_interval_ms: Option<u64>,
telemetry_max_bytes: Option<u64>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct CodeStartOptions {
verbosity: Option<String>,
#[incurs(alias = "v", count)]
#[serde(default)]
verbose: u32,
#[incurs(alias = "q", count)]
#[serde(default)]
quiet: u32,
#[incurs(deprecated)]
view: Option<String>,
profile: Option<String>,
#[serde(default)]
telemetry: bool,
telemetry_interval_ms: Option<u64>,
telemetry_max_bytes: Option<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,
profile: Option<String>,
}
#[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,
profile: Option<String>,
cwd: Option<String>,
idempotency_key: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct EnvironmentLookupOptions {
#[serde(default)]
global: bool,
profile: Option<String>,
cwd: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct ProfileNameArgs {
name: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct ProfileRootArgs {
name: String,
path: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct ProfileDefaultArgs {
name: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ProfileMutationOptions {
idempotency_key: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ProfileDefaultOptions {
#[serde(default)]
clear: bool,
idempotency_key: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ProfileResolveOptions {
cwd: Option<String>,
profile: 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::Args)]
struct HookPutArgs {
name: String,
command: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct HookPutOptions {
on_start: Option<String>,
on_success: Option<String>,
on_failure: Option<String>,
#[serde(default)]
disabled: bool,
#[incurs(default = 3)]
max_attempts: u32,
#[incurs(default = 300000)]
timeout_ms: u64,
#[serde(default)]
global: bool,
cwd: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct HookScopeOptions {
#[serde(default)]
global: bool,
cwd: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct HookDeliveryArgs {
id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct HookDeliveryListOptions {
hook: Option<String>,
status: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecipeRunOptions {
#[incurs(default = 300000)]
timeout_ms: u64,
input: Option<String>,
#[serde(default)]
global: bool,
cwd: Option<String>,
profile: 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::Args)]
struct RecordingStartArgs {
name: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecordingStopArgs {
name: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecordingStartOptions {
#[serde(default)]
replace: bool,
#[serde(default)]
global: bool,
cwd: Option<String>,
idempotency_key: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecordingParamArgs {
assignment: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecordingParamOptions {
#[serde(default)]
json: bool,
#[serde(default)]
global: bool,
cwd: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecordingLiteralArgs {
path: String,
}
#[derive(Serialize, Deserialize, incurs::Args)]
struct RecordingIdArgs {
id: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecordingScopeOptions {
#[serde(default)]
global: bool,
cwd: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecordingStopOptions {
#[serde(default)]
suggest: bool,
#[serde(default)]
skip: Vec<String>,
ttl_ms: Option<u64>,
#[serde(default)]
replace: bool,
#[serde(default)]
global: bool,
cwd: Option<String>,
idempotency_key: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct RecordingMutationOptions {
#[serde(default)]
global: bool,
cwd: Option<String>,
idempotency_key: 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>>,
#[incurs(default = "none")]
profile_mode: String,
profile_header: Option<Vec<String>>,
idempotency_key: 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>>,
#[incurs(default = "none")]
profile_mode: String,
profile_env: Option<Vec<String>>,
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ProviderProfileOptions {
profile: Option<String>,
cwd: Option<String>,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ProviderMutationOptions {
idempotency_key: String,
}
#[derive(Serialize, Deserialize, incurs::Options)]
struct ProviderRefreshOptions {
profile: Option<String>,
cwd: Option<String>,
idempotency_key: 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 {
let level = match verbosity(verbosity_request!(context.options)) {
Ok(level) => level,
Err(error) => return error,
};
let telemetry = match telemetry_policy(
context.options.telemetry,
context.options.telemetry_interval_ms,
context.options.telemetry_max_bytes,
) {
Ok(policy) => policy,
Err(error) => return TypedResult::error("INVALID_TELEMETRY", error),
};
match crate::process::with_request_verbosity(
level.as_str().to_string(),
DaemonClient.call(
"code.run",
serde_json::json!({
"code": context.args.code,
"timeout_ms": context.options.timeout_ms,
"profile": context.options.profile,
"purpose": invocation_purpose(&context.globals),
"idempotency_key": context.globals.get("idempotency_key"),
"telemetry": telemetry,
}),
),
)
.await
{
Ok(state) => projected_code_result(state, true, level).await,
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, CodeStartOptions, (), serde_json::Value, _, _>(
"start",
|context: TypedContext<CodeArgs, CodeStartOptions, ()>| async move {
let level = match verbosity(verbosity_request!(context.options)) {
Ok(level) => level,
Err(error) => return error,
};
let telemetry = match telemetry_policy(
context.options.telemetry,
context.options.telemetry_interval_ms,
context.options.telemetry_max_bytes,
) {
Ok(policy) => policy,
Err(error) => return TypedResult::error("INVALID_TELEMETRY", error),
};
match crate::process::with_request_verbosity(
level.as_str().to_string(),
DaemonClient.call(
"code.start",
serde_json::json!({
"code": context.args.code,
"profile": context.options.profile,
"purpose": invocation_purpose(&context.globals),
"idempotency_key": context.globals.get("idempotency_key"),
"telemetry": telemetry,
}),
),
)
.await
{
Ok(state) => projected_code_result(state, false, level).await,
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, ExecutionViewOptions, (), serde_json::Value, _, _>(
"get",
|context: TypedContext<CodeIdArgs, ExecutionViewOptions, ()>| async move {
let level = match verbosity(verbosity_request!(context.options)) {
Ok(level) => level,
Err(error) => return error,
};
match DaemonClient
.call::<serde_json::Value>(
"code.get",
serde_json::json!({ "id": context.args.id }),
)
.await
{
Ok(state) => match serde_json::from_value(state.clone()) {
Ok(parsed) => {
TypedResult::ok(crate::code::project_execution(parsed, level))
}
Err(_) => 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, ExecutionViewOptions, (), serde_json::Value, _, _>(
"cancel",
|context: TypedContext<CodeIdArgs, ExecutionViewOptions, ()>| async move {
let level = match verbosity(verbosity_request!(context.options)) {
Ok(level) => level,
Err(error) => return error,
};
match crate::process::with_request_verbosity(
level.as_str().to_string(),
DaemonClient
.call("code.cancel", serde_json::json!({ "id": context.args.id })),
)
.await
{
Ok(state) => projected_code_result(state, false, level).await,
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",
discovery_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",
discovery_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(),
)
}
async fn projected_code_result(
summary: serde_json::Value,
report_failure: bool,
level: Verbosity,
) -> TypedResult<serde_json::Value> {
let parsed = match serde_json::from_value::<incurs_codemode::ExecutionState>(summary.clone()) {
Ok(state) => state,
Err(_) => {
let Some(id) = summary.get("id").and_then(serde_json::Value::as_str) else {
return TypedResult::error(
"CODE_RESPONSE_INVALID",
"Code Mode returned no execution ID",
);
};
match DaemonClient
.call::<incurs_codemode::ExecutionState>(
"code.get",
serde_json::json!({ "id": id }),
)
.await
{
Ok(state) => state,
Err(error) => {
return TypedResult::error("CODE_GET_FAILED", format!("{id}: {error}"));
}
}
}
};
let exit_code = if report_failure {
code_run_exit_code(&summary)
} else {
0
};
TypedResult::ok_with_exit_code(crate::code::project_execution(parsed, level), exit_code)
}
fn code_run_exit_code(state: &serde_json::Value) -> i32 {
i32::from(matches!(
state.get("status").and_then(serde_json::Value::as_str),
Some("error" | "rejected" | "rolled_back" | "cancelled")
))
}
fn code_run_result(state: serde_json::Value) -> TypedResult<serde_json::Value> {
let exit_code = code_run_exit_code(&state);
TypedResult::ok_with_exit_code(state, exit_code)
}
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",
provider_action_run_params(
code,
context.options.timeout_ms,
&context.globals,
context.options.profile,
),
)
.await
{
Ok(output) => code_run_result(output),
Err(error) => TypedResult::error("ACTION_FAILED", error),
}
},
)
.description("Invoke one capability and wait for its durable terminal state.")
.mcp(destructive_open_world(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",
provider_action_start_params(
code,
&context.globals,
context.options.profile,
),
)
.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_open_world(false))
.done(),
)
}
fn provider_action_run_params(
code: String,
timeout_ms: u64,
globals: &Value,
profile: Option<String>,
) -> Value {
let mut params = serde_json::json!({
"code": code,
"timeout_ms": timeout_ms,
"purpose": invocation_purpose(globals),
});
if let Some(profile) = profile {
params["profile"] = Value::String(profile);
}
params
}
fn provider_action_start_params(code: String, globals: &Value, profile: Option<String>) -> Value {
let mut params = serde_json::json!({
"code": code,
"purpose": invocation_purpose(globals),
});
if let Some(profile) = profile {
params["profile"] = Value::String(profile);
}
params
}
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 profile_root_cli() -> Cli {
Cli::create("root")
.description("Map canonical workspace roots to isolated profiles.")
.command(
"add",
tracked_typed::<ProfileRootArgs, ProfileMutationOptions, (), ProfileView, _, _>(
"add",
|context: TypedContext<ProfileRootArgs, ProfileMutationOptions, ()>| async move {
match DaemonClient
.call(
"profile.root.add",
serde_json::json!({
"name": context.args.name,
"path": context.args.path,
"idempotency_key": context.options.idempotency_key,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("PROFILE_ROOT_ADD_FAILED", error),
}
},
)
.description("Map one existing canonical workspace root to a profile.")
.mcp(destructive(true))
.done(),
)
.command(
"remove",
tracked_typed::<ProfileRootArgs, ProfileMutationOptions, (), ProfileView, _, _>(
"remove",
|context: TypedContext<ProfileRootArgs, ProfileMutationOptions, ()>| async move {
match DaemonClient
.call(
"profile.root.remove",
serde_json::json!({
"name": context.args.name,
"path": context.args.path,
"idempotency_key": context.options.idempotency_key,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("PROFILE_ROOT_REMOVE_FAILED", error),
}
},
)
.description("Remove one exact canonical workspace-root mapping.")
.mcp(destructive(true))
.done(),
)
}
fn profile_cli() -> Cli {
Cli::create("profile")
.description("Manage isolated environment profiles and workspace selection.")
.command(
"create",
tracked_typed::<ProfileNameArgs, ProfileMutationOptions, (), ProfileView, _, _>(
"create",
|context: TypedContext<ProfileNameArgs, ProfileMutationOptions, ()>| async move {
match DaemonClient
.call(
"profile.create",
serde_json::json!({
"name": context.args.name,
"idempotency_key": context.options.idempotency_key,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("PROFILE_CREATE_FAILED", error),
}
},
)
.description("Create one empty isolated profile.")
.mcp(destructive(true))
.done(),
)
.command(
"list",
tracked_typed::<(), (), (), Vec<ProfileView>, _, _>("list", |_| async move {
match DaemonClient.call("profile.list", serde_json::json!({})).await {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("PROFILE_LIST_FAILED", error),
}
})
.description("List profiles without returning stored or resolved values.")
.mcp(read_only())
.done(),
)
.command(
"show",
tracked_typed::<ProfileNameArgs, (), (), ProfileView, _, _>(
"show",
|context: TypedContext<ProfileNameArgs, (), ()>| async move {
match DaemonClient
.call("profile.show", serde_json::json!({ "name": context.args.name }))
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("PROFILE_SHOW_FAILED", error),
}
},
)
.description("Show one secret-safe profile definition.")
.mcp(read_only())
.done(),
)
.command(
"remove",
tracked_typed::<ProfileNameArgs, ProfileMutationOptions, (), serde_json::Value, _, _>(
"remove",
|context: TypedContext<ProfileNameArgs, ProfileMutationOptions, ()>| async move {
match DaemonClient
.call(
"profile.remove",
serde_json::json!({
"name": context.args.name,
"idempotency_key": context.options.idempotency_key,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("PROFILE_REMOVE_FAILED", error),
}
},
)
.description("Remove one profile that owns no roots or user default.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"default",
tracked_typed::<ProfileDefaultArgs, ProfileDefaultOptions, (), serde_json::Value, _, _>(
"default",
|context: TypedContext<ProfileDefaultArgs, ProfileDefaultOptions, ()>| async move {
match DaemonClient
.call(
"profile.default",
serde_json::json!({
"name": context.args.name,
"clear": context.options.clear,
"idempotency_key": context.options.idempotency_key,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("PROFILE_DEFAULT_FAILED", error),
}
},
)
.description("Set or clear the per-user default profile.")
.mcp(destructive(true))
.done(),
)
.command(
"resolve",
tracked_typed::<(), ProfileResolveOptions, (), ProfileResolution, _, _>(
"resolve",
|context: TypedContext<(), ProfileResolveOptions, ()>| async move {
match DaemonClient
.call(
"profile.resolve",
serde_json::json!({
"cwd": context.options.cwd,
"profile": context.options.profile,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("PROFILE_RESOLVE_FAILED", error),
}
},
)
.description("Resolve the profile selected for one workspace.")
.mcp(read_only())
.done(),
)
.command(
"doctor",
tracked_typed::<(), ProfileResolveOptions, (), ProfileResolution, _, _>(
"doctor",
|context: TypedContext<(), ProfileResolveOptions, ()>| async move {
match DaemonClient
.call(
"profile.doctor",
serde_json::json!({
"cwd": context.options.cwd,
"profile": context.options.profile,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("PROFILE_DOCTOR_FAILED", error),
}
},
)
.description("Check profile selection and secret resolvability without returning values.")
.mcp(read_only())
.done(),
)
.group(profile_root_cli())
}
fn env_cli() -> Cli {
Cli::create("env")
.description("Manage values and unresolved secret references in one selected profile.")
.command(
"set",
tracked_typed::<EnvironmentSetArgs, EnvironmentMutationOptions, (), Option<ProfileView>, _, _>(
"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,
"profile": context.options.profile,
"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 selected profile.")
.mcp(destructive(true))
.done(),
)
.command(
"secret",
tracked_typed::<EnvironmentSecretArgs, EnvironmentMutationOptions, (), Option<ProfileView>, _, _>(
"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,
"profile": context.options.profile,
"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, (), Option<ProfileView>, _, _>(
"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,
"profile": context.options.profile,
"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 profile.")
.mcp(destructive(true))
.done(),
)
.command(
"clear",
tracked_typed::<(), EnvironmentMutationOptions, (), Option<ProfileView>, _, _>(
"clear",
|context: TypedContext<(), EnvironmentMutationOptions, ()>| async move {
match DaemonClient.call("env.clear", serde_json::json!({
"name": null,
"value": null,
"secret": null,
"global": context.options.global,
"profile": context.options.profile,
"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 every value from the selected profile.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"list",
tracked_typed::<(), EnvironmentLookupOptions, (), Option<ProfileView>, _, _>(
"list",
|context: TypedContext<(), EnvironmentLookupOptions, ()>| async move {
match DaemonClient.call("env.list", serde_json::json!({
"global": context.options.global,
"profile": context.options.profile,
"cwd": context.options.cwd,
})).await {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("ENV_LIST_FAILED", error),
}
},
)
.description("List selected profile names without values or secret references.")
.mcp(read_only())
.done(),
)
.command(
"doctor",
tracked_typed::<(), EnvironmentLookupOptions, (), Option<ProfileView>, _, _>(
"doctor",
|context: TypedContext<(), EnvironmentLookupOptions, ()>| async move {
match DaemonClient.call("env.doctor", serde_json::json!({
"global": context.options.global,
"profile": context.options.profile,
"cwd": context.options.cwd,
})).await {
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("ENV_DOCTOR_FAILED", error),
}
},
)
.description("Check whether selected profile values can resolve.")
.mcp(read_only())
.done(),
)
}
fn recording_cli() -> Cli {
Cli::create("recording")
.description("Capture ordinary apoc work and promote it to a durable recipe.")
.command(
"start",
tracked_typed::<RecordingStartArgs, RecordingStartOptions, (), Recording, _, _>(
"start",
|context: TypedContext<RecordingStartArgs, RecordingStartOptions, ()>| async move {
match DaemonClient
.call(
"recording.start",
serde_json::json!({
"name": context.args.name,
"replace": context.options.replace,
"global": context.options.global,
"cwd": context.options.cwd,
"idempotency_key": context.options.idempotency_key,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECORDING_START_FAILED", error),
}
},
)
.description("Start or extend a capture session that becomes one named recipe.")
.mcp(destructive(true))
.done(),
)
.command(
"param",
tracked_typed::<RecordingParamArgs, RecordingParamOptions, (), Recording, _, _>(
"param",
|context: TypedContext<RecordingParamArgs, RecordingParamOptions, ()>| async move {
match DaemonClient
.call(
"recording.param",
serde_json::json!({
"assignment": context.args.assignment,
"json": context.options.json,
"global": context.options.global,
"cwd": context.options.cwd,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECORDING_PARAM_FAILED", error),
}
},
)
.description("Pin one recorded value as a required recipe input.")
.mcp(destructive(true))
.done(),
)
.command(
"literal",
tracked_typed::<RecordingLiteralArgs, RecordingParamOptions, (), Recording, _, _>(
"literal",
|context: TypedContext<RecordingLiteralArgs, RecordingParamOptions, ()>| async move {
match DaemonClient
.call(
"recording.literal",
serde_json::json!({
"path": context.args.path,
"global": context.options.global,
"cwd": context.options.cwd,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECORDING_LITERAL_FAILED", error),
}
},
)
.description("Force one recorded JSON path to stay literal in every step.")
.mcp(destructive(true))
.done(),
)
.command(
"status",
tracked_typed::<(), RecordingScopeOptions, (), Option<RecordingDetail>, _, _>(
"status",
|context: TypedContext<(), RecordingScopeOptions, ()>| async move {
match DaemonClient
.call(
"recording.status",
serde_json::json!({
"global": context.options.global,
"cwd": context.options.cwd,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECORDING_STATUS_FAILED", error),
}
},
)
.description("Read the active recording and the steps it would emit today.")
.mcp(read_only())
.done(),
)
.command(
"list",
tracked_typed::<(), RecordingScopeOptions, (), Vec<Recording>, _, _>(
"list",
|context: TypedContext<(), RecordingScopeOptions, ()>| async move {
match DaemonClient
.call(
"recording.list",
serde_json::json!({
"global": context.options.global,
"cwd": context.options.cwd,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECORDING_LIST_FAILED", error),
}
},
)
.description("List recordings in the selected scope, newest first.")
.mcp(read_only())
.done(),
)
.command(
"get",
tracked_typed::<RecordingIdArgs, (), (), RecordingDetail, _, _>(
"get",
|context: TypedContext<RecordingIdArgs, (), ()>| async move {
match DaemonClient
.call(
"recording.get",
serde_json::json!({ "id": context.args.id }),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECORDING_GET_FAILED", error),
}
},
)
.description("Get one recording and its ordered call sites.")
.mcp(read_only())
.done(),
)
.command(
"discard",
tracked_typed::<(), RecordingMutationOptions, (), Recording, _, _>(
"discard",
|context: TypedContext<(), RecordingMutationOptions, ()>| async move {
match DaemonClient
.call(
"recording.discard",
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("RECORDING_DISCARD_FAILED", error),
}
},
)
.description("End the active recording without emitting anything.")
.mcp(destructive(true))
.done(),
)
.command(
"stop",
tracked_typed::<RecordingStopArgs, RecordingStopOptions, (), RecordingStopOutput, _, _>(
"stop",
|context: TypedContext<RecordingStopArgs, RecordingStopOptions, ()>| async move {
match DaemonClient
.call(
"recording.stop",
serde_json::json!({
"name": context.args.name,
"suggest": context.options.suggest,
"skip": context.options.skip,
"ttl_ms": context.options.ttl_ms,
"replace": context.options.replace,
"global": context.options.global,
"cwd": context.options.cwd,
"idempotency_key": context.options.idempotency_key,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("RECORDING_STOP_FAILED", error),
}
},
)
.description("Transcribe the recording into a runnable recipe or a candidate.")
.mcp(destructive(true))
.done(),
)
}
fn hook_cli() -> Cli {
Cli::create("hook")
.description("Run durable JavaScript in response to typed apoc calls.")
.command(
"put",
tracked_typed::<HookPutArgs, HookPutOptions, (), Hook, _, _>(
"put",
|context: TypedContext<HookPutArgs, HookPutOptions, ()>| async move {
match DaemonClient
.call(
"hook.put",
serde_json::json!({
"name": context.args.name,
"command": context.args.command,
"on_start": context.options.on_start,
"on_success": context.options.on_success,
"on_failure": context.options.on_failure,
"enabled": !context.options.disabled,
"max_attempts": context.options.max_attempts,
"timeout_ms": context.options.timeout_ms,
"global": context.options.global,
"cwd": context.options.cwd,
}),
)
.await
{
Ok(hook) => TypedResult::ok(hook),
Err(error) => TypedResult::error("HOOK_PUT_FAILED", error),
}
},
)
.description("Create or replace one exact-command hook.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"get",
tracked_typed::<NameArgs, HookScopeOptions, (), Hook, _, _>(
"get",
|context: TypedContext<NameArgs, HookScopeOptions, ()>| async move {
match DaemonClient
.call(
"hook.get",
serde_json::json!({
"name": context.args.name,
"global": context.options.global,
"cwd": context.options.cwd,
}),
)
.await
{
Ok(hook) => TypedResult::ok(hook),
Err(error) => TypedResult::error("HOOK_GET_FAILED", error),
}
},
)
.description("Get one visible hook definition.")
.mcp(read_only())
.done(),
)
.command(
"list",
tracked_typed::<(), HookScopeOptions, (), Vec<Hook>, _, _>(
"list",
|context: TypedContext<(), HookScopeOptions, ()>| async move {
match DaemonClient
.call(
"hook.list",
serde_json::json!({
"global": context.options.global,
"cwd": context.options.cwd,
}),
)
.await
{
Ok(hooks) => TypedResult::ok(hooks),
Err(error) => TypedResult::error("HOOK_LIST_FAILED", error),
}
},
)
.description("List visible hook definitions.")
.mcp(read_only())
.done(),
)
.command(
"remove",
tracked_typed::<NameArgs, HookScopeOptions, (), RemoveOutput, _, _>(
"remove",
|context: TypedContext<NameArgs, HookScopeOptions, ()>| async move {
match DaemonClient
.call(
"hook.remove",
serde_json::json!({
"name": context.args.name,
"global": context.options.global,
"cwd": context.options.cwd,
}),
)
.await
{
Ok(output) => TypedResult::ok(output),
Err(error) => TypedResult::error("HOOK_REMOVE_FAILED", error),
}
},
)
.description("Delete one hook definition from the selected scope.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"delivery",
tracked_typed::<HookDeliveryArgs, (), (), HookDelivery, _, _>(
"delivery",
|context: TypedContext<HookDeliveryArgs, (), ()>| async move {
match DaemonClient
.call("hook.delivery", serde_json::json!({"id": context.args.id}))
.await
{
Ok(delivery) => TypedResult::ok(delivery),
Err(error) => TypedResult::error("HOOK_DELIVERY_FAILED", error),
}
},
)
.description("Get one durable hook delivery.")
.mcp(read_only())
.done(),
)
.command(
"deliveries",
tracked_typed::<(), HookDeliveryListOptions, (), Vec<HookDelivery>, _, _>(
"deliveries",
|context: TypedContext<(), HookDeliveryListOptions, ()>| async move {
match DaemonClient
.call(
"hook.deliveries",
serde_json::json!({
"hook": context.options.hook,
"status": context.options.status,
}),
)
.await
{
Ok(deliveries) => TypedResult::ok(deliveries),
Err(error) => TypedResult::error("HOOK_DELIVERIES_FAILED", error),
}
},
)
.description("List durable hook deliveries and outcomes.")
.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,
"profile": context.options.profile,
"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),
};
let profile_headers = match parse_env(
context
.options
.profile_header
.as_deref()
.unwrap_or_default(),
) {
Ok(headers) => headers,
Err(error) => return TypedResult::error("INVALID_PROFILE_HEADER", error),
};
let profile_mode = match parse_profile_mode(&context.options.profile_mode) {
Ok(mode) => mode,
Err(error) => return TypedResult::error("INVALID_PROFILE_MODE", 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();
let config = 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,
profile_mode,
profile_env: BTreeMap::new(),
profile_headers,
instructions: context.options.instructions,
enabled: true,
generation: format!("config/{now}"),
created_at: now,
updated_at: now,
};
match DaemonClient
.call(
"connector.put",
serde_json::json!({
"config": config,
"idempotency_key": context.options.idempotency_key,
}),
)
.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 profile_env =
match parse_env(context.options.profile_env.as_deref().unwrap_or_default()) {
Ok(env) => env,
Err(error) => return TypedResult::error("INVALID_PROFILE_ENV", error),
};
let profile_mode = match parse_profile_mode(&context.options.profile_mode) {
Ok(mode) => mode,
Err(error) => return TypedResult::error("INVALID_PROFILE_MODE", error),
};
let now = now_ms();
let config = 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(),
profile_mode,
profile_env,
profile_headers: BTreeMap::new(),
instructions: context.options.instructions,
enabled: true,
generation: format!("config/{now}"),
created_at: now,
updated_at: now,
};
match DaemonClient
.call(
"provider.put",
serde_json::json!({
"config": config,
"idempotency_key": context.options.idempotency_key,
}),
)
.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, ProviderProfileOptions, (), serde_json::Value, _, _>(
"doctor",
|context: TypedContext<NameArgs, ProviderProfileOptions, ()>| async move {
match DaemonClient
.call(
"provider.doctor",
serde_json::json!({
"id": context.args.name,
"profile": context.options.profile,
"cwd": context.options.cwd,
}),
)
.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, ProviderRefreshOptions, (), serde_json::Value, _, _>(
"refresh",
|context: TypedContext<NameArgs, ProviderRefreshOptions, ()>| async move {
match DaemonClient
.call(
"provider.refresh",
serde_json::json!({
"id": context.args.name,
"profile": context.options.profile,
"cwd": context.options.cwd,
"idempotency_key": context.options.idempotency_key
}),
)
.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, ProviderMutationOptions, (), RemoveOutput, _, _>(
"remove",
|context: TypedContext<NameArgs, ProviderMutationOptions, ()>| async move {
match DaemonClient
.call(
"provider.remove",
serde_json::json!({
"id": context.args.name,
"idempotency_key": context.options.idempotency_key
}),
)
.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<ExecutionRequest, 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 expect = parse_expectation(ExpectationInput {
exit_code: options.expect_exit_code.clone(),
stdout_regex: options.expect_stdout_regex.clone(),
stderr_regex: options.expect_stderr_regex.clone(),
json_pointer: options.expect_json_pointer.clone(),
json_equals: options.expect_json_equals.clone(),
js: options.expect_js.clone(),
})?;
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;
let profile = options.profile;
let backend = execution_backend(ExecutionBackendInput {
provider: options.provider,
provider_generation: options.provider_generation,
provider_options: options.provider_options,
isolated: options.isolated,
image: options.image,
workspace_mode: options.workspace_mode,
guest_cwd: options.guest_cwd,
memory_mb: options.memory_mb,
cpu_count: options.cpu_count,
pids_max: options.pids_max,
network: options.network,
exports: options.export,
})?;
let telemetry = telemetry_policy(
options.telemetry,
options.telemetry_interval_ms,
options.telemetry_max_bytes,
)?;
Ok((
ExecutionSpec {
schema_version: SCHEMA_VERSION,
idempotency_key: options.idempotency_key,
name,
purpose: options.purpose,
labels,
program: ExecutionProgram::Command {
argv,
shell: options.shell,
},
backend,
workspace: WorkspaceContext {
cwd: options.cwd,
..WorkspaceContext::default()
},
env,
secrets,
profile_selection: None,
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,
memory_bytes: options
.memory_limit_mb
.map(|value| {
value
.checked_mul(1024 * 1024)
.ok_or_else(|| "--memory-limit-mb overflows bytes".to_string())
})
.transpose()?,
cpu_percent: options.cpu_percent,
cpu_time_ms: options.cpu_time_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,
},
telemetry,
expect,
},
parent_id,
session_id,
profile,
))
}
#[derive(Default)]
struct ExecutionBackendInput {
provider: Option<String>,
provider_generation: Option<String>,
provider_options: Option<String>,
isolated: bool,
image: Option<String>,
workspace_mode: Option<String>,
guest_cwd: Option<String>,
memory_mb: Option<u64>,
cpu_count: Option<u32>,
pids_max: Option<u32>,
network: Option<String>,
exports: Option<Vec<ExecutionExportSpec>>,
}
fn execution_backend(input: ExecutionBackendInput) -> Result<ExecutionBackendSpec, String> {
let isolation_fields = input.image.is_some()
|| input.workspace_mode.is_some()
|| input.guest_cwd.is_some()
|| input.memory_mb.is_some()
|| input.cpu_count.is_some()
|| input.pids_max.is_some()
|| input.network.is_some()
|| input.exports.is_some();
if input.isolated {
if input.provider.is_some() {
return Err("--isolated cannot be combined with --provider".to_string());
}
if input.provider_generation.is_some() || input.provider_options.is_some() {
return Err(
"--provider-generation and --provider-options require --provider".to_string(),
);
}
let image = input.image.unwrap_or_else(|| "local".to_string());
validate_isolated_image(&image)?;
let workspace = match input.workspace_mode.as_deref().unwrap_or("read_write") {
"none" => IsolatedWorkspaceMode::None,
"read_write" => IsolatedWorkspaceMode::ReadWrite,
other => {
return Err(format!(
"Unknown --workspace-mode \"{other}\"; expected none or read_write"
));
}
};
let network = match input.network.as_deref().unwrap_or("none") {
"none" => IsolatedNetworkPolicy::None,
"nat" => IsolatedNetworkPolicy::Nat,
other => {
return Err(format!(
"Unknown --network \"{other}\"; expected none or nat"
));
}
};
if input
.guest_cwd
.as_deref()
.is_some_and(|cwd| !std::path::Path::new(cwd).is_absolute())
{
return Err("--guest-cwd must be absolute".to_string());
}
for (name, value) in [
("--memory-mb", input.memory_mb),
("--cpu-count", input.cpu_count.map(u64::from)),
("--pids-max", input.pids_max.map(u64::from)),
] {
if value == Some(0) {
return Err(format!("{name} must be at least 1"));
}
}
let exports = input.exports.unwrap_or_default();
let mut destinations = std::collections::BTreeSet::new();
for export in &exports {
if !std::path::Path::new(&export.source).is_absolute() {
return Err("--export source must be absolute inside the guest".to_string());
}
if export.destination.trim().is_empty() {
return Err("--export destination must not be empty".to_string());
}
if !destinations.insert(export.destination.as_str()) {
return Err(format!(
"Duplicate --export destination {:?}",
export.destination
));
}
}
return Ok(ExecutionBackendSpec::Isolated {
isolation: IsolatedExecutionSpec {
image,
workspace,
guest_cwd: input.guest_cwd,
memory_mb: input.memory_mb,
cpu_count: input.cpu_count,
pids_max: input.pids_max,
network,
exports,
},
});
}
if isolation_fields {
return Err("Isolation options require --isolated".to_string());
}
let Some(provider) = input.provider else {
if input.provider_generation.is_some() || input.provider_options.is_some() {
return Err(
"--provider-generation and --provider-options require --provider".to_string(),
);
}
return Ok(ExecutionBackendSpec::Native);
};
let generation = input
.provider_generation
.filter(|generation| !generation.is_empty())
.ok_or_else(|| "--provider requires --provider-generation".to_string())?;
let options = input
.provider_options
.map(|value| {
serde_json::from_str::<serde_json::Value>(&value)
.map_err(|error| format!("Invalid --provider-options JSON: {error}"))
})
.transpose()?
.unwrap_or_else(|| serde_json::json!({}));
if !options.is_object() {
return Err("--provider-options must be one JSON object".to_string());
}
Ok(ExecutionBackendSpec::Provider {
name: provider,
generation,
options,
})
}
fn validate_isolated_image(image: &str) -> Result<(), String> {
if image == "local" || std::path::Path::new(image).is_absolute() {
return Ok(());
}
if let Some(digest) = image.strip_prefix("sha256:")
&& digest.len() == 64
&& digest
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
{
return Ok(());
}
Err(
"--image must be local, an absolute bundle path, or sha256:<64 lowercase hex characters>"
.to_string(),
)
}
fn telemetry_policy(
enabled: bool,
interval_ms: Option<u64>,
max_bytes: Option<u64>,
) -> Result<TelemetryPolicy, String> {
if !enabled {
if interval_ms.is_some() || max_bytes.is_some() {
return Err(
"--telemetry-interval-ms and --telemetry-max-bytes require --telemetry".to_string(),
);
}
return Ok(TelemetryPolicy::Off);
}
let interval_ms = interval_ms.unwrap_or(DEFAULT_TELEMETRY_INTERVAL_MS);
let minimum_interval_ms = sysinfo::MINIMUM_CPU_UPDATE_INTERVAL.as_millis() as u64;
if interval_ms < minimum_interval_ms {
return Err(format!(
"--telemetry-interval-ms must be at least {minimum_interval_ms}"
));
}
let max_bytes = max_bytes.unwrap_or(DEFAULT_TELEMETRY_MAX_BYTES);
if max_bytes == 0 {
return Err("--telemetry-max-bytes must be greater than zero".to_string());
}
Ok(TelemetryPolicy::Sample {
interval_ms,
max_bytes,
})
}
struct ExpectationInput {
exit_code: Option<Vec<i32>>,
stdout_regex: Option<String>,
stderr_regex: Option<String>,
json_pointer: Option<String>,
json_equals: Option<String>,
js: Option<String>,
}
fn parse_expectation(input: ExpectationInput) -> Result<Option<PollCondition>, String> {
let mut declared = Vec::new();
if let Some(codes) = input.exit_code {
declared.push(PollCondition::ExitCode { codes });
}
if let Some(pattern) = input.stdout_regex {
Regex::new(&pattern).map_err(|error| format!("Invalid --expect-stdout-regex: {error}"))?;
declared.push(PollCondition::StdoutRegex { pattern });
}
if let Some(pattern) = input.stderr_regex {
Regex::new(&pattern).map_err(|error| format!("Invalid --expect-stderr-regex: {error}"))?;
declared.push(PollCondition::StderrRegex { pattern });
}
match (input.json_pointer, input.json_equals) {
(Some(pointer), Some(value)) => {
let value = serde_json::from_str(&value)
.map_err(|error| format!("Invalid --expect-json-equals JSON: {error}"))?;
declared.push(PollCondition::JsonEquals { pointer, value });
}
(Some(_), None) => {
return Err("--expect-json-pointer requires --expect-json-equals".to_string());
}
(None, Some(_)) => {
return Err("--expect-json-equals requires --expect-json-pointer".to_string());
}
(None, None) => {}
}
if let Some(expression) = input.js {
declared.push(PollCondition::Javascript { expression });
}
if declared.len() > 1 {
return Err(
"Declare one expectation. Combine checks inside --expect-js when you need several."
.to_string(),
);
}
Ok(declared.pop())
}
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>,
profile: Option<String>,
env: Option<Vec<String>>,
secret_env: Option<Vec<String>>,
owner: String,
session: Option<String>,
parent: Option<String>,
artifact_bytes: Option<u64>,
telemetry: bool,
telemetry_interval_ms: Option<u64>,
telemetry_max_bytes: Option<u64>,
}
fn poll_command_spec(
args: RunArgv,
options: PollCommandOptions,
) -> Result<ExecutionRequest, 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,
profile: options.profile,
env: options.env,
secret_env: options.secret_env,
owner: options.owner,
session: options.session,
parent: options.parent,
artifact_bytes: options.artifact_bytes,
telemetry: options.telemetry,
telemetry_interval_ms: options.telemetry_interval_ms,
telemetry_max_bytes: options.telemetry_max_bytes,
},
)
}
fn poll_apoc_spec(
args: PollMethodArgs,
options: PollApocOptions,
) -> Result<ExecutionRequest, 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,
profile: options.profile,
env: options.env,
secret_env: options.secret_env,
owner: options.owner,
session: options.session,
parent: options.parent,
artifact_bytes: options.artifact_bytes,
telemetry: options.telemetry,
telemetry_interval_ms: options.telemetry_interval_ms,
telemetry_max_bytes: options.telemetry_max_bytes,
},
)
}
fn poll_execution_spec(
target: PollTarget,
options: PollSpecOptions,
) -> Result<ExecutionRequest, 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 profile = options.profile;
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}"),
};
let telemetry = telemetry_policy(
options.telemetry,
options.telemetry_interval_ms,
options.telemetry_max_bytes,
)?;
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,
},
backend: ExecutionBackendSpec::default(),
workspace: WorkspaceContext {
cwd: options.cwd,
..WorkspaceContext::default()
},
env,
secrets,
profile_selection: None,
io: IoMode::Pipes,
owner_kind,
owner_id,
expires_at: None,
retry: RetryPolicy::default(),
budget: ExecutionBudget {
artifact_bytes: options.artifact_bytes,
..ExecutionBudget::default()
},
telemetry,
expect: None,
},
parent_id,
session_id,
profile,
))
}
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>,
profile: Option<String>,
session: Option<String>,
parent: Option<String>,
telemetry: bool,
telemetry_interval_ms: Option<u64>,
telemetry_max_bytes: Option<u64>,
topology: crate::model::CommandTopology,
}
fn command_group_spec(options: CommandGroupInput) -> Result<ExecutionRequest, 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());
let profile = options.profile;
let telemetry = telemetry_policy(
options.telemetry,
options.telemetry_interval_ms,
options.telemetry_max_bytes,
)?;
Ok((
ExecutionSpec {
schema_version: SCHEMA_VERSION,
idempotency_key: options.idempotency_key,
name,
purpose: options.purpose,
labels: BTreeMap::new(),
program: ExecutionProgram::Commands { commands, topology },
backend: ExecutionBackendSpec::default(),
workspace: WorkspaceContext {
cwd: options.cwd,
..WorkspaceContext::default()
},
env: BTreeMap::new(),
secrets: BTreeMap::new(),
profile_selection: None,
io: IoMode::Pipes,
owner_kind,
owner_id,
expires_at: None,
retry: RetryPolicy::default(),
budget: ExecutionBudget::default(),
telemetry,
expect: None,
},
options.parent,
options.session,
profile,
))
}
fn parse_env(values: &[String]) -> Result<std::collections::BTreeMap<String, String>, String> {
parse_pairs(values, "environment")
}
fn parse_profile_mode(value: &str) -> Result<ProfileMode, String> {
match value {
"none" => Ok(ProfileMode::None),
"optional" => Ok(ProfileMode::Optional),
"required" => Ok(ProfileMode::Required),
value => Err(format!(
"Unknown profile mode \"{value}\"; expected none, optional, or required"
)),
}
}
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 rr_cli() -> Cli {
let mut cli = Cli::create("rr").description(
"Record and replay native rr traces through apoc-owned executions and artifacts.",
);
cli = cli.command(
"record",
tracked_typed::<RunArgv, RrRecordOptions, (), RrExecutionResult, _, _>(
"record",
|context: TypedContext<RunArgv, RrRecordOptions, ()>| async move {
let backend = match rr_backend(
context.options.backend.as_deref(),
context.options.image.clone(),
) {
Ok(backend) => backend,
Err(error) => return TypedResult::error("INVALID_RR_BACKEND", error),
};
let env = match parse_env(context.options.env.as_deref().unwrap_or_default()) {
Ok(env) => env,
Err(error) => return TypedResult::error("INVALID_RR_ENV", error),
};
let mut command = vec![context.args.executable];
command.extend(context.args.arg.unwrap_or_default());
match DaemonClient
.execute(RrRecordOperation {
name: context.options.name,
command,
rr_executable: context.options.rr_executable,
backend,
cwd: context.options.cwd,
env,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("RR_RECORD_FAILED", error),
}
},
)
.description(
"Start rr record as a durable exact-argv execution and retain its trace in apoc CAS.",
)
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"replay",
tracked_typed::<RrTraceArgs, RrReplayOptions, (), RrExecutionResult, _, _>(
"replay",
|context: TypedContext<RrTraceArgs, RrReplayOptions, ()>| async move {
let backend = match rr_backend(
context.options.backend.as_deref(),
context.options.image.clone(),
) {
Ok(backend) => backend,
Err(error) => return TypedResult::error("INVALID_RR_BACKEND", error),
};
match DaemonClient
.execute(RrReplayOperation {
trace_id: context.args.trace_id,
rr_executable: context.options.rr_executable,
backend,
event: context.options.event,
pid: context.options.pid,
end: context.options.end,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("RR_REPLAY_FAILED", error),
}
},
)
.description(
"Start interactive rr replay as a durable PTY execution addressable by execution ID.",
)
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"ps",
tracked_typed::<RrTraceArgs, RrProcessStatusOptions, (), RrProcessStatus, _, _>(
"ps",
|context: TypedContext<RrTraceArgs, RrProcessStatusOptions, ()>| async move {
let backend = match rr_backend(
context.options.backend.as_deref(),
context.options.image.clone(),
) {
Ok(backend) => backend,
Err(error) => return TypedResult::error("INVALID_RR_BACKEND", error),
};
match DaemonClient
.execute(RrProcessStatusOperation {
trace_id: context.args.trace_id,
rr_executable: context.options.rr_executable,
backend,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("RR_PS_FAILED", error),
}
},
)
.description("Run rr ps as a durable one-shot execution and return its bounded logs.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"import",
tracked_typed::<RrImportArgs, RrImportOptions, (), RrTrace, _, _>(
"import",
|context: TypedContext<RrImportArgs, RrImportOptions, ()>| async move {
match DaemonClient
.execute(RrImportOperation {
path: context.args.path,
name: context.options.name,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("RR_IMPORT_FAILED", error),
}
},
)
.description(
"Archive and materialize an existing rr trace under apoc content-addressed ownership.",
)
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"list",
tracked_typed::<(), (), (), Vec<RrTrace>, _, _>(
"list",
|_context: TypedContext<(), (), ()>| async move {
match DaemonClient.execute(RrListOperation {}).await {
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("RR_LIST_FAILED", error),
}
},
)
.description("List durable rr trace records newest first.")
.mcp(read_only())
.done(),
);
cli.command(
"show",
tracked_typed::<RrTraceArgs, (), (), RrTrace, _, _>(
"show",
|context: TypedContext<RrTraceArgs, (), ()>| async move {
match DaemonClient
.execute(RrShowOperation {
trace_id: context.args.trace_id,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("RR_SHOW_FAILED", error),
}
},
)
.description("Show one durable rr trace and its execution and artifact links.")
.mcp(read_only())
.done(),
)
}
fn rr_backend(backend: Option<&str>, image: Option<String>) -> Result<RrBackend, String> {
let backend = backend.unwrap_or(if cfg!(target_os = "macos") {
"isolated"
} else {
"native"
});
match backend {
"native" => {
if image.is_some() {
return Err("--image requires --backend isolated".to_string());
}
Ok(RrBackend::Native)
}
"isolated" => Ok(RrBackend::Isolated {
image: image.unwrap_or_else(|| "local".to_string()),
}),
other => Err(format!(
"Unsupported rr backend \"{other}\"; expected native or isolated"
)),
}
}
fn evidence_trace_cli() -> Cli {
let mut cli = Cli::create("trace").description(
"Own durable debugger evidence traces, replay cursors, portable bundles, and retention.",
);
cli = cli.command(
"start",
tracked_typed::<
EvidenceTraceStartArgs,
DebuggerIdempotencyOptions,
(),
DebuggerEvidenceTrace,
_,
_,
>(
"start",
|context: TypedContext<
EvidenceTraceStartArgs,
DebuggerIdempotencyOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerEvidenceTraceStartOperation {
id: context.args.id,
name: context.args.name,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(trace) => TypedResult::ok(trace),
Err(error) => TypedResult::error("TRACE_START_FAILED", error),
}
},
)
.description("Start one evidence trace bound to an existing debugger session.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"stop",
tracked_typed::<
EvidenceTraceStopArgs,
DebuggerIdempotencyOptions,
(),
DebuggerEvidenceTrace,
_,
_,
>(
"stop",
|context: TypedContext<
EvidenceTraceStopArgs,
DebuggerIdempotencyOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerEvidenceTraceStopOperation {
id: context.args.id,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(trace) => TypedResult::ok(trace),
Err(error) => TypedResult::error("TRACE_STOP_FAILED", error),
}
},
)
.description("Complete the active evidence trace for one debugger session.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"list",
tracked_typed::<(), (), (), Vec<DebuggerEvidenceTrace>, _, _>(
"list",
|_context: TypedContext<(), (), ()>| async move {
match DaemonClient
.execute(DebuggerEvidenceTraceListOperation {})
.await
{
Ok(traces) => TypedResult::ok(traces),
Err(error) => TypedResult::error("TRACE_LIST_FAILED", error),
}
},
)
.description("List durable evidence traces newest first.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"show",
tracked_typed::<EvidenceTraceIdArgs, (), (), DebuggerEvidenceTraceView, _, _>(
"show",
|context: TypedContext<EvidenceTraceIdArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerEvidenceTraceShowOperation {
trace_id: context.args.trace_id,
})
.await
{
Ok(trace) => TypedResult::ok(trace),
Err(error) => TypedResult::error("TRACE_SHOW_FAILED", error),
}
},
)
.description("Show one trace and its bounded unified timeline.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"use",
tracked_typed::<
EvidenceTraceIdArgs,
DebuggerIdempotencyOptions,
(),
DebuggerEvidenceTrace,
_,
_,
>(
"use",
|context: TypedContext<
EvidenceTraceIdArgs,
DebuggerIdempotencyOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerEvidenceTraceUseOperation {
trace_id: context.args.trace_id,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(trace) => TypedResult::ok(trace),
Err(error) => TypedResult::error("TRACE_USE_FAILED", error),
}
},
)
.description("Select one trace for this actor cursor.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"replay",
tracked_typed::<
EvidenceTraceIdArgs,
EvidenceTraceReplayOptions,
(),
DebuggerTraceReplayResult,
_,
_,
>(
"replay",
|context: TypedContext<
EvidenceTraceIdArgs,
EvidenceTraceReplayOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerEvidenceTraceReplayOperation {
trace_id: context.args.trace_id,
at: context.options.at,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(trace) => TypedResult::ok(trace),
Err(error) => TypedResult::error("TRACE_REPLAY_FAILED", error),
}
},
)
.description("Select replay context and restore a capture anchor when available.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"export",
tracked_typed::<
EvidenceTraceIdArgs,
DebuggerIdempotencyOptions,
(),
DebuggerTraceExport,
_,
_,
>(
"export",
|context: TypedContext<
EvidenceTraceIdArgs,
DebuggerIdempotencyOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerEvidenceTraceExportOperation {
trace_id: context.args.trace_id,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(exported) => TypedResult::ok(exported),
Err(error) => TypedResult::error("TRACE_EXPORT_FAILED", error),
}
},
)
.description("Export one trace as a content-addressed JSON bundle artifact.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"import",
tracked_typed::<
EvidenceTraceImportArgs,
DebuggerIdempotencyOptions,
(),
DebuggerTraceImport,
_,
_,
>(
"import",
|context: TypedContext<
EvidenceTraceImportArgs,
DebuggerIdempotencyOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerEvidenceTraceImportOperation {
path: context.args.path,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(imported) => TypedResult::ok(imported),
Err(error) => TypedResult::error("TRACE_IMPORT_FAILED", error),
}
},
)
.description("Validate and import one JSON trace bundle into durable state and CAS.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"gc",
tracked_typed::<(), EvidenceTraceGcOptions, (), DebuggerTraceGc, _, _>(
"gc",
|context: TypedContext<(), EvidenceTraceGcOptions, ()>| async move {
match DaemonClient
.execute(DebuggerEvidenceTraceGcOperation {
keep: context.options.keep,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("TRACE_GC_FAILED", error),
}
},
)
.description("Remove older terminal trace records while preserving active traces.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"cursor",
tracked_typed::<(), EvidenceTraceCursorOptions, (), Option<DebuggerTraceCursor>, _, _>(
"cursor",
|context: TypedContext<(), EvidenceTraceCursorOptions, ()>| async move {
match DaemonClient
.execute(DebuggerEvidenceTraceCursorOperation {
trace_id: context.options.trace_id,
})
.await
{
Ok(cursor) => TypedResult::ok(cursor),
Err(error) => TypedResult::error("TRACE_CURSOR_FAILED", error),
}
},
)
.description("Read one explicit or actor-selected trace cursor.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"move",
tracked_typed::<
EvidenceTraceMoveArgs,
EvidenceTraceMoveOptions,
(),
DebuggerTraceCursor,
_,
_,
>(
"move",
|context: TypedContext<
EvidenceTraceMoveArgs,
EvidenceTraceMoveOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerEvidenceTraceMoveOperation {
direction: context.args.direction,
count: context.options.count,
kind: context.options.kind,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(cursor) => TypedResult::ok(cursor),
Err(error) => TypedResult::error("TRACE_MOVE_FAILED", error),
}
},
)
.description("Move backward or forward through the selected trace timeline.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli.command(
"jump",
tracked_typed::<
EvidenceTraceJumpArgs,
DebuggerIdempotencyOptions,
(),
DebuggerTraceCursor,
_,
_,
>(
"jump",
|context: TypedContext<
EvidenceTraceJumpArgs,
DebuggerIdempotencyOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerEvidenceTraceJumpOperation {
direction: context.args.direction,
count: 1,
kind: Some(context.args.kind),
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(cursor) => TypedResult::ok(cursor),
Err(error) => TypedResult::error("TRACE_JUMP_FAILED", error),
}
},
)
.description("Jump to the previous or next selected trace item of one kind.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn debugger_cli() -> Cli {
let mut cli = Cli::create("debugger").description(
"Attach to and control named Node.js and browser debugger sessions through the apoc daemon.",
);
cli = cli.command(
"run",
tracked_typed::<RunArgv, DebuggerRunOptions, (), DebuggerRunResult, _, _>(
"run",
|context: TypedContext<RunArgv, DebuggerRunOptions, ()>| async move {
let env = match parse_env(context.options.env.as_deref().unwrap_or_default()) {
Ok(env) => env,
Err(error) => return TypedResult::error("INVALID_DEBUGGER_ENV", error),
};
let mut argv = vec![context.args.executable];
argv.extend(context.args.arg.unwrap_or_default());
match DaemonClient
.execute(DebuggerRunOperation {
id: context.options.id,
host: context.options.host,
port: context.options.port,
argv,
cwd: context.options.cwd,
env,
timeout_ms: context.options.timeout_ms,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DEBUGGER_RUN_FAILED", error),
}
},
)
.description(
"Launch an exact-argv apoc execution, enable Node inspection when needed, and return its linked debugger session.",
)
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"open",
tracked_typed::<DebuggerOpenArgs, DebuggerOpenOptions, (), DebuggerSessionView, _, _>(
"open",
|context: TypedContext<DebuggerOpenArgs, DebuggerOpenOptions, ()>| async move {
match DaemonClient
.execute(DebuggerOpenOperation {
id: context.options.id,
host: context.options.host,
port: context.args.port,
target_id: context.options.target_id,
execution_id: context.options.execution_id,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(session) => TypedResult::ok(session),
Err(error) => TypedResult::error("DEBUGGER_OPEN_FAILED", error),
}
},
)
.description("Attach a named session to a running Node or browser CDP endpoint.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"status",
tracked_typed::<DebuggerSessionArgs, (), (), DebuggerSessionView, _, _>(
"status",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerStatusOperation {
id: context.args.id,
})
.await
{
Ok(session) => TypedResult::ok(session),
Err(error) => TypedResult::error("DEBUGGER_STATUS_FAILED", error),
}
},
)
.description("Read connection, pause, and top-frame state for one session.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"list",
tracked_typed::<(), (), (), Vec<DebuggerSessionRecord>, _, _>("list", |_| async move {
match DaemonClient.execute(DebuggerListOperation {}).await {
Ok(sessions) => TypedResult::ok(sessions),
Err(error) => TypedResult::error("DEBUGGER_LIST_FAILED", error),
}
})
.description("List durable debugger sessions, including disconnected and closed records.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"select",
tracked_typed::<DebuggerSessionArgs, DebuggerMutationOptions, (), DebuggerSelection, _, _>(
"select",
|context: TypedContext<DebuggerSessionArgs, DebuggerMutationOptions, ()>| async move {
match DaemonClient
.execute(DebuggerSelectOperation {
id: context.args.id,
idempotency_key: context.options.idempotency_key,
timeout_ms: context.options.timeout_ms,
})
.await
{
Ok(selection) => TypedResult::ok(selection),
Err(error) => TypedResult::error("DEBUGGER_SELECT_FAILED", error),
}
},
)
.description("Select one durable debugger session for the current apoc actor.")
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"selected",
tracked_typed::<(), (), (), Option<DebuggerSelection>, _, _>("selected", |_| async move {
match DaemonClient.execute(DebuggerSelectedOperation {}).await {
Ok(selection) => TypedResult::ok(selection),
Err(error) => TypedResult::error("DEBUGGER_SELECTED_FAILED", error),
}
})
.description("Read the actor-scoped durable debugger session selection.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"events",
tracked_typed::<DebuggerSessionArgs, DebuggerEventsOptions, (), Vec<DebuggerEvent>, _, _>(
"events",
|context: TypedContext<DebuggerSessionArgs, DebuggerEventsOptions, ()>| async move {
match DaemonClient
.execute(DebuggerEventsOperation {
id: context.args.id,
after: context.options.after,
limit: context.options.limit,
})
.await
{
Ok(events) => TypedResult::ok(events),
Err(error) => TypedResult::error("DEBUGGER_EVENTS_FAILED", error),
}
},
)
.description("Read durable debugger lifecycle and mutation events after a sequence cursor.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"targets",
tracked_typed::<DebuggerOpenArgs, DebuggerTargetsOptions, (), Vec<DebuggerTarget>, _, _>(
"targets",
|context: TypedContext<DebuggerOpenArgs, DebuggerTargetsOptions, ()>| async move {
match DaemonClient
.execute(DebuggerTargetsOperation {
host: context.options.host,
port: context.args.port,
})
.await
{
Ok(targets) => TypedResult::ok(targets),
Err(error) => TypedResult::error("DEBUGGER_TARGETS_FAILED", error),
}
},
)
.description(
"Discover Node or page CDP targets with stable identity and websocket endpoint.",
)
.mcp(read_only())
.done(),
);
cli = cli.command(
"stack",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<DebuggerFrame>, _, _>(
"stack",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerStackOperation {
id: context.args.id,
})
.await
{
Ok(frames) => TypedResult::ok(frames),
Err(error) => TypedResult::error("DEBUGGER_STACK_FAILED", error),
}
},
)
.description("Read the current paused call stack with one-based locations.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"scopes",
tracked_typed::<DebuggerFrameArgs, (), (), Vec<DebuggerScope>, _, _>(
"scopes",
|context: TypedContext<DebuggerFrameArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerScopesOperation {
id: context.args.id,
frame: context.args.frame,
})
.await
{
Ok(scopes) => TypedResult::ok(scopes),
Err(error) => TypedResult::error("DEBUGGER_SCOPES_FAILED", error),
}
},
)
.description("Read scope object identities for one paused frame.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"variables",
tracked_typed::<DebuggerFrameArgs, (), (), Vec<DebuggerVariable>, _, _>(
"variables",
|context: TypedContext<DebuggerFrameArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerVariablesOperation {
id: context.args.id,
frame: context.args.frame,
})
.await
{
Ok(variables) => TypedResult::ok(variables),
Err(error) => TypedResult::error("DEBUGGER_VARIABLES_FAILED", error),
}
},
)
.description("Read typed variables and child object identities for one paused frame.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"properties",
tracked_typed::<DebuggerObjectArgs, (), (), Vec<DebuggerProperty>, _, _>(
"properties",
|context: TypedContext<DebuggerObjectArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerPropertiesOperation {
id: context.args.id,
object_id: context.args.object_id,
})
.await
{
Ok(properties) => TypedResult::ok(properties),
Err(error) => TypedResult::error("DEBUGGER_PROPERTIES_FAILED", error),
}
},
)
.description("Read own and internal properties for one CDP object identity.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"prototypes",
tracked_typed::<
DebuggerObjectArgs,
DebuggerPrototypeOptions,
(),
Vec<DebuggerPrototype>,
_,
_,
>(
"prototypes",
|context: TypedContext<DebuggerObjectArgs, DebuggerPrototypeOptions, ()>| async move {
match DaemonClient
.execute(DebuggerPrototypesOperation {
id: context.args.id,
object_id: context.args.object_id,
limit: context.options.limit,
})
.await
{
Ok(prototypes) => TypedResult::ok(prototypes),
Err(error) => TypedResult::error("DEBUGGER_PROTOTYPES_FAILED", error),
}
},
)
.description("Walk bounded CDP prototype identities and their properties.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"listeners",
tracked_typed::<DebuggerObjectArgs, (), (), Vec<DebuggerListener>, _, _>(
"listeners",
|context: TypedContext<DebuggerObjectArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerListenersOperation {
id: context.args.id,
object_id: context.args.object_id,
})
.await
{
Ok(listeners) => TypedResult::ok(listeners),
Err(error) => TypedResult::error("DEBUGGER_LISTENERS_FAILED", error),
}
},
)
.description("Read event listeners for one CDP object identity.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"this",
tracked_typed::<DebuggerFrameArgs, (), (), Vec<DebuggerProperty>, _, _>(
"this",
|context: TypedContext<DebuggerFrameArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerThisOperation {
id: context.args.id,
frame: context.args.frame,
})
.await
{
Ok(properties) => TypedResult::ok(properties),
Err(error) => TypedResult::error("DEBUGGER_THIS_FAILED", error),
}
},
)
.description("Read properties of this for one paused frame.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"source",
tracked_typed::<DebuggerSessionArgs, DebuggerSourceOptions, (), DebuggerSource, _, _>(
"source",
|context: TypedContext<DebuggerSessionArgs, DebuggerSourceOptions, ()>| async move {
match DaemonClient
.execute(DebuggerSourceOperation {
id: context.args.id,
script_id: context.options.script_id,
file: context.options.file,
from_line: context.options.from_line,
to_line: context.options.to_line,
})
.await
{
Ok(source) => TypedResult::ok(source),
Err(error) => TypedResult::error("DEBUGGER_SOURCE_FAILED", error),
}
},
)
.description("Read up to 500 one-based source lines by current frame, script, or file.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"scripts",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<DebuggerScript>, _, _>(
"scripts",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerScriptsOperation {
id: context.args.id,
})
.await
{
Ok(scripts) => TypedResult::ok(scripts),
Err(error) => TypedResult::error("DEBUGGER_SCRIPTS_FAILED", error),
}
},
)
.description("Read parsed scripts and source-map metadata.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"console",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<DebuggerConsoleEntry>, _, _>(
"console",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerConsoleOperation {
id: context.args.id,
})
.await
{
Ok(entries) => TypedResult::ok(entries),
Err(error) => TypedResult::error("DEBUGGER_CONSOLE_FAILED", error),
}
},
)
.description("Read retained console entries, including after disconnect.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"exceptions",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<DebuggerExceptionEntry>, _, _>(
"exceptions",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerExceptionsOperation {
id: context.args.id,
})
.await
{
Ok(entries) => TypedResult::ok(entries),
Err(error) => TypedResult::error("DEBUGGER_EXCEPTIONS_FAILED", error),
}
},
)
.description("Read retained runtime exceptions, including after disconnect.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"health",
tracked_typed::<DebuggerSessionArgs, (), (), DebuggerHealth, _, _>(
"health",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerHealthOperation {
id: context.args.id,
})
.await
{
Ok(health) => TypedResult::ok(health),
Err(error) => TypedResult::error("DEBUGGER_HEALTH_FAILED", error),
}
},
)
.description("Read durable CDP connection and request health.")
.mcp(read_only())
.done(),
);
cli =
cli.command(
"trace",
tracked_typed::<
DebuggerSessionArgs,
DebuggerTraceOptions,
(),
Vec<DebuggerTraceEntry>,
_,
_,
>(
"trace",
|context: TypedContext<DebuggerSessionArgs, DebuggerTraceOptions, ()>| async move {
match DaemonClient
.execute(DebuggerTraceOperation {
id: context.args.id,
after: context.options.after,
limit: context.options.limit,
})
.await
{
Ok(trace) => TypedResult::ok(trace),
Err(error) => TypedResult::error("DEBUGGER_TRACE_FAILED", error),
}
},
)
.description("Read bounded CDP request, response, event, and latency trace entries.")
.mcp(read_only())
.done(),
);
macro_rules! debugger_control_command {
($name:literal, $operation:ident, $description:literal) => {
cli =
cli.command(
$name,
tracked_typed::<
DebuggerSessionArgs,
DebuggerMutationOptions,
(),
DebuggerSessionView,
_,
_,
>(
$name,
|context: TypedContext<
DebuggerSessionArgs,
DebuggerMutationOptions,
(),
>| async move {
match DaemonClient
.execute($operation {
id: context.args.id,
idempotency_key: context.options.idempotency_key,
timeout_ms: context.options.timeout_ms,
})
.await
{
Ok(session) => TypedResult::ok(session),
Err(error) => TypedResult::error("DEBUGGER_CONTROL_FAILED", error),
}
},
)
.description($description)
.mcp(destructive(true))
.destructive(true)
.done(),
);
};
}
debugger_control_command!(
"pause",
DebuggerPauseOperation,
"Pause execution and wait for V8 to publish the stack."
);
debugger_control_command!(
"resume",
DebuggerResumeOperation,
"Resume a paused debugger session."
);
debugger_control_command!(
"continue",
DebuggerContinueOperation,
"Continue and wait for the next pause, exit, or disconnect."
);
debugger_control_command!(
"close",
DebuggerCloseOperation,
"Close and forget a debugger session."
);
debugger_control_command!(
"reconnect",
DebuggerReconnectOperation,
"Reconnect a durable debugger session and restore its breakpoints."
);
cli = cli.command(
"restart",
tracked_typed::<
DebuggerSessionArgs,
DebuggerMutationOptions,
(),
DebuggerRunResult,
_,
_,
>(
"restart",
|context: TypedContext<
DebuggerSessionArgs,
DebuggerMutationOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerRestartOperation {
id: context.args.id,
idempotency_key: context.options.idempotency_key,
timeout_ms: context.options.timeout_ms,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DEBUGGER_RESTART_FAILED", error),
}
},
)
.description(
"Cancel the linked execution, relaunch its exact specification, reconnect, and restore durable breakpoints.",
)
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"step",
tracked_typed::<DebuggerStepArgs, DebuggerMutationOptions, (), DebuggerSessionView, _, _>(
"step",
|context: TypedContext<DebuggerStepArgs, DebuggerMutationOptions, ()>| async move {
match DaemonClient
.execute(DebuggerStepOperation {
id: context.args.id,
kind: context.args.kind,
idempotency_key: context.options.idempotency_key,
timeout_ms: context.options.timeout_ms,
})
.await
{
Ok(session) => TypedResult::ok(session),
Err(error) => TypedResult::error("DEBUGGER_STEP_FAILED", error),
}
},
)
.description("Step over, into, or out and wait for the next paused stack.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
let mut breakpoint =
Cli::create("breakpoint")
.description("Manage restart-safe debugger breakpoints.")
.command(
"set",
tracked_typed::<
DebuggerBreakpointArgs,
DebuggerBreakpointOptions,
(),
DebuggerBreakpoint,
_,
_,
>(
"set",
|context: TypedContext<
DebuggerBreakpointArgs,
DebuggerBreakpointOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerBreakpointSetOperation {
id: context.args.id,
file: context.args.file,
line: context.args.line,
condition: context.options.condition,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(breakpoint) => TypedResult::ok(breakpoint),
Err(error) => TypedResult::error("DEBUGGER_BREAKPOINT_FAILED", error),
}
},
)
.description("Set a one-based conditional breakpoint by source suffix.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
breakpoint = breakpoint.command(
"list",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<DebuggerBreakpoint>, _, _>(
"list",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerBreakpointListOperation {
id: context.args.id,
})
.await
{
Ok(breakpoints) => TypedResult::ok(breakpoints),
Err(error) => TypedResult::error("DEBUGGER_BREAKPOINT_LIST_FAILED", error),
}
},
)
.description("List durable breakpoints and their current resolution and hit counts.")
.mcp(read_only())
.done(),
);
breakpoint = breakpoint.command(
"delete",
tracked_typed::<
DebuggerBreakpointIdArgs,
DebuggerMutationOptions,
(),
DebuggerBreakpoint,
_,
_,
>(
"delete",
|context: TypedContext<
DebuggerBreakpointIdArgs,
DebuggerMutationOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerBreakpointDeleteOperation {
id: context.args.id,
breakpoint_id: context.args.breakpoint_id,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(breakpoint) => TypedResult::ok(breakpoint),
Err(error) => TypedResult::error("DEBUGGER_BREAKPOINT_DELETE_FAILED", error),
}
},
)
.description("Delete one apoc-owned breakpoint from the live adapter and durable state.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.group(breakpoint);
cli = cli.command(
"evaluate",
tracked_typed::<
DebuggerEvaluateArgs,
DebuggerEvaluateOptions,
(),
DebuggerEvaluation,
_,
_,
>(
"evaluate",
|context: TypedContext<DebuggerEvaluateArgs, DebuggerEvaluateOptions, ()>| async move {
match DaemonClient
.execute(DebuggerEvaluateOperation {
id: context.args.id,
expression: context.args.expression,
frame: context.options.frame,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(value) => TypedResult::ok(value),
Err(error) => TypedResult::error("DEBUGGER_EVALUATE_FAILED", error),
}
},
)
.description("Evaluate JavaScript in a paused frame or the running runtime.")
.mcp(debugger_evaluation_annotations())
.destructive(true)
.done(),
);
cli.group(debugger_browser_cli())
.group(debugger_extension_cli())
.group(debugger_legacy_cli())
.group(debugger_apple_cli())
.group(debugger_dap_cli())
.group(debugger_tap_cli())
.group(debugger_watch_cli())
.group(debugger_flow_cli())
.group(debugger_recording_cli())
}
fn debugger_legacy_cli() -> Cli {
Cli::create("legacy")
.description("Migrate and query a sanitized, read-only index of legacy dbg data.")
.command(
"import",
tracked_typed::<
LegacyDebuggerImportArgs,
LegacyDebuggerImportOptions,
(),
LegacyDebuggerMigration,
_,
_,
>(
"import",
|context: TypedContext<
LegacyDebuggerImportArgs,
LegacyDebuggerImportOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerLegacyImportOperation {
source: context.args.source,
index: context.options.index,
artifacts: context.options.artifact.unwrap_or_default(),
replace: context.options.replace,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("LEGACY_DEBUGGER_IMPORT_FAILED", error),
}
},
)
.description("Copy every legacy dbg table into an isolated index, import explicit artifact roots into content-addressed storage, and verify digests.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"query",
tracked_typed::<
LegacyDebuggerQueryArgs,
LegacyDebuggerQueryOptions,
(),
LegacyDebuggerQuery,
_,
_,
>(
"query",
|context: TypedContext<
LegacyDebuggerQueryArgs,
LegacyDebuggerQueryOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerLegacyQueryOperation {
index: context.options.index,
sql: context.args.sql,
limit: context.options.limit,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("LEGACY_DEBUGGER_QUERY_FAILED", error),
}
},
)
.description("Run one bounded read-only query against the sanitized legacy dbg index.")
.mcp(read_only())
.done(),
)
.command(
"status",
tracked_typed::<(), LegacyDebuggerStatusOptions, (), LegacyDebuggerIndexStatus, _, _>(
"status",
|context: TypedContext<(), LegacyDebuggerStatusOptions, ()>| async move {
match DaemonClient
.execute(DebuggerLegacyStatusOperation {
index: context.options.index,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("LEGACY_DEBUGGER_STATUS_FAILED", error),
}
},
)
.description("Inspect the isolated legacy dbg index without opening the durable apoc database.")
.mcp(read_only())
.done(),
)
}
fn debugger_extension_cli() -> Cli {
Cli::create("extension")
.description("Control the apoc-owned Chrome native-messaging bridge and extension probe.")
.command(
"install-host",
tracked_typed::<(), ExtensionInstallHostOptions, (), ExtensionHostInstallation, _, _>(
"install-host",
|context: TypedContext<(), ExtensionInstallHostOptions, ()>| async move {
match DaemonClient
.execute(DebuggerExtensionInstallHostOperation {
browser: context.options.browser,
extension_id: context.options.extension_id,
host_name: context.options.host_name,
host_path: context.options.host_path,
home: context.options.home,
user_data_dir: context.options.user_data_dir,
dry_run: context.options.dry_run,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("EXTENSION_INSTALL_HOST_FAILED", error),
}
},
)
.description("Install the apoc native-messaging manifest for one Chrome distribution.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"doctor",
tracked_typed::<(), ExtensionDoctorOptions, (), ExtensionDoctor, _, _>(
"doctor",
|context: TypedContext<(), ExtensionDoctorOptions, ()>| async move {
match DaemonClient
.execute(DebuggerExtensionDoctorOperation {
browser: context.options.browser,
host_name: context.options.host_name,
host_path: context.options.host_path,
home: context.options.home,
user_data_dir: context.options.user_data_dir,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("EXTENSION_DOCTOR_FAILED", error),
}
},
)
.description("Check the installed Chrome native-host manifest and executable.")
.mcp(read_only())
.done(),
)
.command(
"bridge",
tracked_typed::<(), (), (), ExtensionStatusView, _, _>("bridge", |_| async move {
match DaemonClient.execute(DebuggerExtensionBridgeOperation {}).await {
Ok(status) => TypedResult::ok(status),
Err(error) => TypedResult::error("EXTENSION_BRIDGE_FAILED", error),
}
})
.description("Read the native-host socket and current bridge connection identity.")
.mcp(read_only())
.done(),
)
.command(
"status",
tracked_typed::<(), (), (), ExtensionStatusView, _, _>("status", |_| async move {
match DaemonClient.execute(DebuggerExtensionStatusOperation {}).await {
Ok(status) => TypedResult::ok(status),
Err(error) => TypedResult::error("EXTENSION_STATUS_FAILED", error),
}
})
.description("Read bridge identity and extension-reported attachment state.")
.mcp(read_only())
.done(),
)
.command(
"tabs",
tracked_typed::<(), (), (), Vec<ExtensionTab>, _, _>("tabs", |_| async move {
match DaemonClient.execute(DebuggerExtensionTabsOperation {}).await {
Ok(tabs) => TypedResult::ok(tabs),
Err(error) => TypedResult::error("EXTENSION_TABS_FAILED", error),
}
})
.description("List Chrome tabs visible to the connected extension.")
.mcp(read_only())
.done(),
)
.command(
"attach",
tracked_typed::<ExtensionTabArgs, DebuggerMutationOptions, (), ExtensionAttachResult, _, _>(
"attach",
|context: TypedContext<ExtensionTabArgs, DebuggerMutationOptions, ()>| async move {
match DaemonClient.execute(DebuggerExtensionAttachOperation {
tab_id: context.args.tab_id,
idempotency_key: context.options.idempotency_key,
timeout_ms: context.options.timeout_ms,
}).await {
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("EXTENSION_ATTACH_FAILED", error),
}
},
)
.description("Attach Chrome debugger domains to one tab through the extension.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"detach",
tracked_typed::<(), ExtensionDetachOptions, (), ExtensionAttachResult, _, _>(
"detach",
|context: TypedContext<(), ExtensionDetachOptions, ()>| async move {
match DaemonClient.execute(DebuggerExtensionDetachOperation {
tab_id: context.options.tab_id,
idempotency_key: context.options.idempotency_key,
timeout_ms: context.options.timeout_ms,
}).await {
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("EXTENSION_DETACH_FAILED", error),
}
},
)
.description("Detach Chrome debugger domains from one or the current tab.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"eval",
tracked_typed::<ExtensionEvaluateArgs, ExtensionEvaluateOptions, (), ExtensionEvaluation, _, _>(
"eval",
|context: TypedContext<ExtensionEvaluateArgs, ExtensionEvaluateOptions, ()>| async move {
if !matches!(context.options.world.as_str(), "page" | "content") {
return TypedResult::error("INVALID_EXTENSION_WORLD", "world must be page or content");
}
match DaemonClient.execute(DebuggerExtensionEvaluateOperation {
tab_id: context.options.tab_id,
expression: context.args.expression,
world: context.options.world,
idempotency_key: context.options.idempotency_key,
timeout_ms: context.options.timeout_ms,
}).await {
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("EXTENSION_EVAL_FAILED", error),
}
},
)
.description("Evaluate JavaScript in the page or isolated content-script world.")
.mcp(debugger_evaluation_annotations())
.destructive(true)
.done(),
)
.command(
"cdp",
tracked_typed::<ExtensionCdpArgs, ExtensionCdpOptions, (), ExtensionCdpResult, _, _>(
"cdp",
|context: TypedContext<ExtensionCdpArgs, ExtensionCdpOptions, ()>| async move {
let params = match serde_json::from_str::<Value>(&context.options.params) {
Ok(Value::Object(params)) => Value::Object(params),
Ok(_) => return TypedResult::error("INVALID_EXTENSION_PARAMS", "params must be a JSON object"),
Err(error) => return TypedResult::error("INVALID_EXTENSION_PARAMS", error.to_string()),
};
match DaemonClient.execute(DebuggerExtensionCdpOperation {
tab_id: context.options.tab_id,
method: context.args.method,
params,
idempotency_key: context.options.idempotency_key,
timeout_ms: context.options.timeout_ms,
}).await {
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("EXTENSION_CDP_FAILED", error),
}
},
)
.description("Send one raw Chrome DevTools Protocol command through the extension.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"snapshot",
tracked_typed::<(), ExtensionSnapshotOptions, (), ExtensionSnapshotResult, _, _>(
"snapshot",
|context: TypedContext<(), ExtensionSnapshotOptions, ()>| async move {
match DaemonClient.execute(DebuggerExtensionSnapshotOperation {
tab_id: context.options.tab_id,
dom: context.options.dom,
state: context.options.state,
storage: context.options.storage,
react: context.options.react,
idempotency_key: context.options.idempotency_key,
timeout_ms: context.options.timeout_ms,
}).await {
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("EXTENSION_SNAPSHOT_FAILED", error),
}
},
)
.description("Capture a structured page, state, storage, and React snapshot.")
.mcp(destructive(false))
.done(),
)
.command(
"observe",
tracked_typed::<ExtensionObserveArgs, ExtensionObserveOptions, (), ExtensionObserveResult, _, _>(
"observe",
|context: TypedContext<ExtensionObserveArgs, ExtensionObserveOptions, ()>| async move {
const KINDS: &[&str] = &["console", "errors", "network", "dom", "storage", "route", "app"];
if context.args.kinds.is_empty() || context.args.kinds.iter().any(|kind| !KINDS.contains(&kind.as_str())) {
return TypedResult::error("INVALID_EXTENSION_OBSERVE_KIND", "kinds must contain console, errors, network, dom, storage, route, or app");
}
match DaemonClient.execute(DebuggerExtensionObserveOperation {
tab_id: context.options.tab_id,
kinds: context.args.kinds,
idempotency_key: context.options.idempotency_key,
timeout_ms: context.options.timeout_ms,
}).await {
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("EXTENSION_OBSERVE_FAILED", error),
}
},
)
.description("Retain selected extension events for one tab.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"unobserve",
tracked_typed::<(), ExtensionDetachOptions, (), ExtensionObserveResult, _, _>(
"unobserve",
|context: TypedContext<(), ExtensionDetachOptions, ()>| async move {
match DaemonClient.execute(DebuggerExtensionUnobserveOperation {
tab_id: context.options.tab_id,
idempotency_key: context.options.idempotency_key,
timeout_ms: context.options.timeout_ms,
}).await {
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("EXTENSION_UNOBSERVE_FAILED", error),
}
},
)
.description("Stop retaining extension events for one or the current tab.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"events",
tracked_typed::<(), ExtensionEventsOptions, (), Vec<ExtensionEvent>, _, _>(
"events",
|context: TypedContext<(), ExtensionEventsOptions, ()>| async move {
match DaemonClient.execute(DebuggerExtensionEventsOperation {
after: context.options.after,
limit: context.options.limit,
}).await {
Ok(events) => TypedResult::ok(events),
Err(error) => TypedResult::error("EXTENSION_EVENTS_FAILED", error),
}
},
)
.description("Read bounded extension events newer than an epoch-millisecond cursor.")
.mcp(read_only())
.done(),
)
}
fn debugger_apple_cli() -> Cli {
let mut cli = Cli::create("apple")
.description("Discover Apple targets and resolve execution-owned DAP attach inputs.");
cli = cli.command(
"devices",
tracked_typed::<(), AppleDevicesOptions, (), Vec<AppleDeviceTarget>, _, _>(
"devices",
|context: TypedContext<(), AppleDevicesOptions, ()>| async move {
match DaemonClient
.execute(AppleDevicesOperation {
platform: context.options.platform,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("APPLE_DEVICES_FAILED", error),
}
},
)
.description("List physical Apple devices and simulators through the built-in provider.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"apps",
tracked_typed::<AppleAppsArgs, (), (), Vec<AppleDeviceApp>, _, _>(
"apps",
|context: TypedContext<AppleAppsArgs, (), ()>| async move {
match DaemonClient
.execute(AppleAppsOperation {
device_id: context.args.device_id,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("APPLE_APPS_FAILED", error),
}
},
)
.description("List installed apps on one Apple device or simulator.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"resolve",
tracked_typed::<AppleResolveArgs, AppleResolveOptions, (), AppleAttachResolution, _, _>(
"resolve",
|context: TypedContext<AppleResolveArgs, AppleResolveOptions, ()>| async move {
let device_key = context.options.device.as_deref().unwrap_or("auto");
match DaemonClient
.execute(AppleResolveOperation {
id: format!("apple:{}:{device_key}", context.args.bundle_id),
bundle_id: context.args.bundle_id,
platform: context.options.platform,
device: context.options.device,
pid: context.options.pid,
launch: context.options.launch,
attach_strategy: context.options.attach_strategy,
attach_timeout_ms: context.options.attach_timeout_ms,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("APPLE_RESOLVE_FAILED", error),
}
},
)
.description(
"Resolve one installed Apple app to a device, process, and DAP attach strategy.",
)
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"attach",
tracked_typed::<AppleResolveArgs, AppleAttachOptions, (), AppleAttachResult, _, _>(
"attach",
|context: TypedContext<AppleResolveArgs, AppleAttachOptions, ()>| async move {
let env = match parse_env(context.options.env.as_deref().unwrap_or_default()) {
Ok(env) => env,
Err(error) => return TypedResult::error("INVALID_DAP_ENV", error),
};
let adapter_argv = dap_adapter_argv(
context.options.adapter,
context.options.adapter_arg,
);
match DaemonClient
.execute(AppleAttachOperation {
id: context.options.id,
bundle_id: context.args.bundle_id,
platform: context.options.platform,
device: context.options.device,
pid: context.options.pid,
launch: context.options.launch,
attach_strategy: context.options.attach_strategy,
adapter_argv,
cwd: context.options.cwd,
env,
timeout_ms: context.options.timeout_ms,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("APPLE_ATTACH_FAILED", error),
}
},
)
.description(
"Resolve an Apple app and attach one execution-owned DAP session with strategy fallback.",
)
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli
}
fn debugger_dap_cli() -> Cli {
let mut cli = Cli::create("dap").description(
"Launch and attach native debugger sessions through execution-owned DAP adapters.",
);
cli = cli.command(
"launch",
tracked_typed::<RunArgv, DapLaunchOptions, (), DebuggerRunResult, _, _>(
"launch",
|context: TypedContext<RunArgv, DapLaunchOptions, ()>| async move {
let env = match parse_env(context.options.env.as_deref().unwrap_or_default()) {
Ok(env) => env,
Err(error) => return TypedResult::error("INVALID_DAP_ENV", error),
};
let adapter_argv =
dap_adapter_argv(context.options.adapter, context.options.adapter_arg);
match DaemonClient
.execute(DapLaunchOperation {
id: context.options.id,
adapter_argv,
program: context.args.executable,
args: context.args.arg.unwrap_or_default(),
cwd: context.options.cwd,
env,
timeout_ms: context.options.timeout_ms,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DAP_LAUNCH_FAILED", error),
}
},
)
.description(
"Launch an exact-argv native target through an apoc-owned DAP adapter execution.",
)
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"attach",
tracked_typed::<DapAttachArgs, DapAttachOptions, (), DebuggerRunResult, _, _>(
"attach",
|context: TypedContext<DapAttachArgs, DapAttachOptions, ()>| async move {
let env = match parse_env(context.options.env.as_deref().unwrap_or_default()) {
Ok(env) => env,
Err(error) => return TypedResult::error("INVALID_DAP_ENV", error),
};
let adapter_argv = dap_adapter_argv(
context.options.adapter,
context.options.adapter_arg,
);
match DaemonClient
.execute(DapAttachOperation {
id: context.options.id,
adapter_argv,
pid: context.args.pid,
wait_for: context.options.wait_for,
attach_commands: context.options.attach_command.unwrap_or_default(),
started_stopped: context.options.started_stopped,
cwd: context.options.cwd,
env,
timeout_ms: context.options.timeout_ms,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DAP_ATTACH_FAILED", error),
}
},
)
.description(
"Attach through an apoc-owned DAP adapter after resolving one stable external process identity.",
)
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"request",
tracked_typed::<DapRequestArgs, DapRequestOptions, (), Value, _, _>(
"request",
|context: TypedContext<DapRequestArgs, DapRequestOptions, ()>| async move {
let arguments = match dap_request_arguments(context.args.arguments) {
Ok(arguments) => arguments,
Err(error) => return TypedResult::error("VALIDATION_ERROR", error),
};
match DaemonClient
.execute(DapRequestOperation {
id: context.args.id,
command: context.args.command,
arguments,
timeout_ms: context.options.timeout_ms,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DAP_REQUEST_FAILED", error),
}
},
)
.description("Send one schema-preserving raw DAP request through a named live session.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"state",
tracked_typed::<DebuggerSessionArgs, (), (), DapSessionState, _, _>(
"state",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DapStateOperation {
id: context.args.id,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DAP_STATE_FAILED", error),
}
},
)
.description("Read live DAP state, threads, modules, capabilities, and execution links.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"threads",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<DapThread>, _, _>(
"threads",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DapThreadsOperation {
id: context.args.id,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DAP_THREADS_FAILED", error),
}
},
)
.description("Read live native debugger threads.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"modules",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<DapModule>, _, _>(
"modules",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DapModulesOperation {
id: context.args.id,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DAP_MODULES_FAILED", error),
}
},
)
.description("Read loaded native modules with base addresses and sizes.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"registers",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<DapRegister>, _, _>(
"registers",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DapRegistersOperation {
id: context.args.id,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DAP_REGISTERS_FAILED", error),
}
},
)
.description("Read CPU registers for the active native thread.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"memory",
tracked_typed::<DapMemoryArgs, (), (), DapMemory, _, _>(
"memory",
|context: TypedContext<DapMemoryArgs, (), ()>| async move {
match DaemonClient
.execute(DapMemoryOperation {
id: context.args.id,
address: context.args.address,
count: context.args.count,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DAP_MEMORY_FAILED", error),
}
},
)
.description("Read bounded process memory as base64 through DAP.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"disassemble",
tracked_typed::<DapDisassembleArgs, DapDisassembleOptions, (), Vec<DapInstruction>, _, _>(
"disassemble",
|context: TypedContext<DapDisassembleArgs, DapDisassembleOptions, ()>| async move {
match DaemonClient
.execute(DapDisassembleOperation {
id: context.args.id,
address: context.args.address,
count: context.options.count,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DAP_DISASSEMBLE_FAILED", error),
}
},
)
.description("Disassemble bounded native instructions around a memory reference.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"signals",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<DapSignal>, _, _>(
"signals",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DapSignalsOperation {
id: context.args.id,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DAP_SIGNALS_FAILED", error),
}
},
)
.description("Read native signal handling policy from the adapter.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"watchpoints",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<DapWatchpoint>, _, _>(
"watchpoints",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DapWatchpointsOperation {
id: context.args.id,
})
.await
{
Ok(result) => TypedResult::ok(result),
Err(error) => TypedResult::error("DAP_WATCHPOINTS_FAILED", error),
}
},
)
.description("Read native watchpoints reported by the adapter.")
.mcp(read_only())
.done(),
);
cli
}
fn debugger_tap_cli() -> Cli {
let mut cli = Cli::create("tap")
.description("Manage durable non-pausing JavaScript logpoints and retained hits.");
cli = cli.command(
"add",
tracked_typed::<DebuggerTapAddArgs, DebuggerTapAddOptions, (), DebuggerTap, _, _>(
"add",
|context: TypedContext<DebuggerTapAddArgs, DebuggerTapAddOptions, ()>| async move {
match DaemonClient
.execute(DebuggerTapAddOperation {
id: context.args.id,
file: context.args.file,
line: context.args.line,
expression: context.args.expression,
url_regex: context.options.url_regex,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(tap) => TypedResult::ok(tap),
Err(error) => TypedResult::error("DEBUGGER_TAP_ADD_FAILED", error),
}
},
)
.description("Add a one-based logpoint that captures an expression without pausing.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"list",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<DebuggerTap>, _, _>(
"list",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerTapListOperation {
id: context.args.id,
})
.await
{
Ok(taps) => TypedResult::ok(taps),
Err(error) => TypedResult::error("DEBUGGER_TAP_LIST_FAILED", error),
}
},
)
.description("List durable taps with pending resolution and hit counts.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"hits",
tracked_typed::<DebuggerTapIdArgs, DebuggerHitOptions, (), Vec<DebuggerTapHit>, _, _>(
"hits",
|context: TypedContext<DebuggerTapIdArgs, DebuggerHitOptions, ()>| async move {
match DaemonClient
.execute(DebuggerTapHitsOperation {
id: context.args.id,
tap_id: context.args.tap_id,
limit: context.options.limit,
})
.await
{
Ok(hits) => TypedResult::ok(hits),
Err(error) => TypedResult::error("DEBUGGER_TAP_HITS_FAILED", error),
}
},
)
.description("Read retained tap hits in chronological order.")
.mcp(read_only())
.done(),
);
cli.command(
"remove",
tracked_typed::<DebuggerTapIdArgs, DebuggerIdempotencyOptions, (), DebuggerTap, _, _>(
"remove",
|context: TypedContext<DebuggerTapIdArgs, DebuggerIdempotencyOptions, ()>| async move {
match DaemonClient
.execute(DebuggerTapRemoveOperation {
id: context.args.id,
tap_id: context.args.tap_id,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(tap) => TypedResult::ok(tap),
Err(error) => TypedResult::error("DEBUGGER_TAP_REMOVE_FAILED", error),
}
},
)
.description("Disable one tap in the adapter while retaining its durable hits.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn debugger_watch_cli() -> Cli {
let mut cli = Cli::create("watch")
.description("Sample durable JavaScript evidence watches and retain value changes.");
cli = cli.command(
"add",
tracked_typed::<DebuggerWatchAddArgs, DebuggerWatchAddOptions, (), DebuggerWatch, _, _>(
"add",
|context: TypedContext<DebuggerWatchAddArgs, DebuggerWatchAddOptions, ()>| async move {
match DaemonClient
.execute(DebuggerWatchAddOperation {
id: context.args.id,
target: context.args.target,
expression: context.options.expression,
access: context.options.access,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(watch) => TypedResult::ok(watch),
Err(error) => TypedResult::error("DEBUGGER_WATCH_ADD_FAILED", error),
}
},
)
.description("Add a sampled expression watch; the target is the default expression.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"list",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<DebuggerWatch>, _, _>(
"list",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerWatchListOperation {
id: context.args.id,
})
.await
{
Ok(watches) => TypedResult::ok(watches),
Err(error) => TypedResult::error("DEBUGGER_WATCH_LIST_FAILED", error),
}
},
)
.description("List durable watches, current values, errors, and hit counts.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"hits",
tracked_typed::<DebuggerWatchIdArgs, DebuggerHitOptions, (), Vec<DebuggerWatchHit>, _, _>(
"hits",
|context: TypedContext<DebuggerWatchIdArgs, DebuggerHitOptions, ()>| async move {
match DaemonClient
.execute(DebuggerWatchHitsOperation {
id: context.args.id,
watch_id: context.args.watch_id,
limit: context.options.limit,
})
.await
{
Ok(hits) => TypedResult::ok(hits),
Err(error) => TypedResult::error("DEBUGGER_WATCH_HITS_FAILED", error),
}
},
)
.description("Read retained watch value and error transitions in chronological order.")
.mcp(read_only())
.done(),
);
cli.command(
"remove",
tracked_typed::<
DebuggerWatchIdArgs,
DebuggerIdempotencyOptions,
(),
DebuggerWatch,
_,
_,
>(
"remove",
|context: TypedContext<
DebuggerWatchIdArgs,
DebuggerIdempotencyOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerWatchRemoveOperation {
id: context.args.id,
watch_id: context.args.watch_id,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(watch) => TypedResult::ok(watch),
Err(error) => TypedResult::error("DEBUGGER_WATCH_REMOVE_FAILED", error),
}
},
)
.description("Disable one watch while retaining its durable hit history.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn debugger_flow_cli() -> Cli {
let mut cli = Cli::create("flow").description(
"Record browser actions and replay them with readiness, captures, console verdicts, and visual diffs.",
);
cli = cli.command(
"record",
tracked_typed::<FlowNameArgs, FlowRecordOptions, (), DebuggerFlow, _, _>(
"record",
|context: TypedContext<FlowNameArgs, FlowRecordOptions, ()>| async move {
match DaemonClient
.execute(DebuggerFlowRecordOperation {
id: context.args.id,
name: context.args.name,
url: context.options.url,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(flow) => TypedResult::ok(flow),
Err(error) => TypedResult::error("DEBUGGER_FLOW_RECORD_FAILED", error),
}
},
)
.description("Start recording trusted browser actions into a named durable flow.")
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"stop",
tracked_typed::<DebuggerSessionArgs, BrowserMutationOptions, (), DebuggerFlow, _, _>(
"stop",
|context: TypedContext<DebuggerSessionArgs, BrowserMutationOptions, ()>| async move {
match DaemonClient
.execute(DebuggerFlowStopOperation {
id: context.args.id,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(flow) => TypedResult::ok(flow),
Err(error) => TypedResult::error("DEBUGGER_FLOW_STOP_FAILED", error),
}
},
)
.description("Drain pending actions and stop the active flow recording.")
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"run",
tracked_typed::<FlowNameArgs, FlowRunOptions, (), DebuggerFlowRun, _, _>(
"run",
|context: TypedContext<FlowNameArgs, FlowRunOptions, ()>| async move {
match DaemonClient
.execute(DebuggerFlowRunOperation {
id: context.args.id,
name: context.args.name,
step_timeout_ms: context.options.step_timeout_ms,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(run) => TypedResult::ok(run),
Err(error) => TypedResult::error("DEBUGGER_FLOW_RUN_FAILED", error),
}
},
)
.description("Replay one flow and persist every passed, failed, or skipped step.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"list",
tracked_typed::<(), (), (), Vec<DebuggerFlow>, _, _>("list", |_| async move {
match DaemonClient.execute(DebuggerFlowListOperation {}).await {
Ok(flows) => TypedResult::ok(flows),
Err(error) => TypedResult::error("DEBUGGER_FLOW_LIST_FAILED", error),
}
})
.description("List durable browser flows.")
.mcp(read_only())
.done(),
);
cli.command(
"show",
tracked_typed::<FlowNameArgs, (), (), DebuggerFlowView, _, _>(
"show",
|context: TypedContext<FlowNameArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerFlowShowOperation {
id: context.args.id,
name: context.args.name,
})
.await
{
Ok(flow) => TypedResult::ok(flow),
Err(error) => TypedResult::error("DEBUGGER_FLOW_SHOW_FAILED", error),
}
},
)
.description("Read one flow with ordered steps and durable replay runs.")
.mcp(read_only())
.done(),
)
}
fn debugger_browser_cli() -> Cli {
let mut cli = Cli::create("browser")
.description("Inspect and control browser page targets through durable CDP sessions.");
cli = cli.command(
"state",
tracked_typed::<DebuggerSessionArgs, (), (), DebuggerBrowserState, _, _>(
"state",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerBrowserStateOperation {
id: context.args.id,
})
.await
{
Ok(state) => TypedResult::ok(state),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_STATE_FAILED", error),
}
},
)
.description("Read the durable page URL, traffic, mocks, emulation, and coverage state.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"navigate",
tracked_typed::<BrowserNavigateArgs, BrowserNavigateOptions, (), BrowserNavigation, _, _>(
"navigate",
|context: TypedContext<BrowserNavigateArgs, BrowserNavigateOptions, ()>| async move {
match DaemonClient
.execute(DebuggerBrowserNavigateOperation {
id: context.args.id,
action: context.args.action,
target: context.options.target,
timeout_ms: context.options.timeout_ms,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(navigation) => TypedResult::ok(navigation),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_NAVIGATE_FAILED", error),
}
},
)
.description("Navigate to a URL, reload, or move backward or forward and await readiness.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"dom",
tracked_typed::<BrowserSelectorArgs, (), (), Vec<BrowserDomNode>, _, _>(
"dom",
|context: TypedContext<BrowserSelectorArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerBrowserDomOperation {
id: context.args.id,
selector: context.args.selector,
})
.await
{
Ok(node) => TypedResult::ok(node),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_DOM_FAILED", error),
}
},
)
.description("Read DOM nodes matched by one CSS selector.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"styles",
tracked_typed::<BrowserSelectorArgs, (), (), Vec<BrowserStyle>, _, _>(
"styles",
|context: TypedContext<BrowserSelectorArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerBrowserStylesOperation {
id: context.args.id,
selector: context.args.selector,
})
.await
{
Ok(styles) => TypedResult::ok(styles),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_STYLES_FAILED", error),
}
},
)
.description("Read computed styles for one DOM node.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"cookies",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<BrowserCookie>, _, _>(
"cookies",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerBrowserCookiesOperation {
id: context.args.id,
})
.await
{
Ok(cookies) => TypedResult::ok(cookies),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_COOKIES_FAILED", error),
}
},
)
.description("Read cookies visible to the current page target.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"storage",
tracked_typed::<BrowserStorageArgs, (), (), Vec<BrowserStorageEntry>, _, _>(
"storage",
|context: TypedContext<BrowserStorageArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerBrowserStorageOperation {
id: context.args.id,
kind: context.args.kind,
})
.await
{
Ok(entries) => TypedResult::ok(entries),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_STORAGE_FAILED", error),
}
},
)
.description("Read local or session storage from the current page.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"performance",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<BrowserMetric>, _, _>(
"performance",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerBrowserPerformanceOperation {
id: context.args.id,
})
.await
{
Ok(metrics) => TypedResult::ok(metrics),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_PERFORMANCE_FAILED", error),
}
},
)
.description("Read browser performance metrics for the page target.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"network",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<BrowserNetworkRequest>, _, _>(
"network",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerBrowserNetworkOperation {
id: context.args.id,
})
.await
{
Ok(requests) => TypedResult::ok(requests),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_NETWORK_FAILED", error),
}
},
)
.description("Read retained page network requests and terminal status.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"network-body",
tracked_typed::<BrowserRequestArgs, (), (), BrowserNetworkBody, _, _>(
"network-body",
|context: TypedContext<BrowserRequestArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerBrowserNetworkBodyOperation {
id: context.args.id,
request_id: context.args.request_id,
})
.await
{
Ok(body) => TypedResult::ok(body),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_BODY_FAILED", error),
}
},
)
.description("Read one response body by retained CDP request identity.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"websockets",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<BrowserWebSocketFrame>, _, _>(
"websockets",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerBrowserWebSocketsOperation {
id: context.args.id,
})
.await
{
Ok(frames) => TypedResult::ok(frames),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_WEBSOCKETS_FAILED", error),
}
},
)
.description("Read retained WebSocket frames in capture order.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"page-events",
tracked_typed::<DebuggerSessionArgs, (), (), Vec<BrowserPageEvent>, _, _>(
"page-events",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerBrowserPageEventsOperation {
id: context.args.id,
})
.await
{
Ok(events) => TypedResult::ok(events),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_EVENTS_FAILED", error),
}
},
)
.description("Read retained page lifecycle and navigation events.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"screenshot",
tracked_typed::<BrowserScreenshotArgs, BrowserScreenshotOptions, (), BrowserScreenshot, _, _>(
"screenshot",
|context: TypedContext<BrowserScreenshotArgs, BrowserScreenshotOptions, ()>| async move {
if context.options.width.is_some() != context.options.height.is_some() {
return TypedResult::error(
"INVALID_SCREENSHOT_VIEWPORT",
"Screenshot width and height must be supplied together",
);
}
match DaemonClient
.execute(DebuggerBrowserScreenshotOperation {
id: context.args.id,
selector: context.options.selector,
state: context.options.state,
full_page: context.options.full_page,
width: context.options.width,
height: context.options.height,
inline: context.options.inline,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(screenshot) => TypedResult::ok(screenshot),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_SCREENSHOT_FAILED", error),
}
},
)
.description("Capture a page or selector as a content-addressed PNG artifact.")
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"click",
tracked_typed::<BrowserSelectorArgs, BrowserMutationOptions, (), BrowserInteraction, _, _>(
"click",
|context: TypedContext<BrowserSelectorArgs, BrowserMutationOptions, ()>| async move {
match DaemonClient
.execute(DebuggerBrowserClickOperation {
id: context.args.id,
selector: context.args.selector,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(interaction) => TypedResult::ok(interaction),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_INTERACTION_FAILED", error),
}
},
)
.description("Click the center of one visible DOM node with trusted input events.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
for (name, description) in [
(
"type",
"Focus one node and type text through trusted key events.",
),
(
"select",
"Select an option and dispatch input and change events.",
),
] {
cli = cli.command(
name,
tracked_typed::<BrowserValueArgs, BrowserMutationOptions, (), BrowserInteraction, _, _>(
name,
move |context: TypedContext<BrowserValueArgs, BrowserMutationOptions, ()>| async move {
let result = if name == "type" {
DaemonClient
.execute(DebuggerBrowserTypeOperation {
id: context.args.id,
selector: context.args.selector,
value: context.args.value,
idempotency_key: context.options.idempotency_key,
})
.await
} else {
DaemonClient
.execute(DebuggerBrowserSelectOperation {
id: context.args.id,
selector: context.args.selector,
value: context.args.value,
idempotency_key: context.options.idempotency_key,
})
.await
};
match result {
Ok(interaction) => TypedResult::ok(interaction),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_INTERACTION_FAILED", error),
}
},
)
.description(description)
.mcp(destructive(true))
.destructive(true)
.done(),
);
}
cli = cli.command(
"mock",
tracked_typed::<BrowserMockArgs, BrowserMockOptions, (), BrowserMockRule, _, _>(
"mock",
|context: TypedContext<BrowserMockArgs, BrowserMockOptions, ()>| async move {
let headers = match context
.options
.header
.as_deref()
.unwrap_or_default()
.iter()
.map(|entry| {
entry
.split_once('=')
.filter(|(name, _)| !name.is_empty())
.map(|(name, value)| (name.to_string(), value.to_string()))
.ok_or_else(|| format!("Mock header \"{entry}\" must use NAME=VALUE"))
})
.collect::<Result<Vec<_>, _>>()
{
Ok(headers) => headers,
Err(error) => return TypedResult::error("INVALID_MOCK_HEADER", error),
};
match DaemonClient
.execute(DebuggerBrowserMockOperation {
id: context.args.id,
pattern: context.args.pattern,
body: context.args.body,
status: context.options.status,
headers,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(rule) => TypedResult::ok(rule),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_MOCK_FAILED", error),
}
},
)
.description("Persist and enable one URL-substring response mock across reconnects.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
cli = cli.command(
"unmock",
tracked_typed::<BrowserUnmockArgs, BrowserUnmockOptions, (), Vec<BrowserMockRule>, _, _>(
"unmock",
|context: TypedContext<BrowserUnmockArgs, BrowserUnmockOptions, ()>| async move {
match DaemonClient
.execute(DebuggerBrowserUnmockOperation {
id: context.args.id,
pattern: context.options.pattern,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(rule) => TypedResult::ok(rule),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_UNMOCK_FAILED", error),
}
},
)
.description("Remove one response mock by URL pattern, or every mock when omitted.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
for (name, description) in [
(
"emulate",
"Apply a named device preset or reset browser emulation.",
),
(
"throttle",
"Apply a named network preset, offline mode, or disable throttling.",
),
] {
cli = cli.command(
name,
tracked_typed::<BrowserPresetArgs, BrowserMutationOptions, (), String, _, _>(
name,
move |context: TypedContext<BrowserPresetArgs, BrowserMutationOptions, ()>| async move {
let result = if name == "emulate" {
DaemonClient
.execute(DebuggerBrowserEmulateOperation {
id: context.args.id,
preset: context.args.preset,
idempotency_key: context.options.idempotency_key,
})
.await
} else {
DaemonClient
.execute(DebuggerBrowserThrottleOperation {
id: context.args.id,
preset: context.args.preset,
idempotency_key: context.options.idempotency_key,
})
.await
};
match result {
Ok(preset) => TypedResult::ok(preset),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_PRESET_FAILED", error),
}
},
)
.description(description)
.mcp(destructive(true))
.destructive(true)
.done(),
);
}
cli.command(
"coverage",
tracked_typed::<BrowserPresetArgs, BrowserMutationOptions, (), BrowserCoverageSnapshot, _, _>(
"coverage",
|context: TypedContext<BrowserPresetArgs, BrowserMutationOptions, ()>| async move {
match DaemonClient
.execute(DebuggerBrowserCoverageOperation {
id: context.args.id,
preset: context.args.preset,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(snapshot) => TypedResult::ok(snapshot),
Err(error) => TypedResult::error("DEBUGGER_BROWSER_COVERAGE_FAILED", error),
}
},
)
.description("Start precise coverage or stop it and persist the resulting snapshot.")
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn debugger_recording_cli() -> Cli {
let mut cli = Cli::create("recording").description(
"Capture, mark, inspect, bound, and replay durable browser flight recordings.",
);
cli =
cli.command(
"start",
tracked_typed::<
DebuggerSessionArgs,
DebuggerRecordingStartOptions,
(),
DebuggerRecordingStart,
_,
_,
>(
"start",
|context: TypedContext<DebuggerSessionArgs, DebuggerRecordingStartOptions, ()>| async move {
match DaemonClient
.execute(DebuggerRecordingStartOperation {
id: context.args.id,
max_frames: context.options.max_frames,
max_bytes: context.options.max_bytes,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(recording) => TypedResult::ok(recording),
Err(error) => TypedResult::error("DEBUGGER_RECORDING_START_FAILED", error),
}
},
)
.description(
"Start a bounded durable recording and capture the current page immediately.",
)
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"status",
tracked_typed::<DebuggerSessionArgs, (), (), Option<DebuggerRecording>, _, _>(
"status",
|context: TypedContext<DebuggerSessionArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerRecordingStatusOperation {
id: context.args.id,
})
.await
{
Ok(recording) => TypedResult::ok(recording),
Err(error) => TypedResult::error("DEBUGGER_RECORDING_STATUS_FAILED", error),
}
},
)
.description("Read the latest recording state for one browser session.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"list",
tracked_typed::<(), (), (), Vec<DebuggerRecording>, _, _>("list", |_| async move {
match DaemonClient
.execute(DebuggerRecordingListOperation {})
.await
{
Ok(recordings) => TypedResult::ok(recordings),
Err(error) => TypedResult::error("DEBUGGER_RECORDING_LIST_FAILED", error),
}
})
.description("List durable recordings across debugger sessions.")
.mcp(read_only())
.done(),
);
for (name, description) in [
(
"capture",
"Capture the current page into the active recording.",
),
(
"shoot",
"Deliberately capture the current page into the active recording.",
),
] {
cli =
cli.command(
name,
tracked_typed::<
DebuggerSessionArgs,
RecordingCaptureOptions,
(),
DebuggerCapture,
_,
_,
>(
name,
move |context: TypedContext<
DebuggerSessionArgs,
RecordingCaptureOptions,
(),
>| async move {
let reason = if name == "shoot" && context.options.reason == "manual" {
"shoot".to_string()
} else {
context.options.reason
};
let result = if name == "shoot" {
DaemonClient
.execute(DebuggerRecordingShootOperation {
id: context.args.id,
reason,
idempotency_key: context.options.idempotency_key,
})
.await
} else {
DaemonClient
.execute(DebuggerRecordingCaptureOperation {
id: context.args.id,
reason,
idempotency_key: context.options.idempotency_key,
})
.await
};
match result {
Ok(capture) => TypedResult::ok(capture),
Err(error) => {
TypedResult::error("DEBUGGER_RECORDING_CAPTURE_FAILED", error)
}
}
},
)
.description(description)
.mcp(destructive(false))
.done(),
);
}
cli = cli.command(
"mark",
tracked_typed::<RecordingMarkArgs, BrowserMutationOptions, (), DebuggerMark, _, _>(
"mark",
|context: TypedContext<RecordingMarkArgs, BrowserMutationOptions, ()>| async move {
match DaemonClient
.execute(DebuggerRecordingMarkOperation {
id: context.args.id,
name: context.args.name,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(mark) => TypedResult::ok(mark),
Err(error) => TypedResult::error("DEBUGGER_RECORDING_MARK_FAILED", error),
}
},
)
.description("Capture the current page and stamp a named durable mark.")
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"correlate",
tracked_typed::<
RecordingCorrelateArgs,
RecordingCorrelateOptions,
(),
CausalEvent,
_,
_,
>(
"correlate",
|context: TypedContext<
RecordingCorrelateArgs,
RecordingCorrelateOptions,
(),
>| async move {
match DaemonClient
.execute(DebuggerRecordingCorrelateOperation {
id: context.args.id,
kind: context.args.kind,
reference: context.args.reference,
path: context.options.path,
at: context.options.at,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(event) => TypedResult::ok(event),
Err(error) => {
TypedResult::error("DEBUGGER_RECORDING_CORRELATE_FAILED", error)
}
}
},
)
.description("Attach one replay-safe edit or commit event to the active recording timeline.")
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"after",
tracked_typed::<DebuggerSessionArgs, RecordingAfterOptions, (), DebuggerAfter, _, _>(
"after",
|context: TypedContext<DebuggerSessionArgs, RecordingAfterOptions, ()>| async move {
match DaemonClient
.execute(DebuggerRecordingAfterOperation { id: context.args.id, anchor: context.options.at, idempotency_key: context.options.idempotency_key })
.await
{
Ok(after) => TypedResult::ok(after),
Err(error) => TypedResult::error("DEBUGGER_RECORDING_AFTER_FAILED", error),
}
},
)
.description(
"Capture current browser state, compare it with an earlier capture, and persist an HTML report.",
)
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"after-get",
tracked_typed::<RecordingAfterIdArgs, (), (), Option<DebuggerAfter>, _, _>(
"after-get",
|context: TypedContext<RecordingAfterIdArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerRecordingAfterGetOperation {
id: context.args.id,
})
.await
{
Ok(after) => TypedResult::ok(after),
Err(error) => TypedResult::error("DEBUGGER_RECORDING_AFTER_READ_FAILED", error),
}
},
)
.description("Read one durable after analysis by identity.")
.mcp(read_only())
.done(),
);
cli = cli.command(
"timeline",
tracked_typed::<
DebuggerSessionArgs,
RecordingTimelineOptions,
(),
DebuggerTimeline,
_,
_,
>(
"timeline",
|context: TypedContext<DebuggerSessionArgs, RecordingTimelineOptions, ()>| async move {
match DaemonClient
.execute(DebuggerRecordingTimelineOperation { id: context.args.id, limit: context.options.limit, idempotency_key: context.options.idempotency_key })
.await
{
Ok(timeline) => TypedResult::ok(timeline),
Err(error) => TypedResult::error("DEBUGGER_TIMELINE_FAILED", error),
}
},
)
.description(
"Join captures, marks, errors, network failures, diffs, prompts, executions, commits, and causal events into one report.",
)
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"why",
tracked_typed::<RecordingWhyArgs, RecordingWhyOptions, (), DebuggerWhy, _, _>(
"why",
|context: TypedContext<RecordingWhyArgs, RecordingWhyOptions, ()>| async move {
match DaemonClient
.execute(DebuggerRecordingWhyOperation { id: context.args.id, substring: context.args.substring, window_ms: context.options.window_ms })
.await
{
Ok(why) => TypedResult::ok(why),
Err(error) => TypedResult::error("DEBUGGER_WHY_FAILED", error),
}
},
)
.description(
"Rank recorded edits, diffs, executions, and causal events behind the latest matching error.",
)
.mcp(read_only())
.done(),
);
cli = cli.command(
"stop",
tracked_typed::<DebuggerSessionArgs, BrowserMutationOptions, (), DebuggerRecording, _, _>(
"stop",
|context: TypedContext<DebuggerSessionArgs, BrowserMutationOptions, ()>| async move {
match DaemonClient
.execute(DebuggerRecordingStopOperation {
id: context.args.id,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(recording) => TypedResult::ok(recording),
Err(error) => TypedResult::error("DEBUGGER_RECORDING_STOP_FAILED", error),
}
},
)
.description("Capture a final frame and stop the active recording.")
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"replay",
tracked_typed::<RecordingReplayArgs, RecordingReplayOptions, (), DebuggerReplay, _, _>(
"replay",
|context: TypedContext<RecordingReplayArgs, RecordingReplayOptions, ()>| async move {
match DaemonClient
.execute(DebuggerRecordingReplayOperation {
id: context.args.id,
capture_id: context.args.capture_id,
timeout_ms: context.options.timeout_ms,
idempotency_key: context.options.idempotency_key,
})
.await
{
Ok(replay) => TypedResult::ok(replay),
Err(error) => TypedResult::error("DEBUGGER_RECORDING_REPLAY_FAILED", error),
}
},
)
.description("Restore one capture URL and vertical scroll position.")
.mcp(destructive(true))
.destructive(true)
.done(),
);
for (name, description) in [
("captures", "List retained captures in sequence order."),
("marks", "List durable recording marks in timeline order."),
] {
if name == "captures" {
cli = cli.command(
name,
tracked_typed::<DebuggerRecordingIdArgs, (), (), Vec<DebuggerCapture>, _, _>(
name,
move |context: TypedContext<DebuggerRecordingIdArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerRecordingCapturesOperation {
recording_id: context.args.recording_id,
})
.await
{
Ok(captures) => TypedResult::ok(captures),
Err(error) => {
TypedResult::error("DEBUGGER_RECORDING_READ_FAILED", error)
}
}
},
)
.description(description)
.mcp(read_only())
.done(),
);
} else {
cli = cli.command(
name,
tracked_typed::<DebuggerRecordingIdArgs, (), (), Vec<DebuggerMark>, _, _>(
name,
move |context: TypedContext<DebuggerRecordingIdArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerRecordingMarksOperation {
recording_id: context.args.recording_id,
})
.await
{
Ok(marks) => TypedResult::ok(marks),
Err(error) => {
TypedResult::error("DEBUGGER_RECORDING_READ_FAILED", error)
}
}
},
)
.description(description)
.mcp(read_only())
.done(),
);
}
}
cli = cli.command(
"afters",
tracked_typed::<DebuggerRecordingIdArgs, (), (), Vec<DebuggerAfter>, _, _>(
"afters",
|context: TypedContext<DebuggerRecordingIdArgs, (), ()>| async move {
match DaemonClient
.execute(DebuggerRecordingAftersOperation {
recording_id: context.args.recording_id,
})
.await
{
Ok(afters) => TypedResult::ok(afters),
Err(error) => TypedResult::error("DEBUGGER_RECORDING_AFTER_READ_FAILED", error),
}
},
)
.description("List durable after analyses for one recording.")
.mcp(read_only())
.done(),
);
cli
}
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, (), ExecutionInvocationResponse, _, _>(
"start",
|context: TypedContext<RunArgv, ExecutionOptions, ()>| async move {
let level = match verbosity(verbosity_request!(context.options)) {
Ok(level) => level,
Err(error) => return error,
};
let keep_alive = context.options.keep_alive;
let lifetime_ms = context.options.lifetime_ms;
let (spec, parent_id, session_id, profile) =
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,
"profile": profile,
"keep_alive": keep_alive,
"lifetime_ms": lifetime_ms
}),
)
.await
{
Ok(execution) => TypedResult::ok(invocation_response(execution, level)),
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, (), ExecutionInvocationResponse, _, _>(
"command",
|context: TypedContext<RunArgv, ExecutionOptions, ()>| async move {
let level = match verbosity(verbosity_request!(context.options)) {
Ok(level) => level,
Err(error) => return error,
};
let (spec, parent_id, session_id, profile) =
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,
"profile": profile
}),
)
.await
{
Ok(execution) => invocation_result(execution, level),
Err(error) => TypedResult::error("EXECUTION_COMMAND_FAILED", error),
}
},
)
.description(
"Run an exact-argv command to completion and answer with one verdict: passed, failed, error, or skipped. Declare what a correct result looks like with --expect-stdout-regex, --expect-exit-code, --expect-json-pointer with --expect-json-equals, or --expect-js. Output is withheld: read it with `execution logs ID --grep PATTERN`, or raise --verbosity.",
)
.command_aliases(vec!["exec".to_string()])
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"batch",
tracked_typed::<(), BatchOptions, (), ExecutionInvocationResponse, _, _>(
"batch",
|context: TypedContext<(), BatchOptions, ()>| async move {
let options = context.options;
let level = match verbosity(verbosity_request!(options)) {
Ok(level) => level,
Err(error) => return error,
};
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, profile) = 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,
profile: options.profile,
session: options.session,
parent: options.parent,
telemetry: options.telemetry,
telemetry_interval_ms: options.telemetry_interval_ms,
telemetry_max_bytes: options.telemetry_max_bytes,
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,
"profile": profile
}),
)
.await
{
Ok(execution) => invocation_result(execution, level),
Err(error) => TypedResult::error("EXECUTION_BATCH_FAILED", error),
}
},
)
.description(
"Run exact-argv commands concurrently and answer with one verdict for the group. Inspect children with `execution list --parent ID`, and read any child with `execution logs ID --grep PATTERN`.",
)
.mcp(destructive(false))
.done(),
);
cli = cli.command(
"pipeline",
tracked_typed::<(), PipelineOptions, (), ExecutionInvocationResponse, _, _>(
"pipeline",
|context: TypedContext<(), PipelineOptions, ()>| async move {
let options = context.options;
let level = match verbosity(verbosity_request!(options)) {
Ok(level) => level,
Err(error) => return error,
};
let (spec, parent_id, session_id, profile) = 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,
profile: options.profile,
session: options.session,
parent: options.parent,
telemetry: options.telemetry,
telemetry_interval_ms: options.telemetry_interval_ms,
telemetry_max_bytes: options.telemetry_max_bytes,
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,
"profile": profile
}),
)
.await
{
Ok(execution) => invocation_result(execution, level),
Err(error) => TypedResult::error("EXECUTION_PIPELINE_FAILED", error),
}
},
)
.description(
"Run an exact-argv native pipeline with pipefail and answer with one verdict for the group. Inspect stages with `execution list --parent ID`, and read any stage with `execution logs ID --grep PATTERN`.",
)
.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,
"error_code": context.options.error_code,
"parent": context.options.parent
}),
)
.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, optionally filtered to one parent's direct children; use get for a full record.",
)
.command_aliases(vec!["ls".to_string()])
.mcp(read_only())
.done(),
);
cli = cli.command(
"get",
tracked_typed::<RunIdArgs, ExecutionViewOptions, (), ExecutionResponse, _, _>(
"get",
|context: TypedContext<RunIdArgs, ExecutionViewOptions, ()>| async move {
let level = match verbosity(verbosity_request!(context.options)) {
Ok(level) => level,
Err(error) => return error,
};
match DaemonClient
.call(
"execution.get",
serde_json::json!({ "id": context.args.id }),
)
.await
{
Ok(execution) => TypedResult::ok(execution_response(execution, level)),
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(
"tree",
tracked_typed::<RunIdArgs, (), (), ExecutionTree, _, _>(
"tree",
|context: TypedContext<RunIdArgs, (), ()>| async move {
match DaemonClient
.call(
"execution.tree",
serde_json::json!({ "id": context.args.id }),
)
.await
{
Ok(tree) => TypedResult::ok(tree),
Err(error) => TypedResult::error("EXECUTION_TREE_FAILED", error),
}
},
)
.description(
"Return fresh live processes for an execution and every recursively owned child.",
)
.mcp(read_only())
.done(),
);
cli = cli.command(
"logs",
tracked_typed::<RunIdArgs, LogQueryOptions, (), LogResponse, _, _>(
"logs",
|context: TypedContext<RunIdArgs, LogQueryOptions, ()>| async move {
let addressed =
context.options.grep.is_some() || context.options.lines.is_some();
match DaemonClient
.call::<serde_json::Value>(
"execution.logs",
serde_json::json!({
"id": context.args.id,
"tail_bytes": context.options.tail_bytes,
"grep": context.options.grep,
"context": context.options.context,
"max_matches": context.options.max_matches,
"lines": context.options.lines
}),
)
.await
{
Ok(value) => {
let decoded = if addressed {
serde_json::from_value(value).map(LogResponse::Slice)
} else {
serde_json::from_value(value).map(LogResponse::Tail)
};
match decoded {
Ok(response) => TypedResult::ok(response),
Err(error) => {
TypedResult::error("EXECUTION_LOGS_FAILED", error.to_string())
}
}
}
Err(error) => TypedResult::error("EXECUTION_LOGS_FAILED", error),
}
},
)
.description(
"Read output: bounded tails by default, --grep for numbered matching lines, or --lines START-END to expand around one.",
)
.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, ExecutionMutationOptions, (), InputReceipt, _, _>(
"input",
|context: TypedContext<RunInputArgs, ExecutionMutationOptions, ()>| async move {
match DaemonClient
.call(
"execution.input",
serde_json::json!({
"id": context.args.id,
"data": context.args.data,
"idempotency_key": context.options.idempotency_key
}),
)
.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, (), ExecutionResponse, _, _>(
"wait",
|context: TypedContext<RunIdArgs, RunWaitOptions, ()>| async move {
let level = match verbosity(verbosity_request!(context.options)) {
Ok(level) => level,
Err(error) => return error,
};
match DaemonClient
.call(
"execution.wait",
serde_json::json!({
"id": context.args.id,
"timeout_ms": context.options.timeout_ms
}),
)
.await
{
Ok(execution) => {
let code = verdict_exit_code(&execution);
TypedResult::ok_with_exit_code(execution_response(execution, level), code)
}
Err(error) => TypedResult::error("EXECUTION_WAIT_FAILED", error),
}
},
)
.description(
"Wait for an execution to complete, fail, or cancel, or return the current snapshot at the observation boundary.",
)
.mcp(read_only())
.done(),
);
cli = cli.command(
"signal",
tracked_typed::<RunSignalArgs, ExecutionMutationOptions, (), Execution, _, _>(
"signal",
|context: TypedContext<RunSignalArgs, ExecutionMutationOptions, ()>| async move {
match DaemonClient
.call(
"execution.signal",
serde_json::json!({
"id": context.args.id,
"signal": context.args.signal,
"idempotency_key": context.options.idempotency_key
}),
)
.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, ExecutionCancelOptions, (), ExecutionResponse, _, _>(
"cancel",
|context: TypedContext<RunIdArgs, ExecutionCancelOptions, ()>| async move {
let level = match verbosity(verbosity_request!(context.options)) {
Ok(level) => level,
Err(error) => return error,
};
match DaemonClient
.call(
"execution.cancel",
serde_json::json!({
"id": context.args.id,
"timeout_ms": context.options.timeout_ms,
"idempotency_key": context.options.idempotency_key
}),
)
.await
{
Ok(execution) => TypedResult::ok(execution_response(execution, level)),
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 = 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(),
);
cli.group(execution_image_cli())
.group(execution_isolation_cli())
.group(telemetry_cli())
}
fn execution_image_cli() -> Cli {
Cli::create("image")
.description("Import, inspect, and verify isolated VM image bundles without booting a VM.")
.command(
"import",
tracked_typed::<
ImageImportArgs,
ImageImportOptions,
(),
ImageImportResponse,
_,
_,
>(
"import",
|context: TypedContext<ImageImportArgs, ImageImportOptions, ()>| async move {
match DaemonClient
.call::<ImageImportResponse>(
ImageImportOperation::METHOD,
serde_json::json!({
"source": context.args.source,
"idempotency_key": context.options.idempotency_key
}),
)
.await
{
Ok(imported) => TypedResult::ok(imported),
Err(error) => TypedResult::error("IMAGE_IMPORT_FAILED", error),
}
},
)
.description(
"Verify and atomically copy one bundle's immutable files into apoc-owned digest storage.",
)
.mcp(destructive(true))
.destructive(true)
.done(),
)
.command(
"verify",
tracked_typed::<ImageVerifyArgs, (), (), VerificationReport, _, _>(
"verify",
|context: TypedContext<ImageVerifyArgs, (), ()>| async move {
match verify_reference(&context.args.image) {
Ok(report) => {
let exit_code = match report.status {
VerificationStatus::Verified => 0,
VerificationStatus::LegacyUnverified
| VerificationStatus::Invalid => 1,
};
TypedResult::ok_with_exit_code(report, exit_code)
}
Err(message) => TypedResult::Error {
code: "IMAGE_REFERENCE_INVALID".to_string(),
message,
retryable: false,
exit_code: Some(125),
cta: None,
},
}
},
)
.description(
"Verify bundle configuration, manifest identity, build provenance, and artifact bytes without starting a VM.",
)
.mcp(read_only())
.done(),
)
}
fn execution_isolation_cli() -> Cli {
Cli::create("isolation")
.description("Inspect and control apoc's built-in macOS isolated VM pool.")
.command(
"status",
tracked_typed::<(), (), (), IsolationStatus, _, _>(
"status",
|_context: TypedContext<(), (), ()>| async move {
match DaemonClient
.call("execution.isolation.status", serde_json::json!({}))
.await
{
Ok(status) => TypedResult::ok(status),
Err(error) => TypedResult::error("ISOLATION_STATUS_FAILED", error),
}
},
)
.description(
"Return provider build, verified image, pool counts, memory, snapshot, and boot diagnostics without booting a VM.",
)
.mcp(read_only())
.done(),
)
.command(
"warmup",
tracked_typed::<(), IsolationWarmupOptions, (), IsolationMutationResponse, _, _>(
"warmup",
|context: TypedContext<(), IsolationWarmupOptions, ()>| async move {
let arguments = serde_json::json!({
"timeout_ms": context.options.timeout_ms,
"vm_bundle": context.options.vm_bundle,
"pool_size": context.options.pool_size,
"idle_drain_seconds": context.options.idle_drain_seconds,
"max_pool_memory_mb": context.options.max_pool_memory_mb,
"snapshot_restore": context.options.snapshot_restore
});
match DaemonClient
.call(
"execution.isolation.warmup",
serde_json::json!({
"idempotency_key": context.options.idempotency_key,
"arguments": arguments
}),
)
.await
{
Ok(response) => TypedResult::ok(response),
Err(error) => TypedResult::error("ISOLATION_WARMUP_FAILED", error),
}
},
)
.description("Wait for one verified isolated VM to become usable and return a durable receipt.")
.mcp(destructive(false))
.destructive(true)
.done(),
)
.command(
"drain",
tracked_typed::<(), IsolationMutationOptions, (), IsolationMutationResponse, _, _>(
"drain",
|context: TypedContext<(), IsolationMutationOptions, ()>| async move {
match DaemonClient
.call(
"execution.isolation.drain",
serde_json::json!({
"idempotency_key": context.options.idempotency_key,
"arguments": {}
}),
)
.await
{
Ok(response) => TypedResult::ok(response),
Err(error) => TypedResult::error("ISOLATION_DRAIN_FAILED", error),
}
},
)
.description(
"Wait until every idle or in-flight isolated VM is torn down and return a durable receipt.",
)
.mcp(destructive(true))
.destructive(true)
.done(),
)
}
fn telemetry_cli() -> Cli {
Cli::create("telemetry")
.description(
"Capture and inspect opt-in CPU, memory, disk, and process-count telemetry for one execution and every recursively owned descendant.",
)
.command(
"start",
tracked_typed::<RunIdArgs, TelemetryStartOptions, (), TelemetryCapture, _, _>(
"start",
|context: TypedContext<RunIdArgs, TelemetryStartOptions, ()>| async move {
if let Err(error) = telemetry_policy(
true,
Some(context.options.interval_ms),
Some(context.options.max_bytes),
) {
return TypedResult::error("INVALID_TELEMETRY", error);
}
match DaemonClient
.call(
"execution.telemetry.start",
serde_json::json!({
"id": context.args.id,
"interval_ms": context.options.interval_ms,
"max_bytes": context.options.max_bytes,
"idempotency_key": context.options.idempotency_key
}),
)
.await
{
Ok(capture) => TypedResult::ok(capture),
Err(error) => TypedResult::error("TELEMETRY_START_FAILED", error),
}
},
)
.description(
"Attach one durable sampler to an existing execution. The scope includes that execution, recursively owned apoc executions, and their OS descendants.",
)
.mcp(destructive(false))
.done(),
)
.command(
"get",
tracked_typed::<RunIdArgs, TelemetryGetOptions, (), TelemetryResponse, _, _>(
"get",
|context: TypedContext<RunIdArgs, TelemetryGetOptions, ()>| async move {
let addressed =
context.options.grep.is_some() || context.options.lines.is_some();
match DaemonClient
.call::<serde_json::Value>(
"execution.telemetry.get",
serde_json::json!({
"id": context.args.id,
"grep": context.options.grep,
"context": context.options.context,
"max_matches": context.options.max_matches,
"lines": context.options.lines
}),
)
.await
{
Ok(value) => {
let decoded = if addressed {
serde_json::from_value(value).map(TelemetryResponse::Slice)
} else {
serde_json::from_value(value)
.map(Box::new)
.map(TelemetryResponse::Summary)
};
match decoded {
Ok(response) => TypedResult::ok(response),
Err(error) => TypedResult::error(
"TELEMETRY_GET_FAILED",
error.to_string(),
),
}
}
Err(error) => TypedResult::error("TELEMETRY_GET_FAILED", error),
}
},
)
.description(
"Return a compact summary by default. Use --grep before reading raw output, or --lines START-END to expand a stable sequence range.",
)
.mcp(read_only())
.done(),
)
.command(
"stop",
tracked_typed::<RunIdArgs, TelemetryStopOptions, (), TelemetryCapture, _, _>(
"stop",
|context: TypedContext<RunIdArgs, TelemetryStopOptions, ()>| async move {
match DaemonClient
.call(
"execution.telemetry.stop",
serde_json::json!({
"id": context.args.id,
"idempotency_key": context.options.idempotency_key
}),
)
.await
{
Ok(capture) => TypedResult::ok(capture),
Err(error) => TypedResult::error("TELEMETRY_STOP_FAILED", error),
}
},
)
.description("Stop the sampler while preserving every retained measurement.")
.mcp(destructive(false))
.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, (), ExecutionInvocationResponse, _, _>(
"command",
move |context: TypedContext<RunArgv, PollCommandOptions, ()>| async move {
let level = match verbosity(verbosity_request!(context.options)) {
Ok(level) => level,
Err(error) => return error,
};
let (spec, parent_id, session_id, profile) =
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,
"profile": profile
}),
)
.await
{
Ok(invocation) if wait => invocation_result(invocation, level),
Ok(invocation) => TypedResult::ok(invocation_response(invocation, level)),
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, (), ExecutionInvocationResponse, _, _>(
"apoc",
move |context: TypedContext<PollMethodArgs, PollApocOptions, ()>| async move {
let level = match verbosity(verbosity_request!(context.options)) {
Ok(level) => level,
Err(error) => return error,
};
let (spec, parent_id, session_id, profile) =
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,
"profile": profile
}),
)
.await
{
Ok(invocation) if wait => invocation_result(invocation, level),
Ok(invocation) => TypedResult::ok(invocation_response(invocation, level)),
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,
error_code: options.error_code,
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,
recording_id: None,
recording_take: None,
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()
}
}
fn destructive_open_world(idempotent: bool) -> McpCommandOptions {
let mut options = destructive(idempotent);
options
.annotations
.as_mut()
.expect("destructive tools carry MCP annotations")
.open_world_hint = Some(true);
options
}
fn debugger_evaluation_annotations() -> McpCommandOptions {
McpCommandOptions {
destructive: true,
annotations: Some(McpAnnotations {
read_only_hint: Some(false),
destructive_hint: Some(true),
idempotent_hint: Some(true),
open_world_hint: Some(true),
..McpAnnotations::default()
}),
..McpCommandOptions::default()
}
}
#[cfg(test)]
mod tests {
use std::collections::{BTreeMap, BTreeSet};
use super::*;
use incurs::command::RequestContext;
use incurs::tool::{ToolCallOptions, ToolCallOutcome};
#[test]
fn dap_request_arguments_parses_a_json_string_into_an_object() {
let parsed =
dap_request_arguments(Some(Value::String("{\"threadId\":7}".to_string()))).unwrap();
assert_eq!(parsed, serde_json::json!({"threadId": 7}));
assert_eq!(dap_request_arguments(None).unwrap(), serde_json::json!({}));
assert_eq!(
dap_request_arguments(Some(Value::String(" ".to_string()))).unwrap(),
serde_json::json!({})
);
assert_eq!(
dap_request_arguments(Some(serde_json::json!({"a": 1}))).unwrap(),
serde_json::json!({"a": 1})
);
assert!(dap_request_arguments(Some(Value::String("notjson".to_string()))).is_err());
assert!(dap_request_arguments(Some(Value::String("[1,2]".to_string()))).is_err());
}
#[test]
fn provider_action_lifecycle_requests_include_the_invocation_purpose() {
let globals = serde_json::json!({"purpose": "Invoke the fixture provider."});
assert_eq!(
provider_action_run_params("return 1;".to_string(), 250, &globals, None),
serde_json::json!({
"code": "return 1;",
"timeout_ms": 250,
"purpose": "Invoke the fixture provider."
})
);
assert_eq!(
provider_action_start_params("return 2;".to_string(), &globals, None),
serde_json::json!({
"code": "return 2;",
"purpose": "Invoke the fixture provider."
})
);
}
#[test]
fn public_and_code_mode_catalogs_are_projected_from_one_surface_policy() {
let public = build_cli_for_surface(CommandSurface::Public, None).tool_catalog();
let code_mode = build_cli_for_surface(CommandSurface::CodeMode, None).tool_catalog();
let public_definitions = public
.definitions()
.into_iter()
.map(|definition| (definition.name.clone(), definition))
.collect::<BTreeMap<_, _>>();
let code_mode_definitions = code_mode
.definitions()
.into_iter()
.map(|definition| (definition.name.clone(), definition))
.collect::<BTreeMap<_, _>>();
let public_names = public_definitions.keys().cloned().collect::<BTreeSet<_>>();
let code_mode_names = code_mode_definitions
.keys()
.cloned()
.collect::<BTreeSet<_>>();
assert!(code_mode_names.is_subset(&public_names));
for (name, code_mode) in &code_mode_definitions {
let public = &public_definitions[name];
assert_eq!(
serde_json::to_value(public).unwrap(),
serde_json::to_value(code_mode).unwrap(),
"{name} differs between MCP and Code Mode projections"
);
}
let public_only = public_names
.difference(&code_mode_names)
.cloned()
.collect::<BTreeSet<_>>();
for prefix in CODE_MODE_EXCLUDED_GROUPS {
assert!(
public_only.iter().any(|name| name.starts_with(prefix)),
"declared exclusion {prefix} matched no command"
);
}
assert!(public_only.iter().all(|name| {
CODE_MODE_EXCLUDED_GROUPS
.iter()
.any(|prefix| name.starts_with(prefix))
}));
}
#[test]
fn provider_execution_options_require_and_preserve_an_immutable_generation() {
assert_eq!(
execution_backend(ExecutionBackendInput {
provider: Some("exeggutor".to_string()),
..ExecutionBackendInput::default()
})
.unwrap_err(),
"--provider requires --provider-generation"
);
let backend = execution_backend(ExecutionBackendInput {
provider: Some("exeggutor".to_string()),
provider_generation: Some("sha256:provider-v1".to_string()),
provider_options: Some(r#"{"image_ref":"local"}"#.to_string()),
..ExecutionBackendInput::default()
})
.unwrap();
let ExecutionBackendSpec::Provider {
name,
generation,
options,
} = backend
else {
panic!("provider flags selected the native backend");
};
assert_eq!(name, "exeggutor");
assert_eq!(generation, "sha256:provider-v1");
assert_eq!(options, serde_json::json!({ "image_ref": "local" }));
}
#[test]
fn isolated_execution_options_build_a_typed_backend_without_provider_registration() {
let backend = execution_backend(ExecutionBackendInput {
isolated: true,
image: Some(format!("sha256:{}", "a".repeat(64))),
workspace_mode: Some("read_write".to_string()),
guest_cwd: Some("/workspace/src".to_string()),
memory_mb: Some(2048),
cpu_count: Some(4),
pids_max: Some(256),
network: Some("none".to_string()),
exports: Some(vec![ExecutionExportSpec {
source: "/tmp/result".to_string(),
destination: "result".to_string(),
when: crate::model::ExecutionExportWhen::Always,
}]),
..ExecutionBackendInput::default()
})
.unwrap();
let ExecutionBackendSpec::Isolated { isolation } = backend else {
panic!("--isolated did not select the built-in isolation backend");
};
assert_eq!(isolation.image, format!("sha256:{}", "a".repeat(64)));
assert_eq!(isolation.workspace, IsolatedWorkspaceMode::ReadWrite);
assert_eq!(isolation.guest_cwd.as_deref(), Some("/workspace/src"));
assert_eq!(isolation.memory_mb, Some(2048));
assert_eq!(isolation.cpu_count, Some(4));
assert_eq!(isolation.pids_max, Some(256));
assert_eq!(isolation.network, IsolatedNetworkPolicy::None);
assert_eq!(isolation.exports.len(), 1);
assert_eq!(isolation.exports[0].source, "/tmp/result");
assert_eq!(isolation.exports[0].destination, "result");
assert_eq!(
execution_backend(ExecutionBackendInput {
isolated: true,
provider: Some("external".to_string()),
provider_generation: Some("sha256:external".to_string()),
..ExecutionBackendInput::default()
})
.unwrap_err(),
"--isolated cannot be combined with --provider"
);
assert_eq!(
execution_backend(ExecutionBackendInput {
exports: Some(vec![ExecutionExportSpec {
source: "/tmp/result".to_string(),
destination: "result".to_string(),
when: crate::model::ExecutionExportWhen::Success,
}]),
..ExecutionBackendInput::default()
})
.unwrap_err(),
"Isolation options require --isolated"
);
}
#[test]
fn rr_backend_is_typed_and_rejects_native_image_options() {
assert_eq!(rr_backend(Some("native"), None).unwrap(), RrBackend::Native);
assert_eq!(
rr_backend(Some("isolated"), Some("sha256:fixture".to_string())).unwrap(),
RrBackend::Isolated {
image: "sha256:fixture".to_string()
}
);
assert_eq!(
rr_backend(Some("native"), Some("local".to_string())).unwrap_err(),
"--image requires --backend isolated"
);
assert_eq!(
rr_backend(Some("container"), None).unwrap_err(),
"Unsupported rr backend \"container\"; expected native or isolated"
);
}
#[test]
fn normalizes_cli_and_structured_export_declarations() {
let exports = execution_exports_from_value(serde_json::json!([
"{\"source\":\"/tmp/one\",\"destination\":\"one\"}",
[{"source":"/tmp/two","destination":"two","when":"always"}]
]))
.unwrap();
assert_eq!(exports.len(), 2);
assert_eq!(exports[0].source, "/tmp/one");
assert_eq!(exports[0].when, crate::model::ExecutionExportWhen::Success);
assert_eq!(exports[1].destination, "two");
assert_eq!(exports[1].when, crate::model::ExecutionExportWhen::Always);
}
#[test]
fn normalizes_the_default_macos_lldb_adapter_without_changing_custom_argv() {
let default = dap_adapter_argv("lldb-dap".to_string(), Some(vec!["--wait".to_string()]));
#[cfg(target_os = "macos")]
assert_eq!(default, ["/usr/bin/xcrun", "lldb-dap", "--wait"]);
#[cfg(not(target_os = "macos"))]
assert_eq!(default, ["lldb-dap", "--wait"]);
let custom = dap_adapter_argv(
"/opt/debug-adapter".to_string(),
Some(vec!["--stdio".to_string()]),
);
assert_eq!(custom, ["/opt/debug-adapter", "--stdio"]);
}
#[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);
}
#[test]
fn generic_provider_actions_advertise_open_world_mutation() {
let catalog = build_cli().tool_catalog();
for name in ["action_run", "action_start"] {
let definition = catalog
.get(name)
.unwrap_or_else(|| panic!("missing MCP tool {name}"));
let annotations = definition
.annotations
.as_ref()
.unwrap_or_else(|| panic!("missing MCP annotations for {name}"));
assert_eq!(annotations.read_only_hint, Some(false), "{name}");
assert_eq!(annotations.destructive_hint, Some(true), "{name}");
assert_eq!(annotations.idempotent_hint, Some(false), "{name}");
assert_eq!(annotations.open_world_hint, Some(true), "{name}");
}
}
}