cli-engine 0.2.0

Rust CLI framework for consistent command modules
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
use std::{
    collections::BTreeMap,
    future::Future,
    sync::Arc,
    time::{Duration, Instant},
};

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use tokio::sync::OnceCell;

use crate::{
    CommandResult, Credential, Dispatcher, Result, SchemaRegistry, Tier,
    error::{CliCoreError, exit_code_for_error},
    output::{
        Envelope, HumanViewRegistry, OutputFormat, PipelineOpts, apply_pipeline,
        build_error_envelope, is_valid_output_format, render_human_with_registry_for_schema,
    },
};

/// JSON object map used for command args and metadata.
pub type ValueMap = Map<String, Value>;

/// Per-command metadata consumed by middleware.
///
/// Command specs build this metadata automatically. Applications can also
/// adjust it through `CliConfig::meta_resolver`.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct CommandMeta {
    /// Whether `--dry-run` should short-circuit command business logic.
    pub dry_run_prompt: bool,
    /// Provider-specific auth metadata.
    pub auth_metadata: BTreeMap<String, String>,
    /// OAuth-style scopes derived from `auth_metadata["scopes"]`.
    pub scopes: Vec<String>,
}

impl CommandMeta {
    /// Returns the selected auth provider, if one is present.
    #[must_use]
    pub fn provider(&self) -> Option<&str> {
        self.auth_metadata.get("provider").map(String::as_str)
    }

    /// Returns the risk tier, defaulting to [`Tier::Read`].
    #[must_use]
    pub fn tier(&self) -> Tier {
        self.auth_metadata
            .get("tier")
            .and_then(|value| value.parse::<Tier>().ok())
            .unwrap_or(Tier::Read)
    }

    /// Returns a fixed auth environment override, if present.
    #[must_use]
    pub fn fixed_env(&self) -> Option<&str> {
        self.auth_metadata.get("fixed_env").map(String::as_str)
    }
}

/// Declares whether a command requires an authenticated credential.
///
/// This is the policy that the engine enforces; it is separate from the
/// *mechanism* of resolution (see [`CredentialResolver`]). The default is
/// [`Required`](AuthRequirement::Required), which fails closed: the engine
/// resolves the credential before the handler runs, so a command that should be
/// gated behind authentication cannot execute unauthenticated even if its
/// handler never reads the credential, and audit/activity identity is always
/// populated for it.
///
/// `--schema` and `--dry-run` short-circuit before the engine resolves a
/// `Required` credential, so they never trigger an authentication flow on their
/// own regardless of requirement.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum AuthRequirement {
    /// The engine resolves the credential before the handler runs (fail-closed).
    ///
    /// A failure to resolve is rendered as an `auth-error` and the handler never
    /// runs. This is the default.
    #[default]
    Required,
    /// Resolution is deferred to the handler.
    ///
    /// The engine does not resolve a credential on the command's behalf; the
    /// handler (or an authorizer) triggers the auth flow only by calling
    /// [`CredentialResolver::resolve`]/[`try_resolve`](CredentialResolver::try_resolve).
    /// Use for commands that behave differently when authenticated but must still
    /// run when the user is logged out.
    Optional,
    /// The command never authenticates and has no credential.
    ///
    /// Equivalent to the legacy `no_auth(true)` marker: default-env injection is
    /// suppressed and [`CredentialResolver::resolve`] returns an error.
    None,
}

impl AuthRequirement {
    /// Returns `true` when the command never authenticates.
    #[must_use]
    pub fn is_none(self) -> bool {
        matches!(self, Self::None)
    }

    /// Returns `true` when the engine must resolve the credential before the handler runs.
    #[must_use]
    pub fn is_required(self) -> bool {
        matches!(self, Self::Required)
    }

    /// Returns `true` when resolution is deferred to the handler.
    #[must_use]
    pub fn is_optional(self) -> bool {
        matches!(self, Self::Optional)
    }
}

/// Resolves the credential for a single command invocation, memoizing the result.
///
/// Resolution — including any interactive browser/OAuth flow — runs at most once:
/// a handler and an authorizer that both ask share a single resolution, and the
/// engine resolves it up front for [`AuthRequirement::Required`] commands. For
/// [`Optional`](AuthRequirement::Optional) commands resolution is deferred until a
/// handler or authorizer calls [`resolve`](Self::resolve) or
/// [`try_resolve`](Self::try_resolve), and `--schema`/`--dry-run` short-circuit
/// before any resolution happens.
///
/// The resolved credential is memoized: a handler and an authorizer that both
/// ask share a single resolution. Clones share the same underlying state, so the
/// engine can observe (via [`peek`](Self::peek)) whatever a handler resolved.
#[derive(Clone)]
pub struct CredentialResolver {
    inner: Arc<ResolverInner>,
}

