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    #[serde(default, skip_serializing_if = "Option::is_none")]
393    pub transport: Option<artifact_api::ArtifactDeliveryTransport>,
394    pub grant: String,
395    pub expires_at_unix_ms: u64,
396    pub client_id: String,
397}
398
399#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
400#[serde(rename_all = "camelCase", deny_unknown_fields)]
401pub struct ArtifactDeliveryProjectionResponse {
402    #[serde(default, skip_serializing_if = "Option::is_none")]
403    pub host_identity: Option<artifact_api::HostTlsIdentity>,
404    pub url: String,
405}
406
407#[derive(Debug, Clone, Serialize, Deserialize)]
408#[serde(rename_all = "camelCase", deny_unknown_fields)]
409pub struct ArtifactUploadProjectionRequest {
410    pub grant: String,
411    pub expires_at_unix_ms: u64,
412    pub client_id: String,
413}
414
415#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
416#[serde(rename_all = "camelCase", deny_unknown_fields)]
417pub struct ArtifactUploadProjectionResponse {
418    #[serde(default, skip_serializing_if = "Option::is_none")]
419    pub host_identity: Option<artifact_api::HostTlsIdentity>,
420    pub url: String,
421}
422
423/// An App Facade request delegated by an externally hosted Core to the
424/// application service that owns the target's business logic.
425#[derive(Debug, Clone, Serialize, Deserialize)]
426#[serde(rename_all = "camelCase")]
427pub struct ExternalServiceAppFacadeRequest {
428    pub target: String,
429    pub tenant_id: String,
430    pub space_id: String,
431    pub user_id: String,
432    #[serde(default, skip_serializing_if = "Option::is_none")]
433    pub client_id: Option<String>,
434    pub payload: Value,
435}
436
437/// A platform capability request emitted by an externally hosted Core.
438///
439/// Core owns the onboarding workflow. The native host owns LAN discovery and
440/// transport to a discovered candidate, so Android can satisfy this contract
441/// without moving application logic into the mobile shell.
442#[derive(Debug, Clone, Serialize, Deserialize)]
443#[serde(rename_all = "camelCase")]
444pub struct ExternalHostRuntimeRequest {
445    #[serde(default, skip_serializing_if = "Option::is_none")]
446    pub host_public_key: Option<crate::host::auth::PublicKey>,
447    pub method: ExternalHostRuntimeMethod,
448    #[serde(default, skip_serializing_if = "Option::is_none")]
449    pub candidate_id: Option<String>,
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    pub action: Option<String>,
452    #[serde(default, skip_serializing_if = "Option::is_none")]
453    pub payload: Option<Value>,
454}
455
456#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
457#[serde(rename_all = "camelCase")]
458pub enum ExternalHostRuntimeMethod {
459    Discovery,
460    CandidateRequest,
461}
462
463#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
464#[serde(rename_all = "camelCase")]
465pub struct SpaceOwnedDataPurgeRequest {
466    pub tenant_id: String,
467    pub space_id: String,
468}
469
470#[derive(Debug, Clone, Serialize, Deserialize)]
471#[serde(rename_all = "camelCase")]
472pub struct ExternalCoreEventCompletion {
473    pub event_id: String,
474    pub ok: bool,
475    #[serde(default, skip_serializing_if = "Option::is_none")]
476    pub response: Option<Value>,
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub error: Option<ExternalCoreError>,
479}
480
481#[derive(Debug, Clone, Serialize, Deserialize)]
482pub struct HttpPayloadRequest {
483    pub payload: Value,
484}
485
486#[derive(Debug, Clone, Serialize, Deserialize)]
487pub struct EndpointPayloadRequest {
488    pub endpoint_id: String,
489    pub payload: Value,
490}
491
492#[derive(Debug, Clone, Serialize, Deserialize)]
493#[serde(rename_all = "camelCase")]
494pub struct ExternalCoreRuntimeMetadata {
495    pub backend: String,
496    pub instance_id: String,
497    pub pid: u32,
498    pub state: String,
499    pub started_at: String,
500    pub protocol_version: u32,
501    pub binary_version: String,
502    pub socket_path: String,
503}
504
505#[derive(Debug, Clone, Serialize, Deserialize)]
506#[serde(rename_all = "camelCase")]
507pub struct ExternalCoreHealth {
508    pub runtime_space_policy: Option<crate::runtime_space::RuntimeSpacePolicy>,
509    pub ok: bool,
510    pub ready: bool,
511    pub backend: String,
512    pub binary_version: String,
513    pub agent_version: String,
514    pub protocol_version: u32,
515    #[serde(skip_serializing_if = "Option::is_none")]
516    pub instance_id: Option<String>,
517    #[serde(skip_serializing_if = "Option::is_none")]
518    pub pid: Option<u32>,
519    #[serde(skip_serializing_if = "Option::is_none")]
520    pub state: Option<String>,
521    #[serde(skip_serializing_if = "Option::is_none")]
522    pub started_at: Option<String>,
523    #[serde(default)]
524    pub capabilities: Vec<String>,
525}
526
527impl ExternalArtifactReadDescriptor {
528    /// Decode the bounded inline variant. File descriptors return None.
529    pub fn inline_content(&self) -> Result<Option<Vec<u8>>, String> {
530        use base64::Engine as _;
531        use sha2::{Digest, Sha256};
532        if self.remote.is_some() && (!self.path.is_empty() || self.data_base64.is_some()) {
533            return Err("artifact descriptor has conflicting content sources".into());
534        }
535        let Some(encoded) = &self.data_base64 else {
536            return if self.path.is_empty() && self.remote.is_none() {
537                Err("artifact descriptor has no content".into())
538            } else {
539                Ok(None)
540            };
541        };
542        if !self.path.is_empty()
543            || self.size_bytes > MAX_NATIVE_ARTIFACT_BYTES as u64
544            || encoded.len() > MAX_NATIVE_ARTIFACT_BASE64_BYTES
545        {
546            return Err("invalid inline artifact descriptor".into());
547        }
548        let bytes = base64::engine::general_purpose::STANDARD
549            .decode(encoded)
550            .map_err(|_| "invalid inline artifact base64")?;
551        if bytes.len() as u64 != self.size_bytes
552            || format!("{:x}", Sha256::digest(&bytes)) != self.sha256
553        {
554            return Err("inline artifact failed its integrity check".into());
555        }
556        Ok(Some(bytes))
557    }
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563
564    #[test]
565    fn callback_address_requires_a_fresh_host_observation_and_bound_port() {
566        let mut request = UpdateCallbackBaseRequest {
567            third_party_port: 0,
568            network: crate::host::network::HostNetworkSnapshot {
569                lan_ipv4: Some("192.168.1.5".parse().unwrap()),
570                observed_at_ms: 100_000,
571            },
572            port: 3210,
573        };
574        assert_eq!(
575            request.native_base(100_000).as_deref(),
576            Some("https://192.168.1.5:3210")
577        );
578        let roundtrip: UpdateCallbackBaseRequest =
579            serde_json::from_value(serde_json::to_value(&request).unwrap()).unwrap();
580        assert_eq!(request, roundtrip);
581        assert_eq!(request.callback_base(100_000), None);
582        request.third_party_port = 3211;
583        assert_eq!(
584            request.callback_base(100_000).as_deref(),
585            Some("http://192.168.1.5:3211")
586        );
587        assert_eq!(request.callback_base(145_000), None);
588        assert_eq!(request.native_base(145_000), None);
589        request.port = 0;
590        assert_eq!(request.native_base(100_000), None);
591        assert_eq!(
592            UpdateCallbackBaseRequest::default().native_base(100_000),
593            None
594        );
595    }
596
597    #[test]
598    fn messaging_delivery_is_a_closed_request_response_contract() {
599        let request = serde_json::json!({"tenantId":"t", "spaceId":"s", "surfaceId":"m",
600            "target":"/chat/event", "payload":"{}"});
601        let decoded: MessagingDeliveryRequest = serde_json::from_value(request.clone()).unwrap();
602        assert_eq!(serde_json::to_value(decoded).unwrap(), request);
603        let mut invalid = request;
604        invalid["unknown"] = serde_json::json!(true);
605        assert!(serde_json::from_value::<MessagingDeliveryRequest>(invalid).is_err());
606        assert!(
607            serde_json::from_value::<MessagingDeliveryResponse>(serde_json::json!({})).is_err()
608        );
609        assert_eq!(
610            serde_json::to_value(ExternalCoreEventKind::DeliveryRequested).unwrap(),
611            "deliveryRequested"
612        );
613    }
614
615    #[test]
616    fn artifact_read_metadata_mode_is_explicit_and_defaults_to_content() {
617        let read: ExternalAuthorizeArtifactReadRequest =
618            serde_json::from_value(serde_json::json!({"grant":"signed"})).unwrap();
619        assert!(!read.metadata_only);
620        assert_eq!(
621            serde_json::to_value(read).unwrap(),
622            serde_json::json!({"grant":"signed"})
623        );
624        let head: ExternalAuthorizeArtifactReadRequest =
625            serde_json::from_value(serde_json::json!({"grant":"signed", "metadataOnly":true}))
626                .unwrap();
627        assert!(head.metadata_only);
628        assert!(
629            serde_json::from_value::<ExternalAuthorizeArtifactReadRequest>(
630                serde_json::json!({"grant":"signed", "metadataOnly":"true"})
631            )
632            .is_err()
633        );
634    }
635
636    #[test]
637    fn external_events_use_the_current_wire_shape() {
638        let event = ExternalCoreEvent {
639            event_id: "event-1".to_string(),
640            kind: ExternalCoreEventKind::SpaceOwnedDataPurgeRequested,
641            payload: serde_json::to_value(SpaceOwnedDataPurgeRequest {
642                tenant_id: "tenant-1".to_string(),
643                space_id: "scope-1".to_string(),
644            })
645            .unwrap(),
646            expects_response: true,
647        };
648
649        let value = serde_json::to_value(event).unwrap();
650        assert_eq!(EXTERNAL_CORE_PROTOCOL_VERSION, 26);
651        assert_eq!(value["kind"], "spaceOwnedDataPurgeRequested");
652        assert_eq!(value["payload"]["tenantId"], "tenant-1");
653        assert_eq!(value["payload"]["spaceId"], "scope-1");
654        assert_eq!(value["expectsResponse"], true);
655
656        let facade = ExternalCoreEvent {
657            event_id: "event-2".to_string(),
658            kind: ExternalCoreEventKind::ServiceAppFacadeRequest,
659            payload: serde_json::to_value(ExternalServiceAppFacadeRequest {
660                target: "/app/messaging/provider/list".to_string(),
661                tenant_id: "tenant-1".to_string(),
662                space_id: "scope-1".to_string(),
663                user_id: "user-1".to_string(),
664                client_id: None,
665                payload: serde_json::json!({"placement": "local"}),
666            })
667            .unwrap(),
668            expects_response: true,
669        };
670        let value = serde_json::to_value(facade).unwrap();
671        assert_eq!(value["kind"], "serviceAppFacadeRequest");
672        assert_eq!(value["payload"]["target"], "/app/messaging/provider/list");
673        assert_eq!(value["payload"]["userId"], "user-1");
674        assert!(value["payload"].get("clientId").is_none());
675    }
676
677    #[test]
678    fn artifact_host_contract_uses_canonical_wire_types() {
679        let descriptor = ExternalArtifactReadDescriptor {
680            remote: None,
681            temporary: false,
682            data_base64: None,
683            path: "/runtime/artifacts/blob".to_string(),
684            kind: artifact_api::ArtifactKind::Audio,
685            mime_type: "audio/ogg".to_string(),
686            size_bytes: 42,
687            width: None,
688            height: None,
689            duration_millis: Some(1_500),
690            sha256: "a".repeat(64),
691        };
692        let value = serde_json::to_value(descriptor).unwrap();
693        assert_eq!(value["kind"], "AUDIO");
694        assert_eq!(value["mimeType"], "audio/ogg");
695        assert_eq!(value["durationMillis"], 1_500);
696        assert!(value.get("width").is_none());
697
698        let request = ArtifactDeliveryProjectionRequest {
699            third_party: false,
700            transport: None,
701            grant: "payload.signature".to_string(),
702            expires_at_unix_ms: 123,
703            client_id: "L:client".to_string(),
704        };
705        let value = serde_json::to_value(request).unwrap();
706        assert_eq!(value["expiresAtUnixMs"], 123);
707        assert_eq!(value["clientId"], "L:client");
708    }
709
710    #[test]
711    fn playground_uses_only_the_general_webhook_contract() {
712        let general = serde_json::to_value(ExternalCoreMethod::GeneralWebhookPayload).unwrap();
713        assert_eq!(general, serde_json::json!("GeneralWebhookPayload"));
714        assert!(
715            serde_json::from_value::<ExternalCoreMethod>(serde_json::json!(
716                "PlaygroundWebhookPayload"
717            ))
718            .is_err()
719        );
720    }
721}
722
723/// Host-to-Core bounded transfer commands. Public clients send a binary HTTP body.
724/// Only the owner keeps upload state, digest and staging content.
725pub const ARTIFACT_STREAM_CHUNK_BYTES: usize = 64 * 1024;
726
727#[derive(Debug, Clone, Serialize, Deserialize)]
728#[serde(
729    tag = "operation",
730    rename_all = "camelCase",
731    rename_all_fields = "camelCase",
732    deny_unknown_fields
733)]
734pub enum ExternalArtifactStreamRequest {
735    Begin { grant: String, mime_type: String },
736    Append { grant: String, data_base64: String },
737    Finish { grant: String },
738    Abort { grant: String },
739}
740
741#[derive(Debug, Clone, Serialize, Deserialize)]
742#[serde(
743    tag = "state",
744    rename_all = "camelCase",
745    rename_all_fields = "camelCase",
746    deny_unknown_fields
747)]
748pub enum ExternalArtifactStreamResponse {
749    Receiving {
750        max_size_bytes: u64,
751    },
752    Accepted {},
753    Staged {
754        receipt: artifact_api::ArtifactUploadReceipt,
755    },
756}