Skip to main content

dekopon_run/
lib.rs

1//! Immediate-mode provider execution and an unprivileged broker client for Dekopon.
2//!
3//! Direct and prompt modes load only read-only, import-free provider components. Explicit broker
4//! mode loads no component: it submits identity-free proposals to a separate authenticated broker
5//! and never constructs or receives authorization state.
6
7#![forbid(unsafe_code)]
8
9use std::{
10    env,
11    error::Error as _,
12    fs::File,
13    io::{self, Read, Write},
14    path::{Path, PathBuf},
15    time::{Duration, Instant},
16};
17
18#[cfg(unix)]
19use dekopon_agent::{BrokerLeg, BrokerLegError};
20use dekopon_agent::{
21    SessionInvoker, ShellRuntime,
22    prompt::{PromptError, PromptLimits, format_script_outcome, run_prompt},
23};
24#[cfg(unix)]
25use dekopon_broker_protocol::BrokerSocketDiscovery;
26#[cfg(unix)]
27use dekopon_broker_protocol::{BrokerClient, ClientError, InvocationOutcome, InvocationRequest};
28#[cfg(unix)]
29use dekopon_core::IdentifierError;
30use dekopon_core::{CapabilityId, ExternalSubject, ProviderId};
31use dekopon_model::{
32    chatgpt::{ChatGptCodexModel, ChatGptError},
33    model::{ChatModel, ModelError, OpenAiChatModel},
34};
35use dekopon_provider_host::{
36    HostLimits, HostOptions, ProviderHostError, ProviderManifest, ProviderRegistry,
37};
38use dekopon_shell::{
39    CapabilityCallResult, CapabilityDescription, CapabilityInvoker, Interpreter,
40    Limits as ShellLimits,
41};
42use serde::Serialize;
43use serde_json::Value;
44use thiserror::Error;
45use tracing::Instrument as _;
46
47use crate::cli::{BrokerCommand, BrokerConnectionArgs, Cli, Command, LimitArgs, ShellLimitArgs};
48
49#[cfg(unix)]
50mod chat;
51pub mod cli;
52mod trace;
53
54/// The prompt loop and session types now live in `dekopon-agent`; this re-export keeps the
55/// `dekopon_run::prompt` path stable for existing consumers and tests.
56pub use dekopon_agent::prompt;
57
58/// Runs a parsed CLI invocation and returns a process exit code.
59///
60/// Clap handles syntax failures before this function and exits with code `2`.
61#[must_use]
62pub async fn run(cli: Cli) -> i32 {
63    let trace_guard = match trace::initialize(
64        cli.verbose,
65        cli.no_color,
66        cli.trace.as_deref(),
67        &cli.telemetry,
68    ) {
69        Ok(guard) => guard,
70        Err(error) => {
71            eprintln!("error: {error}");
72            return 1;
73        }
74    };
75
76    let command_name = command_name(&cli.command);
77    let command_span = tracing::info_span!(
78        "runner.command",
79        command.name = command_name,
80        otel.kind = "internal"
81    );
82    // Instrumented rather than entered: an `Entered` guard held across an `.await` stays on the
83    // thread that parked the future, so any future refactor that polls `run` on a worker would
84    // silently mis-parent every event emitted there.
85    let exit_code = async {
86        match evaluate(&cli).await {
87            Ok(output) => match write_output(&output.text) {
88                Ok(()) => output.exit_code,
89                Err(error) if error.kind() == io::ErrorKind::BrokenPipe => output.exit_code,
90                Err(error) => {
91                    tracing::error!(
92                        target: "dekopon_run::audit",
93                        {
94                            audit.event = "runner.command.failed",
95                            command.name = command_name,
96                            error.type = "output-write",
97                        },
98                        "runner command failed"
99                    );
100                    eprintln!("error: could not write output: {error}");
101                    1
102                }
103            },
104            Err(error) => {
105                tracing::error!(
106                    target: "dekopon_run::audit",
107                    {
108                        audit.event = "runner.command.failed",
109                        command.name = command_name,
110                        error.type = error.telemetry_kind(),
111                    },
112                    "runner command failed"
113                );
114                report_error(&error, cli.verbose);
115                1
116            }
117        }
118    }
119    .instrument(command_span.clone())
120    .await;
121
122    // Close the root span before flushing short-lived OTLP exporters.
123    drop(command_span);
124    if let Err(error) = trace_guard.shutdown() {
125        eprintln!("error: {error}");
126        return 1;
127    }
128    exit_code
129}
130
131/// Stable, low-cardinality label for the command under the root span.
132///
133/// Exhaustive on purpose: a new subcommand must be given a name here rather than silently
134/// inheriting a catch-all that would make it invisible in a trace search.
135fn command_name(command: &Command) -> &'static str {
136    match command {
137        Command::Inspect { .. } => "inspect",
138        Command::Invoke { .. } => "invoke",
139        Command::Shell { .. } => "shell",
140        Command::Prompt { .. } => "prompt",
141        Command::Broker {
142            command: BrokerCommand::Capabilities { .. },
143        } => "broker.capabilities",
144        Command::Broker {
145            command: BrokerCommand::Invoke { .. },
146        } => "broker.invoke",
147        Command::Chat { .. } => "chat",
148    }
149}
150
151async fn evaluate(cli: &Cli) -> Result<CommandOutput, AppError> {
152    match &cli.command {
153        Command::Inspect { limits, providers } => {
154            let components = providers.components()?;
155            let span = tracing::info_span!("runner.inspect", provider.count = components.len());
156            let _entered = span.enter();
157            let registry = ProviderRegistry::load_with_options(
158                components,
159                host_limits(limits),
160                &providers.host_options(),
161            )?;
162            let manifests = registry.manifests().collect::<Vec<&ProviderManifest>>();
163            serde_json::to_string_pretty(&manifests)
164                .map(CommandOutput::success)
165                .map_err(AppError::Serialize)
166        }
167        Command::Invoke {
168            limits,
169            providers,
170            capability,
171            input,
172            input_file,
173            repeat,
174        } => {
175            let components = providers.components()?;
176            let span = tracing::info_span!(
177                "runner.invoke",
178                provider.count = components.len(),
179                capability.id = %capability,
180                invocation.count = repeat.get()
181            );
182            let _entered = span.enter();
183            let input = read_input(
184                input.as_deref(),
185                input_file.as_deref(),
186                limits.max_input_bytes,
187            )?;
188            let registry = ProviderRegistry::load_with_options(
189                components,
190                host_limits(limits),
191                &providers.host_options(),
192            )?;
193            let mut samples = TimingSamples::default();
194            let mut last = None;
195            let total_start = Instant::now();
196            for iteration in 1..=repeat.get() {
197                let invocation_span = tracing::info_span!(
198                    "runner.provider_invocation",
199                    capability.id = %capability,
200                    invocation.iteration = iteration
201                );
202                let _entered = invocation_span.enter();
203                let start = Instant::now();
204                match registry.invoke(capability, &input) {
205                    Ok(output) => {
206                        let elapsed = start.elapsed();
207                        samples.record(elapsed);
208                        // A benchmarking loop must not bill the sink for its own iteration count:
209                        // `--repeat 10000` would otherwise ship 10,000 records saying the same
210                        // thing. The first iteration names the provider and proves the loop ran;
211                        // the summary below carries the aggregate, and failures still report
212                        // individually because each one is a distinct fact.
213                        if iteration == 1 {
214                            tracing::info!(
215                                target: "dekopon_run::audit",
216                                {
217                                    audit.event = "guest.invocation.completed",
218                                    provider.id = %output.provider,
219                                    capability.id = %output.capability,
220                                    invocation.iteration = iteration,
221                                    duration_ms = milliseconds(elapsed),
222                                    outcome = "succeeded",
223                                },
224                                "guest provider invocation completed"
225                            );
226                        }
227                        last = Some(output);
228                    }
229                    Err(error) => {
230                        tracing::error!(
231                            target: "dekopon_run::audit",
232                            {
233                                audit.event = "guest.invocation.completed",
234                                capability.id = %capability,
235                                invocation.iteration = iteration,
236                                duration_ms = milliseconds(start.elapsed()),
237                                outcome = "failed",
238                            },
239                            "guest provider invocation failed"
240                        );
241                        return Err(error.into());
242                    }
243                }
244            }
245            let total = total_start.elapsed();
246            let output = last.expect("repeat is represented by NonZeroU32");
247            let report = InvocationReport::new(
248                output.provider,
249                output.capability,
250                repeat.get(),
251                total,
252                &samples,
253                output.output,
254            );
255            if repeat.get() > 1 {
256                tracing::info!(
257                    target: "dekopon_run::audit",
258                    {
259                        audit.event = "guest.invocation.summary",
260                        provider.id = %report.provider,
261                        capability.id = %report.capability,
262                        invocation.count = report.iterations,
263                        duration_ms = report.timing.total_ms,
264                        mean_duration_ms = report.timing.mean_ms,
265                        outcome = "succeeded",
266                    },
267                    "guest provider invocation loop completed"
268                );
269            }
270            serde_json::to_string_pretty(&report)
271                .map(CommandOutput::success)
272                .map_err(AppError::Serialize)
273        }
274        Command::Shell {
275            limits,
276            providers,
277            shell,
278            curl_capability,
279            script,
280        } => {
281            let components = providers.components()?;
282            let span = tracing::info_span!(
283                "runner.shell",
284                provider.count = components.len(),
285                shell.max_steps = shell.shell_max_steps,
286                shell.max_capability_calls = shell.shell_max_capability_calls
287            );
288            let _entered = span.enter();
289            let registry = ProviderRegistry::load_with_options(
290                components,
291                host_limits(limits),
292                &providers.host_options(),
293            )?;
294            let invoker = RegistryInvoker {
295                registry: &registry,
296            };
297            let outcome = Interpreter::new(shell_limits(shell))
298                .with_curl_capability(curl_capability.as_ref().map(CapabilityId::to_string))
299                .run(script, &invoker);
300            Ok(CommandOutput {
301                text: format_script_outcome(&outcome),
302                exit_code: i32::from(outcome.exit_code.get()),
303            })
304        }
305        Command::Broker { command } => evaluate_broker(command).await,
306        Command::Prompt {
307            limits,
308            providers,
309            shell,
310            broker,
311            connection,
312            curl_capability,
313            model,
314            chatgpt_subscription,
315            chatgpt_auth_file,
316            endpoint,
317            api_key_env,
318            system,
319            max_steps,
320            model_timeout_ms,
321            prompt,
322        } => {
323            let backend = if *chatgpt_subscription {
324                "chatgpt-subscription"
325            } else {
326                "openai-compatible"
327            };
328            let components = providers.components()?;
329            let settings = PromptSettings {
330                limits: host_limits(limits),
331                options: providers.host_options(),
332                shell: shell_limits(shell),
333                curl_capability: curl_capability.as_ref().map(CapabilityId::to_string),
334                providers: components.clone(),
335                model: model.clone(),
336                chatgpt_subscription: *chatgpt_subscription,
337                chatgpt_auth_file: chatgpt_auth_file.clone(),
338                endpoint: endpoint.clone(),
339                api_key_env: api_key_env.clone(),
340                system: system.clone(),
341                prompt: prompt.clone(),
342                model_timeout: Duration::from_millis(*model_timeout_ms),
343                prompt_limits: PromptLimits {
344                    max_steps: max_steps.get(),
345                    max_capability_calls: shell.shell_max_capability_calls,
346                },
347            };
348            evaluate_prompt(settings, *broker, connection)
349                .instrument(tracing::info_span!(
350                    "runner.prompt",
351                    provider.count = components.len(),
352                    model = %model,
353                    model.backend = backend,
354                    prompt.max_steps = max_steps.get(),
355                    prompt.broker = *broker
356                ))
357                .await
358        }
359        Command::Chat {
360            gateway,
361            subject,
362            conversation,
363        } => {
364            // The span carries no fields on purpose. The two values a chat session is configured
365            // by are a socket path and a declared subject, and `docs/observability.md` keeps both
366            // filesystem paths and external identities out of exported telemetry.
367            evaluate_chat(gateway, subject, conversation.clone())
368                .instrument(tracing::info_span!("runner.chat"))
369                .await
370        }
371    }
372}
373
374/// Runs one interactive gateway session on the blocking pool.
375///
376/// The loop is synchronous end to end — read a line, write a line, wait for a line — and the wait
377/// lasts as long as a whole agent session inside the daemon, so it belongs off the runtime's
378/// worker threads for exactly the reason a prompt session does.
379#[cfg(unix)]
380async fn evaluate_chat(
381    gateway: &Path,
382    subject: &ExternalSubject,
383    conversation: Option<String>,
384) -> Result<CommandOutput, AppError> {
385    let session = chat::ChatSession::new(gateway.to_path_buf(), subject.clone(), conversation)?;
386    let span = tracing::Span::current();
387    tokio::task::spawn_blocking(move || {
388        let _entered = span.enter();
389        chat::run(&session)
390    })
391    .await
392    .map_err(|error| AppError::Chat(chat::ChatError::Task(error)))??;
393
394    // Replies were printed as they arrived; there is nothing left for the caller to write.
395    Ok(CommandOutput::silent())
396}
397
398#[cfg(not(unix))]
399async fn evaluate_chat(
400    _gateway: &Path,
401    _subject: &ExternalSubject,
402    _conversation: Option<String>,
403) -> Result<CommandOutput, AppError> {
404    Err(AppError::ChatUnsupported)
405}
406
407/// Everything one prompt session needs, gathered before the blocking handoff.
408///
409/// This exists because the session runs on a blocking task: every field has to be owned and
410/// `Send`, so borrowing from the parsed CLI is not an option.
411struct PromptSettings {
412    limits: HostLimits,
413    options: HostOptions,
414    shell: ShellLimits,
415    curl_capability: Option<String>,
416    providers: Vec<PathBuf>,
417    model: String,
418    chatgpt_subscription: bool,
419    chatgpt_auth_file: Option<PathBuf>,
420    endpoint: String,
421    api_key_env: String,
422    system: Option<String>,
423    prompt: String,
424    model_timeout: Duration,
425    prompt_limits: PromptLimits,
426}
427
428/// Runs one prompt session, bridging the synchronous loop onto a blocking task.
429///
430/// Two boundaries this crate consumes are deliberately synchronous — `ChatModel` and
431/// `dekopon_shell::Interpreter` — and both can block for a long time: a model request is a real
432/// HTTP round trip, and a script can `sleep`, drive a broker round trip per command, or do both in
433/// a loop. Running that on a runtime worker thread would stall every other task in the process, so
434/// the whole session moves to the blocking pool and reaches back into the runtime only where it
435/// must, in [`BrokerLeg::invoke`].
436async fn evaluate_prompt(
437    settings: PromptSettings,
438    broker: bool,
439    connection: &BrokerConnectionArgs,
440) -> Result<CommandOutput, AppError> {
441    // Connection flags that silently do nothing are worse than a refusal: an operator who passes
442    // `--socket` believes the broker leg is live, and would read a "command not found" as the
443    // broker denying a capability rather than as never having been asked.
444    if !broker && connection.any_flag_supplied() {
445        return Err(AppError::BrokerFlagsWithoutOptIn);
446    }
447
448    let leg = connect_prompt_broker(broker, connection).await?;
449    let span = tracing::Span::current();
450    let outcome = tokio::task::spawn_blocking(move || {
451        let _entered = span.enter();
452        run_prompt_session(settings, leg)
453    })
454    .await
455    .map_err(AppError::PromptTask)??;
456
457    Ok(CommandOutput::success(outcome.answer))
458}
459
460/// Loads providers, builds the model client, and runs the loop. Blocking throughout.
461fn run_prompt_session(
462    settings: PromptSettings,
463    broker: Option<Box<dyn CapabilityInvoker + Send>>,
464) -> Result<prompt::PromptOutcome, AppError> {
465    let registry = ProviderRegistry::load_with_options(
466        settings.providers,
467        settings.limits,
468        &settings.options,
469    )?;
470    let model: Box<dyn ChatModel> = if settings.chatgpt_subscription {
471        Box::new(ChatGptCodexModel::new(
472            &settings.model,
473            settings.chatgpt_auth_file.as_deref(),
474            settings.model_timeout,
475        )?)
476    } else {
477        let bearer_token = read_optional_secret(&settings.api_key_env)?;
478        Box::new(OpenAiChatModel::new(
479            &settings.endpoint,
480            &settings.model,
481            bearer_token,
482            settings.model_timeout,
483        )?)
484    };
485    let runtime = ShellRuntime {
486        invoker: SessionInvoker {
487            direct: RegistryInvoker {
488                registry: &registry,
489            },
490            broker,
491        },
492        limits: settings.shell,
493        curl_capability: settings.curl_capability,
494    };
495
496    run_prompt(
497        model.as_ref(),
498        &runtime,
499        &settings.prompt,
500        settings.system.as_deref(),
501        settings.prompt_limits,
502    )
503    .map_err(AppError::from)
504}
505
506struct CommandOutput {
507    text: String,
508    exit_code: i32,
509}
510
511impl CommandOutput {
512    fn success(text: String) -> Self {
513        Self { text, exit_code: 0 }
514    }
515
516    /// A command that already streamed its own output and has nothing left to print.
517    #[cfg(unix)]
518    fn silent() -> Self {
519        Self {
520            text: String::new(),
521            exit_code: 0,
522        }
523    }
524}
525
526/// Adapts the direct provider registry to the interpreter's capability seam.
527///
528/// Direct mode performs no broker transition, so no invocation here can be *denied*: there is no
529/// authorization to refuse one. `Denied` stays reachable in the shared vocabulary because a
530/// broker-backed invoker will produce it; this adapter simply never does.
531struct RegistryInvoker<'a> {
532    registry: &'a ProviderRegistry,
533}
534
535impl CapabilityInvoker for RegistryInvoker<'_> {
536    fn granted(&self) -> Vec<String> {
537        self.registry
538            .capabilities()
539            .map(|(_provider, capability)| capability.id.to_string())
540            .collect()
541    }
542
543    fn is_granted(&self, capability: &str) -> bool {
544        capability.parse::<CapabilityId>().is_ok_and(|capability| {
545            self.registry
546                .capabilities()
547                .any(|(_provider, candidate)| candidate.id == capability)
548        })
549    }
550
551    fn describe(&self, capability: &str) -> Option<CapabilityDescription> {
552        let capability = capability.parse::<CapabilityId>().ok()?;
553        self.registry
554            .capabilities()
555            .find(|(_provider, candidate)| candidate.id == capability)
556            .map(|(_provider, candidate)| CapabilityDescription {
557                capability: candidate.id.to_string(),
558                description: candidate.description.clone(),
559                input_schema: candidate.input_schema.clone(),
560            })
561    }
562
563    fn invoke(&self, capability: &str, input: Value) -> CapabilityCallResult {
564        let Ok(capability) = capability.parse::<CapabilityId>() else {
565            return CapabilityCallResult::NotFound;
566        };
567        match self.registry.invoke(&capability, &input) {
568            Ok(output) => CapabilityCallResult::Succeeded(output.output),
569            Err(ProviderHostError::UnknownCapability { .. }) => CapabilityCallResult::NotFound,
570            Err(error) => CapabilityCallResult::Failed {
571                error: error.to_string(),
572            },
573        }
574    }
575}
576
577/// Connects the prompt session's optional broker leg before any blocking work starts.
578///
579/// The capability set is snapshotted here, on the async side, for two reasons. It lets `cap --list`
580/// answer for both legs without a round trip per script, and it turns "the daemon is not running"
581/// into one clear startup failure instead of a capability that inexplicably reports "command not
582/// found" halfway through a script a model already committed to.
583#[cfg(unix)]
584async fn connect_prompt_broker(
585    enabled: bool,
586    connection: &BrokerConnectionArgs,
587) -> Result<Option<Box<dyn CapabilityInvoker + Send>>, AppError> {
588    if !enabled {
589        return Ok(None);
590    }
591    let (client, socket_tier) = broker_client(connection)?;
592    let leg = BrokerLeg::connect(client, "dekopon-run-prompt")
593        .await
594        .map_err(|error| match error {
595            BrokerLegError::Client(source) => AppError::BrokerClient(source),
596            BrokerLegError::SessionIdentifier(source) => AppError::SessionIdentifier(source),
597            BrokerLegError::DuplicateCapabilities { capabilities } => {
598                AppError::BrokerDuplicateCapabilities { capabilities }
599            }
600        })?;
601    // The socket tier and the session trace are what a "this session saw zero capabilities"
602    // investigation asks for first: which broker was reached, and which audit records are this
603    // session's. The socket path itself stays out, as it does everywhere else in telemetry.
604    tracing::info!(
605        target: "dekopon_run::audit",
606        {
607            audit.event = "broker.leg.connected",
608            broker.socket.tier = socket_tier,
609            session.trace = %leg.session_trace(),
610            capability.count = leg.granted().len(),
611        },
612        "broker leg connected for prompt session"
613    );
614
615    Ok(Some(Box::new(leg)))
616}
617
618/// Builds one authenticated broker client from the shared connection flags.
619///
620/// Every broker-reaching command resolves the socket, the trusted server UID, and the frame limits
621/// the same way; one copy means a new discovery tier or limit floor lands everywhere at once.
622/// Returns the resolved socket tier alongside the client so callers can report which one answered
623/// without repeating the precedence rules.
624#[cfg(unix)]
625fn broker_client(
626    connection: &BrokerConnectionArgs,
627) -> Result<(BrokerClient, &'static str), AppError> {
628    let socket = BrokerSocketDiscovery::from_process(connection.socket.clone())
629        .resolve()
630        .ok_or(AppError::BrokerSocketUnresolved)?;
631    let server_uid = resolve_broker_server_uid(connection.server_uid);
632    let client = BrokerClient::new(socket.path(), server_uid, connection.frame_limits())?;
633    Ok((client, socket.tier().label()))
634}
635
636#[cfg(not(unix))]
637async fn connect_prompt_broker(
638    enabled: bool,
639    _connection: &BrokerConnectionArgs,
640) -> Result<Option<Box<dyn CapabilityInvoker + Send>>, AppError> {
641    if enabled {
642        return Err(AppError::BrokerUnsupported);
643    }
644    Ok(None)
645}
646
647fn shell_limits(limits: &ShellLimitArgs) -> ShellLimits {
648    ShellLimits {
649        max_steps: limits.shell_max_steps,
650        max_recursion_depth: limits.shell_max_recursion_depth,
651        max_output_bytes: limits.shell_max_output_bytes,
652        max_output_lines: limits.shell_max_output_lines,
653        timeout: Duration::from_millis(limits.shell_timeout_ms),
654        max_capability_calls: limits.shell_max_capability_calls,
655        max_value_bytes: limits.shell_max_value_bytes,
656        allow_clock: limits.shell_allow_clock,
657    }
658}
659
660fn host_limits(limits: &LimitArgs) -> HostLimits {
661    HostLimits {
662        max_memory_bytes: limits.max_memory_bytes,
663        max_input_bytes: limits.max_input_bytes,
664        max_output_bytes: limits.max_output_bytes,
665        fuel: limits.fuel,
666        timeout: Duration::from_millis(limits.timeout_ms),
667        // Table, instance, and memory-count ceilings have no command-line flag; the host defaults
668        // bound the allocation paths `--max-memory-bytes` does not reach.
669        ..HostLimits::default()
670    }
671}
672
673#[cfg(unix)]
674async fn evaluate_broker(command: &BrokerCommand) -> Result<CommandOutput, AppError> {
675    const ENVELOPE_RESERVE_BYTES: usize = 4 * 1024;
676
677    match command {
678        BrokerCommand::Capabilities { connection } => {
679            async {
680                let (client, _tier) = broker_client(connection)?;
681                let capabilities = client.capabilities().await?;
682                serde_json::to_string_pretty(&capabilities)
683                    .map(CommandOutput::success)
684                    .map_err(AppError::Serialize)
685            }
686            .instrument(tracing::info_span!("runner.broker.capabilities"))
687            .await
688        }
689        BrokerCommand::Invoke {
690            connection,
691            capability,
692            invocation_id,
693            trace_id,
694            input,
695            input_file,
696        } => {
697            async {
698                let (client, _tier) = broker_client(connection)?;
699                let input = read_input(
700                    input.as_deref(),
701                    input_file.as_deref(),
702                    connection
703                        .frame_limits()
704                        .max_frame_bytes
705                        .saturating_sub(ENVELOPE_RESERVE_BYTES),
706                )?;
707                if !input.is_object() {
708                    return Err(AppError::BrokerInputObject);
709                }
710                let result = client
711                    .invoke(InvocationRequest {
712                        id: invocation_id.clone(),
713                        capability: capability.clone(),
714                        trace: trace_id.clone(),
715                        trace_parent: dekopon_agent::current_trace_parent(),
716                        input,
717                    })
718                    .await?;
719                let exit_code = if result.outcome == InvocationOutcome::Succeeded {
720                    0
721                } else {
722                    1
723                };
724                serde_json::to_string_pretty(&result)
725                    .map(|text| CommandOutput { text, exit_code })
726                    .map_err(AppError::Serialize)
727            }
728            .instrument(tracing::info_span!(
729                "runner.broker.invoke",
730                capability.id = %capability,
731                invocation.id = %invocation_id,
732                trace.id = %trace_id
733            ))
734            .await
735        }
736    }
737}
738
739#[cfg(not(unix))]
740async fn evaluate_broker(_command: &BrokerCommand) -> Result<CommandOutput, AppError> {
741    Err(AppError::BrokerUnsupported)
742}
743
744/// Resolves the trusted broker server UID, defaulting to the caller's own effective UID.
745#[cfg(unix)]
746fn resolve_broker_server_uid(explicit: Option<u32>) -> u32 {
747    explicit.unwrap_or_else(|| rustix::process::geteuid().as_raw())
748}
749
750fn read_input(
751    inline: Option<&str>,
752    path: Option<&Path>,
753    maximum: usize,
754) -> Result<Value, AppError> {
755    let source = match (inline, path) {
756        (Some(input), None) => {
757            if input.len() > maximum {
758                return Err(AppError::InputTooLarge {
759                    length: input.len(),
760                    maximum,
761                });
762            }
763            input.to_owned()
764        }
765        (None, Some(path)) if path == Path::new("-") => {
766            let stdin = io::stdin();
767            read_bounded(stdin.lock(), "stdin", maximum)?
768        }
769        (None, Some(path)) => {
770            let file = File::open(path).map_err(|source| AppError::ReadInput {
771                path: path.to_path_buf(),
772                source,
773            })?;
774            read_bounded(file, &path.display().to_string(), maximum)?
775        }
776        (None, None) => "{}".to_owned(),
777        (Some(_), Some(_)) => unreachable!("Clap rejects conflicting input sources"),
778    };
779
780    serde_json::from_str(&source).map_err(AppError::ParseInput)
781}
782
783fn read_bounded(reader: impl Read, source_name: &str, maximum: usize) -> Result<String, AppError> {
784    let read_limit = u64::try_from(maximum).unwrap_or(u64::MAX).saturating_add(1);
785    let mut bytes = Vec::new();
786    reader
787        .take(read_limit)
788        .read_to_end(&mut bytes)
789        .map_err(|source| AppError::ReadInputStream {
790            source_name: source_name.to_owned(),
791            source,
792        })?;
793    if bytes.len() > maximum {
794        return Err(AppError::InputTooLarge {
795            length: bytes.len(),
796            maximum,
797        });
798    }
799    String::from_utf8(bytes).map_err(|source| AppError::InputUtf8 {
800        source_name: source_name.to_owned(),
801        source,
802    })
803}
804
805#[allow(
806    clippy::map_err_ignore,
807    reason = "the error `OsString::into_string` returns is the rejected OsString itself — the \
808              secret this function reads — so naming the cause would print key bytes to stderr"
809)]
810fn read_optional_secret(variable: &str) -> Result<Option<String>, AppError> {
811    if variable.trim().is_empty() {
812        return Err(AppError::Environment(
813            "API key environment variable name must not be empty".to_owned(),
814        ));
815    }
816    let Some(value) = env::var_os(variable) else {
817        return Ok(None);
818    };
819    value
820        .into_string()
821        .map(Some)
822        .map_err(|_| AppError::Environment(format!("environment variable {variable} is not UTF-8")))
823}
824
825fn write_output(output: &str) -> io::Result<()> {
826    // A command that printed as it went returns nothing here, and a bare newline would append a
827    // blank line to output it already finished.
828    if output.is_empty() {
829        return Ok(());
830    }
831    let stdout = io::stdout();
832    let mut handle = stdout.lock();
833    handle.write_all(output.as_bytes())?;
834    if !output.ends_with('\n') {
835        handle.write_all(b"\n")?;
836    }
837    handle.flush()
838}
839
840fn report_error(error: &AppError, verbosity: u8) {
841    eprintln!("error: {error}");
842    if verbosity > 0 {
843        let mut source = error.source();
844        while let Some(cause) = source {
845            eprintln!("  caused by: {cause}");
846            source = cause.source();
847        }
848    }
849    if verbosity > 1 {
850        eprintln!("  debug: {error:#?}");
851    }
852}
853
854#[derive(Debug, Serialize)]
855#[serde(rename_all = "camelCase")]
856struct InvocationReport {
857    provider: ProviderId,
858    capability: CapabilityId,
859    iterations: u32,
860    timing: TimingReport,
861    output: Value,
862}
863
864impl InvocationReport {
865    fn new(
866        provider: ProviderId,
867        capability: CapabilityId,
868        iterations: u32,
869        total: Duration,
870        samples: &TimingSamples,
871        output: Value,
872    ) -> Self {
873        let minimum = samples.minimum.unwrap_or_default();
874        let maximum = samples.maximum.unwrap_or_default();
875        let mean = samples.total / iterations;
876
877        Self {
878            provider,
879            capability,
880            iterations,
881            timing: TimingReport {
882                total_ms: milliseconds(total),
883                min_ms: milliseconds(minimum),
884                mean_ms: milliseconds(mean),
885                max_ms: milliseconds(maximum),
886            },
887            output,
888        }
889    }
890}
891
892#[derive(Debug, Serialize)]
893#[serde(rename_all = "camelCase")]
894struct TimingReport {
895    total_ms: f64,
896    min_ms: f64,
897    mean_ms: f64,
898    max_ms: f64,
899}
900
901#[derive(Debug, Default)]
902struct TimingSamples {
903    total: Duration,
904    minimum: Option<Duration>,
905    maximum: Option<Duration>,
906}
907
908impl TimingSamples {
909    fn record(&mut self, sample: Duration) {
910        self.total = self.total.saturating_add(sample);
911        self.minimum = Some(self.minimum.map_or(sample, |current| current.min(sample)));
912        self.maximum = Some(self.maximum.map_or(sample, |current| current.max(sample)));
913    }
914}
915
916pub(crate) fn milliseconds(duration: Duration) -> f64 {
917    duration.as_secs_f64() * 1000.0
918}
919
920#[derive(Debug, Error)]
921enum AppError {
922    #[cfg(unix)]
923    #[error(transparent)]
924    BrokerClient(#[from] ClientError),
925    #[cfg(unix)]
926    #[error("could not determine broker socket path; pass --socket or set DEKOPON_BROKER_SOCKET")]
927    BrokerSocketUnresolved,
928    #[cfg(not(unix))]
929    #[error("broker client mode requires Unix peer credentials and Unix-domain sockets")]
930    BrokerUnsupported,
931    #[cfg(unix)]
932    #[error(transparent)]
933    Chat(#[from] chat::ChatError),
934    #[cfg(not(unix))]
935    #[error("the gateway chat client requires a Unix-domain socket")]
936    ChatUnsupported,
937    #[error(
938        "broker connection flags were supplied without --broker; \
939         a prompt session contacts no broker until you ask it to"
940    )]
941    BrokerFlagsWithoutOptIn,
942    #[cfg(unix)]
943    #[error("could not derive a unique identifier for this broker session")]
944    SessionIdentifier(#[source] IdentifierError),
945    #[cfg(unix)]
946    #[error("the broker answered with duplicate capability identifiers: {capabilities}")]
947    BrokerDuplicateCapabilities {
948        /// Every repeated identifier, in identifier order.
949        capabilities: String,
950    },
951    #[error("the prompt session did not run to completion")]
952    PromptTask(#[source] tokio::task::JoinError),
953    #[error("broker capability input must be a JSON object")]
954    BrokerInputObject,
955    #[error(transparent)]
956    ChatGpt(#[from] ChatGptError),
957    #[error(transparent)]
958    Provider(#[from] ProviderHostError),
959    #[error(transparent)]
960    ProviderArgs(#[from] cli::ProviderArgsError),
961    #[error(transparent)]
962    Model(#[from] ModelError),
963    #[error(transparent)]
964    Prompt(#[from] PromptError),
965    #[error("could not read input file {}", path.display())]
966    ReadInput {
967        path: PathBuf,
968        #[source]
969        source: io::Error,
970    },
971    #[error("could not read capability input from {source_name}")]
972    ReadInputStream {
973        source_name: String,
974        #[source]
975        source: io::Error,
976    },
977    #[error("capability input from {source_name} is not UTF-8")]
978    InputUtf8 {
979        source_name: String,
980        #[source]
981        source: std::string::FromUtf8Error,
982    },
983    #[error("capability input is {length} bytes; the maximum is {maximum}")]
984    InputTooLarge { length: usize, maximum: usize },
985    #[error("capability input is not valid JSON")]
986    ParseInput(#[source] serde_json::Error),
987    #[error("could not serialize command output")]
988    Serialize(#[source] serde_json::Error),
989    #[error("invalid environment configuration: {0}")]
990    Environment(String),
991}
992
993impl AppError {
994    /// Stable, low-cardinality failure category for telemetry.
995    ///
996    /// Deliberately not the error's own message: several variants wrap untrusted provider,
997    /// transport, or model text, and `docs/observability.md` keeps that text out of exported
998    /// telemetry. An operator correlates the category here with the full message on stderr.
999    fn telemetry_kind(&self) -> &'static str {
1000        match self {
1001            #[cfg(unix)]
1002            Self::BrokerClient(_) => "broker-client",
1003            #[cfg(unix)]
1004            Self::BrokerSocketUnresolved => "broker-socket-unresolved",
1005            #[cfg(not(unix))]
1006            Self::BrokerUnsupported => "broker-unsupported",
1007            // Delegated rather than flattened: a chat session fails in a dozen distinct ways and
1008            // collapsing them to one category would hide which end of the socket went wrong.
1009            #[cfg(unix)]
1010            Self::Chat(error) => error.telemetry_kind(),
1011            #[cfg(not(unix))]
1012            Self::ChatUnsupported => "chat-unsupported",
1013            Self::BrokerFlagsWithoutOptIn => "broker-flags-without-opt-in",
1014            #[cfg(unix)]
1015            Self::SessionIdentifier(_) => "session-identifier",
1016            #[cfg(unix)]
1017            Self::BrokerDuplicateCapabilities { .. } => "broker-duplicate-capabilities",
1018            Self::PromptTask(_) => "prompt-task",
1019            Self::BrokerInputObject => "broker-input-object",
1020            Self::ChatGpt(_) => "chatgpt",
1021            Self::Provider(_) => "provider",
1022            Self::ProviderArgs(_) => "provider-args",
1023            Self::Model(_) => "model",
1024            Self::Prompt(_) => "prompt",
1025            Self::ReadInput { .. } => "input-read",
1026            Self::ReadInputStream { .. } => "input-stream-read",
1027            Self::InputUtf8 { .. } => "input-utf8",
1028            Self::InputTooLarge { .. } => "input-too-large",
1029            Self::ParseInput(_) => "input-json",
1030            Self::Serialize(_) => "output-serialize",
1031            Self::Environment(_) => "environment",
1032        }
1033    }
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038    use std::{fs, time::Duration};
1039
1040    use serde_json::json;
1041
1042    #[cfg(unix)]
1043    use super::{AppError, BrokerSocketDiscovery, resolve_broker_server_uid};
1044    use super::{InvocationReport, TimingSamples, read_input};
1045
1046    #[test]
1047    fn defaults_direct_invocations_to_an_empty_object() {
1048        assert_eq!(
1049            read_input(None, None, 1024).expect("default input"),
1050            json!({})
1051        );
1052    }
1053
1054    #[test]
1055    fn reads_json_input_files() {
1056        let directory = tempfile::tempdir().expect("temporary directory");
1057        let path = directory.path().join("input.json");
1058        fs::write(&path, r#"{"message":"hello"}"#).expect("fixture writes");
1059
1060        assert_eq!(
1061            read_input(None, Some(&path), 1024).expect("file input"),
1062            json!({"message": "hello"})
1063        );
1064    }
1065
1066    #[test]
1067    fn timing_reports_include_all_samples() {
1068        let mut samples = TimingSamples::default();
1069        samples.record(Duration::from_millis(2));
1070        samples.record(Duration::from_millis(4));
1071        let report = InvocationReport::new(
1072            "echo".parse().expect("valid provider"),
1073            "echo.echo".parse().expect("valid capability"),
1074            2,
1075            Duration::from_millis(7),
1076            &samples,
1077            json!({}),
1078        );
1079
1080        assert_eq!(report.timing.total_ms, 7.0);
1081        assert_eq!(report.timing.min_ms, 2.0);
1082        assert_eq!(report.timing.mean_ms, 3.0);
1083        assert_eq!(report.timing.max_ms, 4.0);
1084    }
1085
1086    // The precedence itself is pinned in `dekopon-broker-protocol`, which owns the one definition
1087    // every client shares. What belongs here is the mapping this crate applies on top of it: an
1088    // unresolvable socket is a runner usage failure with actionable guidance, not a silent default.
1089    #[cfg(unix)]
1090    #[test]
1091    fn unresolvable_broker_socket_reports_actionable_guidance() {
1092        let error = BrokerSocketDiscovery::new(None, None, None, None)
1093            .resolve()
1094            .ok_or(AppError::BrokerSocketUnresolved)
1095            .expect_err("no socket candidate");
1096
1097        assert!(matches!(error, AppError::BrokerSocketUnresolved));
1098        assert!(
1099            error
1100                .to_string()
1101                .contains("pass --socket or set DEKOPON_BROKER_SOCKET"),
1102            "the refusal must name both ways out: {error}"
1103        );
1104    }
1105
1106    #[cfg(unix)]
1107    #[test]
1108    fn broker_server_uid_defaults_to_the_calling_process() {
1109        assert_eq!(
1110            resolve_broker_server_uid(None),
1111            rustix::process::geteuid().as_raw()
1112        );
1113        assert_eq!(resolve_broker_server_uid(Some(4242)), 4242);
1114    }
1115
1116    // Composite dispatch and broker-leg behavior are covered in `dekopon-agent`, where those
1117    // types now live.
1118}