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