#[derive(Debug)]
struct ResolverInner {
    auth: Dispatcher,
    provider: String,
    env: String,
    command_path: String,
    tier: String,
    no_auth: bool,
    cell: OnceCell<Credential>,
}

impl std::fmt::Debug for CredentialResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("CredentialResolver")
            .field("provider", &self.inner.provider)
            .field("env", &self.inner.env)
            .field("no_auth", &self.inner.no_auth)
            .field("resolved", &self.inner.cell.get().is_some())
            .finish_non_exhaustive()
    }
}

impl CredentialResolver {
    fn new(
        auth: Dispatcher,
        provider: String,
        env: String,
        command_path: String,
        tier: String,
        no_auth: bool,
    ) -> Self {
        Self {
            inner: Arc::new(ResolverInner {
                auth,
                provider,
                env,
                command_path,
                tier,
                no_auth,
                cell: OnceCell::new(),
            }),
        }
    }

    /// Resolves the credential, memoizing the result after the first success.
    ///
    /// # Errors
    ///
    /// Returns an error when the command is marked [`no_auth`](crate::CommandSpec::no_auth)
    /// (such commands have no credential), or when the auth provider fails to
    /// produce one.
    pub async fn resolve(&self) -> Result<Credential> {
        if self.inner.no_auth {
            return Err(CliCoreError::message(
                "command is marked no_auth and has no credential",
            ));
        }
        let inner = &self.inner;
        let credential = inner
            .cell
            .get_or_try_init(async || {
                inner
                    .auth
                    .get_credential(
                        &inner.provider,
                        &inner.env,
                        &inner.command_path,
                        &inner.tier,
                    )
                    .await
                    // Mark resolution failures so the engine can classify them as
                    // `auth-error` based on the error a handler actually returns,
                    // rather than tracking a separate side-channel flag that could
                    // go stale if the handler swallows the failure.
                    .map_err(|source| auth_resolution_error(&inner.provider, source))
            })
            .await?;
        Ok(credential.clone())
    }

    /// Resolves the credential when one is available.
    ///
    /// Returns `Ok(None)` for no-auth commands, `Ok(Some(_))` on success, and
    /// propagates the provider error on failure. Use this for commands whose
    /// auth is genuinely optional; most commands should call
    /// [`resolve`](Self::resolve) instead.
    ///
    /// # Errors
    ///
    /// Propagates the auth provider error when resolution is attempted and fails.
    pub async fn try_resolve(&self) -> Result<Option<Credential>> {
        if self.inner.no_auth {
            return Ok(None);
        }
        self.resolve().await.map(Some)
    }

    /// Returns the memoized credential without triggering resolution.
    ///
    /// Yields `None` until something resolves the credential. Used by the engine
    /// to record identity in audit/activity output after a handler runs.
    #[must_use]
    pub fn peek(&self) -> Option<&Credential> {
        self.inner.cell.get()
    }
}

/// Marks a credential-resolution failure so its auth origin is detectable via
/// [`CliCoreError::is_auth`], leaving errors that are already auth-typed
/// unchanged. Display is preserved except for the `auth: provider …:` prefix that
/// the [`AuthProvider`](CliCoreError::AuthProvider) wrapper adds.
fn auth_resolution_error(provider: &str, source: CliCoreError) -> CliCoreError {
    match source {
        auth @ (CliCoreError::MissingAuthProvider(_) | CliCoreError::AuthProvider { .. }) => auth,
        other => CliCoreError::AuthProvider {
            provider: provider.to_owned(),
            source: Box::new(other),
        },
    }
}

#[async_trait]
/// Authorization hook called before business logic.
///
/// The authorizer receives a [`CredentialResolver`] rather than an
/// already-resolved credential so authorization remains lazy: an authorizer that
/// does not need identity never triggers a credential/auth flow. Call
/// [`CredentialResolver::try_resolve`] only when a decision actually depends on
/// the credential.
pub trait Authorizer: Send + Sync + std::fmt::Debug {
    /// Verifies whether `command_path` may run with the provided args, reason, and tier.
    async fn authorize(
        &self,
        command_path: &str,
        args: &ValueMap,
        credential: &CredentialResolver,
        reason: &str,
        tier: Tier,
    ) -> Result<()>;
}

