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 = 24;
8/// Maximum single native artifact body, separate from the JSON control frame limit.
9pub const MAX_NATIVE_ARTIFACT_BYTES: usize = 50 * 1024 * 1024;
10pub const MAX_NATIVE_ARTIFACT_BASE64_BYTES: usize = MAX_NATIVE_ARTIFACT_BYTES.div_ceil(3) * 4;
11/// Protocol 18 sends large dataBase64 strings after the JSON frame. The JSON field
12/// is an empty string marker, followed by a u32 byte length and that many ASCII
13/// bytes on the same connection. Only artifact commit requests and open/read
14/// responses support this attachment. Control frames keep their 16 MiB limit.
15pub const ARTIFACT_ATTACHMENT_CHUNK_BYTES: usize = 1024 * 1024;
16pub const ARTIFACT_CONTENT_PATH_PREFIX: &str = "/artifact/v1/content/";
17pub const ARTIFACT_UPLOAD_PATH_PREFIX: &str = "/artifact/v1/upload/";
18
19/// Derive a bounded, workdir-specific Windows IPC name from the metadata socket path.
20/// The metadata itself stays in the ordinary runtime directory on every platform.
21pub fn external_core_pipe_name(socket_path: &std::path::Path) -> String {
22    use sha2::{Digest, Sha256};
23    let normalized = socket_path
24        .to_string_lossy()
25        .replace('/', "\\")
26        .to_lowercase();
27    format!(
28        r"\\.\pipe\meowcore-{:x}",
29        Sha256::digest(normalized.as_bytes())
30    )
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct ExternalCoreRequest {
35    pub id: String,
36    pub method: ExternalCoreMethod,
37    pub payload: Value,
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct ExternalCoreResponse {
42    pub id: String,
43    pub ok: bool,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub result: Option<Value>,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub error: Option<ExternalCoreError>,
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct ExternalCoreError {
52    pub code: String,
53    pub message: String,
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub details: Option<Value>,
56}
57
58impl From<crate::ErrorResponse> for ExternalCoreError {
59    fn from(error: crate::ErrorResponse) -> Self {
60        Self {
61            code: error.error,
62            message: error.message,
63            details: error.details,
64        }
65    }
66}
67
68impl From<ExternalCoreError> for crate::ErrorResponse {
69    fn from(error: ExternalCoreError) -> Self {
70        Self {
71            error: error.code,
72            message: error.message,
73            details: error.details,
74        }
75    }
76}
77
78impl std::fmt::Display for ExternalCoreError {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        write!(f, "[{}] {}", self.code, self.message)
81    }
82}
83
84impl std::error::Error for ExternalCoreError {}
85
86/// A completed JSON HTTP handler response, including non-2xx responses.
87/// This is an RPC result, not an RPC error. Hosts must preserve both fields.
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90pub struct HttpPayloadResponse {
91    pub status_code: u16,
92    pub body: Value,
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub enum ExternalCoreMethod {
97    HandleCoreInput,
98    RegisterLocalAppClient,
99    RegisterNodeConnection,
100    CleanupWsState,
101    UpdateCallbackBase,
102    PutArtifact,
103    OpenArtifact,
104    AuthorizeArtifactRead,
105    AuthorizeArtifactUpload,
106    CommitArtifactUpload,
107    StreamArtifactUpload,
108    DeviceIdentity,
109    CommissionFingerprint,
110    CommissionPublicKeyBase64,
111    ListMdnsRecords,
112    PollEvents,
113    CompleteEvents,
114    CommissionChallengePayload,
115    PairingStartPayload,
116    SetupStartPayload,
117    GeneralWebhookPayload,
118    InvokeWasmPayload,
119    Health,
120    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}
263
264/// Messaging-only Core -> Host request. A successful response means delivery was accepted by
265/// the provider implementation, not merely queued in the Core event pump or read by a user.
266#[derive(Debug, Clone, Serialize, Deserialize)]
267#[serde(rename_all = "camelCase", deny_unknown_fields)]
268pub struct MessagingDeliveryRequest {
269    pub tenant_id: String,
270    pub scope_id: String,
271    pub surface_id: String,
272    pub target: String,
273    pub payload: String,
274}
275
276#[derive(Debug, Clone, Serialize, Deserialize)]
277#[serde(rename_all = "camelCase", deny_unknown_fields)]
278pub struct MessagingDeliveryResponse {
279    pub outcome: crate::DeliveryOutcome,
280}
281
282#[derive(Debug, Clone, Serialize, Deserialize)]
283#[serde(rename_all = "camelCase", deny_unknown_fields)]
284pub struct ExternalArtifactRequestContext {
285    pub tenant_id: String,
286    pub scope_id: String,
287    pub actor_user_id: String,
288    pub client_id: String,
289}
290
291#[derive(Debug, Clone, Serialize, Deserialize)]
292#[serde(rename_all = "camelCase", deny_unknown_fields)]
293pub struct ExternalPutArtifactRequest {
294    pub context: ExternalArtifactRequestContext,
295    pub artifact: artifact_api::PutArtifactRequest,
296}
297
298#[derive(Debug, Clone, Serialize, Deserialize)]
299#[serde(rename_all = "camelCase", deny_unknown_fields)]
300pub struct ExternalOpenArtifactRequest {
301    pub context: ExternalArtifactRequestContext,
302    pub uri: String,
303}
304
305#[derive(Debug, Clone, Serialize, Deserialize)]
306#[serde(rename_all = "camelCase", deny_unknown_fields)]
307pub struct ExternalAuthorizeArtifactReadRequest {
308    pub grant: String,
309    /// Inspect existence and metadata without reading content or renewing idle expiry.
310    /// The response has neither a file path nor inline content in this mode.
311    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
312    pub metadata_only: bool,
313}
314
315#[derive(Debug, Clone, Serialize, Deserialize)]
316#[serde(rename_all = "camelCase", deny_unknown_fields)]
317pub struct ExternalAuthorizeArtifactUploadRequest {
318    pub grant: String,
319}
320
321#[derive(Debug, Clone, Serialize, Deserialize)]
322#[serde(rename_all = "camelCase", deny_unknown_fields)]
323pub struct ExternalCommitArtifactUploadRequest {
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub data_base64: Option<String>,
326    pub grant: String,
327}
328
329#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
330#[serde(rename_all = "camelCase", deny_unknown_fields)]
331pub struct ExternalArtifactReadDescriptor {
332    #[serde(default, skip_serializing_if = "Option::is_none")]
333    pub data_base64: Option<String>,
334    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
335    pub temporary: bool,
336    pub path: String,
337    pub kind: artifact_api::ArtifactKind,
338    pub mime_type: String,
339    pub size_bytes: u64,
340    #[serde(default, skip_serializing_if = "Option::is_none")]
341    pub width: Option<u32>,
342    #[serde(default, skip_serializing_if = "Option::is_none")]
343    pub height: Option<u32>,
344    #[serde(default, skip_serializing_if = "Option::is_none")]
345    pub duration_millis: Option<u64>,
346    pub sha256: String,
347}
348
349#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
350#[serde(rename_all = "camelCase", deny_unknown_fields)]
351pub struct ExternalArtifactUploadDescriptor {
352    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
353    pub temporary: bool,
354    pub upload_id: String,
355    pub path: String,
356    pub kind: artifact_api::ArtifactKind,
357    pub mime_type: String,
358    pub size_bytes: u64,
359    pub sha256: String,
360    #[serde(default, skip_serializing_if = "Option::is_none")]
361    pub duration_millis: Option<u64>,
362    pub expires_at_unix_ms: u64,
363}
364
365#[derive(Debug, Clone, Serialize, Deserialize)]
366#[serde(rename_all = "camelCase", deny_unknown_fields)]
367pub struct ArtifactDeliveryProjectionRequest {
368    /// Explicit compatibility request; native traffic must remain HTTPS.
369    #[serde(default)]
370    pub third_party: bool,
371    pub grant: String,
372    pub expires_at_unix_ms: u64,
373    pub client_id: String,
374}
375
376#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
377#[serde(rename_all = "camelCase", deny_unknown_fields)]
378pub struct ArtifactDeliveryProjectionResponse {
379    #[serde(default, skip_serializing_if = "Option::is_none")]
380    pub host_identity: Option<artifact_api::HostTlsIdentity>,
381    pub url: String,
382}
383
384#[derive(Debug, Clone, Serialize, Deserialize)]
385#[serde(rename_all = "camelCase", deny_unknown_fields)]
386pub struct ArtifactUploadProjectionRequest {
387    pub grant: String,
388    pub expires_at_unix_ms: u64,
389    pub client_id: String,
390}
391
392#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
393#[serde(rename_all = "camelCase", deny_unknown_fields)]
394pub struct ArtifactUploadProjectionResponse {
395    #[serde(default, skip_serializing_if = "Option::is_none")]
396    pub host_identity: Option<artifact_api::HostTlsIdentity>,
397    pub url: String,
398}
399
400/// An App Facade request delegated by an externally hosted Core to the
401/// application service that owns the target's business logic.
402#[derive(Debug, Clone, Serialize, Deserialize)]
403#[serde(rename_all = "camelCase")]
404pub struct ExternalServiceAppFacadeRequest {
405    pub target: String,
406    pub tenant_id: String,
407    pub scope_id: String,
408    pub user_id: String,
409    #[serde(default, skip_serializing_if = "Option::is_none")]
410    pub client_id: Option<String>,
411    pub payload: Value,
412}
413
414/// A platform capability request emitted by an externally hosted Core.
415///
416/// Core owns the onboarding workflow. The native host owns LAN discovery and
417/// transport to a discovered candidate, so Android can satisfy this contract
418/// without moving application logic into the mobile shell.
419#[derive(Debug, Clone, Serialize, Deserialize)]
420#[serde(rename_all = "camelCase")]
421pub struct ExternalHostRuntimeRequest {
422    #[serde(default, skip_serializing_if = "Option::is_none")]
423    pub host_public_key: Option<crate::host::auth::PublicKey>,
424    pub method: ExternalHostRuntimeMethod,
425    #[serde(default, skip_serializing_if = "Option::is_none")]
426    pub candidate_id: Option<String>,
427    #[serde(default, skip_serializing_if = "Option::is_none")]
428    pub action: Option<String>,
429    #[serde(default, skip_serializing_if = "Option::is_none")]
430    pub payload: Option<Value>,
431}
432
433#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
434#[serde(rename_all = "camelCase")]
435pub enum ExternalHostRuntimeMethod {
436    Discovery,
437    CandidateRequest,
438}
439
440#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
441#[serde(rename_all = "camelCase")]
442pub struct ScopeOwnedDataPurgeRequest {
443    pub tenant_id: String,
444    pub scope_id: String,
445}
446
447#[derive(Debug, Clone, Serialize, Deserialize)]
448#[serde(rename_all = "camelCase")]
449pub struct ExternalCoreEventCompletion {
450    pub event_id: String,
451    pub ok: bool,
452    #[serde(default, skip_serializing_if = "Option::is_none")]
453    pub response: Option<Value>,
454    #[serde(default, skip_serializing_if = "Option::is_none")]
455    pub error: Option<ExternalCoreError>,
456}
457
458#[derive(Debug, Clone, Serialize, Deserialize)]
459pub struct HttpPayloadRequest {
460    pub payload: Value,
461}
462
463#[derive(Debug, Clone, Serialize, Deserialize)]
464pub struct EndpointPayloadRequest {
465    pub endpoint_id: String,
466    pub payload: Value,
467}
468
469#[derive(Debug, Clone, Serialize, Deserialize)]
470#[serde(rename_all = "camelCase")]
471pub struct ExternalCoreRuntimeMetadata {
472    pub backend: String,
473    pub instance_id: String,
474    pub pid: u32,
475    pub state: String,
476    pub started_at: String,
477    pub protocol_version: u32,
478    pub binary_version: String,
479    pub socket_path: String,
480}
481
482#[derive(Debug, Clone, Serialize, Deserialize)]
483#[serde(rename_all = "camelCase")]
484pub struct ExternalCoreHealth {
485    pub runtime_space_policy: Option<crate::runtime_space::RuntimeSpacePolicy>,
486    pub ok: bool,
487    pub ready: bool,
488    pub backend: String,
489    pub binary_version: String,
490    pub agent_version: String,
491    pub protocol_version: u32,
492    #[serde(skip_serializing_if = "Option::is_none")]
493    pub instance_id: Option<String>,
494    #[serde(skip_serializing_if = "Option::is_none")]
495    pub pid: Option<u32>,
496    #[serde(skip_serializing_if = "Option::is_none")]
497    pub state: Option<String>,
498    #[serde(skip_serializing_if = "Option::is_none")]
499    pub started_at: Option<String>,
500    #[serde(default)]
501    pub capabilities: Vec<String>,
502}
503
504impl ExternalArtifactReadDescriptor {
505    /// Decode the bounded inline variant. File descriptors return None.
506    pub fn inline_content(&self) -> Result<Option<Vec<u8>>, String> {
507        use base64::Engine as _;
508        use sha2::{Digest, Sha256};
509        let Some(encoded) = &self.data_base64 else {
510            return if self.path.is_empty() {
511                Err("artifact descriptor has no content".into())
512            } else {
513                Ok(None)
514            };
515        };
516        if !self.path.is_empty()
517            || self.size_bytes > MAX_NATIVE_ARTIFACT_BYTES as u64
518            || encoded.len() > MAX_NATIVE_ARTIFACT_BASE64_BYTES
519        {
520            return Err("invalid inline artifact descriptor".into());
521        }
522        let bytes = base64::engine::general_purpose::STANDARD
523            .decode(encoded)
524            .map_err(|_| "invalid inline artifact base64")?;
525        if bytes.len() as u64 != self.size_bytes
526            || format!("{:x}", Sha256::digest(&bytes)) != self.sha256
527        {
528            return Err("inline artifact failed its integrity check".into());
529        }
530        Ok(Some(bytes))
531    }
532}
533
534#[cfg(test)]
535mod tests {
536    use super::*;
537
538    #[test]
539    fn callback_address_requires_a_fresh_host_observation_and_bound_port() {
540        let mut request = UpdateCallbackBaseRequest {
541            third_party_port: 0,
542            network: crate::host::network::HostNetworkSnapshot {
543                lan_ipv4: Some("192.168.1.5".parse().unwrap()),
544                observed_at_ms: 100_000,
545            },
546            port: 3210,
547        };
548        assert_eq!(
549            request.native_base(100_000).as_deref(),
550            Some("https://192.168.1.5:3210")
551        );
552        let roundtrip: UpdateCallbackBaseRequest =
553            serde_json::from_value(serde_json::to_value(&request).unwrap()).unwrap();
554        assert_eq!(request, roundtrip);
555        assert_eq!(request.callback_base(100_000), None);
556        request.third_party_port = 3211;
557        assert_eq!(
558            request.callback_base(100_000).as_deref(),
559            Some("http://192.168.1.5:3211")
560        );
561        assert_eq!(request.callback_base(145_000), None);
562        assert_eq!(request.native_base(145_000), None);
563        request.port = 0;
564        assert_eq!(request.native_base(100_000), None);
565        assert_eq!(
566            UpdateCallbackBaseRequest::default().native_base(100_000),
567            None
568        );
569    }
570
571    #[test]
572    fn messaging_delivery_is_a_closed_request_response_contract() {
573        let request = serde_json::json!({"tenantId":"t", "scopeId":"s", "surfaceId":"m",
574            "target":"/chat/event", "payload":"{}"});
575        let decoded: MessagingDeliveryRequest = serde_json::from_value(request.clone()).unwrap();
576        assert_eq!(serde_json::to_value(decoded).unwrap(), request);
577        let mut invalid = request;
578        invalid["unknown"] = serde_json::json!(true);
579        assert!(serde_json::from_value::<MessagingDeliveryRequest>(invalid).is_err());
580        assert!(
581            serde_json::from_value::<MessagingDeliveryResponse>(serde_json::json!({})).is_err()
582        );
583        assert_eq!(
584            serde_json::to_value(ExternalCoreEventKind::DeliveryRequested).unwrap(),
585            "deliveryRequested"
586        );
587    }
588
589    #[test]
590    fn artifact_read_metadata_mode_is_explicit_and_defaults_to_content() {
591        let read: ExternalAuthorizeArtifactReadRequest =
592            serde_json::from_value(serde_json::json!({"grant":"signed"})).unwrap();
593        assert!(!read.metadata_only);
594        assert_eq!(
595            serde_json::to_value(read).unwrap(),
596            serde_json::json!({"grant":"signed"})
597        );
598        let head: ExternalAuthorizeArtifactReadRequest =
599            serde_json::from_value(serde_json::json!({"grant":"signed", "metadataOnly":true}))
600                .unwrap();
601        assert!(head.metadata_only);
602        assert!(
603            serde_json::from_value::<ExternalAuthorizeArtifactReadRequest>(
604                serde_json::json!({"grant":"signed", "metadataOnly":"true"})
605            )
606            .is_err()
607        );
608    }
609
610    #[test]
611    fn external_events_use_the_current_wire_shape() {
612        let event = ExternalCoreEvent {
613            event_id: "event-1".to_string(),
614            kind: ExternalCoreEventKind::ScopeOwnedDataPurgeRequested,
615            payload: serde_json::to_value(ScopeOwnedDataPurgeRequest {
616                tenant_id: "tenant-1".to_string(),
617                scope_id: "scope-1".to_string(),
618            })
619            .unwrap(),
620            expects_response: true,
621        };
622
623        let value = serde_json::to_value(event).unwrap();
624        assert_eq!(EXTERNAL_CORE_PROTOCOL_VERSION, 24);
625        assert_eq!(value["kind"], "scopeOwnedDataPurgeRequested");
626        assert_eq!(value["payload"]["tenantId"], "tenant-1");
627        assert_eq!(value["payload"]["scopeId"], "scope-1");
628        assert_eq!(value["expectsResponse"], true);
629
630        let facade = ExternalCoreEvent {
631            event_id: "event-2".to_string(),
632            kind: ExternalCoreEventKind::ServiceAppFacadeRequest,
633            payload: serde_json::to_value(ExternalServiceAppFacadeRequest {
634                target: "/app/messaging/provider/list".to_string(),
635                tenant_id: "tenant-1".to_string(),
636                scope_id: "scope-1".to_string(),
637                user_id: "user-1".to_string(),
638                client_id: None,
639                payload: serde_json::json!({"placement": "local"}),
640            })
641            .unwrap(),
642            expects_response: true,
643        };
644        let value = serde_json::to_value(facade).unwrap();
645        assert_eq!(value["kind"], "serviceAppFacadeRequest");
646        assert_eq!(value["payload"]["target"], "/app/messaging/provider/list");
647        assert_eq!(value["payload"]["userId"], "user-1");
648        assert!(value["payload"].get("clientId").is_none());
649    }
650
651    #[test]
652    fn artifact_host_contract_uses_canonical_wire_types() {
653        let descriptor = ExternalArtifactReadDescriptor {
654            temporary: false,
655            data_base64: None,
656            path: "/runtime/artifacts/blob".to_string(),
657            kind: artifact_api::ArtifactKind::Audio,
658            mime_type: "audio/ogg".to_string(),
659            size_bytes: 42,
660            width: None,
661            height: None,
662            duration_millis: Some(1_500),
663            sha256: "a".repeat(64),
664        };
665        let value = serde_json::to_value(descriptor).unwrap();
666        assert_eq!(value["kind"], "AUDIO");
667        assert_eq!(value["mimeType"], "audio/ogg");
668        assert_eq!(value["durationMillis"], 1_500);
669        assert!(value.get("width").is_none());
670
671        let request = ArtifactDeliveryProjectionRequest {
672            third_party: false,
673            grant: "payload.signature".to_string(),
674            expires_at_unix_ms: 123,
675            client_id: "L:client".to_string(),
676        };
677        let value = serde_json::to_value(request).unwrap();
678        assert_eq!(value["expiresAtUnixMs"], 123);
679        assert_eq!(value["clientId"], "L:client");
680    }
681
682    #[test]
683    fn playground_uses_only_the_general_webhook_contract() {
684        let general = serde_json::to_value(ExternalCoreMethod::GeneralWebhookPayload).unwrap();
685        assert_eq!(general, serde_json::json!("GeneralWebhookPayload"));
686        assert!(
687            serde_json::from_value::<ExternalCoreMethod>(serde_json::json!(
688                "PlaygroundWebhookPayload"
689            ))
690            .is_err()
691        );
692    }
693}
694
695/// Host-to-Core bounded transfer commands. Public clients send a binary HTTP body.
696/// Only the owner keeps upload state, digest and staging content.
697pub const ARTIFACT_STREAM_CHUNK_BYTES: usize = 64 * 1024;
698
699#[derive(Debug, Clone, Serialize, Deserialize)]
700#[serde(
701    tag = "operation",
702    rename_all = "camelCase",
703    rename_all_fields = "camelCase",
704    deny_unknown_fields
705)]
706pub enum ExternalArtifactStreamRequest {
707    Begin { grant: String, mime_type: String },
708    Append { grant: String, data_base64: String },
709    Finish { grant: String },
710    Abort { grant: String },
711}
712
713#[derive(Debug, Clone, Serialize, Deserialize)]
714#[serde(
715    tag = "state",
716    rename_all = "camelCase",
717    rename_all_fields = "camelCase",
718    deny_unknown_fields
719)]
720pub enum ExternalArtifactStreamResponse {
721    Receiving {
722        max_size_bytes: u64,
723    },
724    Accepted {},
725    Staged {
726        receipt: artifact_api::ArtifactUploadReceipt,
727    },
728}