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 = 17;
8pub const ARTIFACT_CONTENT_PATH_PREFIX: &str = "/artifact/v1/content/";
9pub const ARTIFACT_UPLOAD_PATH_PREFIX: &str = "/artifact/v1/upload/";
10
11/// Derive a bounded, workdir-specific Windows IPC name from the metadata socket path.
12/// The metadata itself stays in the ordinary runtime directory on every platform.
13pub fn external_core_pipe_name(socket_path: &std::path::Path) -> String {
14    use sha2::{Digest, Sha256};
15    let normalized = socket_path
16        .to_string_lossy()
17        .replace('/', "\\")
18        .to_lowercase();
19    format!(
20        r"\\.\pipe\meowcore-{:x}",
21        Sha256::digest(normalized.as_bytes())
22    )
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct ExternalCoreRequest {
27    pub id: String,
28    pub method: ExternalCoreMethod,
29    pub payload: Value,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct ExternalCoreResponse {
34    pub id: String,
35    pub ok: bool,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub result: Option<Value>,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub error: Option<ExternalCoreError>,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct ExternalCoreError {
44    pub code: String,
45    pub message: String,
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub details: Option<Value>,
48}
49
50impl From<crate::ErrorResponse> for ExternalCoreError {
51    fn from(error: crate::ErrorResponse) -> Self {
52        Self {
53            code: error.error,
54            message: error.message,
55            details: error.details,
56        }
57    }
58}
59
60impl From<ExternalCoreError> for crate::ErrorResponse {
61    fn from(error: ExternalCoreError) -> Self {
62        Self {
63            error: error.code,
64            message: error.message,
65            details: error.details,
66        }
67    }
68}
69
70impl std::fmt::Display for ExternalCoreError {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        write!(f, "[{}] {}", self.code, self.message)
73    }
74}
75
76impl std::error::Error for ExternalCoreError {}
77
78/// A completed JSON HTTP handler response, including non-2xx responses.
79/// This is an RPC result, not an RPC error. Hosts must preserve both fields.
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81#[serde(rename_all = "camelCase")]
82pub struct HttpPayloadResponse {
83    pub status_code: u16,
84    pub body: Value,
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub enum ExternalCoreMethod {
89    HandleCoreInput,
90    RegisterLocalAppClient,
91    RegisterNodeConnection,
92    CleanupWsState,
93    UpdateCallbackBase,
94    PutArtifact,
95    OpenArtifact,
96    AuthorizeArtifactRead,
97    AuthorizeArtifactUpload,
98    CommitArtifactUpload,
99    DeviceIdentity,
100    CommissionFingerprint,
101    CommissionPublicKeyBase64,
102    ListMdnsRecords,
103    PollEvents,
104    CompleteEvents,
105    CommissionChallengePayload,
106    PairingStartPayload,
107    SetupStartPayload,
108    GeneralWebhookPayload,
109    InvokeWasmPayload,
110    Health,
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct HandleCoreInputRequest {
115    pub input: ServiceCoreInput,
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct HandleCoreInputResponse {
120    pub output: ServiceCoreOutput,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct RegisterLocalAppClientRequest {
125    pub ws_id: String,
126    pub auth_request: AuthRequest,
127    pub session: AuthenticatedSession,
128}
129
130#[derive(Debug, Clone, Serialize, Deserialize)]
131pub struct RegisterNodeConnectionRequest {
132    pub ws_id: String,
133    pub session_id: String,
134    pub node_type: String,
135    pub node_id: String,
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub host_name: Option<String>,
138    pub tenant_id: String,
139    pub scope_id: String,
140}
141
142#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct CleanupWsStateRequest {
144    pub ws_id: String,
145}
146
147#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
148pub struct UpdateCallbackBaseRequest {
149    /// Host observation, never an independently discovered or fallback address.
150    pub network: crate::host::network::HostNetworkSnapshot,
151    /// Actual bound native HTTPS listener port. Zero means it is not ready.
152    pub port: u16,
153    /// Restricted third-party HTTP listener. Zero disables compatibility URLs.
154    #[serde(default)]
155    pub third_party_port: u16,
156}
157
158impl UpdateCallbackBaseRequest {
159    pub fn callback_base(&self, now_ms: i64) -> Option<String> {
160        if self.third_party_port == 0 {
161            return None;
162        }
163        self.network
164            .available_ipv4(now_ms)
165            .map(|ip| format!("http://{ip}:{}", self.third_party_port))
166    }
167    pub fn native_base(&self, now_ms: i64) -> Option<String> {
168        if self.port == 0 {
169            return None;
170        }
171        self.network
172            .available_ipv4(now_ms)
173            .map(|ip| format!("https://{ip}:{}", self.port))
174    }
175}
176
177#[derive(Debug, Clone, Serialize, Deserialize)]
178#[serde(rename_all = "camelCase")]
179pub struct ExternalCoreDeviceIdentity {
180    pub device_id: String,
181    pub device_name: String,
182}
183
184#[derive(Debug, Clone, Serialize, Deserialize)]
185#[serde(rename_all = "camelCase")]
186pub struct ListMdnsRecordsRequest {
187    pub port: u16,
188    pub addresses: Vec<String>,
189    pub host_type: String,
190}
191
192#[derive(Debug, Clone, Serialize, Deserialize)]
193#[serde(rename_all = "camelCase")]
194pub struct ExternalCoreMdnsRecord {
195    pub service_type: String,
196    pub instance_name: String,
197    pub port: u16,
198    pub properties: HashMap<String, String>,
199}
200
201#[derive(Debug, Clone, Serialize, Deserialize)]
202#[serde(rename_all = "camelCase")]
203pub struct PollExternalCoreEventsRequest {
204    pub consumer_id: String,
205    pub max_events: u16,
206    pub timeout_ms: u64,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
210#[serde(rename_all = "camelCase")]
211pub struct PollExternalCoreEventsResponse {
212    pub events: Vec<ExternalCoreEvent>,
213    pub timed_out: bool,
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize)]
217#[serde(rename_all = "camelCase")]
218pub struct CompleteExternalCoreEventsRequest {
219    pub consumer_id: String,
220    pub completions: Vec<ExternalCoreEventCompletion>,
221}
222
223#[derive(Debug, Clone, Serialize, Deserialize)]
224#[serde(rename_all = "camelCase")]
225pub struct CompleteExternalCoreEventsResponse {
226    pub completed_event_ids: Vec<String>,
227    pub missing_event_ids: Vec<String>,
228}
229
230#[derive(Debug, Clone, Serialize, Deserialize)]
231#[serde(rename_all = "camelCase")]
232pub struct ExternalCoreEvent {
233    pub event_id: String,
234    pub kind: ExternalCoreEventKind,
235    pub payload: Value,
236    pub expects_response: bool,
237}
238
239#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
240#[serde(rename_all = "camelCase")]
241pub enum ExternalCoreEventKind {
242    MdnsRecordsChanged,
243    DeliveryRequested,
244    ConnectionControlRequested,
245    HostRuntimeRequest,
246    ServiceAppFacadeRequest,
247    ScopeOwnedDataPurgeRequested,
248    ArtifactDeliveryProjectionRequested,
249    ArtifactUploadProjectionRequested,
250}
251
252/// Messaging-only Core -> Host request. A successful response means delivery was accepted by
253/// the provider implementation, not merely queued in the Core event pump or read by a user.
254#[derive(Debug, Clone, Serialize, Deserialize)]
255#[serde(rename_all = "camelCase", deny_unknown_fields)]
256pub struct MessagingDeliveryRequest {
257    pub tenant_id: String,
258    pub scope_id: String,
259    pub surface_id: String,
260    pub target: String,
261    pub payload: String,
262}
263
264#[derive(Debug, Clone, Serialize, Deserialize)]
265#[serde(rename_all = "camelCase", deny_unknown_fields)]
266pub struct MessagingDeliveryResponse {
267    pub outcome: crate::DeliveryOutcome,
268}
269
270#[derive(Debug, Clone, Serialize, Deserialize)]
271#[serde(rename_all = "camelCase", deny_unknown_fields)]
272pub struct ExternalArtifactRequestContext {
273    pub tenant_id: String,
274    pub scope_id: String,
275    pub actor_user_id: String,
276    pub client_id: String,
277}
278
279#[derive(Debug, Clone, Serialize, Deserialize)]
280#[serde(rename_all = "camelCase", deny_unknown_fields)]
281pub struct ExternalPutArtifactRequest {
282    pub context: ExternalArtifactRequestContext,
283    pub artifact: artifact_api::PutArtifactRequest,
284}
285
286#[derive(Debug, Clone, Serialize, Deserialize)]
287#[serde(rename_all = "camelCase", deny_unknown_fields)]
288pub struct ExternalOpenArtifactRequest {
289    pub context: ExternalArtifactRequestContext,
290    pub uri: String,
291}
292
293#[derive(Debug, Clone, Serialize, Deserialize)]
294#[serde(rename_all = "camelCase", deny_unknown_fields)]
295pub struct ExternalAuthorizeArtifactReadRequest {
296    pub grant: String,
297}
298
299#[derive(Debug, Clone, Serialize, Deserialize)]
300#[serde(rename_all = "camelCase", deny_unknown_fields)]
301pub struct ExternalAuthorizeArtifactUploadRequest {
302    pub grant: String,
303}
304
305#[derive(Debug, Clone, Serialize, Deserialize)]
306#[serde(rename_all = "camelCase", deny_unknown_fields)]
307pub struct ExternalCommitArtifactUploadRequest {
308    pub grant: String,
309}
310
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
312#[serde(rename_all = "camelCase", deny_unknown_fields)]
313pub struct ExternalArtifactReadDescriptor {
314    pub path: String,
315    pub kind: artifact_api::ArtifactKind,
316    pub mime_type: String,
317    pub size_bytes: u64,
318    #[serde(default, skip_serializing_if = "Option::is_none")]
319    pub width: Option<u32>,
320    #[serde(default, skip_serializing_if = "Option::is_none")]
321    pub height: Option<u32>,
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub duration_millis: Option<u64>,
324    pub sha256: String,
325}
326
327#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
328#[serde(rename_all = "camelCase", deny_unknown_fields)]
329pub struct ExternalArtifactUploadDescriptor {
330    pub upload_id: String,
331    pub path: String,
332    pub kind: artifact_api::ArtifactKind,
333    pub mime_type: String,
334    pub size_bytes: u64,
335    pub sha256: String,
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub duration_millis: Option<u64>,
338    pub expires_at_unix_ms: u64,
339}
340
341#[derive(Debug, Clone, Serialize, Deserialize)]
342#[serde(rename_all = "camelCase", deny_unknown_fields)]
343pub struct ArtifactDeliveryProjectionRequest {
344    /// Explicit compatibility request; native traffic must remain HTTPS.
345    #[serde(default)]
346    pub third_party: bool,
347    pub grant: String,
348    pub expires_at_unix_ms: u64,
349    pub client_id: String,
350}
351
352#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
353#[serde(rename_all = "camelCase", deny_unknown_fields)]
354pub struct ArtifactDeliveryProjectionResponse {
355    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub host_identity: Option<artifact_api::HostTlsIdentity>,
357    pub url: String,
358}
359
360#[derive(Debug, Clone, Serialize, Deserialize)]
361#[serde(rename_all = "camelCase", deny_unknown_fields)]
362pub struct ArtifactUploadProjectionRequest {
363    pub grant: String,
364    pub expires_at_unix_ms: u64,
365    pub client_id: String,
366}
367
368#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
369#[serde(rename_all = "camelCase", deny_unknown_fields)]
370pub struct ArtifactUploadProjectionResponse {
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    pub host_identity: Option<artifact_api::HostTlsIdentity>,
373    pub url: String,
374}
375
376/// An App Facade request delegated by an externally hosted Core to the
377/// application service that owns the target's business logic.
378#[derive(Debug, Clone, Serialize, Deserialize)]
379#[serde(rename_all = "camelCase")]
380pub struct ExternalServiceAppFacadeRequest {
381    pub target: String,
382    pub tenant_id: String,
383    pub scope_id: String,
384    pub user_id: String,
385    #[serde(default, skip_serializing_if = "Option::is_none")]
386    pub client_id: Option<String>,
387    pub payload: Value,
388}
389
390/// A platform capability request emitted by an externally hosted Core.
391///
392/// Core owns the onboarding workflow. The native host owns LAN discovery and
393/// transport to a discovered candidate, so Android can satisfy this contract
394/// without moving application logic into the mobile shell.
395#[derive(Debug, Clone, Serialize, Deserialize)]
396#[serde(rename_all = "camelCase")]
397pub struct ExternalHostRuntimeRequest {
398    #[serde(default, skip_serializing_if = "Option::is_none")]
399    pub host_public_key: Option<crate::host::auth::PublicKey>,
400    pub method: ExternalHostRuntimeMethod,
401    #[serde(default, skip_serializing_if = "Option::is_none")]
402    pub candidate_id: Option<String>,
403    #[serde(default, skip_serializing_if = "Option::is_none")]
404    pub action: Option<String>,
405    #[serde(default, skip_serializing_if = "Option::is_none")]
406    pub payload: Option<Value>,
407}
408
409#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
410#[serde(rename_all = "camelCase")]
411pub enum ExternalHostRuntimeMethod {
412    Discovery,
413    CandidateRequest,
414}
415
416#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
417#[serde(rename_all = "camelCase")]
418pub struct ScopeOwnedDataPurgeRequest {
419    pub tenant_id: String,
420    pub scope_id: String,
421}
422
423#[derive(Debug, Clone, Serialize, Deserialize)]
424#[serde(rename_all = "camelCase")]
425pub struct ExternalCoreEventCompletion {
426    pub event_id: String,
427    pub ok: bool,
428    #[serde(default, skip_serializing_if = "Option::is_none")]
429    pub response: Option<Value>,
430    #[serde(default, skip_serializing_if = "Option::is_none")]
431    pub error: Option<ExternalCoreError>,
432}
433
434#[derive(Debug, Clone, Serialize, Deserialize)]
435pub struct HttpPayloadRequest {
436    pub payload: Value,
437}
438
439#[derive(Debug, Clone, Serialize, Deserialize)]
440pub struct EndpointPayloadRequest {
441    pub endpoint_id: String,
442    pub payload: Value,
443}
444
445#[derive(Debug, Clone, Serialize, Deserialize)]
446#[serde(rename_all = "camelCase")]
447pub struct ExternalCoreRuntimeMetadata {
448    pub backend: String,
449    pub instance_id: String,
450    pub pid: u32,
451    pub state: String,
452    pub started_at: String,
453    pub protocol_version: u32,
454    pub binary_version: String,
455    pub socket_path: String,
456}
457
458#[derive(Debug, Clone, Serialize, Deserialize)]
459#[serde(rename_all = "camelCase")]
460pub struct ExternalCoreHealth {
461    pub ok: bool,
462    pub ready: bool,
463    pub backend: String,
464    pub binary_version: String,
465    pub agent_version: String,
466    pub protocol_version: u32,
467    #[serde(skip_serializing_if = "Option::is_none")]
468    pub instance_id: Option<String>,
469    #[serde(skip_serializing_if = "Option::is_none")]
470    pub pid: Option<u32>,
471    #[serde(skip_serializing_if = "Option::is_none")]
472    pub state: Option<String>,
473    #[serde(skip_serializing_if = "Option::is_none")]
474    pub started_at: Option<String>,
475    #[serde(default)]
476    pub capabilities: Vec<String>,
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482
483    #[test]
484    fn callback_address_requires_a_fresh_host_observation_and_bound_port() {
485        let mut request = UpdateCallbackBaseRequest {
486            third_party_port: 0,
487            network: crate::host::network::HostNetworkSnapshot {
488                lan_ipv4: Some("192.168.1.5".parse().unwrap()),
489                observed_at_ms: 100_000,
490            },
491            port: 3210,
492        };
493        assert_eq!(
494            request.native_base(100_000).as_deref(),
495            Some("https://192.168.1.5:3210")
496        );
497        let roundtrip: UpdateCallbackBaseRequest =
498            serde_json::from_value(serde_json::to_value(&request).unwrap()).unwrap();
499        assert_eq!(request, roundtrip);
500        assert_eq!(request.callback_base(100_000), None);
501        request.third_party_port = 3211;
502        assert_eq!(
503            request.callback_base(100_000).as_deref(),
504            Some("http://192.168.1.5:3211")
505        );
506        assert_eq!(request.callback_base(145_000), None);
507        assert_eq!(request.native_base(145_000), None);
508        request.port = 0;
509        assert_eq!(request.native_base(100_000), None);
510        assert_eq!(
511            UpdateCallbackBaseRequest::default().native_base(100_000),
512            None
513        );
514    }
515
516    #[test]
517    fn messaging_delivery_is_a_closed_request_response_contract() {
518        let request = serde_json::json!({"tenantId":"t", "scopeId":"s", "surfaceId":"m",
519            "target":"/chat/event", "payload":"{}"});
520        let decoded: MessagingDeliveryRequest = serde_json::from_value(request.clone()).unwrap();
521        assert_eq!(serde_json::to_value(decoded).unwrap(), request);
522        let mut invalid = request;
523        invalid["unknown"] = serde_json::json!(true);
524        assert!(serde_json::from_value::<MessagingDeliveryRequest>(invalid).is_err());
525        assert!(
526            serde_json::from_value::<MessagingDeliveryResponse>(serde_json::json!({})).is_err()
527        );
528        assert_eq!(
529            serde_json::to_value(ExternalCoreEventKind::DeliveryRequested).unwrap(),
530            "deliveryRequested"
531        );
532    }
533
534    #[test]
535    fn external_events_use_the_current_wire_shape() {
536        let event = ExternalCoreEvent {
537            event_id: "event-1".to_string(),
538            kind: ExternalCoreEventKind::ScopeOwnedDataPurgeRequested,
539            payload: serde_json::to_value(ScopeOwnedDataPurgeRequest {
540                tenant_id: "tenant-1".to_string(),
541                scope_id: "scope-1".to_string(),
542            })
543            .unwrap(),
544            expects_response: true,
545        };
546
547        let value = serde_json::to_value(event).unwrap();
548        assert_eq!(EXTERNAL_CORE_PROTOCOL_VERSION, 17);
549        assert_eq!(value["kind"], "scopeOwnedDataPurgeRequested");
550        assert_eq!(value["payload"]["tenantId"], "tenant-1");
551        assert_eq!(value["payload"]["scopeId"], "scope-1");
552        assert_eq!(value["expectsResponse"], true);
553
554        let facade = ExternalCoreEvent {
555            event_id: "event-2".to_string(),
556            kind: ExternalCoreEventKind::ServiceAppFacadeRequest,
557            payload: serde_json::to_value(ExternalServiceAppFacadeRequest {
558                target: "/app/messaging/provider/list".to_string(),
559                tenant_id: "tenant-1".to_string(),
560                scope_id: "scope-1".to_string(),
561                user_id: "user-1".to_string(),
562                client_id: None,
563                payload: serde_json::json!({"placement": "local"}),
564            })
565            .unwrap(),
566            expects_response: true,
567        };
568        let value = serde_json::to_value(facade).unwrap();
569        assert_eq!(value["kind"], "serviceAppFacadeRequest");
570        assert_eq!(value["payload"]["target"], "/app/messaging/provider/list");
571        assert_eq!(value["payload"]["userId"], "user-1");
572        assert!(value["payload"].get("clientId").is_none());
573    }
574
575    #[test]
576    fn artifact_host_contract_uses_canonical_wire_types() {
577        let descriptor = ExternalArtifactReadDescriptor {
578            path: "/runtime/artifacts/blob".to_string(),
579            kind: artifact_api::ArtifactKind::Audio,
580            mime_type: "audio/ogg".to_string(),
581            size_bytes: 42,
582            width: None,
583            height: None,
584            duration_millis: Some(1_500),
585            sha256: "a".repeat(64),
586        };
587        let value = serde_json::to_value(descriptor).unwrap();
588        assert_eq!(value["kind"], "AUDIO");
589        assert_eq!(value["mimeType"], "audio/ogg");
590        assert_eq!(value["durationMillis"], 1_500);
591        assert!(value.get("width").is_none());
592
593        let request = ArtifactDeliveryProjectionRequest {
594            third_party: false,
595            grant: "payload.signature".to_string(),
596            expires_at_unix_ms: 123,
597            client_id: "L:client".to_string(),
598        };
599        let value = serde_json::to_value(request).unwrap();
600        assert_eq!(value["expiresAtUnixMs"], 123);
601        assert_eq!(value["clientId"], "L:client");
602    }
603
604    #[test]
605    fn playground_uses_only_the_general_webhook_contract() {
606        let general = serde_json::to_value(ExternalCoreMethod::GeneralWebhookPayload).unwrap();
607        assert_eq!(general, serde_json::json!("GeneralWebhookPayload"));
608        assert!(
609            serde_json::from_value::<ExternalCoreMethod>(serde_json::json!(
610                "PlaygroundWebhookPayload"
611            ))
612            .is_err()
613        );
614    }
615}