#[async_trait]
/// Audit hook called for success, error, denied, auth-error, and dry-run outcomes.
pub trait Auditor: Send + Sync + std::fmt::Debug {
    /// Appends an audit record.
    async fn append(
        &self,
        command_path: &str,
        args: &ValueMap,
        identity: &str,
        result: &str,
        reason: &str,
    ) -> Result<()>;
}

#[async_trait]
/// Activity hook for structured command lifecycle events.
pub trait ActivityEmitter: Send + Sync + std::fmt::Debug {
    /// Emits one completed command event.
    async fn emit(&self, event: ActivityEvent) -> Result<()>;
}

/// Structured activity event emitted after command execution paths.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ActivityEvent {
    /// UTC timestamp in RFC3339 seconds format.
    pub timestamp: String,
    /// CLI application id.
    pub app: String,
    /// Colon-separated command path.
    pub command: String,
    /// Selected environment.
    pub env: String,
    /// Backend/system id.
    pub backend: String,
    /// Human identity from the resolved credential.
    pub identity: String,
    /// Subject identifier from the resolved credential.
    pub sub: String,
    /// Account type from the resolved credential.
    pub account_type: String,
    /// Outcome such as `ok`, `error`, `denied`, `auth-error`, or `dry-run`.
    pub status: String,
    /// Error message for failed outcomes.
    pub error: String,
    /// User-provided reason.
    pub reason: String,
    /// Effective command args.
    pub args: ValueMap,
    /// Command duration in milliseconds.
    pub duration_ms: i64,
    /// Reserved extension metadata.
    pub meta: ValueMap,
}

/// Cross-cutting command execution state and dependencies.
///
/// Middleware is intentionally a plain, cloneable struct so tests and command
/// handlers can inspect what will be used for a run. Application setup usually
/// mutates it through `CliConfig` hooks or `ModuleContext`.
#[derive(Clone, Debug, Default)]
pub struct Middleware {
    /// Optional authorization provider.
    pub authz: Option<Arc<dyn Authorizer>>,
    /// Auth provider dispatcher.
    pub auth: Dispatcher,
    /// Optional audit sink.
    pub auditor: Option<Arc<dyn Auditor>>,
    /// Optional activity sink.
    pub activity: Option<Arc<dyn ActivityEmitter>>,
    /// Application id used in output metadata.
    pub app_id: String,
    /// Fallback auth provider for commands without an explicit provider.
    pub default_auth_provider: String,
    /// Output format: `json`, `human`, or `toon`.
    pub output_format: String,
    /// Selected environment.
    pub env: String,
    /// Metadata verbosity selector.
    pub verbose: String,
    /// Whether mutating commands should short-circuit.
    pub dry_run: bool,
    /// User field projection.
    pub fields: String,
    /// JMESPath per-item list predicate.
    pub filter: String,
    /// JMESPath whole-result expression.
    pub expr: String,
    /// Client-side page size.
    pub limit: i64,
    /// Client-side page offset.
    pub offset: i64,
    /// User reason passed to authorization and audit.
    pub reason: String,
    /// Whether schema rendering was requested.
    pub schema: bool,
    /// Optional command deadline.
    pub timeout: Option<Duration>,
    /// Debug selector, interpreted by applications.
    pub debug: String,
    /// Search query, interpreted before command execution.
    pub search: String,
    /// Output schema registry.
    pub schema_registry: SchemaRegistry,
    /// Human output view registry.
    pub human_views: HumanViewRegistry,
}

/// Rendered result produced by middleware.
#[derive(Clone, Debug, PartialEq)]
pub struct MiddlewareOutput {
    /// Prepared output envelope.
    pub envelope: Envelope,
    /// Rendered output string.
    pub rendered: String,
    /// Process-style exit code.
    pub exit_code: i32,
}

/// Inputs for one middleware-managed command execution.
#[derive(Clone, Debug, PartialEq)]
pub struct MiddlewareRequest<'request> {
    /// Per-command metadata used by authentication, authorization, dry-run, audit, and activity.
    pub meta: CommandMeta,
    /// Colon-separated command path.
    pub command_path: &'request str,
    /// Backend/system id used in output metadata and generic error attribution.
    pub system: &'request str,
    /// Arguments explicitly supplied by the user.
    pub user_args: ValueMap,
    /// Effective arguments, including defaults.
    pub args: ValueMap,
    /// Default field projection when `--fields` is absent.
    pub default_fields: &'request str,
    /// Authentication requirement enforced by the engine for this command.
    pub auth: AuthRequirement,
}

