Skip to main content

gent_protocol/
lib.rs

1//! Portable identities, local RPC types, and endpoint permission semantics.
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4pub mod administration;
5pub mod babysitter;
6pub mod configuration_log;
7pub mod dashboard;
8pub mod directory;
9pub mod file_objects;
10pub mod history;
11pub mod hosted_mcp;
12pub mod notifications;
13pub mod owner_transfer;
14pub mod permissions;
15mod release_channel;
16pub mod service;
17pub mod stats;
18pub mod transport_batch;
19pub mod transport_exchange;
20pub mod transport_sweep;
21pub mod transport_watch;
22pub mod transport_wss;
23pub mod wake;
24pub mod web_failover;
25pub mod work;
26pub use release_channel::ReleaseChannel;
27
28pub const MAX_TEXT_BYTES: usize = 64 * 1024;
29pub const MAX_FILE_BYTES: usize = 1024 * 1024;
30pub const MAX_FRAME_BYTES: usize = 6 * 1024 * 1024;
31pub const MAX_EXCHANGE_MESSAGES: u32 = 32;
32pub const EXCHANGE_TTL_SECONDS: i64 = 24 * 60 * 60;
33pub const MAX_RELAY_GRANT_LIFETIME: u64 = 7 * 24 * 60 * 60;
34pub const MAX_REGISTRATION_GENERATION: u64 = (1 << 53) - 1;
35
36#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
37pub struct Agent {
38    pub id: String,
39    pub node_id: String,
40    pub name: String,
41    pub provider: String,
42    pub last_seen: i64,
43    pub revoked: bool,
44}
45
46#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
47#[serde(
48    tag = "kind",
49    content = "id",
50    rename_all = "snake_case",
51    deny_unknown_fields
52)]
53pub enum Selector {
54    All,
55    #[serde(alias = "chat")]
56    Agent(String),
57    Node(String),
58    SameNode,
59    Group(String),
60}
61
62#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
63#[serde(rename_all = "snake_case")]
64pub enum Permission {
65    Enumerate,
66    Receive,
67    Send,
68}
69
70#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
71#[serde(rename_all = "snake_case")]
72pub enum Effect {
73    Allow,
74    Deny,
75}
76
77#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
78#[serde(deny_unknown_fields)]
79pub struct Rule {
80    pub actor: Selector,
81    pub peer: Selector,
82    pub permission: Permission,
83    pub effect: Effect,
84}
85
86#[derive(Clone, Debug, Default, Serialize, Deserialize)]
87#[serde(deny_unknown_fields)]
88pub struct Policy {
89    #[serde(default)]
90    pub rules: Vec<Rule>,
91    /// Signed membership, changed by the owner or a separately delegated chat.
92    #[serde(default)]
93    pub groups: BTreeMap<String, Vec<String>>,
94    /// Legacy relay authorizations, retained to verify existing signed state.
95    /// New relay selections use ordinary messaging permissions alone.
96    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
97    pub relay_grants: BTreeMap<String, RelayGrant>,
98    /// Editing authority is separate from message permissions. Empty maps keep
99    /// previously signed policy bytes unchanged.
100    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
101    pub admin_grants: BTreeMap<String, administration::AdminGrant>,
102    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
103    pub group_admin_grants: BTreeMap<String, administration::GroupAdminGrant>,
104}
105
106#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
107#[serde(deny_unknown_fields)]
108pub struct RelayGrant {
109    pub intermediary: String,
110    pub target: String,
111    pub issued_at: u64,
112    pub expires_at: u64,
113}
114
115#[derive(Clone, Debug, Serialize, Deserialize)]
116#[serde(deny_unknown_fields)]
117pub struct RelayAttachment {
118    pub id: String,
119    pub intermediary: String,
120    pub target: String,
121    /// Present only on selections created by older daemons.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub grant_id: Option<String>,
124    pub security_mode: RelaySecurityMode,
125    pub created_at: u64,
126    /// New selections last until detached; legacy selections retain their expiry.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub expires_at: Option<u64>,
129    pub detached: bool,
130}
131
132#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
133#[serde(rename_all = "snake_case")]
134pub enum RelaySecurityMode {
135    LocalDaemon,
136    EncryptedDaemonLink,
137}
138
139/// Authenticated relay context inside the encrypted message, never inferred
140/// from text. Relay access follows messaging policy, not asserted human authorship.
141#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
142#[serde(deny_unknown_fields)]
143pub struct RelayMessage {
144    pub attachment_id: String,
145    /// Retained on legacy turns so their original restrictions and retries survive.
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub grant_id: Option<String>,
148    pub turn_id: String,
149    pub kind: RelayMessageKind,
150}
151
152#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
153#[serde(rename_all = "snake_case")]
154pub enum RelayMessageKind {
155    Request,
156    Progress,
157    Complete,
158    Cancel,
159    Cancelled,
160}
161
162#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
163#[serde(rename_all = "snake_case")]
164pub enum RelayResponseKind {
165    Progress,
166    Complete,
167    Cancelled,
168}
169
170impl Policy {
171    fn matches(&self, selector: &Selector, subject: &Agent, other: &Agent) -> bool {
172        match selector {
173            Selector::All => true,
174            Selector::Agent(id) => subject.id == *id,
175            Selector::Node(id) => subject.node_id == *id,
176            Selector::SameNode => subject.node_id == other.node_id,
177            Selector::Group(id) => self
178                .groups
179                .get(id)
180                .is_some_and(|ids| ids.contains(&subject.id)),
181        }
182    }
183
184    /// None means default denial; it is distinct from an explicit denial for reply grants.
185    pub fn decision(&self, actor: &Agent, peer: &Agent, permission: Permission) -> Option<Effect> {
186        if actor.revoked || peer.revoked {
187            return Some(Effect::Deny);
188        }
189        let mut decision = None;
190        for (_, rule) in self.matching_rules(actor, peer, permission) {
191            if rule.effect == Effect::Deny {
192                return Some(Effect::Deny);
193            }
194            decision = Some(Effect::Allow);
195        }
196        decision
197    }
198
199    pub fn visible(&self, actor: &Agent, peer: &Agent) -> bool {
200        self.decision(actor, peer, Permission::Enumerate) == Some(Effect::Allow)
201    }
202
203    pub fn can_open(&self, sender: &Agent, recipient: &Agent) -> bool {
204        self.open_checks(sender, recipient)
205            .all(|(_, allowed)| allowed)
206    }
207
208    /// Call only after verifying an accepted, unexpired exchange and its participants.
209    pub fn can_reply(&self, sender: &Agent, recipient: &Agent) -> bool {
210        self.reply_checks(sender, recipient)
211            .all(|(_, allowed)| allowed)
212    }
213}
214
215#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
216#[serde(deny_unknown_fields)]
217pub struct FilePart {
218    pub name: String,
219    pub media_type: String,
220    pub data_base64: String,
221}
222
223/// Chat-visible attachment metadata. Decryption keys are a separate private
224/// wire type and must never be serialized into a chat RPC or MCP response.
225#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
226#[serde(deny_unknown_fields)]
227pub struct FileDescriptor {
228    pub id: String,
229    pub name: String,
230    pub media_type: String,
231    pub byte_length: u64,
232    pub sha256: String,
233}
234
235#[derive(Clone, Debug, Serialize, Deserialize)]
236#[serde(deny_unknown_fields)]
237pub struct Message {
238    pub id: String,
239    pub exchange_id: String,
240    pub sender: String,
241    pub recipient: String,
242    pub text: String,
243    pub files: Vec<FilePart>,
244    #[serde(default, skip_serializing_if = "Vec::is_empty")]
245    pub attachments: Vec<FileDescriptor>,
246    pub reply_to: Option<String>,
247    pub created_at: i64,
248    pub expires_at: i64,
249    pub acknowledged: bool,
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub relay: Option<RelayMessage>,
252}
253
254#[derive(Clone, Debug, Serialize, Deserialize)]
255#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
256pub enum AgentOp {
257    DashboardGet,
258    Babysit {
259        enabled: Option<bool>,
260    },
261    BabysitterClaim {
262        goal: String,
263        turn: uuid::Uuid,
264        failed_at: i64,
265        reason: notifications::Failure,
266    },
267    BabysitterSubmitted {
268        attempt: uuid::Uuid,
269        scope: Option<notifications::Scope>,
270    },
271    BabysitterCheck {
272        attempt: uuid::Uuid,
273    },
274    BabysitterChatProbe {
275        turn: uuid::Uuid,
276        operator: uuid::Uuid,
277        failed_at: i64,
278    },
279    BabysitterChatClaim {
280        turn: uuid::Uuid,
281        failed_at: i64,
282        reason: notifications::Failure,
283        origin: babysitter::ChatOrigin,
284    },
285    BabysitterChatCheck {
286        attempt: uuid::Uuid,
287    },
288    BabysitterChatSubmitted {
289        attempt: uuid::Uuid,
290    },
291    DashboardPublish {
292        expected_revision: u64,
293        title: String,
294        file_id: Option<uuid::Uuid>,
295        html: Option<String>,
296        // Preserve fingerprints for publications made before actions were supported.
297        #[serde(
298            default,
299            deserialize_with = "dashboard::supplied_actions",
300            skip_serializing_if = "Option::is_none"
301        )]
302        actions: Option<Vec<dashboard::Action>>,
303    },
304    DashboardDefine {
305        expected_revision: u64,
306        board: dashboard::Board,
307    },
308    DashboardAttachHtml {
309        expected_revision: u64,
310        file_id: uuid::Uuid,
311    },
312    DashboardUpdate {
313        expected_revision: u64,
314        values: BTreeMap<String, serde_json::Value>,
315    },
316    DashboardDelete {
317        expected_revision: u64,
318    },
319    Register {
320        name: String,
321        provider: String,
322    },
323    Identity,
324    /// Rename only this authenticated registration, preserving its identity.
325    Rename {
326        name: String,
327        expected_generation: u64,
328    },
329    /// Current relationship with one visible peer; never exposes raw policy.
330    PermissionCheck {
331        peer: String,
332    },
333    PermissionAdminCheck {
334        actor: String,
335        peer: String,
336    },
337    PermissionPreview {
338        changes: Vec<administration::PermissionChange>,
339    },
340    PermissionApply {
341        request_id: String,
342        changes: Vec<administration::PermissionChange>,
343    },
344    PermissionRequest {
345        request_id: String,
346    },
347    PermissionRuleScopes,
348    GroupAdminScopes,
349    GroupMembers {
350        group: String,
351    },
352    GroupPreview {
353        changes: Vec<administration::GroupChange>,
354    },
355    GroupApply {
356        request_id: String,
357        changes: Vec<administration::GroupChange>,
358    },
359    GroupRequest {
360        request_id: String,
361    },
362    PermissionRulePreview {
363        changes: Vec<administration::PermissionRuleChange>,
364    },
365    PermissionRuleApply {
366        request_id: String,
367        changes: Vec<administration::PermissionRuleChange>,
368    },
369    Agents,
370    Resolve {
371        name: String,
372        node: Option<String>,
373        provider: Option<String>,
374    },
375    RequestIds {
376        #[serde(default = "one_request_id")]
377        count: u32,
378    },
379    FilePaths,
380    FileImport {
381        request_id: String,
382        name: String,
383        media_type: String,
384    },
385    FileStatus {
386        file_id: String,
387    },
388    /// Private local RPC preflight; absent from the MCP tool surface.
389    FileReceiveStatus {
390        file: file_objects::IncomingFile,
391    },
392    /// Header for a bounded binary body after the daemon's ready response.
393    FileReceive {
394        file: file_objects::IncomingFile,
395        byte_length: u64,
396        sha256: String,
397    },
398    /// Constructed only by the local transport after receiving the whole body.
399    #[serde(skip)]
400    FileReceiveData {
401        file: file_objects::IncomingFile,
402        bytes: zeroize::Zeroizing<Vec<u8>>,
403    },
404    FileRead {
405        file_id: String,
406        chunk_index: u32,
407    },
408    FileView {
409        file_id: String,
410    },
411    /// Local historical imports explicitly assigned to this authenticated chat.
412    HistoryImports,
413    HistoryMessages {
414        import_id: String,
415        #[serde(default)]
416        after: u64,
417    },
418    HistoryFileRead {
419        import_id: String,
420        message_id: String,
421        file_index: u32,
422        chunk_index: u32,
423    },
424    HistoryFileView {
425        import_id: String,
426        message_id: String,
427        file_index: u32,
428    },
429    FileExport {
430        file_id: String,
431    },
432    Send {
433        recipient: String,
434        request_id: String,
435        text: String,
436        #[serde(default)]
437        files: Vec<FilePart>,
438        #[serde(default, skip_serializing_if = "Vec::is_empty")]
439        file_ids: Vec<String>,
440    },
441    /// Response-required send; uses an isolated relay turn without changing the
442    /// chat's persistent relay selection. MCP waits outside the daemon lock.
443    RequestReply {
444        recipient: String,
445        request_id: String,
446        text: String,
447        #[serde(default)]
448        files: Vec<FilePart>,
449        #[serde(default, skip_serializing_if = "Vec::is_empty")]
450        file_ids: Vec<String>,
451    },
452    Reply {
453        message_id: String,
454        request_id: String,
455        text: String,
456        #[serde(default)]
457        files: Vec<FilePart>,
458        #[serde(default, skip_serializing_if = "Vec::is_empty")]
459        file_ids: Vec<String>,
460    },
461    Inbox,
462    /// Local host adapter operations; not exposed as model-callable MCP tools.
463    WakePending,
464    WakeClaim {
465        message_id: String,
466        attempt_id: String,
467        target: wake::WakeTarget,
468    },
469    /// Recheck an existing claim without creating or renewing submission rights.
470    WakeCheck {
471        message_id: String,
472        attempt_id: String,
473        target: wake::WakeTarget,
474    },
475    WakeSubmitted {
476        message_id: String,
477        attempt_id: String,
478        submission_id: String,
479    },
480    /// Native adapter APIs, deliberately absent from model-callable MCP tools.
481    WakeDirectClaim {
482        message_id: String,
483        attempt_id: String,
484        target: wake::WakeTarget,
485    },
486    WakeDirectPending {
487        target: wake::WakeTarget,
488    },
489    WakeDirectRead {
490        message_id: String,
491        attempt_id: String,
492        target: wake::WakeTarget,
493    },
494    WakeDirectObserve {
495        message_id: String,
496        attempt_id: String,
497        target: wake::WakeTarget,
498        turn_id: String,
499    },
500    WakeDirectComplete {
501        message_id: String,
502        attempt_id: String,
503        target: wake::WakeTarget,
504        turn_id: String,
505        text: String,
506    },
507    WorkStatus {
508        message_id: String,
509    },
510    WorkBegin {
511        message_id: String,
512        #[serde(default)]
513        expect_revision: u64,
514        description: String,
515    },
516    WorkComplete {
517        message_id: String,
518        expect_revision: u64,
519        note: String,
520    },
521    Ack {
522        message_id: String,
523    },
524    MessageStatus {
525        message_id: String,
526    },
527    RelayAttach {
528        target: String,
529        request_id: String,
530    },
531    RelayStatus {
532        attachment_id: Option<String>,
533    },
534    RelayDetach {
535        attachment_id: String,
536    },
537    RelaySend {
538        attachment_id: String,
539        request_id: String,
540        text: String,
541        #[serde(default)]
542        files: Vec<FilePart>,
543        #[serde(default, skip_serializing_if = "Vec::is_empty")]
544        file_ids: Vec<String>,
545    },
546    RelayTurnStatus {
547        turn_id: String,
548        after_message_id: Option<String>,
549    },
550    RelayTurns {
551        after_turn_id: Option<String>,
552    },
553    RelayNext,
554    RelayRespond {
555        turn_id: String,
556        request_id: String,
557        text: String,
558        #[serde(default)]
559        files: Vec<FilePart>,
560        #[serde(default, skip_serializing_if = "Vec::is_empty")]
561        file_ids: Vec<String>,
562        outcome: RelayResponseKind,
563    },
564    RelayCancel {
565        turn_id: String,
566        request_id: String,
567    },
568}
569
570fn one_request_id() -> u32 {
571    1
572}
573
574#[derive(Clone, Debug, Serialize, Deserialize)]
575#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
576pub enum ConfigurationEdit {
577    EnrollNode {
578        request: String,
579        can_configure: bool,
580        invitation: Option<String>,
581    },
582    RemoveNode {
583        node_id: String,
584    },
585    DelegateNode {
586        node_id: String,
587        allow: bool,
588    },
589    /// Administrator-approved chat transport delegation; does not grant configuration access.
590    HostNode {
591        node_id: String,
592        parent: String,
593    },
594    CreateGroup {
595        name: String,
596    },
597    DeleteGroup {
598        name: String,
599    },
600    GroupMembers {
601        group: String,
602        members: Vec<String>,
603        action: administration::GroupAction,
604    },
605    GrantGroupAdmin {
606        grant_id: String,
607        administrator: String,
608        group: String,
609        members: Selector,
610        actions: Vec<administration::GroupAction>,
611        lifetime_seconds: u64,
612    },
613    RevokeGroupAdmin {
614        grant_id: String,
615    },
616    AgentGroups {
617        administrator: String,
618        request_id: String,
619        changes: Vec<administration::GroupChange>,
620    },
621    SetPermissionRule {
622        actor: Selector,
623        peer: Selector,
624        permission: Permission,
625        effect: Option<Effect>,
626    },
627    Policy {
628        policy: Policy,
629    },
630    Replace {
631        cluster_name: String,
632        node_name: String,
633        policy: Policy,
634    },
635    RenameNode {
636        name: String,
637    },
638    /// Rename this enrolled member in signed configuration, independently of the proposer.
639    RenameMember {
640        node_id: String,
641        name: String,
642    },
643    SetReleaseChannel {
644        channel: ReleaseChannel,
645    },
646    Renew,
647    GrantRelay {
648        grant_id: String,
649        intermediary: String,
650        target: String,
651        lifetime_seconds: u64,
652    },
653    RevokeRelay {
654        grant_id: String,
655    },
656    GrantPermissionAdmin {
657        grant_id: String,
658        administrator: String,
659        actor: Selector,
660        peer: Selector,
661        permissions: Vec<Permission>,
662        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
663        selector_rules: bool,
664        lifetime_seconds: u64,
665    },
666    RevokePermissionAdmin {
667        grant_id: String,
668    },
669    /// Internal authenticated proposal; MCP supplies neither administrator nor
670    /// origin node. The owner rechecks both and every grant before accepting it.
671    AgentPermissions {
672        administrator: String,
673        request_id: String,
674        changes: Vec<administration::PermissionChange>,
675    },
676    AgentPermissionRules {
677        administrator: String,
678        request_id: String,
679        changes: Vec<administration::PermissionRuleChange>,
680    },
681}
682
683#[derive(Clone, Debug, Serialize, Deserialize)]
684#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
685pub enum OwnerOp {
686    DashboardGrant {
687        agent: uuid::Uuid,
688        action: dashboard::GrantAdmin,
689    },
690    /// Read owner-visible Gent usage without probing hosts or modifying state.
691    Stats,
692    /// Refresh peer usage and return the latest available cluster totals.
693    RefreshStats,
694    DashboardRemoteHtml {
695        boards: Vec<dashboard::HtmlProbe>,
696    },
697    Dashboards {
698        after: Option<String>,
699    },
700    NotificationPut {
701        notice: notifications::Notice,
702        scope: Option<notifications::Scope>,
703    },
704    NotificationPending {
705        scope: notifications::Scope,
706    },
707    NotificationSent {
708        id: uuid::Uuid,
709    },
710    DashboardClick {
711        agent: String,
712        revision: u64,
713        widget: String,
714        request_id: String,
715    },
716    DashboardRefresh {
717        agent: String,
718        revision: u64,
719        request_id: String,
720    },
721    /// Scoped proof for the hosted checkpoint service; never exports a signing key.
722    WebAdmission {
723        node_id: String,
724        body_hash: [u8; 32],
725    },
726    WebCheckpoint {
727        node_id: String,
728    },
729    WebCommit {
730        node_id: String,
731        revision: u64,
732        #[serde(default, skip_serializing_if = "Option::is_none")]
733        epoch: Option<u64>,
734    },
735    WebLease {
736        node_id: String,
737        seconds: u64,
738    },
739    /// Absolute Unix deadline bounded by the start of the authority request.
740    /// Zero closes the epoch and fences delayed grants for the same session.
741    WebGrant {
742        node_id: String,
743        epoch: u64,
744        expires_at: u64,
745    },
746    RestoreWebNode {
747        node_id: String,
748        home: std::path::PathBuf,
749        checkpoint: std::path::PathBuf,
750        #[serde(default, skip_serializing_if = "Option::is_none")]
751        epoch: Option<u64>,
752    },
753    PreparePeerConfiguration,
754    Groups {
755        name: Option<String>,
756    },
757    GroupAdmins,
758    GroupAdminHistory {
759        administrator: Option<String>,
760        before: Option<u64>,
761    },
762    Configure {
763        request_id: String,
764        edit: ConfigurationEdit,
765    },
766    ConfigurationRequests {
767        request_id: Option<String>,
768    },
769    DelegateConfiguration {
770        node_id: String,
771        allow: bool,
772    },
773    /// Local signing-owner administration, never exposed as a chat tool.
774    RemoveNode {
775        node_id: String,
776    },
777    NodeRemovals {
778        after: Option<String>,
779        pending_only: bool,
780    },
781    ConfirmNodeRemoval {
782        node_id: String,
783        revision: u64,
784    },
785    Status,
786    /// Move a stopped, locally owned web node's retained state into this daemon.
787    PrepareHostedNode {
788        node_id: String,
789        home: std::path::PathBuf,
790    },
791    /// Read-only local-owner diagnostics; never advances clocks or projects files.
792    Diagnose,
793    PermissionRules,
794    PermissionExplain {
795        actor: String,
796        peer: String,
797    },
798    PermissionAdmins,
799    PermissionAdminHistory {
800        administrator: Option<String>,
801        before: Option<u64>,
802    },
803    Nodes,
804    RefreshNodes,
805    Agents,
806    NativeMessageDates,
807    ObserveActivity {
808        agent_id: String,
809        last_activity_at: i64,
810        #[serde(default, skip_serializing_if = "Option::is_none")]
811        last_native_message_at: Option<i64>,
812    },
813    ClearRetiredAgents {
814        dry_run: bool,
815    },
816    Resolve {
817        name: String,
818        node: Option<String>,
819        provider: Option<String>,
820    },
821    Agent {
822        agent_id: String,
823    },
824    RenameAgent {
825        agent_id: String,
826        name: String,
827        expected_generation: u64,
828    },
829    Providers,
830    FilesStatus,
831    HistoryStatus,
832    /// Private recovery evidence. These operations grant no replacement authority.
833    RecoveryChallenge,
834    OwnerHandoffStatus,
835    OwnerTransfer {
836        action: owner_transfer::OwnerTransferOp,
837    },
838    RecoveryObserve {
839        challenge: String,
840    },
841    WorkList {
842        after_message_id: Option<String>,
843    },
844    WakeList {
845        after_message_id: Option<String>,
846    },
847    WakeStatus,
848    /// Owner-only pending recipient IDs; does not expose message content.
849    WakePendingAgents {
850        after: Option<String>,
851    },
852    /// Local supervisor lookup for one retained Codex dispatch. Metadata only.
853    WakeDirectTurnEvidence {
854        /// A second input to a drained queue requires a completed relay request.
855        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
856        completed_relay: bool,
857        agent_credential: String,
858        thread_id: uuid::Uuid,
859        turn: uuid::Uuid,
860    },
861    /// The bound supervisor has corroborated the blocked goal and native history.
862    BabysitterVerifiedBlockedClaim {
863        agent_credential: String,
864        thread_id: uuid::Uuid,
865        goal: String,
866        turn: uuid::Uuid,
867        failed_at: i64,
868        reason: notifications::Failure,
869    },
870    WakeClean {
871        dry_run: bool,
872    },
873    WakeShow {
874        message_id: String,
875    },
876    WorkShow {
877        message_id: String,
878    },
879    WorkReconcile {
880        message_id: String,
881        expect_revision: u64,
882        resolution: work::WorkResolution,
883        note: String,
884    },
885    HistoryImports,
886    AgentRecover {
887        directory: String,
888        manifest_sha256: String,
889        source_agent: String,
890        agent_credential: String,
891        name: String,
892        provider: String,
893    },
894    HistoryImport {
895        directory: String,
896        manifest_sha256: String,
897        source_agent: String,
898        target_agent: String,
899        restore_revision: Option<u64>,
900    },
901    HistoryRemove {
902        import_id: String,
903        expected_revision: u64,
904    },
905    HistoryClean {
906        dry_run: bool,
907    },
908    TransportStatus,
909    WebDeliveryDemand {
910        node_id: String,
911    },
912    WebDeliveryChecked {
913        node_id: String,
914        message_id: String,
915    },
916    TransportClean {
917        dry_run: bool,
918    },
919    FilesClean {
920        dry_run: bool,
921    },
922    RelayGrants,
923    RelayAttachments,
924    SetPolicy {
925        policy: Policy,
926    },
927    Renew,
928    RenameNode {
929        name: String,
930    },
931    Revoke {
932        agent_id: String,
933    },
934    /// Owner-only bootstrap over an independently authenticated private channel.
935    Pair {
936        cluster_id: String,
937        action: PairingOp,
938    },
939    /// Local owner administration; private invitation material is never a chat tool.
940    Invitation {
941        action: InvitationOp,
942    },
943    /// Local administrator request, forwarded over authenticated node streams.
944    NodeInvite {
945        request_id: String,
946        name: String,
947        can_configure: bool,
948        activate: bool,
949    },
950}
951
952#[derive(Clone, Debug, Serialize, Deserialize)]
953#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
954pub enum InvitationOp {
955    Create {
956        request_id: String,
957        can_configure: bool,
958        continuation: Option<String>,
959        #[serde(default, skip_serializing_if = "Option::is_none")]
960        replace_node: Option<String>,
961    },
962    Activate {
963        id: String,
964    },
965    Revoke {
966        id: String,
967    },
968    List,
969}
970
971#[derive(Clone, Debug, Serialize, Deserialize)]
972#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
973pub enum PairingOp {
974    Snapshot,
975    Enroll {
976        request: String,
977    },
978    Configuration {
979        request_id: String,
980        peer: String,
981        key_package: String,
982    },
983    History {
984        revision: u64,
985        digest: [u8; 32],
986    },
987    Data {
988        request_id: String,
989        peer: String,
990        key_package: String,
991        legacy_agents: Vec<String>,
992    },
993    AcceptData {
994        peer: String,
995        packet: String,
996        outgoing_group: String,
997    },
998}
999
1000#[derive(Serialize, Deserialize)]
1001#[serde(tag = "role", rename_all = "snake_case", deny_unknown_fields)]
1002pub enum Request {
1003    DashboardDelegate {
1004        agent: uuid::Uuid,
1005        secret: String,
1006        action: dashboard::GrantOp,
1007    },
1008    Agent {
1009        credential: String,
1010        action: AgentOp,
1011    },
1012    Owner {
1013        credential: String,
1014        action: OwnerOp,
1015    },
1016    /// Private gateway-to-daemon RPC. The node scope is never supplied by MCP.
1017    HostedAgent {
1018        node_id: String,
1019        gateway_credential: String,
1020        #[serde(default, skip_serializing_if = "Option::is_none")]
1021        epoch: Option<u64>,
1022        credential: String,
1023        action: AgentOp,
1024    },
1025    HostedStatus {
1026        node_id: String,
1027        gateway_credential: String,
1028    },
1029}
1030
1031#[derive(Debug, Serialize, Deserialize)]
1032#[serde(tag = "status", content = "data", rename_all = "snake_case")]
1033pub enum Response {
1034    Ok(serde_json::Value),
1035    Error(String),
1036}
1037
1038#[cfg(test)]
1039mod tests {
1040    use super::*;
1041    fn agent(id: &str, node: &str) -> Agent {
1042        Agent {
1043            id: id.into(),
1044            node_id: node.into(),
1045            name: id.into(),
1046            provider: "anything".into(),
1047            last_seen: 0,
1048            revoked: false,
1049        }
1050    }
1051    fn allow(policy: &mut Policy, a: &str, b: &str, permission: Permission) {
1052        policy.rules.push(Rule {
1053            actor: Selector::Agent(a.into()),
1054            peer: Selector::Agent(b.into()),
1055            permission,
1056            effect: Effect::Allow,
1057        });
1058    }
1059    #[test]
1060    fn default_deny_and_scoped_reply() {
1061        let (a, b) = (agent("a", "node"), agent("b", "node"));
1062        let mut p = Policy::default();
1063        assert!(!p.can_open(&a, &b));
1064        allow(&mut p, "a", "b", Permission::Enumerate);
1065        allow(&mut p, "b", "a", Permission::Enumerate);
1066        allow(&mut p, "a", "b", Permission::Send);
1067        allow(&mut p, "b", "a", Permission::Receive);
1068        assert!(p.can_open(&a, &b));
1069        assert!(!p.can_open(&b, &a));
1070        assert!(p.can_reply(&b, &a));
1071        p.rules.push(Rule {
1072            actor: Selector::Agent("b".into()),
1073            peer: Selector::Agent("a".into()),
1074            permission: Permission::Send,
1075            effect: Effect::Deny,
1076        });
1077        assert!(p.can_reply(&b, &a));
1078        p.rules.push(Rule {
1079            actor: Selector::Agent("a".into()),
1080            peer: Selector::Agent("b".into()),
1081            permission: Permission::Receive,
1082            effect: Effect::Deny,
1083        });
1084        assert!(!p.can_reply(&b, &a));
1085        assert!(!p.can_open(&a, &b));
1086    }
1087    #[test]
1088    fn denials_override_same_node_grants_and_location_changes() {
1089        let (a, mut b) = (agent("a", "one"), agent("b", "one"));
1090        let mut p = Policy::default();
1091        for permission in [Permission::Enumerate, Permission::Send, Permission::Receive] {
1092            p.rules.push(Rule {
1093                actor: Selector::All,
1094                peer: Selector::SameNode,
1095                permission,
1096                effect: Effect::Allow,
1097            });
1098        }
1099        assert!(p.can_open(&a, &b));
1100        b.node_id = "two".into();
1101        assert!(!p.can_open(&a, &b));
1102        b.node_id = "one".into();
1103        p.rules.insert(
1104            0,
1105            Rule {
1106                actor: Selector::Agent("a".into()),
1107                peer: Selector::All,
1108                permission: Permission::Enumerate,
1109                effect: Effect::Deny,
1110            },
1111        );
1112        assert!(!p.can_open(&a, &b));
1113        assert!(!p.can_reply(&a, &b));
1114    }
1115    #[test]
1116    fn authenticated_groups_and_revocation() {
1117        let (a, mut b) = (agent("a", "one"), agent("b", "two"));
1118        let mut p = Policy::default();
1119        p.groups.insert("team".into(), vec!["a".into(), "b".into()]);
1120        for permission in [Permission::Enumerate, Permission::Send, Permission::Receive] {
1121            p.rules.push(Rule {
1122                actor: Selector::Group("team".into()),
1123                peer: Selector::Group("team".into()),
1124                permission,
1125                effect: Effect::Allow,
1126            });
1127        }
1128        assert!(p.can_open(&a, &b));
1129        b.revoked = true;
1130        assert!(!p.can_open(&a, &b));
1131        assert!(!p.can_reply(&b, &a));
1132    }
1133}