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 = 21;
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    StreamArtifactUpload,
108    DeviceIdentity,
109    CommissionFingerprint,
110    CommissionPublicKeyBase64,
111    ListMdnsRecords,
112    PollEvents,
113    CompleteEvents,
114    CommissionChallengePayload,
115    PairingStartPayload,
116    SetupStartPayload,
117    GeneralWebhookPayload,
118    InvokeWasmPayload,
119    Health,
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct HandleCoreInputRequest {
124    pub input: ServiceCoreInput,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
128pub struct HandleCoreInputResponse {
129    pub output: ServiceCoreOutput,
130}
131
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct RegisterLocalAppClientRequest {
134    pub ws_id: String,
135    pub auth_request: AuthRequest,
136    pub session: AuthenticatedSession,
137}
138
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct RegisterNodeConnectionRequest {
141    pub binding_metadata: crate::NodeBindingMetadata,
142    pub ws_id: String,
143    pub session_id: String,
144    pub node_type: String,
145    pub node_id: String,
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub host_name: Option<String>,
148    pub tenant_id: String,
149    pub scope_id: String,
150}
151
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct CleanupWsStateRequest {
154    pub ws_id: String,
155}
156
157#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
158pub struct UpdateCallbackBaseRequest {
159    /// Host observation, never an independently discovered or fallback address.
160    pub network: crate::host::network::HostNetworkSnapshot,
161    /// Actual bound native HTTPS listener port. Zero means it is not ready.
162    pub port: u16,
163    /// Restricted third-party HTTP listener. Zero disables compatibility URLs.
164    #[serde(default)]
165    pub third_party_port: u16,
166}
167
168impl UpdateCallbackBaseRequest {
169    pub fn callback_base(&self, now_ms: i64) -> Option<String> {
170        if self.third_party_port == 0 {
171            return None;
172        }
173        self.network
174            .available_ipv4(now_ms)
175            .map(|ip| format!("http://{ip}:{}", self.third_party_port))
176    }
177    pub fn native_base(&self, now_ms: i64) -> Option<String> {
178        if self.port == 0 {
179            return None;
180        }
181        self.network
182            .available_ipv4(now_ms)
183            .map(|ip| format!("https://{ip}:{}", self.port))
184    }
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize)]
188#[serde(rename_all = "camelCase")]
189pub struct ExternalCoreDeviceIdentity {
190    pub device_id: String,
191    pub device_name: String,
192}
193
194#[derive(Debug, Clone, Serialize, Deserialize)]
195#[serde(rename_all = "camelCase")]
196pub struct ListMdnsRecordsRequest {
197    pub port: u16,
198    pub addresses: Vec<String>,
199    pub host_type: String,
200}
201
202#[derive(Debug, Clone, Serialize, Deserialize)]
203#[serde(rename_all = "camelCase")]
204pub struct ExternalCoreMdnsRecord {
205    pub service_type: String,
206    pub instance_name: String,
207    pub port: u16,
208    pub properties: HashMap<String, String>,
209}
210
211#[derive(Debug, Clone, Serialize, Deserialize)]
212#[serde(rename_all = "camelCase")]
213pub struct PollExternalCoreEventsRequest {
214    pub consumer_id: String,
215    pub max_events: u16,
216    pub timeout_ms: u64,
217}
218
219#[derive(Debug, Clone, Serialize, Deserialize)]
220#[serde(rename_all = "camelCase")]
221pub struct PollExternalCoreEventsResponse {
222    pub events: Vec<ExternalCoreEvent>,
223    pub timed_out: bool,
224}
225
226#[derive(Debug, Clone, Serialize, Deserialize)]
227#[serde(rename_all = "camelCase")]
228pub struct CompleteExternalCoreEventsRequest {
229    pub consumer_id: String,
230    pub completions: Vec<ExternalCoreEventCompletion>,
231}
232
233#[derive(Debug, Clone, Serialize, Deserialize)]
234#[serde(rename_all = "camelCase")]
235pub struct CompleteExternalCoreEventsResponse {
236    pub completed_event_ids: Vec<String>,
237    pub missing_event_ids: Vec<String>,
238}
239
240#[derive(Debug, Clone, Serialize, Deserialize)]
241#[serde(rename_all = "camelCase")]
242pub struct ExternalCoreEvent {
243    pub event_id: String,
244    pub kind: ExternalCoreEventKind,
245    pub payload: Value,
246    pub expects_response: bool,
247}
248
249#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
250#[serde(rename_all = "camelCase")]
251pub enum ExternalCoreEventKind {
252    MdnsRecordsChanged,
253    DeliveryRequested,
254    ConnectionControlRequested,
255    HostRuntimeRequest,
256    ServiceAppFacadeRequest,
257    ScopeOwnedDataPurgeRequested,
258    ArtifactDeliveryProjectionRequested,
259    ArtifactUploadProjectionRequested,
260}
261
262/// Messaging-only Core -> Host request. A successful response means delivery was accepted by
263/// the provider implementation, not merely queued in the Core event pump or read by a user.
264#[derive(Debug, Clone, Serialize, Deserialize)]
265#[serde(rename_all = "camelCase", deny_unknown_fields)]
266pub struct MessagingDeliveryRequest {
267    pub tenant_id: String,
268    pub scope_id: String,
269    pub surface_id: String,
270    pub target: String,
271    pub payload: String,
272}
273
274#[derive(Debug, Clone, Serialize, Deserialize)]
275#[serde(rename_all = "camelCase", deny_unknown_fields)]
276pub struct MessagingDeliveryResponse {
277    pub outcome: crate::DeliveryOutcome,
278}
279
280#[derive(Debug, Clone, Serialize, Deserialize)]
281#[serde(rename_all = "camelCase", deny_unknown_fields)]
282pub struct ExternalArtifactRequestContext {
283    pub tenant_id: String,
284    pub scope_id: String,
285    pub actor_user_id: String,
286    pub client_id: String,
287}
288
289#[derive(Debug, Clone, Serialize, Deserialize)]
290#[serde(rename_all = "camelCase", deny_unknown_fields)]
291pub struct ExternalPutArtifactRequest {
292    pub context: ExternalArtifactRequestContext,
293    pub artifact: artifact_api::PutArtifactRequest,
294}
295
296#[derive(Debug, Clone, Serialize, Deserialize)]
297#[serde(rename_all = "camelCase", deny_unknown_fields)]
298pub struct ExternalOpenArtifactRequest {
299    pub context: ExternalArtifactRequestContext,
300    pub uri: String,
301}
302
303#[derive(Debug, Clone, Serialize, Deserialize)]
304#[serde(rename_all = "camelCase", deny_unknown_fields)]
305pub struct ExternalAuthorizeArtifactReadRequest {
306    pub grant: String,
307    /// Inspect existence and metadata without reading content or renewing idle expiry.
308    /// The response has neither a file path nor inline content in this mode.
309    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
310    pub metadata_only: bool,
311}
312
313#[derive(Debug, Clone, Serialize, Deserialize)]
314#[serde(rename_all = "camelCase", deny_unknown_fields)]
315pub struct ExternalAuthorizeArtifactUploadRequest {
316    pub grant: String,
317}
318
319#[derive(Debug, Clone, Serialize, Deserialize)]
320#[serde(rename_all = "camelCase", deny_unknown_fields)]
321pub struct ExternalCommitArtifactUploadRequest {
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub data_base64: Option<String>,
324    pub grant: String,
325}
326
327#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
328#[serde(rename_all = "camelCase", deny_unknown_fields)]
329pub struct ExternalArtifactReadDescriptor {
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub data_base64: Option<String>,
332    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
333    pub temporary: bool,
334    pub path: String,
335    pub kind: artifact_api::ArtifactKind,
336    pub mime_type: String,
337    pub size_bytes: u64,
338    #[serde(default, skip_serializing_if = "Option::is_none")]
339    pub width: Option<u32>,
340    #[serde(default, skip_serializing_if = "Option::is_none")]
341    pub height: Option<u32>,
342    #[serde(default, skip_serializing_if = "Option::is_none")]
343    pub duration_millis: Option<u64>,
344    pub sha256: String,
345}
346
347#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
348#[serde(rename_all = "camelCase", deny_unknown_fields)]
349pub struct ExternalArtifactUploadDescriptor {
350    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
351    pub temporary: bool,
352    pub upload_id: String,
353    pub path: String,
354    pub kind: artifact_api::ArtifactKind,
355    pub mime_type: String,
356    pub size_bytes: u64,
357    pub sha256: String,
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub duration_millis: Option<u64>,
360    pub expires_at_unix_ms: u64,
361}
362
363#[derive(Debug, Clone, Serialize, Deserialize)]
364#[serde(rename_all = "camelCase", deny_unknown_fields)]
365pub struct ArtifactDeliveryProjectionRequest {
366    /// Explicit compatibility request; native traffic must remain HTTPS.
367    #[serde(default)]
368    pub third_party: bool,
369    pub grant: String,
370    pub expires_at_unix_ms: u64,
371    pub client_id: String,
372}
373
374#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
375#[serde(rename_all = "camelCase", deny_unknown_fields)]
376pub struct ArtifactDeliveryProjectionResponse {
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    pub host_identity: Option<artifact_api::HostTlsIdentity>,
379    pub url: String,
380}
381
382#[derive(Debug, Clone, Serialize, Deserialize)]
383#[serde(rename_all = "camelCase", deny_unknown_fields)]
384pub struct ArtifactUploadProjectionRequest {
385    pub grant: String,
386    pub expires_at_unix_ms: u64,
387    pub client_id: String,
388}
389
390#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
391#[serde(rename_all = "camelCase", deny_unknown_fields)]
392pub struct ArtifactUploadProjectionResponse {
393    #[serde(default, skip_serializing_if = "Option::is_none")]
394    pub host_identity: Option<artifact_api::HostTlsIdentity>,
395    pub url: String,
396}
397
398/// An App Facade request delegated by an externally hosted Core to the
399/// application service that owns the target's business logic.
400#[derive(Debug, Clone, Serialize, Deserialize)]
401#[serde(rename_all = "camelCase")]
402pub struct ExternalServiceAppFacadeRequest {
403    pub target: String,
404    pub tenant_id: String,
405    pub scope_id: String,
406    pub user_id: String,
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub client_id: Option<String>,
409    pub payload: Value,
410}
411
412/// A platform capability request emitted by an externally hosted Core.
413///
414/// Core owns the onboarding workflow. The native host owns LAN discovery and
415/// transport to a discovered candidate, so Android can satisfy this contract
416/// without moving application logic into the mobile shell.
417#[derive(Debug, Clone, Serialize, Deserialize)]
418#[serde(rename_all = "camelCase")]
419pub struct ExternalHostRuntimeRequest {
420    #[serde(default, skip_serializing_if = "Option::is_none")]
421    pub host_public_key: Option<crate::host::auth::PublicKey>,
422    pub method: ExternalHostRuntimeMethod,
423    #[serde(default, skip_serializing_if = "Option::is_none")]
424    pub candidate_id: Option<String>,
425    #[serde(default, skip_serializing_if = "Option::is_none")]
426    pub action: Option<String>,
427    #[serde(default, skip_serializing_if = "Option::is_none")]
428    pub payload: Option<Value>,
429}
430
431#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
432#[serde(rename_all = "camelCase")]
433pub enum ExternalHostRuntimeMethod {
434    Discovery,
435    CandidateRequest,
436}
437
438#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
439#[serde(rename_all = "camelCase")]
440pub struct ScopeOwnedDataPurgeRequest {
441    pub tenant_id: String,
442    pub scope_id: String,
443}
444
445#[derive(Debug, Clone, Serialize, Deserialize)]
446#[serde(rename_all = "camelCase")]
447pub struct ExternalCoreEventCompletion {
448    pub event_id: String,
449    pub ok: bool,
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    pub response: Option<Value>,
452    #[serde(default, skip_serializing_if = "Option::is_none")]
453    pub error: Option<ExternalCoreError>,
454}
455
456#[derive(Debug, Clone, Serialize, Deserialize)]
457pub struct HttpPayloadRequest {
458    pub payload: Value,
459}
460
461#[derive(Debug, Clone, Serialize, Deserialize)]
462pub struct EndpointPayloadRequest {
463    pub endpoint_id: String,
464    pub payload: Value,
465}
466
467#[derive(Debug, Clone, Serialize, Deserialize)]
468#[serde(rename_all = "camelCase")]
469pub struct ExternalCoreRuntimeMetadata {
470    pub backend: String,
471    pub instance_id: String,
472    pub pid: u32,
473    pub state: String,
474    pub started_at: String,
475    pub protocol_version: u32,
476    pub binary_version: String,
477    pub socket_path: String,
478}
479
480#[derive(Debug, Clone, Serialize, Deserialize)]
481#[serde(rename_all = "camelCase")]
482pub struct ExternalCoreHealth {
483    pub runtime_space_policy: Option<crate::runtime_space::RuntimeSpacePolicy>,
484    pub ok: bool,
485    pub ready: bool,
486    pub backend: String,
487    pub binary_version: String,
488    pub agent_version: String,
489    pub protocol_version: u32,
490    #[serde(skip_serializing_if = "Option::is_none")]
491    pub instance_id: Option<String>,
492    #[serde(skip_serializing_if = "Option::is_none")]
493    pub pid: Option<u32>,
494    #[serde(skip_serializing_if = "Option::is_none")]
495    pub state: Option<String>,
496    #[serde(skip_serializing_if = "Option::is_none")]
497    pub started_at: Option<String>,
498    #[serde(default)]
499    pub capabilities: Vec<String>,
500}
501
502impl ExternalArtifactReadDescriptor {
503    /// Decode the bounded inline variant. File descriptors return None.
504    pub fn inline_content(&self) -> Result<Option<Vec<u8>>, String> {
505        use base64::Engine as _;
506        use sha2::{Digest, Sha256};
507        let Some(encoded) = &self.data_base64 else {
508            return if self.path.is_empty() {
509                Err("artifact descriptor has no content".into())
510            } else {
511                Ok(None)
512            };
513        };
514        if !self.path.is_empty()
515            || self.size_bytes > MAX_NATIVE_ARTIFACT_BYTES as u64
516            || encoded.len() > MAX_NATIVE_ARTIFACT_BASE64_BYTES
517        {
518            return Err("invalid inline artifact descriptor".into());
519        }
520        let bytes = base64::engine::general_purpose::STANDARD
521            .decode(encoded)
522            .map_err(|_| "invalid inline artifact base64")?;
523        if bytes.len() as u64 != self.size_bytes
524            || format!("{:x}", Sha256::digest(&bytes)) != self.sha256
525        {
526            return Err("inline artifact failed its integrity check".into());
527        }
528        Ok(Some(bytes))
529    }
530}
531
532#[cfg(test)]
533mod tests {
534    use super::*;
535
536    #[test]
537    fn callback_address_requires_a_fresh_host_observation_and_bound_port() {
538        let mut request = UpdateCallbackBaseRequest {
539            third_party_port: 0,
540            network: crate::host::network::HostNetworkSnapshot {
541                lan_ipv4: Some("192.168.1.5".parse().unwrap()),
542                observed_at_ms: 100_000,
543            },
544            port: 3210,
545        };
546        assert_eq!(
547            request.native_base(100_000).as_deref(),
548            Some("https://192.168.1.5:3210")
549        );
550        let roundtrip: UpdateCallbackBaseRequest =
551            serde_json::from_value(serde_json::to_value(&request).unwrap()).unwrap();
552        assert_eq!(request, roundtrip);
553        assert_eq!(request.callback_base(100_000), None);
554        request.third_party_port = 3211;
555        assert_eq!(
556            request.callback_base(100_000).as_deref(),
557            Some("http://192.168.1.5:3211")
558        );
559        assert_eq!(request.callback_base(145_000), None);
560        assert_eq!(request.native_base(145_000), None);
561        request.port = 0;
562        assert_eq!(request.native_base(100_000), None);
563        assert_eq!(
564            UpdateCallbackBaseRequest::default().native_base(100_000),
565            None
566        );
567    }
568
569    #[test]
570    fn messaging_delivery_is_a_closed_request_response_contract() {
571        let request = serde_json::json!({"tenantId":"t", "scopeId":"s", "surfaceId":"m",
572            "target":"/chat/event", "payload":"{}"});
573        let decoded: MessagingDeliveryRequest = serde_json::from_value(request.clone()).unwrap();
574        assert_eq!(serde_json::to_value(decoded).unwrap(), request);
575        let mut invalid = request;
576        invalid["unknown"] = serde_json::json!(true);
577        assert!(serde_json::from_value::<MessagingDeliveryRequest>(invalid).is_err());
578        assert!(
579            serde_json::from_value::<MessagingDeliveryResponse>(serde_json::json!({})).is_err()
580        );
581        assert_eq!(
582            serde_json::to_value(ExternalCoreEventKind::DeliveryRequested).unwrap(),
583            "deliveryRequested"
584        );
585    }
586
587    #[test]
588    fn artifact_read_metadata_mode_is_explicit_and_defaults_to_content() {
589        let read: ExternalAuthorizeArtifactReadRequest =
590            serde_json::from_value(serde_json::json!({"grant":"signed"})).unwrap();
591        assert!(!read.metadata_only);
592        assert_eq!(
593            serde_json::to_value(read).unwrap(),
594            serde_json::json!({"grant":"signed"})
595        );
596        let head: ExternalAuthorizeArtifactReadRequest =
597            serde_json::from_value(serde_json::json!({"grant":"signed", "metadataOnly":true}))
598                .unwrap();
599        assert!(head.metadata_only);
600        assert!(
601            serde_json::from_value::<ExternalAuthorizeArtifactReadRequest>(
602                serde_json::json!({"grant":"signed", "metadataOnly":"true"})
603            )
604            .is_err()
605        );
606    }
607
608    #[test]
609    fn external_events_use_the_current_wire_shape() {
610        let event = ExternalCoreEvent {
611            event_id: "event-1".to_string(),
612            kind: ExternalCoreEventKind::ScopeOwnedDataPurgeRequested,
613            payload: serde_json::to_value(ScopeOwnedDataPurgeRequest {
614                tenant_id: "tenant-1".to_string(),
615                scope_id: "scope-1".to_string(),
616            })
617            .unwrap(),
618            expects_response: true,
619        };
620
621        let value = serde_json::to_value(event).unwrap();
622        assert_eq!(EXTERNAL_CORE_PROTOCOL_VERSION, 21);
623        assert_eq!(value["kind"], "scopeOwnedDataPurgeRequested");
624        assert_eq!(value["payload"]["tenantId"], "tenant-1");
625        assert_eq!(value["payload"]["scopeId"], "scope-1");
626        assert_eq!(value["expectsResponse"], true);
627
628        let facade = ExternalCoreEvent {
629            event_id: "event-2".to_string(),
630            kind: ExternalCoreEventKind::ServiceAppFacadeRequest,
631            payload: serde_json::to_value(ExternalServiceAppFacadeRequest {
632                target: "/app/messaging/provider/list".to_string(),
633                tenant_id: "tenant-1".to_string(),
634                scope_id: "scope-1".to_string(),
635                user_id: "user-1".to_string(),
636                client_id: None,
637                payload: serde_json::json!({"placement": "local"}),
638            })
639            .unwrap(),
640            expects_response: true,
641        };
642        let value = serde_json::to_value(facade).unwrap();
643        assert_eq!(value["kind"], "serviceAppFacadeRequest");
644        assert_eq!(value["payload"]["target"], "/app/messaging/provider/list");
645        assert_eq!(value["payload"]["userId"], "user-1");
646        assert!(value["payload"].get("clientId").is_none());
647    }
648
649    #[test]
650    fn artifact_host_contract_uses_canonical_wire_types() {
651        let descriptor = ExternalArtifactReadDescriptor {
652            temporary: false,
653            data_base64: None,
654            path: "/runtime/artifacts/blob".to_string(),
655            kind: artifact_api::ArtifactKind::Audio,
656            mime_type: "audio/ogg".to_string(),
657            size_bytes: 42,
658            width: None,
659            height: None,
660            duration_millis: Some(1_500),
661            sha256: "a".repeat(64),
662        };
663        let value = serde_json::to_value(descriptor).unwrap();
664        assert_eq!(value["kind"], "AUDIO");
665        assert_eq!(value["mimeType"], "audio/ogg");
666        assert_eq!(value["durationMillis"], 1_500);
667        assert!(value.get("width").is_none());
668
669        let request = ArtifactDeliveryProjectionRequest {
670            third_party: false,
671            grant: "payload.signature".to_string(),
672            expires_at_unix_ms: 123,
673            client_id: "L:client".to_string(),
674        };
675        let value = serde_json::to_value(request).unwrap();
676        assert_eq!(value["expiresAtUnixMs"], 123);
677        assert_eq!(value["clientId"], "L:client");
678    }
679
680    #[test]
681    fn playground_uses_only_the_general_webhook_contract() {
682        let general = serde_json::to_value(ExternalCoreMethod::GeneralWebhookPayload).unwrap();
683        assert_eq!(general, serde_json::json!("GeneralWebhookPayload"));
684        assert!(
685            serde_json::from_value::<ExternalCoreMethod>(serde_json::json!(
686                "PlaygroundWebhookPayload"
687            ))
688            .is_err()
689        );
690    }
691}
692
693/// Host-to-Core bounded transfer commands. Public clients send a binary HTTP body.
694/// Only the owner keeps upload state, digest and staging content.
695pub const ARTIFACT_STREAM_CHUNK_BYTES: usize = 64 * 1024;
696
697#[derive(Debug, Clone, Serialize, Deserialize)]
698#[serde(
699    tag = "operation",
700    rename_all = "camelCase",
701    rename_all_fields = "camelCase",
702    deny_unknown_fields
703)]
704pub enum ExternalArtifactStreamRequest {
705    Begin { grant: String, mime_type: String },
706    Append { grant: String, data_base64: String },
707    Finish { grant: String },
708    Abort { grant: String },
709}
710
711#[derive(Debug, Clone, Serialize, Deserialize)]
712#[serde(
713    tag = "state",
714    rename_all = "camelCase",
715    rename_all_fields = "camelCase",
716    deny_unknown_fields
717)]
718pub enum ExternalArtifactStreamResponse {
719    Receiving {
720        max_size_bytes: u64,
721    },
722    Accepted {},
723    Staged {
724        receipt: artifact_api::ArtifactUploadReceipt,
725    },
726}