impl Middleware {
    /// Creates middleware with empty registries and default dependencies.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Runs the middleware chain for a command.
    pub async fn run<F, Fut, Output>(
        &self,
        request: MiddlewareRequest<'_>,
        command: F,
    ) -> Result<MiddlewareOutput>
    where
        F: FnOnce(CredentialResolver) -> Fut + Send,
        Fut: Future<Output = Result<Output>> + Send,
        Output: Into<CommandResult>,
    {
        let start = Instant::now();
        let MiddlewareRequest {
            meta,
            command_path,
            system,
            user_args,
            mut args,
            default_fields,
            auth,
        } = request;
        let no_auth = auth.is_none();
        let command_system = effective_request_system(system, command_path);
        if !no_auth && !self.env.is_empty() && !args.contains_key("env") {
            args.insert("env".to_owned(), Value::String(self.env.clone()));
        }

        // Build a lazy resolver instead of resolving eagerly. No auth flow runs
        // until a handler or authorizer actually asks for the credential, so
        // commands that never use it (and `--schema`/`--dry-run`) skip auth.
        let provider_name = meta
            .provider()
            .filter(|provider| !provider.is_empty())
            .unwrap_or(&self.default_auth_provider)
            .to_owned();
        let resolved_env = meta.fixed_env().unwrap_or(&self.env).to_owned();
        let tier_text = meta
            .auth_metadata
            .get("tier")
            .map_or("", String::as_str)
            .to_owned();
        let resolver = CredentialResolver::new(
            self.auth.clone(),
            provider_name.clone(),
            resolved_env,
            command_path.to_owned(),
            tier_text,
            no_auth,
        );

        if no_auth
            && let Some(output) =
                self.render_schema_if_requested(command_path, start, &user_args, &args, "")?
        {
            return Ok(output);
        }

        if let Some(authz) = &self.authz
            && let Err(err) = authz
                .authorize(command_path, &args, &resolver, &self.reason, meta.tier())
                .await
        {
            // An authorizer may have resolved the credential to make its
            // decision; reflect whatever it resolved in audit identity.
            let identity = resolver.peek().map_or("", |cred| cred.identity.as_str());
            // Classify by the error the authorizer returned: a propagated
            // resolution failure is auth-typed; a policy denial is not.
            let had_auth_error = err.is_auth();
            let result_tag = if had_auth_error {
                "auth-error"
            } else {
                "denied"
            };
            // Attribute auth-provider failures to the provider so telemetry can
            // distinguish them from command backends.
            let backend = if had_auth_error {
                provider_name.as_str()
            } else {
                command_path
            };
            self.write_audit(command_path, &args, identity, result_tag)
                .await;
            self.emit_activity(
                command_path,
                &args,
                resolver.peek(),
                result_tag,
                backend,
                &err.to_string(),
                start,
            )
            .await;
            return self.render_error(&err, command_path, start, &user_args, &args, identity);
        }

        // If the authorizer resolved the credential, include its identity in the
        // schema output metadata. `peek()` never triggers resolution, so schema
        // still doesn't provoke auth on its own.
        let schema_identity = resolver.peek().map_or("", |cred| cred.identity.as_str());
        if let Some(output) = self.render_schema_if_requested(
            command_path,
            start,
            &user_args,
            &args,
            schema_identity,
        )? {
            return Ok(output);
        }

        if self.dry_run && meta.dry_run_prompt {
            let identity = resolver.peek().map_or("", |cred| cred.identity.as_str());
            self.write_audit(command_path, &args, identity, "dry-run")
                .await;
            self.emit_activity(
                command_path,
                &args,
                resolver.peek(),
                "dry-run",
                command_path,
                "",
                start,
            )
            .await;
            let envelope = Envelope::success(
                json!({
                    "command": command_path,
                    "action": "dry-run: would execute",
                }),
                command_path,
            )
            .with_dry_run();
            return self.render_envelope(
                envelope,
                "",
                command_path,
                start,
                &user_args,
                &args,
                identity,
            );
        }

        // Fail closed by default: for `Required` commands the engine resolves the
        // credential before the handler runs, so a command that must be
        // authenticated cannot execute unauthenticated even if its handler never
        // reads the credential, and its audit/activity identity is always
        // populated. `--schema`/`--dry-run` return above, so they never reach this
        // point; `Optional`/`None` commands defer resolution to the handler.
        if auth.is_required()
            && let Err(err) = resolver.resolve().await
        {
            // Mirror the handler-path auth-error treatment: classify as
            // `auth-error` and attribute the activity backend to the auth provider
            // so telemetry can distinguish auth-provider failures from command
            // backends. Resolution failed, so there is no identity to record.
            self.write_audit(command_path, &args, "", "auth-error")
                .await;
            self.emit_activity(
                command_path,
                &args,
                resolver.peek(),
                "auth-error",
                provider_name.as_str(),
                &err.to_string(),
                start,
            )
            .await;
            return self.render_error(&err, command_path, start, &user_args, &args, "");
        }

        let result = match command(resolver.clone()).await {
            Ok(result) => result.into(),
            Err(err) => {
                // A deferred `resolve()` failure surfaces as a handler error;
                // classify it as `auth-error` when the error the handler returned
                // is itself auth-typed. A handler that swallows a resolution
                // failure and then fails for another reason returns a non-auth
                // error here, so it is not misclassified.
                let identity = resolver.peek().map_or("", |cred| cred.identity.as_str());
                let (result_tag, error_system, activity_backend) = if err.is_auth() {
                    // Render against the command path, but attribute the activity
                    // backend to the auth provider so telemetry can distinguish
                    // auth-provider failures from command backends.
                    ("auth-error", command_path, provider_name.as_str())
                } else {
                    let system = err.system().unwrap_or(&command_system);
                    ("error", system, system)
                };
                self.write_audit(command_path, &args, identity, result_tag)
                    .await;
                self.emit_activity(
                    command_path,
                    &args,
                    resolver.peek(),
                    result_tag,
                    activity_backend,
                    &err.to_string(),
                    start,
                )
                .await;
                return self.render_error(&err, error_system, start, &user_args, &args, identity);
            }
        };
        // The handler may have resolved the credential; surface its identity.
        let identity = resolver.peek().map_or("", |cred| cred.identity.as_str());
        self.write_audit(command_path, &args, identity, "ok").await;
        self.emit_activity(
            command_path,
            &args,
            resolver.peek(),
            "ok",
            &command_system,
            "",
            start,
        )
        .await;

        let CommandResult { data, metadata } = result;
        self.render_envelope(
            Envelope::success(data, command_system).with_next_actions(metadata.next_actions),
            default_fields,
            command_path,
            start,
            &user_args,
            &args,
            identity,
        )
    }

