Skip to main content

core_api/
external_rpc.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3
4use crate::{AuthRequest, AuthenticatedSession, ServiceCoreInput, ServiceCoreOutput};
5use std::collections::HashMap;
6
7pub const EXTERNAL_CORE_PROTOCOL_VERSION: u32 = 20;
8/// Maximum single native artifact body, separate from the JSON control frame limit.
9pub const MAX_NATIVE_ARTIFACT_BYTES: usize = 50 * 1024 * 1024;
10pub const MAX_NATIVE_ARTIFACT_BASE64_BYTES: usize = MAX_NATIVE_ARTIFACT_BYTES.div_ceil(3) * 4;
11/// Protocol 18 sends large dataBase64 strings after the JSON frame. The JSON field
12/// is an empty string marker, followed by a u32 byte length and that many ASCII
13/// bytes on the same connection. Only artifact commit requests and open/read
14/// responses support this attachment. Control frames keep their 16 MiB limit.
15pub const ARTIFACT_ATTACHMENT_CHUNK_BYTES: usize = 1024 * 1024;
16pub const ARTIFACT_CONTENT_PATH_PREFIX: &str = "/artifact/v1/content/";
17pub const ARTIFACT_UPLOAD_PATH_PREFIX: &str = "/artifact/v1/upload/";
18
19/// Derive a bounded, workdir-specific Windows IPC name from the metadata socket path.
20/// The metadata itself stays in the ordinary runtime directory on every platform.
21pub fn external_core_pipe_name(socket_path: &std::path::Path) -> String {
22    use sha2::{Digest, Sha256};
23    let normalized = socket_path
24        .to_string_lossy()
25        .replace('/', "\\")
26        .to_lowercase();
27    format!(
28        r"\\.\pipe\meowcore-{:x}",
29        Sha256::digest(normalized.as_bytes())
30    )
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct ExternalCoreRequest {
35    pub id: String,
36    pub method: ExternalCoreMethod,
37    pub payload: Value,
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct ExternalCoreResponse {
42    pub id: String,
43    pub ok: bool,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub result: Option<Value>,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub error: Option<ExternalCoreError>,
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct ExternalCoreError {
52    pub code: String,
53    pub message: String,
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub details: Option<Value>,
56}
57
58impl From<crate::ErrorResponse> for ExternalCoreError {
59    fn from(error: crate::ErrorResponse) -> Self {
60        Self {
61            code: error.error,
62            message: error.message,
63            details: error.details,
64        }
65    }
66}
67
68impl From<ExternalCoreError> for crate::ErrorResponse {
69    fn from(error: ExternalCoreError) -> Self {
70        Self {
71            error: error.code,
72            message: error.message,
73            details: error.details,
74        }
75    }
76}
77
78impl std::fmt::Display for ExternalCoreError {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        write!(f, "[{}] {}", self.code, self.message)
81    }
82}
83
84impl std::error::Error for ExternalCoreError {}
85
86/// A completed JSON HTTP handler response, including non-2xx responses.
87/// This is an RPC result, not an RPC error. Hosts must preserve both fields.
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90pub struct HttpPayloadResponse {
91    pub status_code: u16,
92    pub body: Value,
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub enum ExternalCoreMethod {
97    HandleCoreInput,
98    RegisterLocalAppClient,
99    RegisterNodeConnection,
100    CleanupWsState,
101    UpdateCallbackBase,
102    PutArtifact,
103    OpenArtifact,
104    AuthorizeArtifactRead,
105    AuthorizeArtifactUpload,
106    CommitArtifactUpload,
107    DeviceIdentity,
108    CommissionFingerprint,
109    CommissionPublicKeyBase64,
110    ListMdnsRecords,
111    PollEvents,
112    CompleteEvents,
113    CommissionChallengePayload,
114    PairingStartPayload,
115    SetupStartPayload,
116    GeneralWebhookPayload,
117    InvokeWasmPayload,
118    Health,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct HandleCoreInputRequest {
123    pub input: ServiceCoreInput,
124}
125
126#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct HandleCoreInputResponse {
128    pub output: ServiceCoreOutput,
129}
130
131#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct RegisterLocalAppClientRequest {
133    pub ws_id: String,
134    pub auth_request: AuthRequest,
135    pub session: AuthenticatedSession,
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct RegisterNodeConnectionRequest {
140    pub ws_id: String,
141    pub session_id: String,
142    pub node_type: String,
143    pub node_id: String,
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub host_name: Option<String>,
146    pub tenant_id: String,
147    pub scope_id: String,
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct CleanupWsStateRequest {
152    pub ws_id: String,
153}
154
155#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
156pub struct UpdateCallbackBaseRequest {
157    /// Host observation, never an independently discovered or fallback address.
158    pub network: crate::host::network::HostNetworkSnapshot,
159    /// Actual bound native HTTPS listener port. Zero means it is not ready.
160    pub port: u16,
161    /// Restricted third-party HTTP listener. Zero disables compatibility URLs.
162    #[serde(default)]
163    pub third_party_port: u16,
164}
165
166impl UpdateCallbackBaseRequest {
167    pub fn callback_base(&self, now_ms: i64) -> Option<String> {
168        if self.third_party_port == 0 {
169            return None;
170        }
171        self.network
172            .available_ipv4(now_ms)
173            .map(|ip| format!("http://{ip}:{}", self.third_party_port))
174    }
175    pub fn native_base(&self, now_ms: i64) -> Option<String> {
176        if self.port == 0 {
177            return None;
178        }
179        self.network
180            .available_ipv4(now_ms)
181            .map(|ip| format!("https://{ip}:{}", self.port))
182    }
183}
184
185#[derive(Debug, Clone, Serialize, Deserialize)]
186#[serde(rename_all = "camelCase")]
187pub struct ExternalCoreDeviceIdentity {
188    pub device_id: String,
189    pub device_name: String,
190}
191
192#[derive(Debug, Clone, Serialize, Deserialize)]
193#[serde(rename_all = "camelCase")]
194pub struct ListMdnsRecordsRequest {
195    pub port: u16,
196    pub addresses: Vec<String>,
197    pub host_type: String,
198}
199
200#[derive(Debug, Clone, Serialize, Deserialize)]
201#[serde(rename_all = "camelCase")]
202pub struct ExternalCoreMdnsRecord {
203    pub service_type: String,
204    pub instance_name: String,
205    pub port: u16,
206    pub properties: HashMap<String, String>,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
210#[serde(rename_all = "camelCase")]
211pub struct PollExternalCoreEventsRequest {
212    pub consumer_id: String,
213    pub max_events: u16,
214    pub timeout_ms: u64,
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize)]
218#[serde(rename_all = "camelCase")]
219pub struct PollExternalCoreEventsResponse {
220    pub events: Vec<ExternalCoreEvent>,
221    pub timed_out: bool,
222}
223
224#[derive(Debug, Clone, Serialize, Deserialize)]
225#[serde(rename_all = "camelCase")]
226pub struct CompleteExternalCoreEventsRequest {
227    pub consumer_id: String,
228    pub completions: Vec<ExternalCoreEventCompletion>,
229}
230
231#[derive(Debug, Clone, Serialize, Deserialize)]
232#[serde(rename_all = "camelCase")]
233pub struct CompleteExternalCoreEventsResponse {
234    pub completed_event_ids: Vec<String>,
235    pub missing_event_ids: Vec<String>,
236}
237
238#[derive(Debug, Clone, Serialize, Deserialize)]
239#[serde(rename_all = "camelCase")]
240pub struct ExternalCoreEvent {
241    pub event_id: String,
242    pub kind: ExternalCoreEventKind,
243    pub payload: Value,
244    pub expects_response: bool,
245}
246
247#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
248#[serde(rename_all = "camelCase")]
249pub enum ExternalCoreEventKind {
250    MdnsRecordsChanged,
251    DeliveryRequested,
252    ConnectionControlRequested,
253    HostRuntimeRequest,
254    ServiceAppFacadeRequest,
255    ScopeOwnedDataPurgeRequested,
256    ArtifactDeliveryProjectionRequested,
257    ArtifactUploadProjectionRequested,
258}
259
260/// Messaging-only Core -> Host request. A successful response means delivery was accepted by
261/// the provider implementation, not merely queued in the Core event pump or read by a user.
262#[derive(Debug, Clone, Serialize, Deserialize)]
263#[serde(rename_all = "camelCase", deny_unknown_fields)]
264pub struct MessagingDeliveryRequest {
265    pub tenant_id: String,
266    pub scope_id: String,
267    pub surface_id: String,
268    pub target: String,
269    pub payload: String,
270}
271
272#[derive(Debug, Clone, Serialize, Deserialize)]
273#[serde(rename_all = "camelCase", deny_unknown_fields)]
274pub struct MessagingDeliveryResponse {
275    pub outcome: crate::DeliveryOutcome,
276}
277
278#[derive(Debug, Clone, Serialize, Deserialize)]
279#[serde(rename_all = "camelCase", deny_unknown_fields)]
280pub struct ExternalArtifactRequestContext {
281    pub tenant_id: String,
282    pub scope_id: String,
283    pub actor_user_id: String,
284    pub client_id: String,
285}
286
287#[derive(Debug, Clone, Serialize, Deserialize)]
288#[serde(rename_all = "camelCase", deny_unknown_fields)]
289pub struct ExternalPutArtifactRequest {
290    pub context: ExternalArtifactRequestContext,
291    pub artifact: artifact_api::PutArtifactRequest,
292}
293
294#[derive(Debug, Clone, Serialize, Deserialize)]
295#[serde(rename_all = "camelCase", deny_unknown_fields)]
296pub struct ExternalOpenArtifactRequest {
297    pub context: ExternalArtifactRequestContext,
298    pub uri: String,
299}
300
301#[derive(Debug, Clone, Serialize, Deserialize)]
302#[serde(rename_all = "camelCase", deny_unknown_fields)]
303pub struct ExternalAuthorizeArtifactReadRequest {
304    pub grant: String,
305    /// Inspect existence and metadata without reading content or renewing idle expiry.
306    /// The response has neither a file path nor inline content in this mode.
307    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
308    pub metadata_only: bool,
309}
310
311#[derive(Debug, Clone, Serialize, Deserialize)]
312#[serde(rename_all = "camelCase", deny_unknown_fields)]
313pub struct ExternalAuthorizeArtifactUploadRequest {
314    pub grant: String,
315}
316
317#[derive(Debug, Clone, Serialize, Deserialize)]
318#[serde(rename_all = "camelCase", deny_unknown_fields)]
319pub struct ExternalCommitArtifactUploadRequest {
320    #[serde(default, skip_serializing_if = "Option::is_none")]
321    pub data_base64: Option<String>,
322    pub grant: String,
323}
324
325#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
326#[serde(rename_all = "camelCase", deny_unknown_fields)]
327pub struct ExternalArtifactReadDescriptor {
328    #[serde(default, skip_serializing_if = "Option::is_none")]
329    pub data_base64: Option<String>,
330    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
331    pub temporary: bool,
332    pub path: String,
333    pub kind: artifact_api::ArtifactKind,
334    pub mime_type: String,
335    pub size_bytes: u64,
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub width: Option<u32>,
338    #[serde(default, skip_serializing_if = "Option::is_none")]
339    pub height: Option<u32>,
340    #[serde(default, skip_serializing_if = "Option::is_none")]
341    pub duration_millis: Option<u64>,
342    pub sha256: String,
343}
344
345#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
346#[serde(rename_all = "camelCase", deny_unknown_fields)]
347pub struct ExternalArtifactUploadDescriptor {
348    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
349    pub temporary: bool,
350    pub upload_id: String,
351    pub path: String,
352    pub kind: artifact_api::ArtifactKind,
353    pub mime_type: String,
354    pub size_bytes: u64,
355    pub sha256: String,
356    #[serde(default, skip_serializing_if = "Option::is_none")]
357    pub duration_millis: Option<u64>,
358    pub expires_at_unix_ms: u64,
359}
360
361#[derive(Debug, Clone, Serialize, Deserialize)]
362#[serde(rename_all = "camelCase", deny_unknown_fields)]
363pub struct ArtifactDeliveryProjectionRequest {
364    /// Explicit compatibility request; native traffic must remain HTTPS.
365    #[serde(default)]
366    pub third_party: bool,
367    pub grant: String,
368    pub expires_at_unix_ms: u64,
369    pub client_id: String,
370}
371
372#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
373#[serde(rename_all = "camelCase", deny_unknown_fields)]
374pub struct ArtifactDeliveryProjectionResponse {
375    #[serde(default, skip_serializing_if = "Option::is_none")]
376    pub host_identity: Option<artifact_api::HostTlsIdentity>,
377    pub url: String,
378}
379
380#[derive(Debug, Clone, Serialize, Deserialize)]
381#[serde(rename_all = "camelCase", deny_unknown_fields)]
382pub struct ArtifactUploadProjectionRequest {
383    pub grant: String,
384    pub expires_at_unix_ms: u64,
385    pub client_id: String,
386}
387
388#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
389#[serde(rename_all = "camelCase", deny_unknown_fields)]
390pub struct ArtifactUploadProjectionResponse {
391    #[serde(default, skip_serializing_if = "Option::is_none")]
392    pub host_identity: Option<artifact_api::HostTlsIdentity>,
393    pub url: String,
394}
395
396/// An App Facade request delegated by an externally hosted Core to the
397/// application service that owns the target's business logic.
398#[derive(Debug, Clone, Serialize, Deserialize)]
399#[serde(rename_all = "camelCase")]
400pub struct ExternalServiceAppFacadeRequest {
401    pub target: String,
402    pub tenant_id: String,
403    pub scope_id: String,
404    pub user_id: String,
405    #[serde(default, skip_serializing_if = "Option::is_none")]
406    pub client_id: Option<String>,
407    pub payload: Value,
408}
409
410/// A platform capability request emitted by an externally hosted Core.
411///
412/// Core owns the onboarding workflow. The native host owns LAN discovery and
413/// transport to a discovered candidate, so Android can satisfy this contract
414/// without moving application logic into the mobile shell.
415#[derive(Debug, Clone, Serialize, Deserialize)]
416#[serde(rename_all = "camelCase")]
417pub struct ExternalHostRuntimeRequest {
418    #[serde(default, skip_serializing_if = "Option::is_none")]
419    pub host_public_key: Option<crate::host::auth::PublicKey>,
420    pub method: ExternalHostRuntimeMethod,
421    #[serde(default, skip_serializing_if = "Option::is_none")]
422    pub candidate_id: Option<String>,
423    #[serde(default, skip_serializing_if = "Option::is_none")]
424    pub action: Option<String>,
425    #[serde(default, skip_serializing_if = "Option::is_none")]
426    pub payload: Option<Value>,
427}
428
429#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
430#[serde(rename_all = "camelCase")]
431pub enum ExternalHostRuntimeMethod {
432    Discovery,
433    CandidateRequest,
434}
435
436#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
437#[serde(rename_all = "camelCase")]
438pub struct ScopeOwnedDataPurgeRequest {
439    pub tenant_id: String,
440    pub scope_id: String,
441}
442
443#[derive(Debug, Clone, Serialize, Deserialize)]
444#[serde(rename_all = "camelCase")]
445pub struct ExternalCoreEventCompletion {
446    pub event_id: String,
447    pub ok: bool,
448    #[serde(default, skip_serializing_if = "Option::is_none")]
449    pub response: Option<Value>,
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    pub error: Option<ExternalCoreError>,
452}
453
454#[derive(Debug, Clone, Serialize, Deserialize)]
455pub struct HttpPayloadRequest {
456    pub payload: Value,
457}
458
459#[derive(Debug, Clone, Serialize, Deserialize)]
460pub struct EndpointPayloadRequest {
461    pub endpoint_id: String,
462    pub payload: Value,
463}
464
465#[derive(Debug, Clone, Serialize, Deserialize)]
466#[serde(rename_all = "camelCase")]
467pub struct ExternalCoreRuntimeMetadata {
468    pub backend: String,
469    pub instance_id: String,
470    pub pid: u32,
471    pub state: String,
472    pub started_at: String,
473    pub protocol_version: u32,
474    pub binary_version: String,
475    pub socket_path: String,
476}
477
478#[derive(Debug, Clone, Serialize, Deserialize)]
479#[serde(rename_all = "camelCase")]
480pub struct ExternalCoreHealth {
481    pub ok: bool,
482    pub ready: bool,
483    pub backend: String,
484    pub binary_version: String,
485    pub agent_version: String,
486    pub protocol_version: u32,
487    #[serde(skip_serializing_if = "Option::is_none")]
488    pub instance_id: Option<String>,
489    #[serde(skip_serializing_if = "Option::is_none")]
490    pub pid: Option<u32>,
491    #[serde(skip_serializing_if = "Option::is_none")]
492    pub state: Option<String>,
493    #[serde(skip_serializing_if = "Option::is_none")]
494    pub started_at: Option<String>,
495    #[serde(default)]
496    pub capabilities: Vec<String>,
497}
498
499impl ExternalArtifactReadDescriptor {
500    /// Decode the bounded inline variant. File descriptors return None.
501    pub fn inline_content(&self) -> Result<Option<Vec<u8>>, String> {
502        use base64::Engine as _;
503        use sha2::{Digest, Sha256};
504        let Some(encoded) = &self.data_base64 else {
505            return if self.path.is_empty() {
506                Err("artifact descriptor has no content".into())
507            } else {
508                Ok(None)
509            };
510        };
511        if !self.path.is_empty()
512            || self.size_bytes > MAX_NATIVE_ARTIFACT_BYTES as u64
513            || encoded.len() > MAX_NATIVE_ARTIFACT_BASE64_BYTES
514        {
515            return Err("invalid inline artifact descriptor".into());
516        }
517        let bytes = base64::engine::general_purpose::STANDARD
518            .decode(encoded)
519            .map_err(|_| "invalid inline artifact base64")?;
520        if bytes.len() as u64 != self.size_bytes
521            || format!("{:x}", Sha256::digest(&bytes)) != self.sha256
522        {
523            return Err("inline artifact failed its integrity check".into());
524        }
525        Ok(Some(bytes))
526    }
527}
528
529#[cfg(test)]
530mod tests {
531    use super::*;
532
533    #[test]
534    fn callback_address_requires_a_fresh_host_observation_and_bound_port() {
535        let mut request = UpdateCallbackBaseRequest {
536            third_party_port: 0,
537            network: crate::host::network::HostNetworkSnapshot {
538                lan_ipv4: Some("192.168.1.5".parse().unwrap()),
539                observed_at_ms: 100_000,
540            },
541            port: 3210,
542        };
543        assert_eq!(
544            request.native_base(100_000).as_deref(),
545            Some("https://192.168.1.5:3210")
546        );
547        let roundtrip: UpdateCallbackBaseRequest =
548            serde_json::from_value(serde_json::to_value(&request).unwrap()).unwrap();
549        assert_eq!(request, roundtrip);
550        assert_eq!(request.callback_base(100_000), None);
551        request.third_party_port = 3211;
552        assert_eq!(
553            request.callback_base(100_000).as_deref(),
554            Some("http://192.168.1.5:3211")
555        );
556        assert_eq!(request.callback_base(145_000), None);
557        assert_eq!(request.native_base(145_000), None);
558        request.port = 0;
559        assert_eq!(request.native_base(100_000), None);
560        assert_eq!(
561            UpdateCallbackBaseRequest::default().native_base(100_000),
562            None
563        );
564    }
565
566    #[test]
567    fn messaging_delivery_is_a_closed_request_response_contract() {
568        let request = serde_json::json!({"tenantId":"t", "scopeId":"s", "surfaceId":"m",
569            "target":"/chat/event", "payload":"{}"});
570        let decoded: MessagingDeliveryRequest = serde_json::from_value(request.clone()).unwrap();
571        assert_eq!(serde_json::to_value(decoded).unwrap(), request);
572        let mut invalid = request;
573        invalid["unknown"] = serde_json::json!(true);
574        assert!(serde_json::from_value::<MessagingDeliveryRequest>(invalid).is_err());
575        assert!(
576            serde_json::from_value::<MessagingDeliveryResponse>(serde_json::json!({})).is_err()
577        );
578        assert_eq!(
579            serde_json::to_value(ExternalCoreEventKind::DeliveryRequested).unwrap(),
580            "deliveryRequested"
581        );
582    }
583
584    #[test]
585    fn artifact_read_metadata_mode_is_explicit_and_defaults_to_content() {
586        let read: ExternalAuthorizeArtifactReadRequest =
587            serde_json::from_value(serde_json::json!({"grant":"signed"})).unwrap();
588        assert!(!read.metadata_only);
589        assert_eq!(
590            serde_json::to_value(read).unwrap(),
591            serde_json::json!({"grant":"signed"})
592        );
593        let head: ExternalAuthorizeArtifactReadRequest =
594            serde_json::from_value(serde_json::json!({"grant":"signed", "metadataOnly":true}))
595                .unwrap();
596        assert!(head.metadata_only);
597        assert!(
598            serde_json::from_value::<ExternalAuthorizeArtifactReadRequest>(
599                serde_json::json!({"grant":"signed", "metadataOnly":"true"})
600            )
601            .is_err()
602        );
603    }
604
605    #[test]
606    fn external_events_use_the_current_wire_shape() {
607        let event = ExternalCoreEvent {
608            event_id: "event-1".to_string(),
609            kind: ExternalCoreEventKind::ScopeOwnedDataPurgeRequested,
610            payload: serde_json::to_value(ScopeOwnedDataPurgeRequest {
611                tenant_id: "tenant-1".to_string(),
612                scope_id: "scope-1".to_string(),
613            })
614            .unwrap(),
615            expects_response: true,
616        };
617
618        let value = serde_json::to_value(event).unwrap();
619        assert_eq!(EXTERNAL_CORE_PROTOCOL_VERSION, 20);
620        assert_eq!(value["kind"], "scopeOwnedDataPurgeRequested");
621        assert_eq!(value["payload"]["tenantId"], "tenant-1");
622        assert_eq!(value["payload"]["scopeId"], "scope-1");
623        assert_eq!(value["expectsResponse"], true);
624
625        let facade = ExternalCoreEvent {
626            event_id: "event-2".to_string(),
627            kind: ExternalCoreEventKind::ServiceAppFacadeRequest,
628            payload: serde_json::to_value(ExternalServiceAppFacadeRequest {
629                target: "/app/messaging/provider/list".to_string(),
630                tenant_id: "tenant-1".to_string(),
631                scope_id: "scope-1".to_string(),
632                user_id: "user-1".to_string(),
633                client_id: None,
634                payload: serde_json::json!({"placement": "local"}),
635            })
636            .unwrap(),
637            expects_response: true,
638        };
639        let value = serde_json::to_value(facade).unwrap();
640        assert_eq!(value["kind"], "serviceAppFacadeRequest");
641        assert_eq!(value["payload"]["target"], "/app/messaging/provider/list");
642        assert_eq!(value["payload"]["userId"], "user-1");
643        assert!(value["payload"].get("clientId").is_none());
644    }
645
646    #[test]
647    fn artifact_host_contract_uses_canonical_wire_types() {
648        let descriptor = ExternalArtifactReadDescriptor {
649            temporary: false,
650            data_base64: None,
651            path: "/runtime/artifacts/blob".to_string(),
652            kind: artifact_api::ArtifactKind::Audio,
653            mime_type: "audio/ogg".to_string(),
654            size_bytes: 42,
655            width: None,
656            height: None,
657            duration_millis: Some(1_500),
658            sha256: "a".repeat(64),
659        };
660        let value = serde_json::to_value(descriptor).unwrap();
661        assert_eq!(value["kind"], "AUDIO");
662        assert_eq!(value["mimeType"], "audio/ogg");
663        assert_eq!(value["durationMillis"], 1_500);
664        assert!(value.get("width").is_none());
665
666        let request = ArtifactDeliveryProjectionRequest {
667            third_party: false,
668            grant: "payload.signature".to_string(),
669            expires_at_unix_ms: 123,
670            client_id: "L:client".to_string(),
671        };
672        let value = serde_json::to_value(request).unwrap();
673        assert_eq!(value["expiresAtUnixMs"], 123);
674        assert_eq!(value["clientId"], "L:client");
675    }
676
677    #[test]
678    fn playground_uses_only_the_general_webhook_contract() {
679        let general = serde_json::to_value(ExternalCoreMethod::GeneralWebhookPayload).unwrap();
680        assert_eq!(general, serde_json::json!("GeneralWebhookPayload"));
681        assert!(
682            serde_json::from_value::<ExternalCoreMethod>(serde_json::json!(
683                "PlaygroundWebhookPayload"
684            ))
685            .is_err()
686        );
687    }
688}