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