    #[doc(hidden)]
    pub async fn run_no_auth<F, Fut>(
        &self,
        meta: CommandMeta,
        command_path: &str,
        user_args: ValueMap,
        args: ValueMap,
        default_fields: &str,
        command: F,
    ) -> Result<MiddlewareOutput>
    where
        F: FnOnce() -> Fut + Send,
        Fut: Future<Output = Result<CommandResult>> + Send,
    {
        self.run(
            MiddlewareRequest {
                meta,
                command_path,
                system: fallback_system(command_path),
                user_args,
                args,
                default_fields,
                auth: AuthRequirement::None,
            },
            async move |_resolver| command().await,
        )
        .await
    }

    async fn write_audit(&self, command_path: &str, args: &ValueMap, identity: &str, result: &str) {
        if let Some(auditor) = &self.auditor
            && let Err(err) = auditor
                .append(command_path, args, identity, result, &self.reason)
                .await
        {
            tracing::warn!(command = command_path, error = %err, "audit log write failed");
        }
    }

    #[allow(clippy::too_many_arguments)]
    async fn emit_activity(
        &self,
        command_path: &str,
        args: &ValueMap,
        credential: Option<&Credential>,
        result: &str,
        backend: &str,
        error: &str,
        start: Instant,
    ) {
        let Some(activity) = &self.activity else {
            return;
        };
        let (identity, sub, account_type) = credential.map_or_else(
            || (String::new(), String::new(), String::new()),
            |credential| {
                (
                    credential.identity.clone(),
                    credential.sub.clone(),
                    credential.account_type.clone(),
                )
            },
        );
        let duration_ms = i64::try_from(start.elapsed().as_millis()).unwrap_or(i64::MAX);
        let event = ActivityEvent {
            timestamp: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            app: self.app_id.clone(),
            command: command_path.to_owned(),
            env: self.env.clone(),
            backend: backend.to_owned(),
            identity,
            sub,
            account_type,
            status: result.to_owned(),
            error: error.to_owned(),
            reason: self.reason.clone(),
            args: args.clone(),
            duration_ms,
            meta: ValueMap::new(),
        };
        if let Err(err) = activity.emit(event).await {
            tracing::warn!(command = command_path, error = %err, "activity emit failed");
        }
    }

