Skip to main content

gent_daemon/
store.rs

1use crate::{
2    config::{self, Config},
3    encrypted,
4    runtime::{self, Identity},
5};
6use anyhow::{Context, Result, ensure};
7use base64::{Engine, engine::general_purpose::STANDARD};
8use gent_crypto::VerifiedState;
9use gent_protocol::*;
10use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
11use serde_json::{Value, json};
12use sha2::{Digest, Sha256};
13use std::{
14    collections::{BTreeMap, BTreeSet},
15    path::{Path, PathBuf},
16    sync::Arc,
17    time::{SystemTime, UNIX_EPOCH},
18};
19use tokio::sync::Notify;
20mod activity;
21mod administration;
22mod agents;
23mod babysitter;
24mod configuration;
25mod message_dates;
26mod notifications;
27mod ordinary_babysitter;
28mod wire;
29pub(crate) use configuration::pending::schema as pending_configuration_schema;
30pub(crate) use configuration::routing::schema as configuration_routing_schema;
31mod dashboards;
32mod diagnostics;
33pub mod direct;
34pub(crate) mod directory;
35mod directory_sync;
36mod files;
37pub(crate) mod handoff;
38mod history;
39pub(crate) mod hosted;
40pub mod invitations;
41mod mesh;
42mod network;
43pub mod node_invites;
44mod pairing;
45pub(crate) mod peer_configuration;
46mod permissions;
47mod presence;
48mod recovered;
49mod relay;
50pub(crate) mod removals;
51mod requests;
52#[cfg(test)]
53mod storage_tests;
54mod synchronization;
55mod wake;
56mod work;
57
58pub fn now() -> i64 {
59    SystemTime::now()
60        .duration_since(UNIX_EPOCH)
61        .expect("clock before epoch")
62        .as_secs()
63        .try_into()
64        .expect("clock overflow")
65}
66fn hash(value: &str) -> String {
67    format!("{:x}", Sha256::digest(value.as_bytes()))
68}
69fn require_pro(home: &Path, cfg: &Config, feature: &str) -> Result<()> {
70    ensure!(
71        crate::entitlements::paid(home, cfg),
72        "{feature} requires an active Gent Pro plan for this cluster. See https://gent.link/pricing"
73    );
74    Ok(())
75}
76const UNAVAILABLE: &str = "recipient or message unavailable";
77
78pub struct Store {
79    db: Connection,
80    direct_certs: direct::CertificateCache,
81    home: PathBuf,
82    config: Config,
83    identity: Identity,
84    owner_hash: String,
85    pub(crate) sync_wakeup: Arc<Notify>,
86    pub(crate) sync_health: Arc<crate::sync::health::Health>,
87}
88impl Store {
89    pub(crate) fn local_node_id(&self) -> &str {
90        self.identity.node.id()
91    }
92    /// Called by offline owner provisioning while holding daemon.lock. Service
93    /// registration cannot turn a joined node into a cryptographic owner.
94    pub fn require_provisioning_owner(&self) -> Result<()> {
95        self.identity.signing_owner(&self.db)?;
96        self.require_provisioning_member()
97    }
98
99    pub fn require_provisioning_member(&self) -> Result<()> {
100        let state = self.identity.state(&self.db)?;
101        ensure!(
102            state
103                .state()
104                .nodes
105                .get(self.identity.node.id())
106                .is_some_and(|n| n.signing_key == self.identity.node.public_key()),
107            "this node is no longer enrolled in the cluster"
108        );
109        // Expired authority can still obtain ciphertext transport to recover its
110        // latest signed configuration. RPC access continues to require freshness.
111        Ok(())
112    }
113    pub fn require_provisioning_joined(&self) -> Result<()> {
114        ensure!(
115            !self
116                .identity
117                .is_current_owner(&self.identity.state(&self.db)?),
118            "the existing owner cannot be replaced by a joined identity"
119        );
120        self.require_provisioning_member()
121    }
122
123    /// Service setup records describe enrollment history. A signed handoff can
124    /// change the configuration writer without changing account ownership or
125    /// removing either node's relay access.
126    pub fn require_service_setup_role(&self, originally_owner: bool) -> Result<()> {
127        let state = self.identity.state(&self.db)?;
128        if state.owner_epoch() > 0 || state.state().peer.is_some() {
129            self.require_provisioning_member()
130        } else if originally_owner {
131            self.require_provisioning_owner()
132        } else {
133            self.require_provisioning_joined()
134        }
135    }
136
137    pub fn open(home: &Path) -> Result<Self> {
138        let config = config::load_for_runtime(home)?;
139        ensure!(
140            config.hosted_parent()?.is_none(),
141            "this web node is served by its native host daemon"
142        );
143        let replacement = crate::pairing::replacement::check_intent(home, &config, None)?;
144        let owner_hash = hash(&config::read_private(&home.join("owner.key"))?);
145        ensure!(
146            home.join("state.sqlite3").exists() || !home.join(runtime::KEY_FILE).exists(),
147            "authority database is missing; restore this node's state"
148        );
149        let mut db = encrypted::open_database(home, "state.sqlite3")?;
150        db.busy_timeout(std::time::Duration::from_secs(5))?;
151        db.execute_batch("PRAGMA foreign_keys=ON;
152          CREATE TABLE IF NOT EXISTS agents (id TEXT PRIMARY KEY, credential_hash TEXT UNIQUE NOT NULL, node_id TEXT NOT NULL, name TEXT NOT NULL, provider TEXT NOT NULL, last_seen INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);
153          CREATE TABLE IF NOT EXISTS exchanges (id TEXT PRIMARY KEY, a TEXT NOT NULL REFERENCES agents(id), b TEXT NOT NULL REFERENCES agents(id), expires_at INTEGER NOT NULL, count INTEGER NOT NULL);
154          CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, sender TEXT NOT NULL REFERENCES agents(id), recipient TEXT NOT NULL REFERENCES agents(id), request_id TEXT NOT NULL, fingerprint TEXT NOT NULL, payload TEXT NOT NULL, acknowledged INTEGER NOT NULL DEFAULT 0, UNIQUE(sender,request_id));
155          CREATE INDEX IF NOT EXISTS messages_inbox ON messages(recipient,acknowledged);
156          CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY,value TEXT NOT NULL);
157          CREATE TABLE IF NOT EXISTS stream_relay_upload (
158            group_id BLOB PRIMARY KEY REFERENCES streams(group_id) ON DELETE CASCADE,
159            next_sequence INTEGER NOT NULL CHECK(next_sequence >= 0)
160          );")?;
161        network::schema(&db)?;
162        configuration::schema(&db)?;
163        peer_configuration::schema(&db)?;
164        mesh::schema(&db)?;
165        relay::schema(&db)?;
166        files::schema(&mut db)?;
167        requests::schema(&db, now())?;
168        history::schema(&db)?;
169        recovered::schema(&db)?;
170        work::schema(&db)?;
171        wake::schema(&db)?;
172        presence::schema(&db)?;
173        directory::schema(&db)?;
174        activity::schema(&db)?;
175        wire::schema(&db)?;
176        dashboards::schema(&db)?;
177        babysitter::schema(&db)?;
178        ordinary_babysitter::schema(&db)?;
179        notifications::schema(&db)?;
180        hosted::schema(&db)?;
181        directory_sync::schema(&db)?;
182        direct::schema(&db)?;
183        db.execute("UPDATE hosted_checkpoints SET lease_until=0", [])?;
184        let previous: Option<String> = db
185            .query_row("SELECT value FROM metadata WHERE key='cluster'", [], |r| {
186                r.get(0)
187            })
188            .optional()?;
189        if let Some(previous) = previous {
190            ensure!(
191                previous == config.cluster.id,
192                "database belongs to another cluster"
193            );
194        } else {
195            db.execute(
196                "INSERT INTO metadata VALUES ('cluster',?1)",
197                [&config.cluster.id],
198            )?;
199        }
200        let previous_node: Option<String> = db
201            .query_row("SELECT value FROM metadata WHERE key='node'", [], |r| {
202                r.get(0)
203            })
204            .optional()?;
205        if let Some(previous_node) = previous_node {
206            ensure!(
207                previous_node == config.node.id,
208                "database belongs to another node"
209            );
210        } else {
211            db.execute("INSERT INTO metadata VALUES ('node',?1)", [&config.node.id])?;
212        }
213        let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
214        let identity = Identity::load_or_create(home, &config, &tx, now() as u64)?;
215        peer_configuration::check_state(&tx, &identity.state(&tx)?)?;
216        directory::backfill_names(&tx, &identity.state(&tx)?)?;
217        message_dates::migrate(&tx, identity.node.id())?;
218        configuration::pending::recover(&tx, identity.node.id())?;
219        if let Some(record) = replacement {
220            record.verify_node(&identity.node)?;
221            let target = record.replaces;
222            let state = identity.state(&tx)?;
223            ensure!(
224                !state.state().nodes.contains_key(&target.id)
225                    && state.state().retired_nodes.contains(&target.id)
226                    && state.state().retired_keys.contains(&target.signing_key),
227                "replacement record does not match signed retirement"
228            );
229        }
230        if !identity.is_current_owner(&identity.state(&tx)?) {
231            // Only the SSH owner can issue enrollment snapshots. Conservative
232            // migration pins on a joined runtime cannot represent pending joins.
233            tx.execute("DELETE FROM authority_join_pins", [])?;
234        }
235        tx.commit()?;
236        let mut store = Self {
237            direct_certs: Default::default(),
238            db,
239            home: home.into(),
240            config,
241            owner_hash,
242            identity,
243            sync_wakeup: Arc::new(Notify::new()),
244            sync_health: Arc::default(),
245        };
246        // Projection failure must never replace committed authority with TOML.
247        let _ = store.project_config();
248        Ok(store)
249    }
250
251    pub fn handle(&mut self, request: Request) -> Response {
252        match self.execute(request) {
253            Ok(value) => Response::Ok(value),
254            Err(error) => Response::Error(error.to_string()),
255        }
256    }
257
258    fn execute(&mut self, request: Request) -> Result<Value> {
259        if let Request::Agent {
260            credential,
261            action: AgentOp::FileExport { file_id },
262        } = &request
263        {
264            // Persist capacity before creating plaintext, then persist the
265            // completed inode before publication. Each step rechecks authority.
266            for step in [
267                files::ExportStep::Reserve,
268                files::ExportStep::Write,
269                files::ExportStep::Publish,
270            ] {
271                let value = self.execute_step(
272                    Request::Agent {
273                        credential: credential.clone(),
274                        action: AgentOp::FileExport {
275                            file_id: file_id.clone(),
276                        },
277                    },
278                    step,
279                )?;
280                if !value.is_null() {
281                    return Ok(value);
282                }
283            }
284            anyhow::bail!("export did not finish");
285        }
286        self.execute_step(request, files::ExportStep::Reserve)
287    }
288
289    fn execute_step(&mut self, request: Request, export_step: files::ExportStep) -> Result<Value> {
290        if let Request::Owner { credential, .. } = &request {
291            ensure!(hash(credential) == self.owner_hash, "unauthorized");
292        }
293        if let Request::Owner {
294            action:
295                OwnerOp::RestoreWebNode {
296                    node_id,
297                    home,
298                    checkpoint,
299                    epoch,
300                },
301            ..
302        } = &request
303        {
304            return self.restore_web_node(node_id, home, checkpoint, *epoch);
305        }
306        if let Request::Owner {
307            action: OwnerOp::PrepareHostedNode { node_id, home },
308            ..
309        } = &request
310        {
311            return self.prepare_hosted_node(node_id, home);
312        }
313        if let Request::Owner {
314            credential,
315            action: OwnerOp::PreparePeerConfiguration,
316        } = &request
317        {
318            return Ok(serde_json::to_value(
319                self.prepare_configuration_log(credential)?,
320            )?);
321        }
322        if matches!(
323            &request,
324            Request::Owner {
325                action: OwnerOp::Diagnose,
326                ..
327            }
328        ) {
329            return self.diagnose();
330        }
331        if let Request::Owner {
332            action: OwnerOp::Pair { cluster_id, action },
333            ..
334        } = request
335        {
336            return self.pair(&cluster_id, action);
337        }
338        if let Request::Owner {
339            credential,
340            action: OwnerOp::Invitation { action },
341        } = request
342        {
343            return self.manage_invitation(&credential, action);
344        }
345        if let Request::Owner {
346            credential,
347            action: OwnerOp::OwnerTransfer { action },
348        } = request
349        {
350            return self.owner_transfer(&credential, action);
351        }
352        // Idle service probes and removal polling must not force a disk flush
353        // or wake the encrypted transport on every observation. Pending config
354        // projection retains its usual repair path.
355        let projection_pending = runtime::projection_pending(&self.db)?;
356        let local_only = matches!(
357            &request,
358            Request::Agent {
359                action: AgentOp::BabysitterClaim { .. }
360                    | AgentOp::BabysitterChatProbe { .. }
361                    | AgentOp::BabysitterChatClaim { .. }
362                    | AgentOp::BabysitterChatCheck { .. }
363                    | AgentOp::BabysitterChatSubmitted { .. }
364                    | AgentOp::BabysitterCheck { .. }
365                    | AgentOp::BabysitterSubmitted { .. },
366                ..
367            } | Request::Owner {
368                action: OwnerOp::NotificationPut { .. }
369                    | OwnerOp::NotificationSent { .. }
370                    | OwnerOp::BabysitterVerifiedBlockedClaim { .. },
371                ..
372            }
373        );
374        let read_only = (matches!(
375            &request,
376            Request::Owner {
377                action: OwnerOp::Status
378                    | OwnerOp::Agents
379                    | OwnerOp::Nodes
380                    | OwnerOp::Dashboards { .. }
381                    | OwnerOp::NotificationPending { .. }
382                    | OwnerOp::WebCheckpoint { .. }
383                    | OwnerOp::WebDeliveryDemand { .. }
384                    | OwnerOp::NodeRemovals { .. }
385                    | OwnerOp::WakePendingAgents { .. }
386                    | OwnerOp::WakeDirectTurnEvidence { .. },
387                ..
388            }
389        ) || matches!(
390            &request,
391            Request::HostedStatus { .. }
392                | Request::Agent {
393                    action: AgentOp::BabysitterChatProbe { .. },
394                    ..
395                }
396        )) && !projection_pending;
397        let tx = self.db.transaction_with_behavior(if read_only {
398            TransactionBehavior::Deferred
399        } else {
400            TransactionBehavior::Immediate
401        })?;
402        let timestamp = if read_only {
403            requests::diagnostic_clock(&tx, now())?
404        } else {
405            requests::clock(&tx, now())?
406        };
407        let state = self.identity.state(&tx)?;
408        let mut config = self.config.clone();
409        config.policy = state.state().policy.clone();
410        config.cluster.name.clone_from(&state.state().name);
411        if let Some(node) = state.state().nodes.get(self.identity.node.id()) {
412            config.node.name.clone_from(&node.name);
413        }
414        config.applied_revision = Some(state.checkpoint().revision);
415        let mut session = StoreSession {
416            db: &tx,
417            home: &self.home,
418            config,
419            identity: &self.identity,
420            state,
421            timestamp,
422        };
423        let owner_request = matches!(&request, Request::Owner { .. });
424        let refresh_nodes = matches!(
425            &request,
426            Request::Owner {
427                action: OwnerOp::RefreshNodes,
428                ..
429            }
430        );
431        let status_request = matches!(
432            &request,
433            Request::Owner {
434                action: OwnerOp::Status,
435                ..
436            }
437        );
438        let mut value = match request {
439            Request::Owner { action, .. } => session.owner(action, &self.sync_health)?,
440            Request::Agent { credential, action } => {
441                session.state.authorize_node(
442                    self.identity.node.id(),
443                    &self.identity.node.public_key(),
444                    timestamp as u64,
445                )?;
446                session.agent(self.identity.node.id(), &credential, action, export_step)?
447            }
448            Request::HostedAgent {
449                node_id,
450                gateway_credential,
451                credential,
452                action,
453                epoch,
454            } => {
455                session.check_hosted(&node_id, &gateway_credential)?;
456                hosted::check_epoch(&tx, &node_id, epoch)?;
457                session.require_web_lease(&node_id)?;
458                session.dirty_web(&node_id, &action)?;
459                ensure!(
460                    !matches!(
461                        action,
462                        AgentOp::FilePaths
463                            | AgentOp::FileImport { .. }
464                            | AgentOp::FileExport { .. }
465                    ),
466                    "local filesystem tools are unavailable to hosted chats"
467                );
468                let value = session.agent(&node_id, &credential, action, export_step)?;
469                if epoch.is_some() {
470                    hosted::check_epoch(&tx, &node_id, epoch)?;
471                }
472                value
473            }
474            Request::HostedStatus {
475                node_id,
476                gateway_credential,
477            } => {
478                session.check_hosted(&node_id, &gateway_credential)?;
479                session.hosted_status(&node_id)?
480            }
481        };
482        tx.commit()?;
483        if refresh_nodes
484            && value.as_array().is_some_and(|nodes| {
485                nodes
486                    .iter()
487                    .any(|n| n["presence"]["probe_started_at"].is_i64())
488            })
489            && self
490                .sync_health
491                .connected
492                .load(std::sync::atomic::Ordering::SeqCst)
493        {
494            self.sync_health.verify_watch.notify_one();
495        }
496        if status_request {
497            value["sync"] = self.synchronization_status()?;
498        }
499        if read_only || (local_only && !projection_pending) {
500            return Ok(value);
501        }
502        // Also wakes directory/message publication after a committed agent RPC.
503        self.sync_wakeup.notify_one();
504        // Filesystem projection is retryable after the authoritative commit.
505        // A caller must not interpret a projection failure as an unapplied edit.
506        let projected = self.project_config();
507        if owner_request
508            && (value.get("applied") == Some(&Value::Bool(true))
509                || value.get("config_saved").is_some())
510        {
511            value["config_saved"] = json!(projected.is_ok());
512            if let Err(error) = projected {
513                value["config_error"] = json!(error.to_string());
514            }
515        }
516        Ok(value)
517    }
518
519    fn project_config(&mut self) -> Result<()> {
520        let tx = self
521            .db
522            .transaction_with_behavior(TransactionBehavior::Immediate)?;
523        runtime::project(&self.home, &tx, &self.identity)?;
524        tx.commit()?;
525        Ok(())
526    }
527
528    /// The owner daemon renews its lease without requiring a chat turn.
529    /// Chat RPCs never bypass expiry or trigger a renewal themselves.
530    pub fn maintain(&mut self) -> Result<()> {
531        // Local cleanup remains available after membership/lease loss.
532        self.clean_invitations()?;
533        self.clean_files()?;
534        self.clean_history()?;
535        self.clean_wake()?;
536        {
537            let tx = self
538                .db
539                .transaction_with_behavior(TransactionBehavior::Immediate)?;
540            configuration::pending::recover(&tx, self.identity.node.id())?;
541            encrypted::ordered::storage::clean(&tx, false)?;
542            tx.commit()?;
543        }
544        let timestamp = now() as u64;
545        let tx = self
546            .db
547            .transaction_with_behavior(TransactionBehavior::Immediate)?;
548        let state = self.identity.state(&tx)?;
549        ensure!(
550            state
551                .state()
552                .nodes
553                .get(self.identity.node.id())
554                .is_some_and(|n| n.signing_key == self.identity.node.public_key()),
555            "local node is no longer enrolled"
556        );
557        crate::file_objects::Objects::new(&tx, timestamp)?.reap()?;
558        let renew = !self.identity.legacy_signing_fenced()
559            && self.identity.legacy_service_checked
560            && self.identity.is_current_owner(&state)
561            && !handoff::frozen(&tx, &state)?
562            && state.state().expires_at.saturating_sub(timestamp) <= 6 * 60 * 60;
563        if renew {
564            let update = state.renew(&*self.identity.signing_owner(&tx)?, timestamp)?;
565            self.identity.apply(&tx, update)?;
566        }
567        tx.commit()?;
568        if renew {
569            self.sync_wakeup.notify_one();
570        }
571        self.project_config()?;
572        self.reconcile_configuration()
573    }
574
575    /// Trusted enrollment API. The supplied authority must already be verified
576    /// through protected pairing. It installs no owner signing secret.
577    pub fn install_joined(
578        home: &Path,
579        node: &gent_crypto::NodeIdentity,
580        state: &VerifiedState,
581    ) -> Result<()> {
582        runtime::install_joined(home, node, state)
583    }
584
585    pub(crate) fn relay_settings(&self) -> Option<(config::RelayConfig, PathBuf)> {
586        self.config
587            .relay
588            .clone()
589            .map(|relay| (relay, self.home.clone()))
590    }
591    pub(crate) fn sync_streams(&self) -> Result<Vec<crate::sync::Stream>> {
592        if self.identity.state(&self.db)?.state().peer.is_some() {
593            return self.data_streams();
594        }
595        let mut streams: Vec<_> =
596            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?
597                .configuration_streams(now() as u64)?
598                .into_iter()
599                .map(|s| crate::sync::Stream {
600                    group: s.group,
601                    outgoing: s.outgoing,
602                    configuration: true,
603                })
604                .collect();
605        streams.extend(self.data_streams()?);
606        Ok(streams)
607    }
608    pub(crate) fn sync_pending_groups(
609        &self,
610        streams: &[crate::sync::Stream],
611    ) -> Result<crate::sync::MailboxWork> {
612        let mut work = crate::sync::MailboxWork::default();
613        let mut pending = self.db.prepare(
614            "SELECT s.group_id,s.head>=COALESCE(u.next_sequence,0)
615             FROM streams s LEFT JOIN stream_relay_upload u USING(group_id)
616             LEFT JOIN stream_confirmed c USING(group_id)
617             WHERE s.writer=?1 AND s.head>COALESCE(c.sequence,-1)",
618        )?;
619        let mut rows = pending.query([self.identity.node.id()])?;
620        while let Some(row) = rows.next()? {
621            let group: Vec<u8> = row.get(0)?;
622            work.unconfirmed.insert(group.clone());
623            if row.get::<_, bool>(1)? {
624                work.ready.insert(group);
625            }
626        }
627        let local = self
628            .db
629            .prepare(
630                "SELECT group_id FROM owner_deliveries WHERE next<parts
631             UNION SELECT s.group_id FROM streams s JOIN stream_pending p
632               ON p.group_id=s.group_id AND p.sequence=s.head+1",
633            )?
634            .query_map([], |r| r.get(0))?
635            .collect::<rusqlite::Result<Vec<Vec<u8>>>>()?;
636        work.ready.extend(local);
637        self.add_ready_network_groups(&mut work.ready)?;
638
639        // An unpublished legacy configuration revision is work even before
640        // its first fragment has a stream position. Old owner epochs stop at
641        // their signed handoff baseline.
642        let writers: BTreeSet<_> = streams
643            .iter()
644            .filter(|s| s.configuration && s.outgoing)
645            .map(|s| s.group.as_slice())
646            .collect();
647        if writers.is_empty() {
648            return Ok(work);
649        }
650        let state = self.identity.state(&self.db)?;
651        let mut query = self.db.prepare(
652            "SELECT c.group_id,c.grant,h.revision FROM configuration_streams c
653             JOIN streams s USING(group_id) JOIN authority_history h ON h.revision=c.revision+1
654             WHERE s.writer=?1",
655        )?;
656        let mut rows = query.query([self.identity.node.id()])?;
657        while let Some(row) = rows.next()? {
658            let group: Vec<u8> = row.get(0)?;
659            if !writers.contains(group.as_slice()) {
660                continue;
661            }
662            let grant = gent_crypto::SignedConfigurationGrant::decode(&row.get::<_, Vec<u8>>(1)?)?;
663            let limit = encrypted::ordered::configuration::publication_limit(&grant, &state);
664            let revision: u64 = row.get(2)?;
665            if limit.is_none_or(|last| revision <= last) {
666                work.ready.insert(group);
667            }
668        }
669        Ok(work)
670    }
671
672    /// A relay can roll back its queue or lose a successful PUT response.
673    /// Replay from the lower position, excluding only the verified prefix.
674    pub(crate) fn relay_upload_start(
675        &self,
676        group: &[u8],
677        relay_next: u64,
678        confirmed_next: u64,
679    ) -> Result<u64> {
680        let (local_next, uploaded): (u64, u64) = self.db.query_row(
681            "SELECT s.head+1,COALESCE(u.next_sequence,0) FROM streams s
682             LEFT JOIN stream_relay_upload u USING(group_id) WHERE s.group_id=?1 AND s.writer=?2",
683            params![group, self.identity.node.id()],
684            |r| Ok((r.get(0)?, r.get(1)?)),
685        )?;
686        ensure!(
687            relay_next <= local_next,
688            "relay position exceeds local history"
689        );
690        if relay_next < uploaded {
691            self.record_relay_upload(group, relay_next)?;
692        }
693        Ok(uploaded.min(relay_next).max(confirmed_next))
694    }
695
696    pub(crate) fn record_relay_upload(&self, group: &[u8], next: u64) -> Result<()> {
697        self.db.execute(
698            "INSERT INTO stream_relay_upload(group_id,next_sequence) VALUES(?1,?2)
699             ON CONFLICT(group_id) DO UPDATE SET next_sequence=excluded.next_sequence",
700            params![group, next],
701        )?;
702        Ok(())
703    }
704    pub(crate) fn sync_prepare(&self, group: &[u8]) -> Result<()> {
705        let mut endpoint =
706            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
707        let timestamp = now() as u64;
708        if endpoint
709            .prepare_configuration(group, None, timestamp)?
710            .is_none()
711        {
712            endpoint.prepare_owner_handoff(group, timestamp)?;
713        }
714        Ok(())
715    }
716
717    pub(crate) fn transport_receipt(
718        &self,
719        group: &[u8],
720        configuration: bool,
721    ) -> Result<gent_crypto::stream::Receipt> {
722        if !configuration {
723            self.data_peer(&self.db, group, false)?;
724        }
725        encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?
726            .receipt(group, now() as u64)
727    }
728
729    pub(crate) fn transport_confirm(
730        &self,
731        group: &[u8],
732        configuration: bool,
733        receipt: Option<&gent_crypto::stream::Receipt>,
734    ) -> Result<Option<gent_crypto::stream::Receipt>> {
735        Ok(self
736            .transport_confirmation(group, configuration, receipt)?
737            .0)
738    }
739
740    /// The flag records a newly advanced durable checkpoint, excluding cached or replayed ACKs.
741    pub(crate) fn transport_confirmation(
742        &self,
743        group: &[u8],
744        configuration: bool,
745        receipt: Option<&gent_crypto::stream::Receipt>,
746    ) -> Result<(Option<gent_crypto::stream::Receipt>, bool)> {
747        let mut endpoint =
748            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
749        let reader = if configuration {
750            endpoint.configuration_reader(group)?
751        } else {
752            self.data_peer(&self.db, group, true)?
753        };
754        if let Some(receipt) = receipt {
755            ensure!(
756                receipt.group() == group,
757                "checkpoint belongs to another stream"
758            );
759            return endpoint
760                .confirm_and_get(receipt, &reader, now() as u64)
761                .map(|(receipt, advanced)| (Some(receipt), advanced));
762        }
763        Ok((endpoint.confirmed_receipt(group, now() as u64)?, false))
764    }
765    pub(crate) fn sync_outgoing(
766        &self,
767        group: &[u8],
768        next: u64,
769    ) -> Result<Option<gent_crypto::stream::Packet>> {
770        let mut endpoint =
771            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
772        let timestamp = now() as u64;
773        let status = endpoint.configuration_status(group, timestamp)?;
774        ensure!(next <= status.next, "relay position exceeds local history");
775        Ok(endpoint
776            .configuration_outbox(group, next.checked_sub(1), 1, timestamp)?
777            .pop())
778    }
779    pub(crate) fn sync_next(&mut self, group: &[u8]) -> Result<u64> {
780        let mut endpoint =
781            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
782        let timestamp = now() as u64;
783        // A restart may find a packet committed to the receive buffer before
784        // its authority transaction ran. Apply it without requiring the relay.
785        let pending = endpoint.drain_configuration(group, 1, timestamp)?;
786        let next = endpoint
787            .configuration_status(group, timestamp)
788            .map(|status| status.next);
789        drop(endpoint);
790        if !pending.is_empty() {
791            self.project_config()?;
792            self.reconcile_configuration()?;
793            self.sync_wakeup.notify_one();
794        }
795        next
796    }
797    pub(crate) fn sync_receive(&mut self, packet: &gent_crypto::stream::Packet) -> Result<()> {
798        let mut endpoint =
799            encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
800        let timestamp = now() as u64;
801        endpoint.stage_configuration(packet, timestamp)?;
802        endpoint.drain_configuration(packet.group(), 1, timestamp)?;
803        self.sync_wakeup.notify_one();
804        self.project_config()?;
805        self.reconcile_configuration()
806    }
807}
808
809struct StoreSession<'a> {
810    db: &'a Connection,
811    home: &'a Path,
812    config: Config,
813    identity: &'a Identity,
814    state: VerifiedState,
815    timestamp: i64,
816}
817
818#[derive(Default)]
819struct SendContext {
820    parent: Option<Message>,
821    relay: Option<RelayMessage>,
822    file_ids: Vec<String>,
823}
824
825fn message_fingerprint(
826    recipient: &str,
827    text: &str,
828    files: &[FilePart],
829    reply_to: &Option<String>,
830    relay: &Option<RelayMessage>,
831    file_ids: &[String],
832) -> Result<String> {
833    let mut value = json!({"recipient":recipient,"text":text,"files":files,"reply_to":reply_to});
834    // Preserve exact retry fingerprints for pre-relay messages.
835    if let Some(relay) = relay {
836        value["relay"] = json!(relay);
837    }
838    if !file_ids.is_empty() {
839        value["file_ids"] = json!(file_ids);
840    }
841    Ok(hash(&serde_json::to_string(&value)?))
842}
843impl StoreSession<'_> {
844    fn decode_agent(row: &rusqlite::Row<'_>) -> rusqlite::Result<Agent> {
845        Ok(Agent {
846            id: row.get(0)?,
847            node_id: row.get(1)?,
848            name: row.get(2)?,
849            provider: row.get(3)?,
850            last_seen: row.get(4)?,
851            revoked: row.get(5)?,
852        })
853    }
854    fn get_agent(&self, id: &str) -> Result<Agent> {
855        let mut agent = self
856            .db
857            .query_row(
858                "SELECT id,node_id,name,provider,last_seen,revoked FROM agents WHERE id=?1",
859                [id],
860                Self::decode_agent,
861            )
862            .optional()?
863            .context(UNAVAILABLE)?;
864        agent.revoked |= !self.state.state().nodes.contains_key(&agent.node_id);
865        Ok(agent)
866    }
867    fn all_agents(&self) -> Result<Vec<Agent>> {
868        let mut agents = self
869            .db
870            .prepare("SELECT id,node_id,name,provider,last_seen,revoked FROM agents ORDER BY id")?
871            .query_map([], Self::decode_agent)?
872            .collect::<Result<Vec<_>, _>>()?;
873        for agent in &mut agents {
874            agent.revoked |= !self.state.state().nodes.contains_key(&agent.node_id);
875        }
876        Ok(agents)
877    }
878    fn owner(&mut self, action: OwnerOp, health: &crate::sync::health::Health) -> Result<Value> {
879        match action {
880            OwnerOp::WebDeliveryDemand { node_id } => self.web_delivery_demand(&node_id),
881            OwnerOp::WebDeliveryChecked {
882                node_id,
883                message_id,
884            } => {
885                let cleared = self.db.execute(
886                    "DELETE FROM web_delivery_demand WHERE node=?1 AND message=?2",
887                    params![node_id, message_id],
888                )?;
889                Ok(json!({"cleared":cleared==1}))
890            }
891            OwnerOp::WebAdmission { node_id, body_hash } => self.web_admission(&node_id, body_hash),
892            OwnerOp::WebCheckpoint { node_id } => self.web_checkpoint(&node_id),
893            OwnerOp::WebLease { node_id, seconds } => self.web_lease(&node_id, seconds),
894            OwnerOp::WebGrant {
895                node_id,
896                epoch,
897                expires_at,
898            } => self.web_grant(&node_id, epoch, expires_at),
899            OwnerOp::WebCommit {
900                node_id,
901                revision,
902                epoch,
903            } => self.web_commit(&node_id, revision, epoch),
904            OwnerOp::RestoreWebNode { .. } => unreachable!("handled before session"),
905            OwnerOp::NodeInvite {
906                request_id,
907                name,
908                can_configure,
909                activate,
910            } => self.request_node_invite(&request_id, &name, can_configure, activate),
911            OwnerOp::AgentRecover {
912                directory,
913                manifest_sha256,
914                source_agent,
915                agent_credential,
916                name,
917                provider,
918            } => {
919                let registered = self.agent(
920                    self.identity.node.id(),
921                    &agent_credential,
922                    AgentOp::Register {
923                        name: name.clone(),
924                        provider: provider.clone(),
925                    },
926                    files::ExportStep::Reserve,
927                )?;
928                let id = registered["agent"]["id"]
929                    .as_str()
930                    .context("missing recovered chat identity")?;
931                let agent = self.get_agent(id)?;
932                ensure!(
933                    agent.name == name && agent.provider == provider,
934                    "recovery registration arguments changed"
935                );
936                let history = self.recovered_import(
937                    Path::new(&directory),
938                    &manifest_sha256,
939                    &source_agent,
940                    id,
941                    None,
942                )?;
943                Ok(
944                    json!({"agent":agent,"history":history,"source_agent":source_agent,
945                    "scope":"fresh local registration with assigned history; old credentials, peer permissions and pending work are not restored"}),
946                )
947            }
948            OwnerOp::HistoryImports => self.recovered_imports(None),
949            OwnerOp::HistoryImport {
950                directory,
951                manifest_sha256,
952                source_agent,
953                target_agent,
954                restore_revision,
955            } => self.recovered_import(
956                Path::new(&directory),
957                &manifest_sha256,
958                &source_agent,
959                &target_agent,
960                restore_revision,
961            ),
962            OwnerOp::HistoryRemove {
963                import_id,
964                expected_revision,
965            } => self.recovered_remove(&import_id, expected_revision),
966            OwnerOp::Pair { .. }
967            | OwnerOp::Invitation { .. }
968            | OwnerOp::Diagnose
969            | OwnerOp::PreparePeerConfiguration => {
970                anyhow::bail!("pairing must use its owner-authenticated entry point")
971            }
972            OwnerOp::Status => Ok(
973                json!({"process_id":std::process::id(),"node":self.config.node,"cluster":self.config.cluster,"transport":"local_unix_socket","remote_ready":self.remote_ready()?,
974                    "release_channel":self.state.state().release_channel,
975                    "can_set_release_channel":self.identity.is_current_owner(&self.state) || self.identity.has_configuration_grant(&self.state),
976                    "authority":{"mode":if self.state.state().peer.is_some(){"peers"}else{"legacy"},"sequence":self.state.checkpoint().revision,"revision":self.state.checkpoint().revision,"expires_at":self.state.state().expires_at,"fresh":self.state.require_fresh(self.timestamp as u64).is_ok()},"config_saved":!runtime::projection_pending(self.db)?}),
977            ),
978            OwnerOp::Groups { name } => match name {
979                Some(name) => Ok(
980                    json!({"name":name,"members":self.config.policy.groups.get(&name).context("unknown group")?}),
981                ),
982                None => Ok(json!(self.config.policy.groups)),
983            },
984            OwnerOp::GroupAdmins => Ok(
985                json!({"grants":self.config.policy.group_admin_grants,"retired":self.state.state().retired_admin_grants}),
986            ),
987            OwnerOp::GroupAdminHistory {
988                administrator,
989                before,
990            } => self.administration_history(administrator.as_deref(), before, true),
991            OwnerOp::NotificationPending { scope } => self.pending_notices(&scope),
992            OwnerOp::NotificationPut { notice, scope } => self.enqueue_notice(&notice, scope),
993            OwnerOp::NotificationSent { id } => {
994                self.db
995                    .execute("DELETE FROM account_outbox WHERE id=?1", [id.to_string()])?;
996                Ok(json!({}))
997            }
998            OwnerOp::Dashboards { after } => self.dashboards(after.as_deref()),
999            OwnerOp::DashboardClick {
1000                agent,
1001                revision,
1002                widget,
1003                request_id,
1004            } => self.dashboard_click(&agent, revision, &widget, &request_id),
1005            OwnerOp::PermissionRules => Ok(json!({"rules":self.state.state().policy.rules,
1006                "groups":self.state.state().policy.groups.keys().collect::<Vec<_>>()})),
1007            OwnerOp::PermissionExplain { actor, peer } => self.permission_explain(&actor, &peer),
1008            OwnerOp::PermissionAdmins => {
1009                Ok(json!({"grants":self.state.state().policy.admin_grants,
1010                "retired":self.state.state().retired_admin_grants,"revision":self.state.checkpoint().revision}))
1011            }
1012            OwnerOp::PermissionAdminHistory {
1013                administrator,
1014                before,
1015            } => self.permission_admin_history(administrator.as_deref(), before),
1016            OwnerOp::Nodes => self.nodes(health),
1017            OwnerOp::RefreshNodes => self.refresh_nodes(health),
1018            OwnerOp::Agents => Ok(serde_json::to_value(self.directory(None)?)?),
1019            OwnerOp::Resolve {
1020                name,
1021                node,
1022                provider,
1023            } => self.resolve_agent(None, &name, node.as_deref(), provider.as_deref()),
1024            OwnerOp::NativeMessageDates => self.local_native_message_dates(),
1025            OwnerOp::ObserveActivity {
1026                agent_id,
1027                last_activity_at,
1028                last_native_message_at,
1029            } => self.observe_activity(&agent_id, last_activity_at, last_native_message_at),
1030            OwnerOp::ClearRetiredAgents { dry_run } => self.clear_retired_agents(dry_run),
1031            OwnerOp::Agent { agent_id } => self.agent_details(&agent_id),
1032            OwnerOp::RenameAgent {
1033                agent_id,
1034                name,
1035                expected_generation,
1036            } => {
1037                self.rename_agent(&agent_id, &name, expected_generation)?;
1038                self.agent_details(&agent_id)
1039            }
1040            OwnerOp::FilesStatus => self.files_status(),
1041            OwnerOp::FilesClean { dry_run } => self.files_clean(dry_run),
1042            OwnerOp::HistoryStatus => self.history_status(),
1043            OwnerOp::OwnerHandoffStatus => handoff::status(self.db, &self.state),
1044            OwnerOp::OwnerTransfer { .. } => {
1045                anyhow::bail!("owner transfer requires the authenticated store entry point")
1046            }
1047            OwnerOp::RecoveryChallenge => Ok(serde_json::to_value(
1048                gent_crypto::recovery::RecoveryBaseline::new(&self.state, self.timestamp as u64)?,
1049            )?),
1050            OwnerOp::RecoveryObserve { challenge } => {
1051                let challenge =
1052                    gent_crypto::recovery::RecoveryChallenge::decode(challenge.as_bytes())?;
1053                Ok(serde_json::to_value(self.identity.node.observe_recovery(
1054                    &self.state,
1055                    &challenge,
1056                    self.timestamp as u64,
1057                )?)?)
1058            }
1059            OwnerOp::WorkList { after_message_id } => self.work_list(after_message_id.as_deref()),
1060            OwnerOp::WakeList { after_message_id } => self.wake_list(after_message_id.as_deref()),
1061            OwnerOp::WakeStatus => wake::retention::status(self.db, self.timestamp),
1062            OwnerOp::WakePendingAgents { after } => self.wake_pending_agents(after.as_deref()),
1063            OwnerOp::WakeDirectTurnEvidence {
1064                agent_credential,
1065                thread_id,
1066                turn,
1067            } => {
1068                let who = self.native_supervisor_agent(&agent_credential, thread_id)?;
1069                self.direct_turn_evidence(&who, thread_id, turn)
1070            }
1071            OwnerOp::BabysitterVerifiedBlockedClaim {
1072                agent_credential,
1073                thread_id,
1074                goal,
1075                turn,
1076                failed_at,
1077                reason,
1078            } => {
1079                let who = self.native_supervisor_agent(&agent_credential, thread_id)?;
1080                self.babysitter_claim(
1081                    &who,
1082                    &goal,
1083                    turn,
1084                    failed_at,
1085                    reason,
1086                    babysitter::Window::VerifiedBlocked,
1087                )
1088            }
1089            OwnerOp::WakeClean { dry_run } => {
1090                wake::retention::clean(self.db, self.timestamp, dry_run)
1091            }
1092            OwnerOp::WakeShow { message_id } => self.wake_show(&message_id),
1093            OwnerOp::WorkShow { message_id } => self.work_show(&message_id),
1094            OwnerOp::WorkReconcile {
1095                message_id,
1096                expect_revision,
1097                resolution,
1098                note,
1099            } => self.work_reconcile(&message_id, expect_revision, resolution, &note),
1100            OwnerOp::HistoryClean { dry_run } => self.history_clean(dry_run),
1101            OwnerOp::TransportStatus => encrypted::ordered::storage::status(self.db),
1102            OwnerOp::TransportClean { dry_run } => {
1103                encrypted::ordered::storage::clean(self.db, dry_run)
1104            }
1105            OwnerOp::Providers => {
1106                let mut providers = BTreeMap::<String, Vec<Agent>>::new();
1107                for agent in self.all_agents()? {
1108                    if !agent.revoked {
1109                        providers
1110                            .entry(agent.provider.clone())
1111                            .or_default()
1112                            .push(agent);
1113                    }
1114                }
1115                Ok(json!(providers))
1116            }
1117            OwnerOp::RelayGrants => Ok(json!({"grants":self.state.state().policy.relay_grants,
1118                "retired":self.state.state().retired_relay_grants,"revision":self.state.checkpoint().revision})),
1119            OwnerOp::RelayAttachments => self.relay_attachments(),
1120            OwnerOp::Configure { request_id, edit } => self.submit_configuration(&request_id, edit),
1121            OwnerOp::ConfigurationRequests { request_id } => match request_id {
1122                Some(id) => self.configuration_status(&id),
1123                None => self.configuration_requests(),
1124            },
1125            OwnerOp::DelegateConfiguration { node_id, allow } => {
1126                if self.state.state().peer.is_some() {
1127                    return self.submit_configuration(
1128                        &uuid::Uuid::new_v4().to_string(),
1129                        ConfigurationEdit::DelegateNode { node_id, allow },
1130                    );
1131                }
1132                let update = self.state.delegate_configuration(
1133                    &*self.identity.signing_owner(self.db)?,
1134                    &node_id,
1135                    allow,
1136                    self.timestamp as u64,
1137                )?;
1138                self.state = self.identity.apply(self.db, update)?;
1139                Ok(
1140                    json!({"applied":true,"revision":self.state.checkpoint().revision,"node_id":node_id,"can_configure":allow}),
1141                )
1142            }
1143            OwnerOp::RemoveNode { node_id } => self.remove_node(&node_id),
1144            OwnerOp::NodeRemovals {
1145                after,
1146                pending_only,
1147            } => self.node_removals(after.as_deref(), pending_only),
1148            OwnerOp::ConfirmNodeRemoval { node_id, revision } => {
1149                self.confirm_node_removal(&node_id, revision)
1150            }
1151            OwnerOp::SetPolicy { policy } => {
1152                let disk = config::load_for_runtime(self.home)?;
1153                ensure!(
1154                    disk.node.id == self.config.node.id
1155                        && disk.cluster.id == self.config.cluster.id,
1156                    "cannot change active identities while daemon runs"
1157                );
1158                self.submit_configuration(
1159                    &uuid::Uuid::new_v4().to_string(),
1160                    ConfigurationEdit::Replace {
1161                        cluster_name: disk.cluster.name,
1162                        node_name: disk.node.name,
1163                        policy,
1164                    },
1165                )
1166            }
1167            OwnerOp::Renew => self
1168                .submit_configuration(&uuid::Uuid::new_v4().to_string(), ConfigurationEdit::Renew),
1169            OwnerOp::RenameNode { name } => self.submit_configuration(
1170                &uuid::Uuid::new_v4().to_string(),
1171                ConfigurationEdit::RenameNode { name },
1172            ),
1173            OwnerOp::PrepareHostedNode { .. } => unreachable!("handled before session"),
1174            OwnerOp::Revoke { agent_id } => self.request_unregister(&agent_id),
1175        }
1176    }
1177
1178    fn native_supervisor_agent(&self, credential: &str, thread: uuid::Uuid) -> Result<Agent> {
1179        ensure!(!thread.is_nil(), "invalid native thread");
1180        let node = self.identity.node.id();
1181        self.state.authorize_node(
1182            node,
1183            &self.identity.node.public_key(),
1184            self.timestamp as u64,
1185        )?;
1186        self.registered_agent(node, &hash(credential))
1187    }
1188
1189    fn registered_agent(&self, node: &str, digest: &str) -> Result<Agent> {
1190        let who = self.db.query_row(
1191            "SELECT id,node_id,name,provider,last_seen,revoked FROM agents WHERE credential_hash=?1",
1192            [digest],
1193            Self::decode_agent,
1194        ).optional()?.context("register this connection first")?;
1195        ensure!(!who.revoked, "registration revoked");
1196        ensure!(
1197            who.node_id == node && self.local_node(node),
1198            "credential belongs to another node"
1199        );
1200        Ok(who)
1201    }
1202
1203    fn agent(
1204        &mut self,
1205        node: &str,
1206        credential: &str,
1207        action: AgentOp,
1208        export_step: files::ExportStep,
1209    ) -> Result<Value> {
1210        ensure!(
1211            credential.len() == 64 && credential.bytes().all(|b| b.is_ascii_hexdigit()),
1212            "invalid registration credential"
1213        );
1214        let digest = hash(credential);
1215        if let AgentOp::Register { name, provider } = &action {
1216            config::label(name)?;
1217            config::label(provider)?;
1218            if !self.db.query_row(
1219                "SELECT EXISTS(SELECT 1 FROM agents WHERE credential_hash=?1)",
1220                [&digest],
1221                |r| r.get::<_, bool>(0),
1222            )? {
1223                let nonce = uuid::Uuid::new_v4();
1224                let agent = gent_crypto::agent_id(node, nonce)?;
1225                self.db.execute("INSERT INTO agents(id,credential_hash,node_id,name,provider,last_seen) VALUES (?1,?2,?3,?4,?5,?6)",params![agent,digest,node,name,provider,self.timestamp])?;
1226                self.db.execute("INSERT INTO network_origins(agent,nonce,legacy,generation) VALUES(?1,?2,NULL,1)",params![agent,nonce.to_string()])?;
1227                self.announce(&agent)?;
1228            }
1229        }
1230        let who = self.registered_agent(node, &digest)?;
1231        if !matches!(
1232            &action,
1233            AgentOp::BabysitterClaim { .. }
1234                | AgentOp::BabysitterChatProbe { .. }
1235                | AgentOp::BabysitterChatClaim { .. }
1236                | AgentOp::BabysitterChatCheck { .. }
1237                | AgentOp::BabysitterChatSubmitted { .. }
1238                | AgentOp::BabysitterCheck { .. }
1239                | AgentOp::BabysitterSubmitted { .. }
1240                | AgentOp::WakePending
1241                | AgentOp::WakeClaim { .. }
1242                | AgentOp::WakeCheck { .. }
1243                | AgentOp::WakeSubmitted { .. }
1244                | AgentOp::WakeDirectClaim { .. }
1245                | AgentOp::WakeDirectPending { .. }
1246                | AgentOp::WakeDirectRead { .. }
1247                | AgentOp::WakeDirectObserve { .. }
1248                | AgentOp::WakeDirectComplete { .. }
1249        ) {
1250            self.db.execute(
1251                "UPDATE agents SET last_seen=?1 WHERE id=?2",
1252                params![self.timestamp, who.id],
1253            )?;
1254        }
1255        match action {
1256            AgentOp::Register { .. } | AgentOp::Identity => self.agent_identity(&who.id),
1257            AgentOp::Rename {
1258                name,
1259                expected_generation,
1260            } => {
1261                self.rename_agent(&who.id, &name, expected_generation)?;
1262                self.agent_identity(&who.id)
1263            }
1264            AgentOp::Babysit { enabled } => self.babysit(&who, enabled),
1265            AgentOp::BabysitterClaim {
1266                goal,
1267                turn,
1268                failed_at,
1269                reason,
1270            } => self.babysitter_claim(
1271                &who,
1272                &goal,
1273                turn,
1274                failed_at,
1275                reason,
1276                babysitter::Window::Routine,
1277            ),
1278            AgentOp::BabysitterCheck { attempt } => {
1279                Ok(json!({"eligible":self.babysitter_check(&who,attempt)?}))
1280            }
1281            AgentOp::BabysitterSubmitted { attempt, scope } => {
1282                self.babysitter_submitted(&who, attempt, scope)
1283            }
1284            AgentOp::BabysitterChatProbe {
1285                turn,
1286                operator,
1287                failed_at,
1288            } => {
1289                Ok(json!({"inspect":self.babysitter_chat_probe(&who, turn, operator, failed_at)?}))
1290            }
1291            AgentOp::BabysitterChatClaim {
1292                turn,
1293                failed_at,
1294                reason,
1295                origin,
1296            } => self.babysitter_chat_claim(&who, turn, failed_at, reason, origin),
1297            AgentOp::BabysitterChatCheck { attempt } => self.babysitter_chat_check(&who, attempt),
1298            AgentOp::BabysitterChatSubmitted { attempt } => {
1299                self.babysitter_chat_submitted(&who, attempt)
1300            }
1301            AgentOp::DashboardGet => self.dashboard_get(&who),
1302            op @ (AgentOp::DashboardDefine { .. }
1303            | AgentOp::DashboardUpdate { .. }
1304            | AgentOp::DashboardDelete { .. }) => self.dashboard_mutate(&who, op),
1305            AgentOp::Agents => self.visible_agents(&who),
1306            AgentOp::Resolve {
1307                name,
1308                node,
1309                provider,
1310            } => self.resolve_agent(Some(&who), &name, node.as_deref(), provider.as_deref()),
1311            AgentOp::HistoryImports => self.recovered_imports(Some(&who)),
1312            AgentOp::HistoryMessages { import_id, after } => {
1313                self.recovered_messages(&who, &import_id, after)
1314            }
1315            AgentOp::HistoryFileRead {
1316                import_id,
1317                message_id,
1318                file_index,
1319                chunk_index,
1320            } => self.recovered_file_read(&who, &import_id, &message_id, file_index, chunk_index),
1321            AgentOp::HistoryFileView {
1322                import_id,
1323                message_id,
1324                file_index,
1325            } => self.recovered_file_view(&who, &import_id, &message_id, file_index),
1326            AgentOp::PermissionCheck { peer } => self.permission_check(&who, &peer),
1327            AgentOp::PermissionAdminCheck { actor, peer } => {
1328                self.permission_admin_check(&who, &actor, &peer)
1329            }
1330            AgentOp::PermissionPreview { changes } => self.permission_preview(&who, &changes),
1331            AgentOp::PermissionApply {
1332                request_id,
1333                changes,
1334            } => self.permission_apply(&who, &request_id, changes),
1335            AgentOp::PermissionRequest { request_id } => self.permission_request(&who, &request_id),
1336            AgentOp::PermissionRuleScopes => self.permission_rule_scopes(&who),
1337            AgentOp::GroupAdminScopes => self.group_admin_scopes(&who),
1338            AgentOp::GroupMembers { group } => self.group_members(&who, &group),
1339            AgentOp::GroupPreview { changes } => self.group_preview(&who, &changes),
1340            AgentOp::GroupApply {
1341                request_id,
1342                changes,
1343            } => self.group_apply(&who, &request_id, changes),
1344            AgentOp::GroupRequest { request_id } => self.permission_request(&who, &request_id),
1345            AgentOp::PermissionRulePreview { changes } => {
1346                self.permission_rule_preview(&who, &changes)
1347            }
1348            AgentOp::PermissionRuleApply {
1349                request_id,
1350                changes,
1351            } => self.permission_rule_apply(&who, &request_id, changes),
1352            AgentOp::RequestIds { count } => self.request_ids(count),
1353            AgentOp::WorkStatus { message_id } => self.work_status(&who, &message_id),
1354            AgentOp::WakeDirectClaim {
1355                message_id,
1356                attempt_id,
1357                target,
1358            } => self.wake_direct_claim(&who, &message_id, &attempt_id, target),
1359            AgentOp::WakeDirectPending { target } => self.wake_direct_pending(&who, &target),
1360            AgentOp::WakeDirectRead {
1361                message_id,
1362                attempt_id,
1363                target,
1364            } => self.wake_direct_read(&who, &message_id, &attempt_id, &target),
1365            AgentOp::WakeDirectObserve {
1366                message_id,
1367                attempt_id,
1368                target,
1369                turn_id,
1370            } => self.wake_direct_observe(&who, &message_id, &attempt_id, &target, &turn_id),
1371            AgentOp::WakeDirectComplete {
1372                message_id,
1373                attempt_id,
1374                target,
1375                turn_id,
1376                text,
1377            } => {
1378                self.wake_direct_complete(&who, &message_id, &attempt_id, &target, (&turn_id, text))
1379            }
1380            AgentOp::WakePending => self.wake_pending(&who),
1381            AgentOp::WakeClaim {
1382                message_id,
1383                attempt_id,
1384                target,
1385            } => self.wake_claim(&who, &message_id, &attempt_id, target),
1386            AgentOp::WakeCheck {
1387                message_id,
1388                attempt_id,
1389                target,
1390            } => self.wake_check(&who, &message_id, &attempt_id, &target),
1391            AgentOp::WakeSubmitted {
1392                message_id,
1393                attempt_id,
1394                submission_id,
1395            } => self.wake_submitted(&who, &message_id, &attempt_id, &submission_id),
1396            AgentOp::WorkBegin {
1397                message_id,
1398                expect_revision,
1399                description,
1400            } => self.work_begin(&who, &message_id, expect_revision, &description),
1401            AgentOp::WorkComplete {
1402                message_id,
1403                expect_revision,
1404                note,
1405            } => self.work_complete(&who, &message_id, expect_revision, &note),
1406            AgentOp::FilePaths => self.file_paths(&who),
1407            AgentOp::FileImport {
1408                request_id,
1409                name,
1410                media_type,
1411            } => self.file_import(&who, &request_id, &name, &media_type),
1412            AgentOp::FileStatus { file_id } => self.file_status(&who, &file_id),
1413            AgentOp::FileReceiveStatus { file } => self.file_receive_status(&who, &file),
1414            AgentOp::FileReceive {
1415                file,
1416                byte_length,
1417                sha256,
1418            } => {
1419                ensure!(
1420                    byte_length <= gent_protocol::file_objects::MAX_FILE_BYTES as u64,
1421                    "file exceeds 32 MiB"
1422                );
1423                ensure!(
1424                    sha256.len() == 64
1425                        && sha256
1426                            .bytes()
1427                            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
1428                    "invalid file digest"
1429                );
1430                let status = self.file_receive_status(&who, &file)?;
1431                ensure!(
1432                    status["state"] != "ready"
1433                        || (status["file"]["byte_length"] == byte_length
1434                            && status["file"]["sha256"] == sha256),
1435                    "request_id already used with different content"
1436                );
1437                Ok(status)
1438            }
1439            AgentOp::FileReceiveData { file, bytes } => self.file_receive(&who, &file, &bytes),
1440            AgentOp::FileRead {
1441                file_id,
1442                chunk_index,
1443            } => self.file_read(&who, &file_id, chunk_index),
1444            AgentOp::FileView { file_id } => self.file_view(&who, &file_id),
1445            AgentOp::FileExport { file_id } => self.file_export(&who, &file_id, export_step),
1446            AgentOp::RelayAttach { target, request_id } => {
1447                self.relay_attach(&who, &target, &request_id)
1448            }
1449            AgentOp::RelayStatus { attachment_id } => self.relay_status(&who, attachment_id),
1450            AgentOp::RelayDetach { attachment_id } => self.relay_detach(&who, &attachment_id),
1451            AgentOp::RelaySend {
1452                attachment_id,
1453                request_id,
1454                text,
1455                files,
1456                file_ids,
1457            } => self.relay_send(&who, &attachment_id, &request_id, (text, files, file_ids)),
1458            AgentOp::RelayTurnStatus {
1459                turn_id,
1460                after_message_id,
1461            } => self.relay_turn_status(&who, &turn_id, after_message_id.as_deref()),
1462            AgentOp::RelayNext => self.relay_next(&who),
1463            AgentOp::RelayTurns { after_turn_id } => {
1464                self.relay_turns(&who, after_turn_id.as_deref())
1465            }
1466            AgentOp::RelayRespond {
1467                turn_id,
1468                request_id,
1469                text,
1470                files,
1471                file_ids,
1472                outcome,
1473            } => self.relay_respond(
1474                &who,
1475                &turn_id,
1476                &request_id,
1477                (text, files, file_ids),
1478                outcome,
1479            ),
1480            AgentOp::RelayCancel {
1481                turn_id,
1482                request_id,
1483            } => self.relay_cancel(&who, &turn_id, &request_id),
1484            AgentOp::Send {
1485                recipient,
1486                request_id,
1487                text,
1488                files,
1489                file_ids,
1490            } => self.send(
1491                &who,
1492                &recipient,
1493                &request_id,
1494                text,
1495                files,
1496                SendContext {
1497                    file_ids,
1498                    ..Default::default()
1499                },
1500            ),
1501            AgentOp::RequestReply {
1502                recipient,
1503                request_id,
1504                text,
1505                files,
1506                file_ids,
1507            } => self.request_reply(&who, &recipient, &request_id, (text, files, file_ids)),
1508            AgentOp::Reply {
1509                message_id,
1510                request_id,
1511                text,
1512                files,
1513                file_ids,
1514            } => {
1515                let parent = self.message(&message_id)?;
1516                ensure!(parent.recipient == who.id, UNAVAILABLE);
1517                if parent.relay.as_ref().is_some_and(|r| {
1518                    r.kind == RelayMessageKind::Request && r.attachment_id == r.turn_id
1519                }) {
1520                    return self.relay_respond(
1521                        &who,
1522                        &message_id,
1523                        &request_id,
1524                        (text, files, file_ids),
1525                        RelayResponseKind::Complete,
1526                    );
1527                }
1528                ensure!(parent.relay.is_none(), "use relay_respond for a relay turn");
1529                self.send(
1530                    &who,
1531                    &parent.sender.clone(),
1532                    &request_id,
1533                    text,
1534                    files,
1535                    SendContext {
1536                        parent: Some(parent),
1537                        relay: None,
1538                        file_ids,
1539                    },
1540                )
1541            }
1542            AgentOp::Inbox => {
1543                let mut statement=self.db.prepare("SELECT payload,acknowledged FROM messages WHERE recipient=?1 AND acknowledged=0 ORDER BY rowid")?;
1544                let rows = statement.query_map([&who.id], |r| {
1545                    Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?))
1546                })?;
1547                let mut inbox = Vec::new();
1548                let mut bytes = 0;
1549                for row in rows {
1550                    let (payload, acknowledged) = row?;
1551                    let mut message: Message = serde_json::from_str(&payload)?;
1552                    message.acknowledged = acknowledged;
1553                    if self.deliverable(&message)? && self.relay_inbox_visible(&message)? {
1554                        if inbox.len() >= 50 || bytes + payload.len() > MAX_FRAME_BYTES / 2 {
1555                            break;
1556                        }
1557                        bytes += payload.len();
1558                        self.wake_observe(&who, &message.id)?;
1559                        inbox.push(message);
1560                    }
1561                }
1562                Ok(json!(inbox))
1563            }
1564            AgentOp::Ack { message_id } => self.acknowledge(&who, &message_id),
1565            AgentOp::MessageStatus { message_id } => {
1566                let message = self.message(&message_id)?;
1567                ensure!(
1568                    message.sender == who.id || message.recipient == who.id,
1569                    UNAVAILABLE
1570                );
1571                let state = if message.expires_at <= self.timestamp {
1572                    "expired"
1573                } else if !self.deliverable(&message)?
1574                    || self.db.query_row(
1575                        "SELECT EXISTS(SELECT 1 FROM network_rejections WHERE message=?1)",
1576                        [&message.id],
1577                        |r| r.get::<_, bool>(0),
1578                    )?
1579                {
1580                    "revoked"
1581                } else if message.acknowledged {
1582                    "delivered"
1583                } else {
1584                    "queued"
1585                };
1586                Ok(json!({"message_id":message.id,"state":state}))
1587            }
1588        }
1589    }
1590
1591    fn acknowledge(&self, who: &Agent, message_id: &str) -> Result<Value> {
1592        let message = self.message(message_id)?;
1593        ensure!(
1594            message.recipient == who.id && self.deliverable(&message)?,
1595            UNAVAILABLE
1596        );
1597        let changed = self.db.execute(
1598            "UPDATE messages SET acknowledged=1 WHERE id=?1 AND acknowledged=0",
1599            [message_id],
1600        )?;
1601        let sender = self.get_agent(&message.sender)?;
1602        if changed == 1 {
1603            self.web_state_changed(&sender.node_id)?;
1604        }
1605        if !self.local_node(&sender.node_id) {
1606            self.receipt(
1607                self.state.transport_host(&sender.node_id)?,
1608                message_id,
1609                true,
1610                message.expires_at,
1611            )?;
1612        }
1613        Ok(json!({"acknowledged":true}))
1614    }
1615
1616    fn message(&self, message_id: &str) -> Result<Message> {
1617        let (payload, ack): (String, bool) = self
1618            .db
1619            .query_row(
1620                "SELECT payload,acknowledged FROM messages WHERE id=?1",
1621                [message_id],
1622                |r| Ok((r.get(0)?, r.get(1)?)),
1623            )
1624            .optional()?
1625            .context(UNAVAILABLE)?;
1626        let mut message: Message = serde_json::from_str(&payload)?;
1627        message.acknowledged = ack;
1628        Ok(message)
1629    }
1630    fn deliverable(&self, message: &Message) -> Result<bool> {
1631        if !self.web_message_ready(message)? {
1632            return Ok(false);
1633        }
1634        if message.expires_at <= self.timestamp {
1635            return Ok(false);
1636        }
1637        let a = self.get_agent(&message.sender)?;
1638        let b = self.get_agent(&message.recipient)?;
1639        if !self.relay_authorized(message)? {
1640            return Ok(false);
1641        }
1642        Ok(if message.reply_to.is_some() {
1643            self.config.policy.can_reply(&a, &b)
1644        } else {
1645            self.config.policy.can_open(&a, &b)
1646        })
1647    }
1648
1649    fn send(
1650        &mut self,
1651        sender: &Agent,
1652        recipient_id: &str,
1653        request_id: &str,
1654        text: String,
1655        files: Vec<FilePart>,
1656        context: SendContext,
1657    ) -> Result<Value> {
1658        uuid::Uuid::parse_str(request_id)
1659            .context("request_id must be a UUID; reuse it only when retrying the same message")?;
1660        let SendContext {
1661            parent,
1662            relay,
1663            file_ids,
1664        } = context;
1665        network::validate_contents(&text, &files, file_ids.len())?;
1666        ensure!(
1667            file_ids
1668                .iter()
1669                .collect::<std::collections::BTreeSet<_>>()
1670                .len()
1671                == file_ids.len(),
1672            "duplicate file ID"
1673        );
1674        let reply_to = parent.as_ref().map(|p| p.id.clone());
1675        let fingerprint =
1676            message_fingerprint(recipient_id, &text, &files, &reply_to, &relay, &file_ids)?;
1677        let existing: Option<(String, String)> = self
1678            .db
1679            .query_row(
1680                "SELECT id,fingerprint FROM messages WHERE sender=?1 AND request_id=?2",
1681                params![sender.id, request_id],
1682                |r| Ok((r.get(0)?, r.get(1)?)),
1683            )
1684            .optional()?;
1685        if let Some((message_id, previous)) = existing {
1686            ensure!(
1687                previous == fingerprint,
1688                "request_id already used with different content"
1689            );
1690            return Ok(json!({"message_id":message_id,"duplicate":true}));
1691        }
1692        requests::admit(request_id, self.timestamp)?;
1693        let recipient = self.get_agent(recipient_id)?;
1694        ensure!(sender.id != recipient.id, UNAVAILABLE);
1695        let remote = !self.local_node(&recipient.node_id);
1696        let message_id = crate::messages::message_id(&sender.id, request_id)?;
1697        let timestamp = self.timestamp;
1698        let (exchange_id, expires_at) = if let Some(parent) = parent {
1699            ensure!(
1700                self.config.policy.can_reply(sender, &recipient),
1701                UNAVAILABLE
1702            );
1703            let (a, b, expiry, count): (String, String, i64, u32) = self.db.query_row(
1704                "SELECT a,b,expires_at,count FROM exchanges WHERE id=?1",
1705                [&parent.exchange_id],
1706                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
1707            )?;
1708            ensure!(
1709                (a == sender.id && b == recipient.id) || (b == sender.id && a == recipient.id),
1710                UNAVAILABLE
1711            );
1712            ensure!(expiry > timestamp, "exchange expired");
1713            ensure!(
1714                count < MAX_EXCHANGE_MESSAGES,
1715                "exchange reply limit reached"
1716            );
1717            (parent.exchange_id, expiry)
1718        } else {
1719            ensure!(self.config.policy.can_open(sender, &recipient), UNAVAILABLE);
1720            let mut expiry = timestamp + EXCHANGE_TTL_SECONDS;
1721            if let Some(grant_id) = relay.as_ref().and_then(|relay| relay.grant_id.as_ref()) {
1722                let grant = self
1723                    .config
1724                    .policy
1725                    .relay_grants
1726                    .get(grant_id)
1727                    .context(UNAVAILABLE)?;
1728                expiry = expiry.min(grant.expires_at as i64);
1729            }
1730            (message_id.clone(), expiry)
1731        };
1732        if remote {
1733            let sent: u32 = self.db.query_row(
1734                "SELECT COUNT(*) FROM messages WHERE json_extract(payload,'$.exchange_id')=?1 AND sender=?2",
1735                params![exchange_id, sender.id],
1736                |r| r.get(0),
1737            )?;
1738            ensure!(
1739                sent < MAX_EXCHANGE_MESSAGES / 2,
1740                "remote exchange sender limit reached (16 messages)"
1741            );
1742        }
1743        let attachments = self.seal_attachments(sender, &file_ids, expires_at)?;
1744        let message = Message {
1745            id: message_id,
1746            exchange_id: exchange_id.clone(),
1747            sender: sender.id.clone(),
1748            recipient: recipient.id.clone(),
1749            text,
1750            files,
1751            attachments: attachments
1752                .iter()
1753                .map(|f| f.grant.descriptor().clone())
1754                .collect(),
1755            reply_to,
1756            created_at: timestamp,
1757            expires_at,
1758            acknowledged: false,
1759            relay,
1760        };
1761        self.validate_relay_message(&message)?;
1762        self.validate_local_relay(&message)?;
1763        let tx = self.db;
1764        if message.reply_to.is_none() {
1765            tx.execute(
1766                "INSERT INTO exchanges VALUES (?1,?2,?3,?4,0)",
1767                params![exchange_id, sender.id, recipient.id, expires_at],
1768            )?;
1769        }
1770        ensure!(
1771            tx.execute(
1772                "UPDATE exchanges SET count=count+1 WHERE id=?1 AND count<?2",
1773                params![exchange_id, MAX_EXCHANGE_MESSAGES]
1774            )? == 1,
1775            "exchange reply limit reached"
1776        );
1777        let payload = serde_json::to_string(&message)?;
1778        history::message_capacity(tx, payload.len())?;
1779        tx.execute("INSERT INTO messages(id,sender,recipient,request_id,fingerprint,payload) VALUES (?1,?2,?3,?4,?5,?6)",params![message.id,message.sender,message.recipient,request_id,fingerprint,payload])?;
1780        self.bind_attachments(&message, &attachments)?;
1781        self.record_relay_message(&message)?;
1782        self.web_state_changed(&recipient.node_id)?;
1783        self.gate_web_message(&message)?;
1784        self.save_activity(&sender.id, message.created_at)?;
1785        self.record_gent_message(&sender.id, message.created_at)?;
1786        if !remote {
1787            self.record_gent_message(&recipient.id, message.created_at)?;
1788        }
1789        if remote {
1790            self.record_web_demand(&recipient.node_id, &message.id)?;
1791            self.queue_message(
1792                self.state.transport_host(&recipient.node_id)?,
1793                request_id,
1794                &message,
1795            )?;
1796        }
1797        Ok(json!({"message_id":message.id,"exchange_id":exchange_id,"duplicate":false}))
1798    }
1799}