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