    fn render_schema_if_requested(
        &self,
        command_path: &str,
        start: Instant,
        user_args: &ValueMap,
        effective_args: &ValueMap,
        identity: &str,
    ) -> Result<Option<MiddlewareOutput>> {
        if self.schema
            && let Some(schema) = self.schema_registry.get_by_path(command_path)
        {
            return self
                .render_envelope(
                    Envelope::success(schema, self.app_id.clone()),
                    "",
                    command_path,
                    start,
                    user_args,
                    effective_args,
                    identity,
                )
                .map(Some);
        }
        Ok(None)
    }

    #[allow(clippy::too_many_arguments)]
    fn render_envelope(
        &self,
        mut envelope: Envelope,
        default_fields: &str,
        command_path: &str,
        start: Instant,
        user_args: &ValueMap,
        effective_args: &ValueMap,
        identity: &str,
    ) -> Result<MiddlewareOutput> {
        if !is_valid_output_format(&self.output_format) {
            let err = CliCoreError::InvalidOutputFormat(self.output_format.clone());
            return self.render_error(
                &err,
                &self.app_id,
                start,
                user_args,
                effective_args,
                identity,
            );
        }
        let output_format = self.output_format.parse::<OutputFormat>()?;
        let mut fields = if self.fields.is_empty() {
            default_fields
        } else {
            &self.fields
        };
        if output_format == OutputFormat::Human && self.fields.is_empty() {
            fields = "";
        }
        if let Some(data) = &mut envelope.data {
            let pagination = apply_pipeline(
                data,
                &PipelineOpts {
                    filter: self.filter.clone(),
                    limit: self.limit,
                    offset: self.offset,
                    expr: self.expr.clone(),
                    fields: fields.to_owned(),
                },
            )?;
            if let Some(pagination) = pagination
                && let Some(metadata) = &mut envelope.metadata
            {
                metadata.pagination = Some(pagination);
            }
        }
        envelope.with_context(
            command_path,
            &self.env,
            identity,
            start.elapsed(),
            Some(Value::Object(user_args.clone())),
            Some(Value::Object(effective_args.clone())),
        );
        let system = envelope
            .metadata
            .as_ref()
            .map(|metadata| metadata.system.as_str())
            .unwrap_or_default()
            .to_owned();
        let prepared = envelope.prepare_for_render(&self.verbose);
        let rendered = if output_format == OutputFormat::Human {
            render_human_with_registry_for_schema(&prepared, &self.human_views, &system)
        } else {
            crate::output::render(output_format, &prepared)?
        };
        Ok(MiddlewareOutput {
            envelope: prepared,
            rendered,
            exit_code: 0,
        })
    }

    fn render_error(
        &self,
        err: &(dyn std::error::Error + 'static),
        system: &str,
        start: Instant,
        user_args: &ValueMap,
        effective_args: &ValueMap,
        identity: &str,
    ) -> Result<MiddlewareOutput> {
        let mut envelope = build_error_envelope(err, system);
        envelope.with_context(
            "",
            &self.env,
            identity,
            start.elapsed(),
            Some(Value::Object(user_args.clone())),
            Some(Value::Object(effective_args.clone())),
        );
        let prepared = envelope.prepare_for_render(&self.verbose);
        let rendered = crate::output::render_format(&self.output_format, &prepared)?;
        Ok(MiddlewareOutput {
            envelope: prepared,
            rendered,
            exit_code: exit_code_for_error(err),
        })
    }
}

/// Convenience helper for building a JSON object map.
#[must_use]
pub fn value_map(entries: impl IntoIterator<Item = (impl Into<String>, Value)>) -> ValueMap {
    entries
        .into_iter()
        .map(|(key, value)| (key.into(), value))
        .collect()
}

fn effective_request_system(system: &str, command_path: &str) -> String {
    if system.is_empty() {
        return fallback_system(command_path).to_owned();
    }
    system.to_owned()
}

fn fallback_system(command_path: &str) -> &str {
    command_path
        .split_once(':')
        .map_or(command_path, |(system, _)| system)
}

impl From<CliCoreError> for Value {
    fn from(error: CliCoreError) -> Self {
        Value::String(error.to_string())
    }
}