acorn-lib 0.3.2

ACORN library
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
//! Typed operation registry and JSON-RPC 2.0 transport
use crate::agent::{run_inference, InferenceBackend, InferenceReadiness, InferenceRequest, InferenceResult};
use crate::analyzer::fix::{CheckReferences, FixReport, FixSuggestionRequest};
use crate::io::api::webhooks::store::OperationQueue;
use crate::io::workflow::{RepositoryChangeSet, RepositoryInput, RepositoryWorkflowRegistry};
use crate::io::ApiResult;
use crate::util::constants::app::{APPLICATION, JSON_RPC_VERSION};
use acorn_core::prelude::{Box, String, Vec};
use acorn_schema::validation::Validate;
use alloc::sync::Arc;
use color_eyre::eyre::eyre;
use core::fmt;
use core::future::Future;
use core::pin::Pin;
use futures::StreamExt;
use schemars::{schema_for, JsonSchema};
use serde::de::{DeserializeOwned, Error as DeError, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

#[cfg(feature = "agentic")]
pub mod http;

/// JSON-RPC internal error code.
pub const INTERNAL_ERROR: i32 = -32603;
/// JSON-RPC invalid parameters error code.
pub const INVALID_PARAMS: i32 = -32602;
/// JSON-RPC invalid request error code.
pub const INVALID_REQUEST: i32 = -32600;
/// JSON-RPC method-not-found error code.
pub const METHOD_NOT_FOUND: i32 = -32601;
/// JSON-RPC parse error code.
pub const PARSE_ERROR: i32 = -32700;
/// ACORN authorization-policy error code.
pub const POLICY_DENIED: i32 = -32001;
type OperationFuture = Pin<Box<dyn Future<Output = Result<Value, RpcError>> + Send>>;
type OperationHandler = Arc<dyn Fn(Value, InvocationContext) -> OperationFuture + Send + Sync>;
/// Source transport for an operation invocation.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum InvocationOrigin {
    /// Direct in-process invocation.
    Direct,
    /// Protobuf/gRPC invocation.
    Grpc,
    /// JSON-RPC HTTP invocation.
    JsonRpc,
    /// Normalized webhook invocation.
    Webhook,
}
enum ParsedCall {
    Invalid { id: Value, error: RpcError },
    Notification { method: MethodName, params: Value },
    Request { id: RequestId, method: MethodName, params: Value },
}
/// String or integer JSON-RPC request identifier.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum RequestId {
    /// Signed integer request identifier.
    Number(i64),
    /// String request identifier.
    String(String),
}
/// Result of dispatching one JSON-RPC document.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Dispatch {
    /// Serialized JSON-RPC response, absent for notifications.
    pub body: Option<Vec<u8>>,
    /// Recommended HTTP status.
    pub status_code: u16,
}
#[derive(Serialize)]
#[serde(deny_unknown_fields)]
struct ErrorResponse {
    error: RpcError,
    id: Value,
    jsonrpc: &'static str,
}
/// Policy and provenance supplied to one registered operation.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct InvocationContext {
    /// Whether inference handlers may run.
    pub allow_inference: bool,
    /// Whether mutating handlers may run.
    pub allow_mutation: bool,
    /// Optional transport correlation identifier.
    pub correlation_id: Option<String>,
    /// Maximum serialized result size.
    pub max_output_bytes: usize,
    /// Whether external-system interaction is forbidden.
    pub offline: bool,
    /// Transport that initiated the invocation.
    pub origin: InvocationOrigin,
    /// Authenticated principal.
    pub principal: Principal,
}
/// Validated JSON-RPC method name in the ACORN namespace.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, Ord, PartialEq, PartialOrd, Serialize, Validate)]
#[serde(try_from = "String", into = "String")]
pub struct MethodName {
    /// Ordered method components following the application namespace.
    #[validate(length(min = 1), each(nonempty))]
    pub parts: Vec<String>,
}
/// JSON-RPC 2.0 notification used by internal event adapters.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Notification {
    /// Protocol version, always [`JSON_RPC_VERSION`].
    pub jsonrpc: String,
    /// Registered operation name.
    pub method: MethodName,
    /// Operation parameters.
    pub params: Value,
}
/// Registered operation metadata.
#[derive(Clone, Debug, Serialize)]
#[serde(deny_unknown_fields)]
pub struct OperationDefinition {
    /// Declared side effects.
    pub effects: OperationEffects,
    /// JSON-RPC method name.
    pub name: MethodName,
    /// JSON Schema for operation parameters.
    pub parameters_schema: Value,
    /// JSON Schema for the operation result.
    pub result_schema: Value,
}
/// Effect metadata enforced before an operation handler runs.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct OperationEffects {
    /// Whether the operation can access credentials.
    pub credentials: bool,
    /// Whether the operation can destroy or irreversibly replace data.
    pub destructive: bool,
    /// Whether the operation can read from the host filesystem.
    pub filesystem_read: bool,
    /// Whether the operation can write to the host filesystem.
    pub filesystem_write: bool,
    /// Whether the operation can invoke inference services.
    pub inference: bool,
    /// Whether the operation may change state.
    pub mutation: bool,
    /// Whether the operation can read from remote network services.
    pub network_read: bool,
    /// Whether the operation can start or communicate with processes.
    pub process: bool,
}
/// Immutable registry of explicitly registered ACORN operations.
#[derive(Clone, Default)]
pub struct OperationRegistry {
    operations: Vec<RegisteredOperation>,
}
/// Authenticated caller identity supplied by a transport adapter.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Principal {
    /// Stable caller identifier.
    pub identifier: String,
}
#[derive(Clone)]
struct RegisteredOperation {
    definition: OperationDefinition,
    handler: OperationHandler,
}
/// Secret-safe JSON-RPC or operation error.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RpcError {
    /// Stable JSON-RPC or ACORN error code.
    pub code: i32,
    /// Optional bounded public diagnostic data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
    /// Stable public error message.
    pub message: String,
}
struct StrictValue(Value);
#[derive(Serialize)]
#[serde(deny_unknown_fields)]
struct SuccessResponse {
    id: RequestId,
    jsonrpc: &'static str,
    result: Value,
}
impl Dispatch {
    fn serialize(value: Value) -> Self {
        match serde_json::to_vec(&value) {
            | Ok(body) => Self {
                body: Some(body),
                status_code: 200,
            },
            | Err(_) => Self {
                body: Some(
                    format!(r#"{{"jsonrpc":"{JSON_RPC_VERSION}","id":null,"error":{{"code":-32603,"message":"Internal error"}}}}"#).into_bytes(),
                ),
                status_code: 500,
            },
        }
    }
}
impl Default for InvocationContext {
    fn default() -> Self {
        Self {
            allow_inference: false,
            allow_mutation: false,
            correlation_id: None,
            max_output_bytes: 1024 * 1024,
            offline: false,
            origin: InvocationOrigin::Direct,
            principal: Principal {
                identifier: "local".to_string(),
            },
        }
    }
}
impl fmt::Display for MethodName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{APPLICATION}.{}", self.parts.join("."))
    }
}
impl<'a, const N: usize> From<[&'a str; N]> for MethodName {
    fn from(parts: [&'a str; N]) -> Self {
        Self {
            parts: parts.into_iter().map(str::to_string).collect(),
        }
    }
}
impl TryFrom<&str> for MethodName {
    type Error = color_eyre::Report;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::try_from(value.to_string())
    }
}
impl TryFrom<String> for MethodName {
    type Error = color_eyre::Report;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        let prefix = format!("{APPLICATION}.");
        match value.strip_prefix(&prefix) {
            | Some(value) => {
                let name = Self {
                    parts: value.split('.').map(str::to_string).collect(),
                };
                name.validate()
                    .map(|()| name)
                    .map_err(|why| eyre!("Invalid JSON-RPC method name — {why}"))
            }
            | None => Err(eyre!("Operation name '{value}' must use the non-reserved '{APPLICATION}.' namespace")),
        }
    }
}
impl Notification {
    /// Construct a notification for one registered ACORN operation.
    pub fn new(method: MethodName, params: Value) -> ApiResult<Self> {
        method
            .validate()
            .map_err(|why| eyre!("Invalid JSON-RPC method name — {why}"))
            .map(|()| Self {
                jsonrpc: JSON_RPC_VERSION.to_string(),
                method,
                params,
            })
    }
}
impl OperationDefinition {
    /// Create typed operation metadata and its parameter/result schemas.
    pub fn new<I: JsonSchema, O: JsonSchema>(name: MethodName, effects: OperationEffects) -> ApiResult<Self> {
        name.validate()
            .map_err(|why| eyre!("Invalid JSON-RPC method name — {why}"))
            .map(|()| Self {
                effects,
                name,
                parameters_schema: serde_json::to_value(schema_for!(I)).unwrap_or(Value::Null),
                result_schema: serde_json::to_value(schema_for!(O)).unwrap_or(Value::Null),
            })
    }
}
impl fmt::Debug for OperationRegistry {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let definitions: Vec<OperationDefinition> = self.operations.iter().map(|operation| operation.definition.clone()).collect();
        formatter.debug_struct("OperationRegistry").field("definitions", &definitions).finish()
    }
}
impl OperationRegistry {
    /// Build the baseline ACORN operation registry.
    pub fn acorn() -> ApiResult<Self> {
        #[derive(Deserialize, JsonSchema)]
        #[serde(deny_unknown_fields)]
        struct OperationInput {
            operation_key: String,
        }
        #[derive(JsonSchema, Serialize)]
        #[serde(deny_unknown_fields)]
        struct OperationStatusOutput {
            state: Option<String>,
        }
        #[derive(JsonSchema, Serialize)]
        #[serde(deny_unknown_fields)]
        struct ReplayOutput {
            queued: bool,
        }
        #[derive(Deserialize, JsonSchema)]
        #[serde(deny_unknown_fields)]
        struct ProcessInput {
            input: RepositoryInput,
            workflow: String,
        }
        #[derive(Deserialize, JsonSchema)]
        #[serde(deny_unknown_fields)]
        struct VersionInput {}
        #[derive(JsonSchema, Serialize)]
        #[serde(deny_unknown_fields)]
        struct VersionOutput {
            version: String,
        }
        let registry = OperationDefinition::new::<VersionInput, VersionOutput>(MethodName::from(["version"]), OperationEffects::default())
            .and_then(|definition| {
                Self::default().register(definition, |_: VersionInput, _| async {
                    Ok(VersionOutput {
                        version: env!("CARGO_PKG_VERSION").to_string(),
                    })
                })
            })
            .and_then(|registry| {
                OperationDefinition::new::<ProcessInput, RepositoryChangeSet>(MethodName::from(["workflows", "process"]), OperationEffects::default())
                    .and_then(|definition| {
                        registry.register(definition, |request: ProcessInput, _| async move {
                            RepositoryWorkflowRegistry::acorn().and_then(|registry| registry.process(&request.workflow, request.input))
                        })
                    })
            });
        registry
            .and_then(|registry| {
                OperationDefinition::new::<OperationInput, OperationStatusOutput>(
                    MethodName::from(["operations", "status"]),
                    OperationEffects::default(),
                )
                .and_then(|status| {
                    registry.register(status, |request: OperationInput, _| async move {
                        OperationQueue::configured()
                            .state(&request.operation_key)
                            .map(|state| OperationStatusOutput {
                                state: state.map(|state| state.to_string()),
                            })
                    })
                })
            })
            .and_then(|registry| {
                OperationDefinition::new::<OperationInput, ReplayOutput>(
                    MethodName::from(["operations", "replay"]),
                    OperationEffects {
                        filesystem_read: true,
                        filesystem_write: true,
                        mutation: true,
                        ..OperationEffects::default()
                    },
                )
                .and_then(|replay| {
                    registry.register(replay, |request: OperationInput, _| async move {
                        OperationQueue::configured()
                            .replay(&request.operation_key)
                            .map(|queued| ReplayOutput { queued })
                    })
                })
            })
    }
    /// Dispatch one JSON-RPC 2.0 document through this operation registry.
    pub async fn dispatch(&self, body: &[u8], context: InvocationContext) -> Dispatch {
        match serde_json::from_slice::<StrictValue>(body).map(|StrictValue(value)| value) {
            | Ok(Value::Array(values)) if values.is_empty() => RpcError::new(INVALID_REQUEST, "Invalid Request").dispatch(Value::Null),
            | Ok(Value::Array(values)) => {
                let responses = self.dispatch_calls(values, context).await;
                match responses.is_empty() {
                    | true => Dispatch {
                        body: None,
                        status_code: 204,
                    },
                    | false => Dispatch::serialize(Value::Array(responses)),
                }
            }
            | Ok(value) => match self.dispatch_call(value, context).await {
                | Some(response) => Dispatch::serialize(response),
                | None => Dispatch {
                    body: None,
                    status_code: 204,
                },
            },
            | Err(_) => RpcError::new(PARSE_ERROR, "Parse error").dispatch(Value::Null),
        }
    }
    async fn dispatch_call(&self, value: Value, context: InvocationContext) -> Option<Value> {
        match ParsedCall::from(value) {
            | ParsedCall::Invalid { id, error } => Some(error.value(id)),
            | ParsedCall::Notification { method, params } => {
                self.invoke(&method, params, context).await.ok();
                None
            }
            | ParsedCall::Request { id, method, params } => {
                let context = InvocationContext {
                    correlation_id: Some(id.as_string()),
                    ..context
                };
                Some(match self.invoke(&method, params, context).await {
                    | Ok(result) => serde_json::to_value(SuccessResponse {
                        id,
                        jsonrpc: JSON_RPC_VERSION,
                        result,
                    })
                    .unwrap_or_else(|_| RpcError::internal().value(Value::Null)),
                    | Err(error) => error.value(serde_json::to_value(id).unwrap_or(Value::Null)),
                })
            }
        }
    }
    async fn dispatch_calls(&self, values: Vec<Value>, context: InvocationContext) -> Vec<Value> {
        futures::stream::iter(values)
            .then(|value| self.dispatch_call(value, context.clone()))
            .filter_map(core::future::ready)
            .collect()
            .await
    }
    /// Invoke a registered operation after enforcing declared effects and output bounds.
    pub async fn invoke(&self, method: &MethodName, params: Value, context: InvocationContext) -> Result<Value, RpcError> {
        match self.operations.iter().find(|operation| operation.definition.name == *method) {
            | Some(operation) => match policy_error(&operation.definition.effects, &context) {
                | Some(error) => Err(error),
                | None => (operation.handler)(params, context.clone()).await.and_then(|result| {
                    serde_json::to_vec(&result).map_err(|_| RpcError::internal()).and_then(|encoded| {
                        match encoded.len() <= context.max_output_bytes.max(1) {
                            | true => Ok(result),
                            | false => Err(RpcError::new(INTERNAL_ERROR, "Operation result exceeded the configured output limit")),
                        }
                    })
                }),
            },
            | None => Err(RpcError::new(METHOD_NOT_FOUND, "Method not found")),
        }
    }
    /// Register one typed handler, rejecting invalid or duplicate method names.
    pub fn register<I, O, F, Fut>(self, definition: OperationDefinition, handler: F) -> ApiResult<Self>
    where
        I: DeserializeOwned + Send + 'static,
        O: Serialize + Send + 'static,
        F: Fn(I, InvocationContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ApiResult<O>> + Send + 'static,
    {
        match self.operations.iter().any(|operation| operation.definition.name == definition.name) {
            | true => Err(eyre!("Duplicate operation name '{}'", definition.name)),
            | false => {
                let name = definition.name.clone();
                let handler = Arc::new(handler);
                let typed_handler = move |params: Value, context: InvocationContext| -> OperationFuture {
                    let input = serde_json::from_value::<I>(params).map_err(|_| RpcError::new(INVALID_PARAMS, "Invalid method parameters"));
                    let handler = Arc::clone(&handler);
                    let name = name.clone();
                    Box::pin(async move {
                        match input {
                            | Ok(input) => handler(input, context)
                                .await
                                .map_err(|_| RpcError::new(INTERNAL_ERROR, format!("Operation '{name}' failed")))
                                .and_then(|output| serde_json::to_value(output).map_err(|_| RpcError::internal())),
                            | Err(error) => Err(error),
                        }
                    })
                };
                let mut operations = self.operations;
                operations.push(RegisteredOperation {
                    definition,
                    handler: Arc::new(typed_handler),
                });
                operations.sort_by(|left, right| left.definition.name.cmp(&right.definition.name));
                Ok(Self { operations })
            }
        }
    }
    /// Register the inference run, readiness, and fix-suggestion operations with one backend.
    pub fn register_inference<B>(self, backend: B) -> ApiResult<Self>
    where
        B: InferenceBackend + 'static,
    {
        let backend = Arc::new(backend);
        OperationDefinition::new::<InferenceRequest, InferenceResult>(
            MethodName::from(["inference", "run"]),
            OperationEffects {
                inference: true,
                ..OperationEffects::default()
            },
        )
        .and_then(|definition| {
            let backend = Arc::clone(&backend);
            self.register(definition, move |request: InferenceRequest, _| {
                let backend = Arc::clone(&backend);
                async move { run_inference(backend.as_ref(), &request).await }
            })
        })
        .and_then(|registry| {
            OperationDefinition::new::<InferenceRequest, InferenceReadiness>(
                MethodName::from(["inference", "readiness"]),
                OperationEffects {
                    inference: true,
                    ..OperationEffects::default()
                },
            )
            .and_then(|definition| {
                let backend = Arc::clone(&backend);
                registry.register(definition, move |request: InferenceRequest, _| {
                    let backend = Arc::clone(&backend);
                    async move { InferenceReadiness::run(backend.as_ref(), &request).await }
                })
            })
        })
        .and_then(|registry| {
            OperationDefinition::new::<FixSuggestionRequest, FixReport>(
                MethodName::from(["fixes", "suggest"]),
                OperationEffects {
                    inference: true,
                    ..OperationEffects::default()
                },
            )
            .and_then(|definition| {
                let backend = Arc::clone(&backend);
                registry.register(definition, move |request: FixSuggestionRequest, _| {
                    let backend = Arc::clone(&backend);
                    async move { request.references.suggest(backend.as_ref(), &request.options).await }
                })
            })
        })
    }
}
impl From<Value> for ParsedCall {
    fn from(value: Value) -> Self {
        match value {
            | Value::Object(object) => Self::from_object(object),
            | _ => Self::Invalid {
                id: Value::Null,
                error: RpcError::new(INVALID_REQUEST, "Invalid Request"),
            },
        }
    }
}
impl ParsedCall {
    fn from_object(mut object: Map<String, Value>) -> Self {
        let id_value = object.remove("id");
        let jsonrpc = object.remove("jsonrpc");
        let method = object.remove("method").and_then(|value| match value {
            | Value::String(method) => MethodName::try_from(method).ok(),
            | _ => None,
        });
        let params = object.remove("params").unwrap_or_else(|| Value::Object(Map::new()));
        let valid_shape = object.is_empty()
            && matches!(jsonrpc, Some(Value::String(ref version)) if version == JSON_RPC_VERSION)
            && method.is_some()
            && matches!(params, Value::Object(_) | Value::Array(_));
        match (valid_shape, method) {
            | (false, _) | (_, None) => Self::Invalid {
                id: id_value.as_ref().map_or(Value::Null, RequestId::valid_response_value),
                error: RpcError::new(INVALID_REQUEST, "Invalid Request"),
            },
            | (true, Some(method)) => match id_value {
                | None => Self::Notification { method, params },
                | Some(value) => match serde_json::from_value::<RequestId>(value) {
                    | Ok(id) => Self::Request { id, method, params },
                    | Err(_) => Self::Invalid {
                        id: Value::Null,
                        error: RpcError::new(INVALID_REQUEST, "Invalid Request"),
                    },
                },
            },
        }
    }
}
impl RequestId {
    fn as_string(&self) -> String {
        match self {
            | Self::Number(value) => value.to_string(),
            | Self::String(value) => value.clone(),
        }
    }
    fn valid_response_value(value: &Value) -> Value {
        match value {
            | value @ (Value::String(_) | Value::Number(_)) => value.clone(),
            | _ => Value::Null,
        }
    }
}
impl core::error::Error for RpcError {}
impl fmt::Display for RpcError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{} ({})", self.message, self.code)
    }
}
impl RpcError {
    fn dispatch(self, id: Value) -> Dispatch {
        Dispatch::serialize(self.value(id))
    }
    /// Construct a public JSON-RPC error.
    pub fn new(code: i32, message: impl Into<String>) -> Self {
        Self {
            code,
            data: None,
            message: message.into(),
        }
    }
    fn internal() -> Self {
        Self::new(INTERNAL_ERROR, "Internal error")
    }
    fn value(self, id: Value) -> Value {
        serde_json::to_value(ErrorResponse {
            error: self,
            id,
            jsonrpc: JSON_RPC_VERSION,
        })
        .unwrap_or(Value::Null)
    }
}
impl From<MethodName> for String {
    fn from(value: MethodName) -> Self {
        value.to_string()
    }
}
impl<'de> Deserialize<'de> for StrictValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct StrictVisitor;
        impl<'de> Visitor<'de> for StrictVisitor {
            type Value = StrictValue;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a JSON value without duplicate object fields")
            }
            fn visit_bool<E: DeError>(self, value: bool) -> Result<Self::Value, E> {
                Ok(StrictValue(Value::Bool(value)))
            }
            fn visit_f64<E: DeError>(self, value: f64) -> Result<Self::Value, E> {
                serde_json::Number::from_f64(value)
                    .map(Value::Number)
                    .map(StrictValue)
                    .ok_or_else(|| E::custom("invalid JSON number"))
            }
            fn visit_i64<E: DeError>(self, value: i64) -> Result<Self::Value, E> {
                Ok(StrictValue(Value::Number(value.into())))
            }
            fn visit_map<A: MapAccess<'de>>(self, mut values: A) -> Result<Self::Value, A::Error> {
                let mut object = Map::new();
                let mut result = Ok(());
                loop {
                    match values.next_entry::<String, StrictValue>() {
                        | Ok(Some((key, StrictValue(_)))) if object.contains_key(&key) => {
                            result = Err(A::Error::custom(format!("duplicate field '{key}'")));
                            break;
                        }
                        | Ok(Some((key, StrictValue(value)))) => {
                            object.insert(key, value);
                        }
                        | Ok(None) => break,
                        | Err(why) => {
                            result = Err(why);
                            break;
                        }
                    }
                }
                result.map(|()| StrictValue(Value::Object(object)))
            }
            fn visit_none<E: DeError>(self) -> Result<Self::Value, E> {
                Ok(StrictValue(Value::Null))
            }
            fn visit_seq<A: SeqAccess<'de>>(self, mut values: A) -> Result<Self::Value, A::Error> {
                let mut array = Vec::new();
                let mut result = Ok(());
                loop {
                    match values.next_element::<StrictValue>() {
                        | Ok(Some(StrictValue(value))) => array.push(value),
                        | Ok(None) => break,
                        | Err(why) => {
                            result = Err(why);
                            break;
                        }
                    }
                }
                result.map(|()| StrictValue(Value::Array(array)))
            }
            fn visit_str<E: DeError>(self, value: &str) -> Result<Self::Value, E> {
                Ok(StrictValue(Value::String(value.to_string())))
            }
            fn visit_string<E: DeError>(self, value: String) -> Result<Self::Value, E> {
                Ok(StrictValue(Value::String(value)))
            }
            fn visit_u64<E: DeError>(self, value: u64) -> Result<Self::Value, E> {
                Ok(StrictValue(Value::Number(value.into())))
            }
            fn visit_unit<E: DeError>(self) -> Result<Self::Value, E> {
                Ok(StrictValue(Value::Null))
            }
        }
        deserializer.deserialize_any(StrictVisitor)
    }
}
fn policy_error(effects: &OperationEffects, context: &InvocationContext) -> Option<RpcError> {
    let requires_mutation = effects.destructive || effects.filesystem_write || effects.mutation;
    let unavailable = effects.credentials || effects.process || (effects.inference && !context.allow_inference);
    let mutation_denied = requires_mutation && !context.allow_mutation;
    let offline = effects.network_read && context.offline;
    match (unavailable, mutation_denied, offline) {
        | (true, _, _) => Some(RpcError::new(POLICY_DENIED, "Operation declares an unavailable effect")),
        | (_, true, _) => Some(RpcError::new(POLICY_DENIED, "Operation requires mutation approval")),
        | (_, _, true) => Some(RpcError::new(POLICY_DENIED, "Operation is unavailable while offline")),
        | _ => None,
    }
}
#[cfg(test)]
mod tests;