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