Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
426 changes: 401 additions & 25 deletions native/host/src/bots/mail/done.rs

Large diffs are not rendered by default.

90 changes: 74 additions & 16 deletions native/host/src/bots/mail/escalate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ pub fn private_told_key(bot: &str, key: &str) -> String { pair_key("mail.private
fn note_key(th: &str) -> String { format!("mail.private.note.{th}") }
fn said_key(th: &str) -> String { format!("mail.private.said.{th}") }
fn handed_key(th: &str) -> String { format!("mail.private.handed.{th}") }
/// Cooldown between repeated `triage-end` completion mails for the same unmanaged thread (seconds).
pub const TRIAGE_END_COOLDOWN: u64 = 1800;

/// Continuity.inbound
fn continuity_inbound(m: &Hdr, bot: &str) -> bool { m.from != format!("bot:{bot}") && m.want == "act" && (m.to == format!("bot:{bot}") || m.to.starts_with("room:")) }
Expand Down Expand Up @@ -232,35 +234,91 @@ impl<'a> Ctx<'a> {
if state == "completed" && text.trim().is_empty() { return Step::none() }
self.operational(Origin::new(&self.w.mail_addr(th), "bot", ""), &self.w.triage_thread(), &format!("Bot report from {}:\n{text}", ref_uri("thread", th)), &format!("triage-bot:{th}:{}", self.now), "fyi", vec![])
}
/// Triage.thread.end: a thread nobody manages finished: the uberbot hears it as mail it reads when it next looks (fyi: it starts no turn), and decides; its own thread is not news to it
/// Triage.thread.end: an unmanaged thread finished: the uberbot files it for its done/fallback pipeline, deduplicated per thread.
pub fn triage_thread_end(&mut self, th: &str, state: &str) -> Step {
let tt = self.w.triage_thread();
if tt.is_empty() || th == tt || self.w.managed(th) || self.run_is(th) { return Step::none() }
// its words are not folded here (a big log's messages are not read): the mail names the thread, and the uberbot reads it when it matters
self.operational(Origin::new(&self.w.mail_addr(th), "thread", ""), &tt, &format!("Thread {state}: {}", ref_uri("thread", th)), &format!("triage-end:{th}:{}", self.now), "fyi", vec![])
if state == "completed" {
let ub = self.w.uber_bot();
let in_list = |key: &str| {
serde_json::from_str::<Value>(&self.setting(key, "[]")).ok()
.and_then(|v| v.as_array().cloned())
.map_or(false, |xs| xs.iter().any(|i| i["thread"].as_str() == Some(th)))
};
let last_at: u64 = self.setting(&format!("triage.end.last.{th}"), "").parse().unwrap_or(0);
if in_list(&super::done::batch_key(&ub))
|| in_list(&super::done::pending_key(&ub))
|| (last_at > 0 && self.now.saturating_sub(last_at) < TRIAGE_END_COOLDOWN)
{
return Step::none();
}
}
let title = self.th(th).title;
let uri = ref_uri("thread", th);
let head_line = if title.trim().is_empty() {
format!("Thread {state}: {uri}")
} else {
format!("Thread {state}: {} ({uri})", title.trim())
};
let reply = self.f.last.get(th).map(|l| l.0.trim()).unwrap_or("");
let text = if reply.is_empty() {
head_line
} else {
format!("{head_line}\n{}", take_chars(reply, 2000))
};
let op = self.operational(Origin::new(&self.w.mail_addr(th), "thread", ""), &tt, &text, &format!("triage-end:{th}:{}", self.now), "fyi", vec![]);
if state == "completed" {
let cs = vec![set(format!("triage.end.last.{th}"), &self.now.to_string(), self.now)];
self.replay(&cs);
Step { cs, outs: vec![] }.cat(op)
} else {
op
}
}
pub fn run_is(&self, th: &str) -> bool { self.w.private_is(th) || self.run_of(th).filter(|r| self.runs_on(&r.bot)).is_some() }
fn run_of_any(&self, th: &str) -> Option<Run> { self.run_of(th).filter(|r| !self.w.private_is(&r.thread)) }

/// Private.lost: a lane cut off before it told anyone hands its note to the owner's own agent, once
/// Private.lost: a lane cut off before it told anyone hands its note to the owner's own agent, once;
/// any ended private lane flushes completions that arrived while it ran into a follow-up lane.
pub fn private_lost(&mut self, lane: &str, state: &str) -> Step {
if let Some(st) = self.done_lane_end(lane, state) { return st } // Done.lane.end: a done lane's digest is posted, not handed over
if !self.w.private_is(lane) || !(state == "interrupted" || state == "failed") { return Step::none() }
let note = self.setting(&note_key(lane), ""); let target = self.w.triage_thread();
if note.is_empty() || !self.setting(&said_key(lane), "").is_empty() || !self.setting(&handed_key(lane), "").is_empty() || target.is_empty() { return Step::none() }
let cs = vec![set(handed_key(lane), &self.now.to_string(), self.now)]; self.replay(&cs);
let text = format!("[Backplane] Your private mailroom lane {lane} was cut off (provider limit, failure or restart) before it finished, so this escalation reached no one. Assess it yourself now: told_check first, tell the person only what is material and new, and keep source approvals pending.\n\n{note}");
Step { cs, outs: vec![RouteOut::Ride { thread: target, id: format!("lost:{lane}"), text }] }
if !self.w.private_is(lane) || !["completed", "failed", "interrupted"].contains(&state) { return Step::none() }
let bot = self.w.private_owner(lane);
let mut st = if let Some(s) = self.done_lane_end(lane, state) {
s // Done.lane.end: a done lane's digest is handled here, not handed over
} else if state == "interrupted" || state == "failed" {
let note = self.setting(&note_key(lane), ""); let target = self.w.triage_thread();
if note.is_empty() || !self.setting(&said_key(lane), "").is_empty() || !self.setting(&handed_key(lane), "").is_empty() || target.is_empty() {
Step::none()
} else {
let cs = vec![set(handed_key(lane), &self.now.to_string(), self.now)]; self.replay(&cs);
let text = format!("[Backplane] Your private mailroom lane {lane} was cut off (provider limit, failure or restart) before it finished, so this escalation reached no one. Assess it yourself now: told_check first, tell the person only what is material and new, and keep source approvals pending.\n\n{note}");
Step { cs, outs: vec![RouteOut::Ride { thread: target, id: format!("lost:{lane}"), text }] }
}
} else {
Step::none()
};
if !self.has_live_done_lane(&bot) {
let follow = self.done_flush_now(&bot);
st = st.cat(follow);
}
st
}
/// Private.tell: the one publication from the back office into the person's conversation, once per owner and key; the owner's own agent is told it was said
pub fn private_tell(&mut self, thread: &str, text: &str, key: &str) -> Step {
let bot = self.w.private_owner(thread); let target = self.w.triage_thread();
if !self.setting(&private_told_key(&bot, key), "").is_empty() { return Step::none() }
let bot = self.w.private_owner(thread);
self.private_tell_as(&bot, thread, text, key)
}
/// Publication into the uberbot's conversation on behalf of `bot` (with optional back-office `lane`).
pub(super) fn private_tell_as(&mut self, bot: &str, lane: &str, text: &str, key: &str) -> Step {
let target = self.w.triage_thread();
if bot.is_empty() || target.is_empty() || !self.setting(&private_told_key(bot, key), "").is_empty() { return Step::none() }
let msg = self.id("tell:"); let now = self.now; // Bot.told: `tell:` always shows in the chat
let mut cs = vec![json!({"$":"MessagePosted","thread":target,"msg":msg,"role":"assistant","text":text,"at":now}), json!({"$":"MessageFrom","thread":target,"msg":msg,"from":format!("thread:{thread}"),"kind":"tell-person","ref":key,"at":now}),
set(private_told_key(&bot, key), &msg, now), set(said_key(thread), &msg, now)];
let from = if lane.is_empty() { format!("bot:{bot}") } else { format!("thread:{lane}") };
let mut cs = vec![json!({"$":"MessagePosted","thread":target,"msg":msg,"role":"assistant","text":text,"at":now}), json!({"$":"MessageFrom","thread":target,"msg":msg,"from":from,"kind":"tell-person","ref":key,"at":now}),
set(private_told_key(bot, key), &msg, now)];
if !lane.is_empty() { cs.push(set(said_key(lane), &msg, now)); }
if self.policy_on("needs") || self.policy_on("settled") { cs.push(self.alert_set(&target, "note", &format!("tell-{msg}"), &Self::alert_text(text, 500))) }
cs.extend(self.told_mark(&msg, key, text, "chat", &bot));
cs.extend(self.told_mark(&msg, key, text, "chat", bot));
self.replay(&cs);
let note = format!("[Backplane] Your private mailroom just told the person this in your conversation (key {key}). It is on screen in your conversation, and no phone alert went out: only your notify_person reaches their phone, so call it if they must know now. Do not repeat it otherwise, take it into account. If you have nothing to add, end with an empty reply.\n\n{text}");
Step { cs, outs: vec![RouteOut::Note { thread: target, id: format!("told:{msg}"), text: note }] }
Expand Down
16 changes: 13 additions & 3 deletions native/host/src/bots/mail/gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,15 +157,25 @@ impl<'a> Ctx<'a> {
let bot = self.w.private_owner(lane);
if let Some(why) = refusal(kind, text, proof) { let p = self.report_prefs(&bot); return Err(if p.is_empty() { why } else { format!("{why}\nThe person's rules:{p}") }) }
let rkey = proof.as_ref().map(|(r, _)| r.key()).unwrap_or_default();
if !self.setting(&private_told_key(&bot, &rkey), "").is_empty() || !self.setting(&private_told_key(&bot, key), "").is_empty() { return Ok((Step::none(), 0)) }
if items(&self.setting(&batch_key(&bot), "[]")).iter().any(|i| i["ref"] == rkey.as_str()) { return Ok((Step::none(), 0)) }
let ref_parsed = proof.as_ref().map(|(r, _)| r);
let fallback_recent = if let Some(super::gate::Ref::Thread { id }) = ref_parsed {
let fb_at: u64 = self.setting(&super::done::fallback_at_key(&bot, id), "").parse().unwrap_or(0);
fb_at > 0 && self.now.saturating_sub(fb_at) < super::done::COOLDOWN
} else { false };
if fallback_recent || !self.setting(&private_told_key(&bot, &rkey), "").is_empty() || !self.setting(&private_told_key(&bot, key), "").is_empty()
|| items(&self.setting(&batch_key(&bot), "[]")).iter().any(|i| i["ref"] == rkey.as_str()) {
let clr = self.done_pending_clear(&bot, lane, ref_parsed, text);
if !clr.is_empty() { self.replay(&clr); return Ok((Step { cs: clr, outs: vec![] }, 0)) }
return Ok((Step::none(), 0))
}
let urgent = Kind::parse(kind).is_some_and(Kind::urgent); let now = self.now;
let (last, open) = (num(self.setting(&last_key(&bot), "")), num(self.setting(&due_key(&bot), "")));
let due = if urgent { let at = now.max(last + GAP); if open > 0 { open.min(at) } else { at } } else if open > 0 { open } else { (now + BATCH).max(last + BATCH) };
let mut xs = items(&self.setting(&batch_key(&bot), "[]"));
xs.push(json!({"key":key,"ref":rkey,"text":text,"lane":lane,"kind":kind,"at":now}));
let cs = vec![set(batch_key(&bot), &jshow(json!(xs)), now), set(due_key(&bot), &due.to_string(), now),
let mut cs = vec![set(batch_key(&bot), &jshow(json!(xs)), now), set(due_key(&bot), &due.to_string(), now),
set(private_told_key(&bot, key), &format!("queued:{due}"), now), set(private_told_key(&bot, &rkey), &format!("queued:{due}"), now), set(said_key(lane), &format!("queued:{key}"), now)];
cs.extend(self.done_pending_clear(&bot, lane, ref_parsed, text));
self.replay(&cs);
let st = Step { cs, outs: vec![] };
if due <= now { let f = self.tell_flush(&bot); return Ok((st.cat(f), due)) }
Expand Down
10 changes: 7 additions & 3 deletions native/host/src/bots/mail/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,15 @@ impl Bots {
async fn owner_current(&self, r: &Value) -> bool { self.setting_or_empty(&pending_key(&key(r))).await == show(r) }
fn owner_stamp(&self, w: &World, now: u64) -> String { format!("{now}:{}:{}", self.hub.store.len(), w.lease().1) }

/// Owner.records: at most sixteen pending tickets, by key
/// Owner.records: at most sixteen pending tickets (up to 8 newest + up to 8 oldest so neither starves)
pub async fn owner_records(&self) -> Vec<Value> {
let m = self.hub.model().await; let seqs: Vec<u32> = m.settings_with_prefix("owner.mail.pending.").map(|(_, s)| s).collect(); drop(m);
let m = self.hub.model().await; let mut seqs: Vec<u32> = m.settings_with_prefix("owner.mail.pending.").map(|(_, s)| s).collect(); drop(m);
seqs.sort_unstable();
let mut picked: Vec<u32> = Vec::with_capacity(16);
for &s in seqs.iter().rev().take(8) { picked.push(s); }
for &s in seqs.iter().take(8) { if !picked.contains(&s) { picked.push(s); } }
let mut out = vec![];
for s in seqs { if out.len() >= 16 { break }
for s in picked { if out.len() >= 16 { break }
let Some(v) = self.hub.store.get(s as usize - 1).ok().and_then(|l| serde_json::from_str::<Value>(&l).ok()) else { continue };
let Some(t) = v["value"].as_str().filter(|t| !t.is_empty()) else { continue };
if let Ok(r) = serde_json::from_str::<Value>(t) { out.push(r) }
Expand Down
2 changes: 0 additions & 2 deletions native/host/src/bots/mail/route.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,6 @@ impl<'a> Ctx<'a> {
let on = self.mail_on(); let m = &body.mail;
// a header a run is already bound to is routed: the owner's outbox walk routes pending tickets again and again
if self.w.mail.runs.values().any(|r| r.mail == m.id) { return Step::none() }
// Triage.thread.end: an unmanaged thread's end is filed for the uberbot to read when it next looks; it starts no run (one per worker turn would be noise and cost)
if m.want == "fyi" && m.id.starts_with("triage-end:") { return Step::none() }
match of_addr(&m.to) {
Some((k, bot)) if k == "bot" => if on { self.route_bot(body, &bot) } else { let act = self.triage_owner(&bot) && Self::inbound(m, &bot); self.route_bot_want(act, body, &bot) },
Some((k, _)) if k == "room" => self.route_parts(body),
Expand Down
29 changes: 24 additions & 5 deletions native/host/src/bots/mail/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,16 @@ impl Bots {
}
/// Decide on the world as it is, commit the step, let the world go
pub(crate) async fn decide(self: &Arc<Self>, report: &[String], f: impl FnOnce(&mut Ctx) -> Step) -> Vec<RouteOut> { self.decide_with(report, |c| ((), f(c))).await.1 }
pub(crate) async fn decide_at(self: &Arc<Self>, report: &[String], now: u64, f: impl FnOnce(&mut Ctx) -> Step) -> Vec<RouteOut> { self.decide_acc_at(report, true, now, |c| ((), f(c))).await.1 }
/// the same, for a decision that also answers its caller (a tool)
pub(crate) async fn decide_with<T>(self: &Arc<Self>, report: &[String], f: impl FnOnce(&mut Ctx) -> (T, Step)) -> (T, Vec<RouteOut>) { self.decide_acc(report, true, f).await }
/// `accounts`: Accounts.created binds what the step creates; a step's own after-work (Run.after) comes past it in , and a back office it makes has only its explicit binding
async fn decide_acc<T>(self: &Arc<Self>, report: &[String], accounts: bool, f: impl FnOnce(&mut Ctx) -> (T, Step)) -> (T, Vec<RouteOut>) {
self.decide_acc_at(report, accounts, now_s(), f).await
}
async fn decide_acc_at<T>(self: &Arc<Self>, report: &[String], accounts: bool, now: u64, f: impl FnOnce(&mut Ctx) -> (T, Step)) -> (T, Vec<RouteOut>) {
let w = self.world().await; let facts = self.facts(&w, report).await;
let (now, seq) = (now_s(), self.hub.store.len() as u64);
let seq = self.hub.store.len() as u64;
let mut ctx = Ctx::new(&w, &facts, now, seq); let (t, st) = f(&mut ctx);
let cs = if accounts { self.accounts_created(st.cs).await } else { st.cs }; // Accounts.created: a run's thread starts on the default account
if !cs.is_empty() && self.hub.commit_many(&cs).await.is_err() { eprintln!("mail: routing could not be committed"); return (t, vec![]) }
Expand All @@ -75,9 +79,9 @@ impl Bots {
}
/// Mail.route for a header just filed
pub async fn route_body(self: &Arc<Self>, body: Body) {
let outs = self.decide(&[], |c| c.route(&body)).await; self.perform(outs).await;
// Done.timer: a finish that opened the owner's batch flushes it when its window is over
if body.mail.kind == "launch" { let due = { let w = self.world().await; w.setting(&super::done::due_key(&w.uber_bot()), "").parse().unwrap_or(0) }; self.done_timer(due) }
let report: Vec<String> = super::done::triage_end_thread(&body.mail.id).into_iter().collect();
let outs = self.decide(&report, |c| c.route(&body)).await; self.perform(outs).await;
self.arm_done_timer().await;
}
/// Run.queue.start for RunNext
pub async fn run_next(self: &Arc<Self>, bot: String, conv: String) { let outs = self.decide(&[], |c| c.queue_start(&bot, &conv)).await; self.perform(outs).await }
Expand All @@ -98,7 +102,21 @@ impl Bots {
pub async fn after_steps(self: &Arc<Self>) {
let (steps, on) = { let mut w = self.world().await; (std::mem::take(&mut w.steps), w.setting("mail.on", "off") == "on" || !w.uber_bot().is_empty()) };
if crate::copy::on() || steps.is_empty() { return }
let report: Vec<String> = steps.iter().filter_map(|s| match s { StepEnd::Turn { thread, .. } | StepEnd::Fallback { thread, .. } => Some(thread.clone()), _ => None }).collect();
let mut report: Vec<String> = steps.iter().filter_map(|s| match s { StepEnd::Turn { thread, .. } | StepEnd::Fallback { thread, .. } => Some(thread.clone()), _ => None }).collect();
if on && steps.iter().any(|s| matches!(s, StepEnd::Turn { thread, .. } if thread.starts_with("mailcoord-"))) {
let w = self.world().await;
let ub = w.uber_bot();
if !ub.is_empty() {
if let Ok(serde_json::Value::Array(arr)) = serde_json::from_str::<serde_json::Value>(&w.setting(&super::done::batch_key(&ub), "[]")) {
for i in arr {
if let Some(th) = i["thread"].as_str().filter(|t| !t.is_empty()) {
let s = th.to_string();
if !report.contains(&s) { report.push(s); }
}
}
}
}
}
let ended: Vec<String> = steps.iter().filter_map(|s| match s { StepEnd::Turn { thread, state, .. } if (state == "completed" || state == "failed") && ephemeral(thread) => Some(thread.clone()), _ => None }).collect();
let answers: Vec<(String, String, usize)> = steps.iter().filter_map(|s| match s { StepEnd::RoomReply { thread, room, line } => Some((thread.clone(), room.clone(), *line)), _ => None }).collect();
let (_, outs) = self.decide_acc(&report, false, |c| {
Expand All @@ -119,6 +137,7 @@ impl Bots {
((), st)
}).await;
self.perform(outs).await;
self.arm_done_timer().await;
// Room.answer: the person asked in a room and the bot answered only in its own chat, where they do not look: its reply is posted in the room as the bot's own room_post
let answers = if answers.is_empty() || self.hub.setting("room.answer").await.map_or(false, |v| v == "off") { vec![] } else { answers }; // the setting `room.answer` = off leaves replies where the bot wrote them
for (thread, room, line) in answers {
Expand Down
Loading
Loading