1use std::collections::HashMap;
45use std::path::PathBuf;
46use std::time::{Duration, Instant};
47
48use anyhow::Result;
49use jiff::Timestamp;
50
51use crate::agent::{self, Invocation, SeatState};
52use crate::ask::{Lease, Question, QuestionStatus, Questions, Waiter as Note, WaiterKind, Who};
53use crate::config::{AgentSpec, Config};
54use crate::notices::{self, Notice};
55use crate::prompt;
56use crate::run::RunState;
57
58pub const TICK: Duration = Duration::from_secs(5);
60
61const DELIVERY_TIMEOUT: Duration = Duration::from_secs(15 * 60);
65
66const RETRY_AFTER: Duration = Duration::from_secs(10 * 60);
70
71#[derive(serde::Serialize, serde::Deserialize)]
72struct Retry {
73 key: String,
74 until: i64,
75}
76
77fn retry_path(store: &Questions, id: &str) -> PathBuf {
78 store.root().join(format!("{id}.waiter-retry.json"))
79}
80
81fn retry_blocked(store: &Questions, id: &str, key: &str, now: Timestamp) -> bool {
82 std::fs::read(retry_path(store, id))
83 .ok()
84 .and_then(|bytes| serde_json::from_slice::<Retry>(&bytes).ok())
85 .is_some_and(|retry| retry.key == key && now.as_second() < retry.until)
86}
87
88#[derive(Debug, Clone, PartialEq, Eq)]
90pub enum Word {
91 Said(String),
93 Answered(String),
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
99pub enum Action {
100 Idle,
102 Expire,
104 Deliver(Word),
106}
107
108pub fn decide(
118 q: &Question,
119 lease: Option<&Lease>,
120 seat_busy: bool,
121 default_timeout: u64,
122 now: Timestamp,
123) -> Action {
124 decide_owned(q, lease, seat_busy, default_timeout, now, false)
125}
126
127pub fn decide_owned(
137 q: &Question,
138 lease: Option<&Lease>,
139 seat_busy: bool,
140 default_timeout: u64,
141 now: Timestamp,
142 daemon_owns_action: bool,
143) -> Action {
144 if q.routed_task.is_some() || q.cwd.is_none() || lease.is_some_and(|l| l.fresh(now)) {
145 return Action::Idle;
146 }
147 match q.status {
148 QuestionStatus::Abandoned => Action::Idle,
149 QuestionStatus::Answered => match q.resolution() {
150 _ if q.chosen_action().is_some_and(|a| a.maintenance())
151 || (daemon_owns_action && q.chosen_action().is_some()) =>
152 {
153 Action::Idle
154 }
155 Some(a) if !q.answer_delivered && !seat_busy => Action::Deliver(Word::Answered(a)),
156 _ => Action::Idle,
157 },
158 QuestionStatus::Open => {
159 if let Some(said) = q.unread_from_owner() {
160 if seat_busy {
161 return Action::Idle;
162 }
163 return Action::Deliver(Word::Said(said));
164 }
165 let secs = if q.answer_timeout > 0 {
166 q.answer_timeout
167 } else {
168 default_timeout
169 };
170 let deadline = q.last_activity().saturating_add(secs as i64);
171 if now.as_second() > deadline {
172 Action::Expire
173 } else {
174 Action::Idle
175 }
176 }
177 }
178}
179
180struct Target {
182 coordination: Option<crate::config::Coordination>,
183 fetched_base: Option<crate::run::FetchedBase>,
184 spec: AgentSpec,
185 seat: SeatState,
186 cwd: PathBuf,
187 sessions: bool,
188 allow_write: bool,
189 language: String,
190}
191
192pub struct Waiter {
195 store: Questions,
196 home: PathBuf,
197 conduct_cfg: Option<Config>,
200 default_timeout: u64,
202 memo: HashMap<String, (String, Instant)>,
204}
205
206impl Waiter {
207 pub fn new(store: Questions, home: PathBuf, conduct_cfg: Option<Config>) -> Self {
209 let default_timeout = conduct_cfg
210 .as_ref()
211 .map_or(Config::default().graph.answer_timeout, |c| {
212 c.graph.answer_timeout
213 });
214 Self {
215 store,
216 home,
217 conduct_cfg,
218 default_timeout,
219 memo: HashMap::new(),
220 }
221 }
222
223 pub fn has_work(&self, now: Timestamp) -> bool {
225 self.store.list().iter().any(|q| {
226 let lease = self.store.read_lease(&q.id);
227 match decide_owned(
228 q,
229 lease.as_ref(),
230 false,
231 self.default_timeout,
232 now,
233 self.daemon_owns_action(q),
234 ) {
235 Action::Idle => false,
236 Action::Expire => true,
237 Action::Deliver(_) if q.deputy.is_some() => crate::deputy::exhausted_past_deadline(
238 q,
239 crate::deputy::can_start(self.conduct_cfg.as_ref(), crate::deputy::agent_of(q)),
240 self.default_timeout,
241 now,
242 ),
243 Action::Deliver(word) => {
244 let key = format!("{}:{:?}", q.thread.len(), word);
245 !self.seat_busy(q, now) && !retry_blocked(&self.store, &q.id, &key, now)
246 }
247 }
248 })
249 }
250
251 fn seat_busy(&self, q: &Question, now: Timestamp) -> bool {
253 if q.run == crate::conduct::NODE {
254 return crate::conduct::busy(&self.home);
255 }
256 RunState::load_under(&q.run, &self.home).is_ok_and(|s| {
257 s.seats_active()
258 .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
259 })
260 }
261
262 fn daemon_owns_action(&self, q: &Question) -> bool {
265 q.chosen_action().is_some_and(|a| a.maintenance())
266 || crate::daemon::task_of_question(
267 &crate::queue::Queue::at(self.home.join("queue")).list(),
268 q,
269 )
270 .is_some_and(|t| crate::daemon::action_standing(t, q).daemon_owns())
271 }
272
273 pub async fn tick(&mut self, now: Timestamp, halt: &(dyn Fn() -> bool + Sync)) {
278 for q in self.store.list() {
279 if halt() {
280 return;
281 }
282 if crate::task_chat::routes(&q, &self.home) {
283 continue;
284 }
285 let lease = self.store.read_lease(&q.id);
286 let owned = self.daemon_owns_action(&q);
287 match decide_owned(&q, lease.as_ref(), false, self.default_timeout, now, owned) {
288 Action::Idle => {}
289 Action::Expire => self.expire(&q),
290 Action::Deliver(word) => {
291 if q.deputy.is_some() {
295 if crate::deputy::exhausted_past_deadline(
299 &q,
300 crate::deputy::can_start(
301 self.conduct_cfg.as_ref(),
302 crate::deputy::agent_of(&q),
303 ),
304 self.default_timeout,
305 now,
306 ) {
307 self.expire(&q);
308 }
309 continue;
310 }
311 if self.seat_busy(&q, now) {
312 continue;
313 }
314 let key = format!("{}:{:?}", q.thread.len(), word);
315 if retry_blocked(&self.store, &q.id, &key, now)
316 || matches!(self.memo.get(&q.id), Some((k, until)) if *k == key && Instant::now() < *until)
317 {
318 continue;
319 }
320 if let Err(e) = self.deliver(&q, &word, halt).await {
321 tracing::warn!("question {}: {e:#}", q.short());
322 }
323 }
324 }
325 }
326 }
327
328 fn expire(&self, q: &Question) {
331 let secs = if q.answer_timeout > 0 {
332 q.answer_timeout
333 } else {
334 self.default_timeout
335 };
336 let startable =
337 crate::deputy::can_start(self.conduct_cfg.as_ref(), crate::deputy::agent_of(q));
338 let why = format!("no answer within {}s of asking", secs.max(1));
339 let done = self.store.update(&q.id, |r| {
340 let now = Timestamp::now();
344 let lease = self.store.read_lease(&r.id);
345 if decide(r, lease.as_ref(), false, self.default_timeout, now) != Action::Expire
346 && !(lease.as_ref().is_none_or(|l| !l.fresh(now))
347 && crate::deputy::exhausted_past_deadline(
348 r,
349 startable,
350 self.default_timeout,
351 now,
352 ))
353 {
354 return Ok(false);
355 }
356 r.abandon(&why);
357 r.waiter = None;
358 Ok(true)
359 });
360 match done {
361 Ok((_, false)) => {}
362 Ok((_, true)) => {
363 self.store.drop_lease(&q.id);
364 tracing::warn!(
365 "question {} went unanswered for {secs}s with nobody waiting; \
366 it stays as the record of it",
367 q.short()
368 );
369 }
370 Err(e) => tracing::warn!("could not expire question {}: {e:#}", q.short()),
371 }
372 }
373
374 pub fn can_resume(&self, q: &Question) -> bool {
376 self.target(q).is_ok()
377 }
378
379 fn target(&self, q: &Question) -> std::result::Result<Target, String> {
381 let cwd = q
382 .cwd
383 .as_deref()
384 .map(PathBuf::from)
385 .filter(|p| p.is_dir())
386 .ok_or("the directory the agent was working in is gone")?;
387 let (cfg, seat, allow_write, fetched_base) = if q.run == crate::conduct::NODE {
388 let cfg = self
389 .conduct_cfg
390 .clone()
391 .ok_or("the conductor's configuration is not available")?;
392 let seat = crate::conduct::load_seat(&self.home)
393 .ok_or("the conductor has no recorded session")?;
394 (cfg, seat, false, None)
395 } else {
396 let state = RunState::load_under(&q.run, &self.home)
397 .map_err(|_| "the run that asked is gone".to_owned())?;
398 if !state.status.resumable() {
399 return Err(format!(
400 "the run that asked has already {}",
401 state.status.as_str()
402 ));
403 }
404 let seat = state
405 .seats
406 .get(&q.seat)
407 .cloned()
408 .ok_or("the run has no record of the asking seat")?;
409 let write = matches!(q.node.as_str(), "implement" | "fix");
410 (state.config, seat, write, state.fetched_base)
411 };
412 let spec = cfg
413 .agent(&seat.agent)
414 .map_err(|_| format!("agent `{}` is no longer in the roster", seat.agent))?
415 .clone();
416 if !agent::has_session(spec.kind, &seat, cfg.graph.sessions) {
417 return Err("the seat has no session to resume".to_owned());
418 }
419 Ok(Target {
420 coordination: cfg.coordination.clone(),
421 fetched_base,
422 spec,
423 seat,
424 cwd,
425 sessions: cfg.graph.sessions,
426 allow_write,
427 language: cfg.graph.language.clone(),
428 })
429 }
430
431 fn refuse(&mut self, q: &Question, key: String, why: &str) {
433 tracing::warn!("question {} cannot be delivered: {why}", q.short());
434 notices::raise_in(
435 &self.home,
436 Notice::warn(
437 &format!("question:{}", q.id),
438 format!(
439 "Question {} \"{}\": what you said cannot reach the agent \
440 ({why}). It is recorded, but nothing will read it.",
441 q.short(),
442 q.summary
443 ),
444 ),
445 );
446 let _ = self.store.update(&q.id, |r| {
447 r.waiter = None;
448 Ok(())
449 });
450 let retry = Retry {
451 key: key.clone(),
452 until: Timestamp::now()
453 .as_second()
454 .saturating_add(RETRY_AFTER.as_secs() as i64),
455 };
456 let written = serde_json::to_vec(&retry)
457 .map_err(anyhow::Error::from)
458 .and_then(|bytes| {
459 std::fs::write(retry_path(&self.store, &q.id), bytes).map_err(Into::into)
460 });
461 if let Err(error) = written {
462 tracing::warn!(
463 "question {} retry cooldown could not be saved: {error:#}",
464 q.short()
465 );
466 }
467 self.memo
468 .insert(q.id.clone(), (key, Instant::now() + RETRY_AFTER));
469 }
470
471 async fn deliver(
473 &mut self,
474 q: &Question,
475 word: &Word,
476 halt: &(dyn Fn() -> bool + Sync),
477 ) -> Result<()> {
478 let key = format!("{}:{:?}", q.thread.len(), word);
479 let mut target = match self.target(q) {
480 Ok(t) => t,
481 Err(why) => {
482 self.refuse(q, key, &why);
483 return Ok(());
484 }
485 };
486
487 let claim = self.store.root().join(format!("{}.claim", q.id));
488 if !take_claim(&claim, DELIVERY_TIMEOUT + Duration::from_secs(60)) {
489 return Ok(());
490 }
491 let _release = Release(claim);
492
493 let q = self.store.get(&q.id)?;
496 if crate::task_chat::routes(&q, &self.home) {
497 return Ok(());
498 }
499 let now = Timestamp::now();
500 let lease = self.store.read_lease(&q.id);
501 let owned = self.daemon_owns_action(&q);
502 let Action::Deliver(word) =
503 decide_owned(&q, lease.as_ref(), false, self.default_timeout, now, owned)
504 else {
505 return Ok(());
506 };
507 let snapshot = q.thread.len();
508
509 let queue = crate::queue::Queue::at(self.home.join("queue"));
515 let task_id = crate::daemon::task_of_question(&queue.list(), &q).map(|t| t.id.clone());
516 let _task_claim = match (&task_id, q.chosen_action()) {
520 (Some(id), Some(_)) => match queue.claim(id) {
521 Ok(c) => Some(c),
522 Err(e) => {
523 tracing::debug!(
524 "question {}: task claim not available ({e:#}), deferring delivery",
525 q.short()
526 );
527 return Ok(());
528 }
529 },
530 _ => None,
531 };
532 let task_still_ours = || {
535 if q.chosen_action().is_some_and(|a| a.maintenance()) {
536 false
537 } else {
538 match &task_id {
539 Some(id) => queue
540 .get(id)
541 .map(|t| !crate::daemon::action_standing(&t, &q).daemon_owns())
542 .unwrap_or(true),
543 None => true,
544 }
545 }
546 };
547 if !task_still_ours() {
548 return Ok(());
549 }
550
551 self.store.beat(&q.id, WaiterKind::Daemon);
552 if !task_still_ours() {
555 return Ok(());
556 }
557 self.store.update(&q.id, |r| {
558 r.waiter = Some(Note {
559 kind: WaiterKind::Daemon,
560 since: now,
561 });
562 Ok(())
563 })?;
564 tracing::info!(
565 "question {}: the asker is gone, resuming seat {} with the owner's word",
566 q.short(),
567 q.seat
568 );
569
570 let thread: Vec<(&str, &str)> = q
571 .thread
572 .iter()
573 .map(|t| {
574 (
575 if t.who == Who::Operator {
576 "operator"
577 } else {
578 "agent"
579 },
580 t.body.as_str(),
581 )
582 })
583 .collect();
584 let shown = match word {
587 Word::Said(_) => &thread[..q.delivered_turns.min(thread.len())],
588 Word::Answered(_) => &thread[..],
589 };
590 let owner_word = match &word {
591 Word::Said(s) => prompt::OwnerWord::Said(s),
592 Word::Answered(a) => prompt::OwnerWord::Answered(a),
593 };
594 let body = prompt::question_resumed(
595 &q.id,
596 &q.summary,
597 &q.detail,
598 shown,
599 &owner_word,
600 &target.language,
601 );
602
603 let artifacts = self.store.root().join(format!("{}.delivery", q.id));
604 let stem = format!("deliver-{}", now.as_second());
605 let cache_dir = None;
606 let inv = Invocation {
607 scope: crate::agent::InvocationScope::Repository,
608 coordination: target.coordination.as_ref(),
609 fetched_base: target.fetched_base.as_ref(),
610 cwd: &target.cwd,
611 prompt: &body,
612 timeout: DELIVERY_TIMEOUT,
613 allow_write: target.allow_write,
614 unsandboxed: false,
615 sessions: target.sessions,
616 artifacts: &artifacts,
617 stem: &stem,
618 run: &q.run,
619 node: &q.node,
620 cache_dir,
621 attachments: &[],
622 writable: &[],
623 };
624
625 let store = self.store.clone();
626 let id = q.id.clone();
627 let out = {
628 let fut = agent::invoke(&target.spec, &mut target.seat, &inv);
629 tokio::pin!(fut);
630 let mut beat = tokio::time::interval(Duration::from_secs(1));
631 let mut beats = 0u32;
632 loop {
633 tokio::select! {
634 r = &mut fut => break Some(r),
635 _ = beat.tick() => {
636 if halt() {
637 break None;
638 }
639 beats += 1;
640 if beats % 20 == 0 {
641 store.beat(&id, WaiterKind::Daemon);
642 }
643 }
644 }
645 }
646 };
647
648 let Some(out) = out else {
649 let _ = self.store.update(&q.id, |r| {
651 r.waiter = None;
652 Ok(())
653 });
654 return Ok(());
655 };
656 let out = match out {
657 Ok(o) if o.usable() => o,
658 other => {
659 let why = match other {
660 Ok(o) if o.timed_out => "the resumed turn timed out".to_owned(),
661 Ok(o) if o.quota_exhausted() => "the agent is out of quota".to_owned(),
662 Ok(o) => format!(
663 "the resumed turn failed ({})",
664 notices::exit_status(o.exit_code)
665 ),
666 Err(e) => format!("the agent could not be started: {e:#}"),
667 };
668 self.refuse(&q, key, &why);
669 return Ok(());
670 }
671 };
672
673 let text = out.text.trim().to_owned();
674 self.store.update(&q.id, |r| {
675 r.waiter = None;
676 match &word {
677 Word::Answered(_) => r.answer_delivered = true,
678 Word::Said(_) => {
679 r.delivered_turns = r.delivered_turns.max(snapshot);
680 let agent_spoke = r.thread[snapshot.min(r.thread.len())..]
685 .iter()
686 .any(|t| t.who == Who::Agent);
687 if !agent_spoke && r.thread.len() == snapshot && r.status.open() {
688 let choices = r.choices.clone();
689 r.reply(text, choices)?;
690 }
691 }
692 }
693 Ok(())
694 })?;
695 self.memo.remove(&q.id);
696 let _ = std::fs::remove_file(retry_path(&self.store, &q.id));
697 Ok(())
698 }
699}
700
701pub(crate) fn take_claim(path: &std::path::Path, stale_after: Duration) -> bool {
705 let retry = crate::lock_file::Retry::new(None);
706 let attempt = || retry.create(path).is_ok();
707 if attempt() {
708 return true;
709 }
710 let stale = std::fs::metadata(path)
711 .and_then(|m| m.modified())
712 .ok()
713 .and_then(|t| t.elapsed().ok())
714 .is_some_and(|age| age > stale_after);
715 if stale {
716 let _ = std::fs::remove_file(path);
717 return attempt();
718 }
719 false
720}
721
722pub(crate) struct Release(pub(crate) PathBuf);
724
725impl Drop for Release {
726 fn drop(&mut self) {
727 let _ = std::fs::remove_file(&self.0);
728 }
729}
730
731#[cfg(test)]
732mod tests {
733 use super::*;
734
735 #[test]
736 fn retry_backoff_survives_a_new_finite_waiter() {
737 let home = tempfile::tempdir().expect("home");
738 let store = Questions::at(home.path().join("questions"));
739 std::fs::create_dir_all(store.root()).expect("questions");
740 let retry = Retry {
741 key: "input".to_owned(),
742 until: 700,
743 };
744 std::fs::write(
745 retry_path(&store, "question"),
746 serde_json::to_vec(&retry).expect("retry"),
747 )
748 .expect("save retry");
749 let reopened = Questions::at(home.path().join("questions"));
750 assert!(retry_blocked(&reopened, "question", "input", ts(699)));
751 assert!(!retry_blocked(
752 &reopened,
753 "question",
754 "different input",
755 ts(699)
756 ));
757 assert!(!retry_blocked(&reopened, "question", "input", ts(700)));
758 }
759
760 fn ts(secs: i64) -> Timestamp {
761 Timestamp::from_second(secs).unwrap()
762 }
763
764 fn asked(at: i64) -> Question {
765 let mut q = Question::new(
766 "run".into(),
767 "implement".into(),
768 "impl-A".into(),
769 "which?".into(),
770 String::new(),
771 vec![],
772 );
773 q.cwd = Some("/tmp".into());
774 q.asked_at = ts(at);
775 q.answer_timeout = 1000;
776 q
777 }
778
779 fn lease(at: i64) -> Lease {
780 Lease {
781 kind: WaiterKind::Asker,
782 pid: 1,
783 beat_at: ts(at),
784 }
785 }
786
787 #[test]
788 fn a_fresh_lease_means_nobody_else_acts() {
789 let mut q = asked(0);
790 q.say("why?").unwrap();
791 assert_eq!(
792 decide(&q, Some(&lease(95)), false, 86_400, ts(100)),
793 Action::Idle
794 );
795 }
796
797 #[test]
798 fn a_stale_lease_delivers_what_the_owner_said() {
799 let mut q = asked(0);
800 q.say("why?").unwrap();
801 assert_eq!(
802 decide(&q, Some(&lease(0)), false, 86_400, ts(500)),
803 Action::Deliver(Word::Said("why?".into()))
804 );
805 assert_eq!(
806 decide(&q, None, true, 86_400, ts(500)),
807 Action::Idle,
808 "a seat still mid-turn is not resumed"
809 );
810 }
811
812 #[test]
813 fn an_answer_nobody_read_is_delivered_once() {
814 let mut q = asked(0);
815 q.choices = vec!["A".into()];
816 q.answer(crate::ask::Answer::Choice("A".into())).unwrap();
817 assert_eq!(
818 decide(&q, None, false, 86_400, ts(10)),
819 Action::Deliver(Word::Answered("A".into()))
820 );
821 q.answer_delivered = true;
822 assert_eq!(decide(&q, None, false, 86_400, ts(10)), Action::Idle);
823 }
824
825 #[test]
826 fn only_asked_questions_and_only_before_the_deadline() {
827 let mut q = asked(0);
828 assert_eq!(decide(&q, None, false, 86_400, ts(999)), Action::Idle);
829 assert_eq!(decide(&q, None, false, 86_400, ts(1001)), Action::Expire);
830 q.cwd = None;
831 assert_eq!(decide(&q, None, false, 86_400, ts(1001)), Action::Idle);
832 }
833
834 #[test]
835 fn the_deadline_runs_from_the_last_turn_not_from_asking() {
836 let mut q = asked(0);
837 q.thread.push(crate::ask::Turn {
838 who: Who::Agent,
839 body: "context".into(),
840 at: ts(4000),
841 note: None,
842 });
843 q.delivered_turns = 1;
844 assert_eq!(decide(&q, None, false, 86_400, ts(4500)), Action::Idle);
845 assert_eq!(decide(&q, None, false, 86_400, ts(5001)), Action::Expire);
846 }
847
848 #[test]
849 fn a_word_given_in_time_is_delivered_after_the_deadline() {
850 let mut q = asked(0);
851 q.say("wait").unwrap();
852 assert!(matches!(
853 decide(&q, None, false, 86_400, ts(5000)),
854 Action::Deliver(_)
855 ));
856 }
857
858 #[test]
859 fn an_action_answer_is_left_to_the_daemon() {
860 let mut q = asked(0);
861 q.choices = vec!["A".into()];
862 q.actions
863 .insert("A".into(), crate::ask::ChoiceAction::Requeue);
864 q.answer(crate::ask::Answer::Choice("A".into())).unwrap();
865 assert_eq!(
866 decide_owned(&q, None, false, 86_400, ts(10), true),
867 Action::Idle,
868 "the daemon applies the action; the waiter must not also resume the seat"
869 );
870 q.answer_delivered = true;
872 assert_eq!(
873 decide_owned(&q, None, false, 86_400, ts(10), true),
874 Action::Idle
875 );
876 q.answer_delivered = false;
878 assert_eq!(
879 decide_owned(&q, None, false, 86_400, ts(10), false),
880 Action::Deliver(Word::Answered("A".into()))
881 );
882 let mut plain = asked(0);
884 plain.choices = vec!["A".into()];
885 plain
886 .answer(crate::ask::Answer::Choice("A".into()))
887 .unwrap();
888 assert_eq!(
889 decide_owned(&plain, None, false, 86_400, ts(10), true),
890 Action::Deliver(Word::Answered("A".into()))
891 );
892 }
893}