agentd/runtime/reactor.rs
1// SPDX-License-Identifier: AGPL-3.0-only
2//! The **runtime state + event loop**: one single-threaded reactor over child
3//! frames, reaped children, executor results, timers, the durable inbox and
4//! signals.
5//!
6//! State mutation happens only here. Being the single writer is what makes the
7//! rest of the runtime reasonable about: no lock ordering, no torn reads, and
8//! an answer computed for one caller is computed against one consistent view.
9//! Every mutation is followed by a checkpoint decision, so durable state never
10//! trails the in-memory state by more than one loop turn.
11//!
12//! The other `runtime::*` modules add `impl Runtime` blocks for turns, tools,
13//! steps and subagents; this file owns construction, the loop, lifecycle and
14//! the status view.
15
16use super::artifacts::Artifacts;
17use super::children::{ChildKind, Children};
18use super::events::{Event, kinds};
19use super::timers::Timers;
20use crate::config::v2::{RunUntil, Settings};
21use crate::context::memory::Memory;
22use crate::context::{Contexts, skills, tokens};
23use crate::engine::{RunState, RunStatus, Workflow};
24use crate::governor::Governor;
25use crate::mcp::client::McpClient;
26use crate::obs::log::Logger;
27use crate::registry::Registry;
28use crate::state::{Durable, InboxEvent, Kind, now_ms};
29use crate::subagent::protocol::AgentMsg;
30use crate::supervisor::reap::Reaped;
31use crate::supervisor::tree::NodeId;
32use serde_json::{Value, json};
33use std::collections::{BTreeMap, VecDeque};
34use std::sync::Arc;
35use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};
36use std::time::{Duration, Instant};
37
38/// The reactor tick.
39pub const TICK: Duration = Duration::from_millis(200);
40/// Extra grace after the drain deadline before children are abandoned.
41pub const ABANDON_GRACE: Duration = Duration::from_secs(3);
42
43/// Who receives a deferred tool's answer.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum Target {
46 /// A child's `ToolRequest` (answered with `ToolResult`).
47 Child(NodeId, u64),
48 /// A workflow step (answered as the step's outcome).
49 Step(String, String),
50}
51
52/// A deferred internal-tool request (answered when its wait resolves).
53#[derive(Debug, Clone)]
54pub struct PendingTool {
55 pub target: Target,
56 pub name: String,
57 pub kind: PendingKind,
58 pub started_ms: u64,
59}
60
61#[derive(Debug, Clone)]
62pub enum PendingKind {
63 /// A durable timer (`sleep`).
64 Timer { id: String },
65 /// A subagent result (`subagent.run` sync / `subagent.await`).
66 Subagent { handle: String },
67 /// A think child (`think` tool / `context.compact`).
68 Think { child: NodeId },
69 /// A run's terminal state (`workflow.run wait` / `workflow.wait`).
70 Run { run: String, deadline_ms: u64 },
71 /// A CEL condition polled each tick (`await`).
72 Await { condition: String, deadline_ms: u64 },
73 /// A human's answer (`ask_human` / the `human` node): the
74 /// A2A task `task` sits in `input-required`; a `SendMessage` carrying its
75 /// `taskId` resolves this with the reply text. With no interface to answer
76 /// on, `task` is a synthetic ask id (no A2A task exists).
77 Human {
78 task: String,
79 question: String,
80 deadline_ms: u64,
81 /// The task exists ONLY for this ask (no A2A caller/run owns it) —
82 /// complete it when the answer lands.
83 standalone: bool,
84 /// The `auto` fallback judge is running (or already ran) for this ask.
85 auto_fired: bool,
86 /// The answer's declared shape (`human.schema` / `ask_human.schema`).
87 ///
88 /// Carried on the pending ask so the reply can be validated against it
89 /// when it lands. Forwarding the schema to clients only makes them
90 /// render the right form; a gate that declares it wants
91 /// `{decision: "file"|"hold"}` must also refuse "maybe later", or the
92 /// run proceeds on an answer it never asked for.
93 schema: Option<Value>,
94 /// Who must answer (`to:`). `None` ⇒ whoever holds the task, which is
95 /// the ordinary case. Enforced when the answer lands, for the same
96 /// reason the schema is: a gate that names a decider and then accepts
97 /// anyone records something that did not happen.
98 addressee: Option<crate::a2a::principals::Addressee>,
99 },
100}
101
102/// A queued root/conversation turn, waiting for a worker slot and for its
103/// context to be free. One context runs at most one turn at a time, so turns
104/// for the same conversation queue behind each other rather than interleaving
105/// into the same history.
106#[derive(Debug, Clone)]
107pub struct TurnJob {
108 pub ctx: String,
109 /// The triggering inbox event (marked done when the turn completes).
110 pub event: Option<String>,
111 pub principal: Option<String>,
112 /// The message appended to the context before the turn (already appended
113 /// when `None`).
114 pub message: Option<crate::context::Msg>,
115 /// Skill references to preload.
116 pub skills: Vec<String>,
117 /// The user text (for preflight / knowledge retrieval).
118 pub text: String,
119 /// Preflight ran (or was not needed).
120 pub preflight_done: bool,
121 /// Knowledge auto-context ran (or was not needed).
122 pub knowledge_done: bool,
123 /// The retrieved knowledge block (system message) for this turn.
124 pub knowledge: Option<String>,
125 /// The message-hop depth this turn inherits (see `RunState::msg_depth`).
126 /// A message from a person is depth 0; one a `message` step delivered
127 /// carries that step's depth, and anything this turn starts inherits it.
128 pub msg_depth: u32,
129}
130
131impl TurnJob {
132 pub fn new(
133 ctx: String,
134 event: Option<String>,
135 principal: Option<String>,
136 message: Option<crate::context::Msg>,
137 skills: Vec<String>,
138 text: String,
139 ) -> TurnJob {
140 TurnJob {
141 ctx,
142 event,
143 principal,
144 message,
145 skills,
146 text,
147 preflight_done: false,
148 knowledge_done: false,
149 knowledge: None,
150 msg_depth: 0,
151 }
152 }
153 /// The same job, carrying a delivered message's hop depth.
154 pub fn at_depth(mut self, depth: u32) -> TurnJob {
155 self.msg_depth = depth;
156 self
157 }
158}
159
160/// A subagent registry record, persisted as `subagent/<handle>` so a child's
161/// identity and result outlive both the child and this process.
162#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
163pub struct SubagentRecord {
164 pub handle: String,
165 pub instruction: String,
166 pub mode: String,
167 pub status: String,
168 #[serde(default)]
169 pub attempt: u32,
170 #[serde(default, skip_serializing_if = "Option::is_none")]
171 pub result: Option<Value>,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub error: Option<String>,
174 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub requested_by: Option<Value>,
176 #[serde(default)]
177 pub tokens: u64,
178 #[serde(default)]
179 pub created: u64,
180 #[serde(default)]
181 pub updated: u64,
182 /// The payload (secret-free) for restore re-spawn.
183 #[serde(default, skip_serializing_if = "Option::is_none")]
184 pub payload: Option<Value>,
185 /// The template this child was instantiated from, and its tier
186 /// (`flat` | `instance`). A freeform spawn carries neither.
187 #[serde(default, skip_serializing_if = "Option::is_none")]
188 pub template: Option<String>,
189 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub tier: Option<String>,
191 /// Instance tier: the child daemon's pid, config path, A2A socket and
192 /// (epoch-ms) retire-at deadline.
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub pid: Option<i32>,
195 #[serde(default, skip_serializing_if = "Option::is_none")]
196 pub config_path: Option<String>,
197 #[serde(default, skip_serializing_if = "Option::is_none")]
198 pub socket: Option<String>,
199 #[serde(default, skip_serializing_if = "Option::is_none")]
200 pub retire_at: Option<u64>,
201 /// Instance tier: set when retirement began (SIGTERM sent); the tick
202 /// escalates to SIGKILL after the drain window.
203 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub retiring_since: Option<u64>,
205 /// Durability class (default true). `false` ⇒ the record is memory-only:
206 /// never persisted, never restore-respawned — the fast path for throwaway
207 /// workers. Restored records (all persisted by construction) default true.
208 #[serde(default = "record_durable_default")]
209 pub durable: bool,
210 #[serde(skip)]
211 pub node: Option<NodeId>,
212 #[serde(skip)]
213 pub dirty: bool,
214}
215
216fn record_durable_default() -> bool {
217 true
218}
219
220/// The instruction in force. `version` increments on every change, so a
221/// consumer can tell a re-read from a genuinely new instruction.
222#[derive(Debug, Clone)]
223pub struct Instruction {
224 pub text: String,
225 pub source: &'static str,
226 pub uri: Option<String>,
227 pub server: Option<String>,
228 pub version: u64,
229}
230
231/// Counters for status/reports.
232#[derive(Debug, Default, Clone)]
233pub struct Counters {
234 pub turns: u64,
235 pub tool_calls: u64,
236 pub runs_started: u64,
237 pub runs_finished: u64,
238 pub inbox_processed: u64,
239 pub tokens_in: u64,
240 pub tokens_out: u64,
241}
242
243pub struct Runtime {
244 /// Resource pressure (disk headroom, cgroup memory): consulted at every
245 /// ADMISSION gate — start-node firing, webhook accept, `workflow.run`,
246 /// turn dispatch, subagent spawn — never on work already in flight.
247 pub(crate) pressure: std::sync::Arc<super::pressure::Pressure>,
248 /// The last level the tick reported, so transitions log exactly once.
249 pub(crate) pressure_seen: super::pressure::Level,
250 /// A step reached a terminal state since the last scheduling pass — its
251 /// dependents may be ready NOW (the same-iteration re-schedule fixpoint).
252 pub(crate) resched: bool,
253 /// Reaps already deferred once for frame ordering (by pid) — see
254 /// [`Runtime::on_reaped`].
255 pub(crate) reap_deferred: std::collections::HashSet<i32>,
256 /// Outbound token buckets for steps that declare `rate:`, keyed like the
257 /// breaker (`workflow/unscoped-step`). In-memory on purpose: a rate is a
258 /// statement about LIVE traffic, and a restart briefly refilling the burst
259 /// is harmless where a durable bucket would be bookkeeping for its own
260 /// sake. The paired f64 is the window seconds, for computing the wait.
261 pub(crate) step_rates:
262 std::collections::HashMap<String, (crate::supervisor::tree::TokenBucket, f64, u32)>,
263 pub(crate) settings: Settings,
264 /// The merged document the settings came from (restart-only diff base).
265 pub(crate) settings_doc: Value,
266 /// The invocation (for reload).
267 pub(crate) args: Vec<String>,
268 pub(crate) env: Vec<(String, String)>,
269 /// Workflow definitions pinned by live runs after a reload (hash → definition).
270 pub(crate) pinned: BTreeMap<String, std::sync::Arc<Workflow>>,
271 /// Retired definitions still owning live runs (`runtime::retire`), by hash.
272 pub(crate) retiring: BTreeMap<String, super::retire::Retiring>,
273 /// Definition hashes whose durable pin was written this life (one write
274 /// per version; see `retire::ensure_pin`).
275 pub(crate) pin_written: std::collections::HashSet<String>,
276 /// The last payload per signal name (for `await`/`wait condition` views).
277 pub(crate) recent_signals: BTreeMap<String, Value>,
278 /// Memoized `memory.<key>` references per definition content hash: the
279 /// scan walks the whole definition and `run_data` runs per step.
280 pub(crate) memory_keys: std::collections::HashMap<String, Vec<String>>,
281 /// An `emit` appended since the last stream poll (same-iteration wake).
282 pub(crate) stream_dirty: bool,
283 pub(crate) log: Logger,
284 pub(crate) instance: String,
285 pub(crate) run_id: String,
286 pub(crate) durable: Durable,
287 pub(crate) mcp: BTreeMap<String, Arc<McpClient>>,
288 pub(crate) mcp_specs: BTreeMap<String, crate::config::McpServerSpec>,
289 pub(crate) registry: Registry,
290 pub(crate) contexts: Contexts,
291 pub(crate) memory: Memory,
292 pub(crate) artifacts: Artifacts,
293 pub(crate) skills: skills::Catalogue,
294 pub(crate) governor: Governor,
295 /// Per-principal budgets and rate quotas, indexed by principal id when one
296 /// is first seen. `a2a.principals[].quotas` parsed and validated for a
297 /// long time without anything reading it; these are its readers.
298 pub(crate) principal_budgets: BTreeMap<String, crate::config::v2::Budget>,
299 /// Only the A2A listener admits callers, so a build without it has
300 /// nowhere to spend an arrival quota.
301 #[cfg_attr(not(feature = "a2a"), allow(dead_code))]
302 pub(crate) principal_rates: BTreeMap<String, crate::supervisor::tree::TokenBucket>,
303 /// Labels an id acts under, for `_meta` and audit.
304 pub(crate) principal_labels: BTreeMap<String, BTreeMap<String, String>>,
305 pub(crate) workflows: BTreeMap<String, std::sync::Arc<Workflow>>,
306 pub(crate) runs: BTreeMap<String, RunState>,
307 pub(crate) children: Children,
308 pub(crate) timers: Timers,
309 pub(crate) events_rx: Receiver<Event>,
310 pub(crate) events_tx: Sender<Event>,
311 pub(crate) reap_rx: Receiver<Reaped>,
312 pub(crate) pending: Vec<PendingTool>,
313 pub(crate) turn_queue: VecDeque<TurnJob>,
314 /// Turn jobs parked while their preflight think / knowledge retrieval runs.
315 pub(crate) staged_turns: BTreeMap<u64, TurnJob>,
316 pub(crate) inbox_queue: VecDeque<InboxEvent>,
317 pub(crate) subagents: BTreeMap<String, SubagentRecord>,
318 pub(crate) instruction: Instruction,
319 pub(crate) job_shape: bool,
320 pub(crate) exit: Option<i32>,
321 pub(crate) draining: bool,
322 /// Operator-held (a2a.pause): intake continues; no new turns dispatch and
323 /// no steps schedule until a2a.resume. Reversible, unlike drain.
324 pub(crate) paused: bool,
325 pub(crate) drain_started: Option<Instant>,
326 pub(crate) drain_reason: String,
327 pub(crate) idle_since: Option<Instant>,
328 pub(crate) intel_uri: String,
329 pub(crate) intel_token: Option<String>,
330 /// Resolved `intelligence.headers`, pushed on every LLM dial and threaded
331 /// to subagents via the spawn payload so a child dials identically.
332 pub(crate) intel_headers: Vec<(String, String)>,
333 /// An optional intelligence credential provider: a closure returning the
334 /// current bearer, refreshed from the device-login cache. Its resolved
335 /// bearer overrides `intel_token`, and is threaded to subagents fresh at
336 /// each spawn so no child carries a stale one. `None` when no
337 /// `intelligence.auth` oauth2 block is configured.
338 pub(crate) intel_bearer: Option<std::sync::Arc<dyn Fn() -> Option<String> + Send + Sync>>,
339 pub(crate) model: String,
340 pub(crate) trace_id: Option<String>,
341 pub(crate) started: Instant,
342 pub(crate) seq: u64,
343 pub(crate) counters: Counters,
344 /// The `once`-started run(s) whose finish decides a job's exit code.
345 pub(crate) job_runs: Vec<String>,
346 /// Steps executing on executor threads (`run/step` → started).
347 pub(crate) executing: BTreeMap<String, Instant>,
348 pub(crate) last_manifest_flush: Instant,
349 /// Unix-ms a goal LLM judge was dispatched (so overlapping checks don't spawn
350 /// duplicate judges); `None` = none in flight.
351 pub(crate) goal_judge_at: Option<u64>,
352 /// Durable A2A tasks, keyed by task id.
353 #[cfg(feature = "a2a")]
354 pub(crate) tasks: BTreeMap<String, crate::a2a::Task>,
355 /// Inbox-event id → the A2A task it answers (a conversation turn).
356 #[cfg(feature = "a2a")]
357 pub(crate) event_to_task: BTreeMap<String, String>,
358 /// The task snapshot the A2A listener threads read (None ⇒ not serving).
359 #[cfg(feature = "a2a")]
360 /// The interface event feed. `None` means the interface is disabled.
361 #[cfg(feature = "a2a")]
362 pub(crate) a2a_feed: Option<std::sync::Arc<super::a2a_server::SharedFeed>>,
363 /// Pairing-code login state. `None` means pairing is disabled.
364 #[cfg(feature = "a2a")]
365 pub(crate) a2a_pairing: Option<std::sync::Arc<super::a2a_server::PairingState>>,
366 /// The id the listener reserved for the task the request being served will
367 /// create. Taken by the first `task_create` of that request, and cleared
368 /// after it — an id belongs to one request only.
369 #[cfg(feature = "a2a")]
370 pub(crate) reserved_task_id: Option<String>,
371 /// Where a task transition is published so A2A subscribers see it.
372 #[cfg(feature = "a2a")]
373 pub(crate) a2a_sink: Option<std::sync::Arc<crate::a2a::ports::StreamSink>>,
374 /// The live listener. Held, not used: dropping it stops serving.
375 #[cfg(feature = "a2a")]
376 pub(crate) a2a_listener: Option<crate::a2a::serve::Listener>,
377 /// Live per-unit activity, keyed by child node id.
378 pub(crate) activity: BTreeMap<u64, super::activity::Activity>,
379 /// The newest root-context reply, so a `--prompt` job can print its answer
380 /// (a prompt runs as a turn, not as a `once` run with an output).
381 pub(crate) last_root_reply: Option<String>,
382 /// Per-item fingerprints behind the feed's section diffing (`feed_tick`).
383 #[cfg(feature = "a2a")]
384 pub(crate) feed_marks: BTreeMap<String, u64>,
385 /// The last section-diff pass (rate-limits `feed_tick`).
386 #[cfg(feature = "a2a")]
387 pub(crate) feed_last: Instant,
388 /// The `wait: {on: webhook}` await-callback registry, shared with the webhook
389 /// listener threads.
390 #[cfg(feature = "a2a")]
391 pub(crate) webhook_callbacks: super::webhooks::SharedCallbacks,
392 /// Pending `respond: sync` webhook replies, keyed by the run id they await.
393 #[cfg(feature = "a2a")]
394 pub(crate) webhook_sync: std::collections::HashMap<
395 String,
396 std::sync::mpsc::SyncSender<super::webhooks::WebhookReply>,
397 >,
398}
399
400impl Runtime {
401 /// A fresh id (turn ids, handles).
402 /// The deployment's default durability class for work (runs + subagent
403 /// records): `store.durability.work: ephemeral` ⇒ false.
404 pub(crate) fn work_durable_default(&self) -> bool {
405 !matches!(
406 self.settings.store.durability.work,
407 Some(crate::config::v2::WorkDurability::Ephemeral)
408 )
409 }
410
411 pub(crate) fn next_id(&mut self, prefix: &str) -> String {
412 self.seq += 1;
413 format!("{prefix}-{}", self.seq)
414 }
415
416 // ---- the loop ----------------------------------------------------------
417
418 /// Run until exit. Returns the process exit code.
419 pub fn run_loop(&mut self) -> i32 {
420 self.log.info("proc.ready", json!({"instance": self.instance, "job_shape": self.job_shape, "workflows": self.workflows.len(), "runs": self.runs.len(), "inbox_pending": self.inbox_queue.len()}));
421 loop {
422 crate::obs::health::tick();
423 // Pressure transitions are logged HERE, once per change, so the
424 // per-request gates can refuse silently instead of each writing its
425 // own line per refusal — under real pressure that would be a log
426 // flood on top of a disk that is already full.
427 {
428 let level = self.pressure.level();
429 if level != self.pressure_seen {
430 let free = self
431 .pressure
432 .disk_free
433 .load(std::sync::atomic::Ordering::Relaxed);
434 let detail = json!({
435 "level": level.as_str(),
436 "cause": self.pressure.cause(),
437 "disk_free_bytes": if free == u64::MAX { Value::Null } else { json!(free) },
438 });
439 match level {
440 super::pressure::Level::Ok => self.log.info("pressure.cleared", detail),
441 super::pressure::Level::Warn => self.log.warn("pressure.warn", detail),
442 super::pressure::Level::Shed => self.log.warn("pressure.shed", detail),
443 }
444 self.pressure_seen = level;
445 }
446 }
447 // 1. Child frames.
448 // (child frames arrive as Event::Child on the main channel — they
449 // wake the parked loop instead of waiting for the tick)
450 // 2. Reaped children.
451 let _ = crate::signals::take_child_exit();
452 crate::supervisor::reaper::reap_and_dispatch();
453 while let Ok(r) = self.reap_rx.try_recv() {
454 self.on_reaped(r);
455 }
456 // 3. Executor / internal events.
457 while let Ok(ev) = self.events_rx.try_recv() {
458 self.on_event(ev);
459 }
460 // 3.5. Retiring workflows whose drain deadline passed.
461 self.retire_tick();
462 // 4. Timers.
463 let now = now_ms();
464 for t in self.timers.fire(&self.durable, now) {
465 self.on_timer(t);
466 }
467 // 4.9. The daemon's own events, queued by the tap since the last
468 // tick, become appends — so a tripped breaker or a shed admission
469 // can start a run. Done BEFORE the inbox and the start poll so
470 // this tick's consumers see this tick's telemetry.
471 self.drain_runtime_events();
472 // 5. The inbox.
473 self.process_inbox();
474 // 6. Start nodes + runs (+ suspended waits).
475 self.poll_starts();
476 self.poll_stream_starts();
477 // Runs parked on the log resolve in the same pass that advances
478 // consumers, so a produce→wait hop costs a tick, not a timeout.
479 self.poll_event_waits();
480 self.poll_waits();
481 self.schedule_runs();
482 // Inline steps (assign/map/template/switch…) complete synchronously
483 // inside that pass, which makes their dependents ready NOW — without
484 // this fixpoint a pure data pipeline advanced ONE step per 200 ms
485 // tick (measured: 200 chained assigns = 42 s; with it, milliseconds).
486 // Bounded for the loop's honesty: effectful steps complete via
487 // events, so only inline chains re-enter here, and `limits.run.steps`
488 // already caps how long one can be.
489 let mut passes = 0;
490 while std::mem::take(&mut self.resched) && passes < 1024 {
491 self.schedule_runs();
492 passes += 1;
493 }
494 // 6.6. Streams appended in this iteration fire their consumers
495 // NOW: a same-process produce->consume pipeline advances at
496 // engine speed instead of paying the tick park per hop. Bounded
497 // like the fixpoint; an emit inside a fired consumer re-enters
498 // here, and `limits.run.steps` caps how deep that can go.
499 let mut stream_rounds = 0;
500 while std::mem::take(&mut self.stream_dirty) && stream_rounds < 64 {
501 self.poll_stream_starts();
502 // A run parked on the log is a consumer too: without this, a
503 // saga whose awaited event was emitted by a step in this very
504 // iteration would park until the next tick.
505 self.poll_event_waits();
506 self.schedule_runs();
507 let mut passes = 0;
508 while std::mem::take(&mut self.resched) && passes < 1024 {
509 self.schedule_runs();
510 passes += 1;
511 }
512 stream_rounds += 1;
513 }
514 // 7. Turns.
515 self.dispatch_turns();
516 // 8. Pending waits + MCP notifications.
517 self.poll_pending();
518 self.poll_mcp_notifications();
519 // 9. Children maintenance.
520 for (node, health) in self.children.tick() {
521 self.on_unhealthy_child(node, health);
522 }
523 // 9b. Instance-tier children: ttl retirement, plus the
524 // SIGTERM→SIGKILL escalation for children that ignored the drain.
525 self.instances_tick();
526 // 10. Checkpoints + the point-in-time observability gauges.
527 self.checkpoint(false);
528 crate::obs::metrics::set_inbox_pending(self.inbox_queue.len() as u64);
529 crate::obs::metrics::set_context_tokens(self.contexts.max_est_tokens());
530 {
531 let free = self
532 .pressure
533 .disk_free
534 .load(std::sync::atomic::Ordering::Relaxed);
535 crate::obs::metrics::set_pressure(
536 self.pressure_seen as u64,
537 (free != u64::MAX).then_some(free),
538 );
539 crate::obs::metrics::set_work_backlog(
540 self.runs
541 .values()
542 .filter(|r| !r.status.is_terminal())
543 .count() as u64,
544 self.turn_queue.len() as u64,
545 );
546 }
547 // 10.5. The interface feed's section diff: publish
548 // run/conversation/subagent/child/status deltas to attached display
549 // clients. A no-op unless `interface.enabled`; rate-limited inside.
550 #[cfg(feature = "a2a")]
551 self.feed_tick();
552 // 11. Signals + lifecycle.
553 self.check_signals();
554 if let Some(code) = self.lifecycle_step() {
555 self.shutdown(code);
556 return code;
557 }
558 // 12. Wait for the next event, bounded by the tick or the nearest
559 // imminent deadline (a timer, a schedule/loop start, a pending wait)
560 // so time-based work fires promptly rather than at tick granularity.
561 crate::signals::drain_wakeup();
562 let wait = self.next_wake().min(TICK);
563 match self.events_rx.recv_timeout(wait) {
564 Ok(ev) => self.on_event(ev),
565 Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => {}
566 }
567 }
568 }
569
570 fn on_event(&mut self, ev: Event) {
571 match ev {
572 Event::Child(node, msg) => self.on_child_frame(node, msg),
573 Event::Reaped(r) => self.on_reaped(r),
574 Event::StepDone {
575 run,
576 step,
577 output,
578 is_error,
579 error,
580 tokens,
581 } => self.on_step_done(&run, &step, output, is_error, error, tokens),
582 Event::ToolDone {
583 node,
584 req,
585 result,
586 is_error,
587 } => self.on_tool_done(node, req, result, is_error),
588 Event::KnowledgeDone { job, block } => self.on_knowledge_done(job, block),
589 Event::TimerFired { id, owner, payload } => self.on_timer(crate::state::TimerRecord {
590 id,
591 deadline_ms: now_ms(),
592 owner,
593 payload,
594 }),
595 Event::Inbox(ev) => self.inbox_queue.push_back(ev),
596 #[cfg(feature = "a2a")]
597 Event::A2a(req) => self.on_a2a_request(*req),
598 #[cfg(feature = "a2a")]
599 Event::Webhook(req) => self.on_webhook_request(*req),
600 Event::Background { id, result } if id == "goal.judge" => self.on_goal_judge(&result),
601 Event::Background { id, result } if id.starts_with("human.judge:") => {
602 let ask = id.trim_start_matches("human.judge:").to_string();
603 self.on_human_judge(&ask, &result);
604 }
605 Event::SubscribeRead {
606 server,
607 uri,
608 content,
609 } => self.on_subscribe_read(&server, &uri, content),
610 Event::Background { .. } | Event::Tick => {}
611 }
612 }
613
614 // ---- inbox -------------------------------------------------------------
615
616 /// Accept a durable event: write it to the store first, then queue it for
617 /// the loop. Write-ahead is the whole point — once acceptance is
618 /// acknowledged to the outside world, a crash before the event is acted on
619 /// must replay it rather than drop it.
620 pub(crate) fn accept_event(
621 &mut self,
622 kind: &str,
623 principal: Option<String>,
624 payload: Value,
625 ) -> Result<String, String> {
626 let ev = InboxEvent::new(kind, principal, payload);
627 self.durable
628 .inbox_put(&ev)
629 .map_err(|e| format!("inbox: {e}"))?;
630 let id = ev.id.clone();
631 self.log
632 .info("inbox.accepted", json!({"inbox_event": id, "kind": kind}));
633 self.inbox_queue.push_back(ev);
634 Ok(id)
635 }
636
637 fn process_inbox(&mut self) {
638 // Drain a SNAPSHOT, never the live deque: a start event that overflows
639 // its workflow's concurrency cap re-queues itself (`on_overflow: queue`,
640 // the default), and the cap can only be relieved by `schedule_runs` — a
641 // LATER step of this tick. Popping from the same deque the requeue
642 // pushes onto re-offers the event immediately and the single-writer
643 // reactor spins at 100% CPU forever: no timers, no checkpoint, no
644 // SIGTERM. Requeued (and newly accepted) events land in the fresh
645 // `self.inbox_queue` and are retried on the next tick instead.
646 let mut batch = std::mem::take(&mut self.inbox_queue);
647 while let Some(ev) = batch.pop_front() {
648 if self.draining {
649 // Keep it durable for the next life; stop intake — with one
650 // exception: the start event of a `lifecycle.shutdown` deinit
651 // workflow exists to run DURING the drain, and the drain gate
652 // is waiting for it. Everything else waits for the next life.
653 let deinit = ev.kind == kinds::START_FIRED
654 && ev.payload["workflow"]
655 .as_str()
656 .and_then(|n| self.workflows.get(n))
657 .is_some_and(|w| {
658 w.start_steps().iter().any(|s| {
659 s.kind == "event" && s.field_str("on") == Some("lifecycle.shutdown")
660 })
661 });
662 if !deinit {
663 self.inbox_queue.push_back(ev);
664 continue;
665 }
666 }
667 self.counters.inbox_processed += 1;
668 match ev.kind.as_str() {
669 kinds::START_FIRED | kinds::WORKFLOW_RUN => {
670 let done = self.on_start_event(&ev);
671 if done {
672 self.inbox_done(&ev.id);
673 }
674 }
675 kinds::A2A_MESSAGE => {
676 // Handled the same whether it arrived live or was replayed
677 // from the inbox after a restart.
678 self.on_a2a_message_event(&ev);
679 }
680 kinds::SIGNAL => {
681 let name = ev.payload["name"].as_str().unwrap_or("").to_string();
682 let payload = ev.payload.get("payload").cloned().unwrap_or(Value::Null);
683 let target = ev
684 .payload
685 .get("run")
686 .and_then(Value::as_str)
687 .map(str::to_string);
688 let from = ev
689 .payload
690 .get("from")
691 .and_then(Value::as_str)
692 .map(str::to_string);
693 let delivered =
694 self.deliver_signal(&name, payload, target.as_deref(), from.as_deref());
695 self.log.info(
696 "signal.received",
697 json!({"inbox_event": ev.id, "name": name, "delivered": delivered}),
698 );
699 self.inbox_done(&ev.id);
700 }
701 other => {
702 self.log.warn(
703 "inbox.unknown_kind",
704 json!({"inbox_event": ev.id, "kind": other}),
705 );
706 self.inbox_done(&ev.id);
707 }
708 }
709 }
710 // Whatever the drain did not consume keeps its place ahead of the
711 // events requeued (or accepted) while the batch was processing.
712 batch.append(&mut self.inbox_queue);
713 self.inbox_queue = batch;
714 }
715
716 pub(crate) fn inbox_done(&mut self, id: &str) {
717 if let Err(e) = self.durable.inbox_done(id) {
718 self.log.warn(
719 "inbox.done.fail",
720 json!({"inbox_event": id, "err": e.to_string()}),
721 );
722 }
723 }
724
725 /// An A2A message event, routed to whichever reader owns it. Control-plane
726 /// ops are consumed first, then a waiting step, then a start node, and only
727 /// what is left becomes a conversation turn.
728 fn on_a2a_message_event(&mut self, ev: &InboxEvent) {
729 let ctx = ev.payload["context_id"]
730 .as_str()
731 .unwrap_or("default")
732 .to_string();
733 let text = ev.payload["text"]
734 .as_str()
735 .map(str::to_string)
736 .unwrap_or_else(|| ev.payload["parts"].to_string());
737 let principal = ev.principal.clone();
738 // Re-link a replayed message to its durable task (crash recovery).
739 #[cfg(feature = "a2a")]
740 if let Some(task_id) = ev.payload["task"].as_str() {
741 self.event_to_task
742 .insert(ev.id.clone(), task_id.to_string());
743 }
744 // `_instance.*` ops are a child reporting home. The runtime consumes
745 // them BEFORE any reader, so they can never be mistaken for a wait's
746 // answer, a start's request, or a conversational turn — control-plane
747 // traffic must not reach a model.
748 #[cfg(feature = "a2a")]
749 if self.handle_instance_op(ev) {
750 return;
751 }
752 // An inbound message has three possible readers, in this order. Only one
753 // takes it: a message that woke a waiting step is an ANSWER, and a
754 // message that fired a workflow is a REQUEST — neither should also
755 // become a conversational turn, or the agent replies to itself.
756 //
757 // 1. A step suspended on this conversation (`a2a.wait` / `wait {on:
758 // message}`) — the reply half of an asynchronous exchange.
759 let msg = json!({"parts": ev.payload.get("parts").cloned().unwrap_or(Value::Null),
760 "text": text, "message_id": ev.payload.get("message_id").cloned()});
761 if self.deliver_a2a_message(&ctx, &msg, principal.as_deref()) > 0 {
762 self.log.info(
763 "a2a.message.delivered",
764 json!({"inbox_event": ev.id, "conversation": ctx}),
765 );
766 return;
767 }
768 // 2. An `a2a` START node whose command and roles match — a peer or an
769 // operator asking for a workflow rather than a conversation.
770 if self.fire_a2a_start(ev, &ctx) {
771 return;
772 }
773 // 3. Otherwise it is what it looks like: something to answer.
774 #[allow(unused)]
775 let skills = self.skills.references(&text);
776 let depth = ev.payload["msg_depth"].as_u64().unwrap_or(0) as u32;
777 self.turn_queue.push_back(
778 TurnJob::new(
779 ctx,
780 Some(ev.id.clone()),
781 principal.clone(),
782 Some(crate::context::Msg::user(text.clone(), principal)),
783 skills,
784 text,
785 )
786 .at_depth(depth),
787 );
788 }
789
790 /// Without the `a2a` feature there is no listener to deliver a message, so a
791 /// replayed event simply degrades to a turn.
792 #[cfg(not(feature = "a2a"))]
793 fn fire_a2a_start(&mut self, _ev: &InboxEvent, _ctx: &str) -> bool {
794 false
795 }
796
797 /// Match an inbound A2A message against every `a2a` start node and fire the
798 /// first that accepts it. Returns whether a run was started.
799 ///
800 /// `command` selects on the command DataPart's `op` — absent means "any
801 /// message", which is how a workflow takes plain conversation as its
802 /// trigger. `roles` restricts which principals may fire it, and defaults to
803 /// no restriction beyond the authorization the listener already applied:
804 /// the start node narrows, it never widens.
805 #[cfg(feature = "a2a")]
806 fn fire_a2a_start(&mut self, ev: &InboxEvent, ctx: &str) -> bool {
807 let op = ev.payload.get("parts").and_then(|parts| {
808 crate::runtime::a2a_server::command_op(&json!({"parts": parts.clone()}))
809 });
810 // The typed command payload, `op` removed: a workflow reads
811 // `{{ steps.cmd.output.args.<field> }}` instead of parsing parts.
812 let args = ev.payload.get("parts").and_then(|parts| {
813 crate::runtime::a2a_server::command_data(&json!({"parts": parts.clone()})).map(
814 |mut d| {
815 if let Some(o) = d.as_object_mut() {
816 o.remove("op");
817 }
818 d
819 },
820 )
821 });
822 let role = ev.payload["role"].as_str().unwrap_or("");
823 let specs: Vec<(String, String, serde_json::Map<String, Value>)> = self
824 .workflows
825 .values()
826 .flat_map(|w| {
827 w.start_steps()
828 .into_iter()
829 .filter(|s| s.kind == "a2a")
830 .map(|s| (w.name.clone(), s.id.clone(), s.spec.clone()))
831 .collect::<Vec<_>>()
832 })
833 .collect();
834 for (workflow, node, spec) in specs {
835 if let Some(want) = spec.get("command").and_then(Value::as_str)
836 && Some(want) != op.as_deref()
837 {
838 continue;
839 }
840 if let Some(roles) = spec.get("roles").and_then(Value::as_array)
841 && !roles.is_empty()
842 && !roles.iter().any(|r| r.as_str() == Some(role))
843 {
844 continue;
845 }
846 let payload = json!({
847 "conversation": ctx,
848 "principal": ev.principal,
849 "role": role,
850 "command": op,
851 "args": args.clone().unwrap_or(Value::Null),
852 // The A2A task tracking this message: carried onto the run so
853 // its terminal status completes the task — which is what lets
854 // a peer's `a2a.delegate {command}` BLOCK on the answer.
855 "task": ev.payload.get("task").cloned().unwrap_or(Value::Null),
856 "parts": ev.payload.get("parts").cloned().unwrap_or(Value::Null),
857 "text": ev.payload.get("text").cloned().unwrap_or(Value::Null),
858 "message_id": ev.payload.get("message_id").cloned().unwrap_or(Value::Null),
859 // The message-hop depth rides through this reader too. Without
860 // it a chain routed through an `a2a` start would reset to zero
861 // on every hop, and the cap would never bite — the run this
862 // fires can `message` again, and that is the same loop.
863 "msg_depth": ev.payload.get("msg_depth").cloned().unwrap_or(json!(0)),
864 });
865 self.log.info(
866 "start.a2a.fired",
867 json!({"workflow": workflow, "node": node, "conversation": ctx,
868 "command": op, "role": role}),
869 );
870 self.fire_start(&workflow, &node, &spec, payload, "a2a");
871 return true;
872 }
873 false
874 }
875
876 // ---- children ----------------------------------------------------------
877
878 fn on_child_frame(&mut self, node: NodeId, msg: AgentMsg) {
879 if !self.children.on_frame(node, &msg) {
880 return; // a late frame from a reaped child
881 }
882 match msg {
883 AgentMsg::Ready
884 | AgentMsg::Pong { .. }
885 | AgentMsg::Gate { .. }
886 | AgentMsg::GateClosed { .. } => {}
887 // Coarse progress from the child: what this unit is doing right
888 // now, for the display clients' working row.
889 AgentMsg::Event { event, fields } => self.on_child_progress(node, &event, &fields),
890 AgentMsg::Usage(u) => {
891 self.counters.tokens_in += u.input_tokens;
892 self.counters.tokens_out += u.output_tokens;
893 crate::obs::metrics::record_tokens(u.input_tokens, u.output_tokens);
894 // A subagent's usage is charged as it reports; turn usage is
895 // settled on TurnDone against its reservation.
896 if let Some(ChildKind::Subagent { .. }) = self.children.get(node).map(|c| &c.kind) {
897 self.governor.charge(u, &[]);
898 }
899 }
900 AgentMsg::IntelHealth { all_down, .. } => {
901 if crate::signals::set_intel_all_down(all_down) {
902 self.log.warn("intel.health", json!({"all_down": all_down}));
903 }
904 }
905 AgentMsg::ToolRequest { id, name, args } => self.on_tool_request(node, id, &name, args),
906 AgentMsg::BudgetRequest { id, estimate } => self.on_budget_request(node, id, estimate),
907 AgentMsg::TurnDone { turn } => self.on_turn_done(node, *turn),
908 AgentMsg::Turn { outcome } => self.on_subagent_turn(node, outcome),
909 AgentMsg::Result { outcome } => self.on_subagent_result(node, Ok(outcome)),
910 AgentMsg::Failed { error } => {
911 let kind = self.children.get(node).map(|c| c.kind.clone());
912 match kind {
913 Some(ChildKind::Subagent { .. }) => self.on_subagent_result(node, Err(error)),
914 Some(_) => self.on_turn_failed(node, error),
915 None => {}
916 }
917 }
918 }
919 }
920
921 fn on_reaped(&mut self, r: Reaped) {
922 // Frames-before-reap. A child's terminal frame rides the same event
923 // queue as everything else (that is what makes its arrival WAKE the
924 // loop), so a reap racing ahead of it would read as "worker exited
925 // without a result". Restore the invariant by construction: join the
926 // child's reader thread — bounded, its pipe has already EOF'd — so
927 // every frame it ever wrote is IN the queue, then requeue the reap
928 // BEHIND them. FIFO does the rest; one deferral suffices.
929 if !self.reap_deferred.remove(&r.pid) && self.children.has_pid(r.pid) {
930 self.children.join_reader_of(r.pid);
931 self.reap_deferred.insert(r.pid);
932 let _ = self.events_tx.send(Event::Reaped(r));
933 return;
934 }
935 // An instance-tier daemon child has no control channel and no node in
936 // the child table, so its exit closes the subagent record directly.
937 if !self.children.has_pid(r.pid) && self.on_instance_reaped(&r) {
938 return;
939 }
940 let Some((node, child)) = self.children.on_reaped(&r) else {
941 return;
942 };
943 self.activity_end(node);
944 self.log.info("child.exit", json!({"node": node.0, "pid": r.pid, "kind": super::children::kind_label(&child.kind), "outcome": format!("{:?}", r.outcome)}));
945 // A child that died without its terminal frame: fail its unit.
946 match child.kind {
947 // Ask the STEP, not the child table, whether this worker died
948 // owing a result. The child table cannot answer it here: a
949 // `TurnDone` settles the step but leaves the child in the table
950 // until it is reaped, and `Children::on_reaped` above has already
951 // removed the entry — so "is the child in the table?" reads the
952 // same for a settled worker and an orphaned one. The step is
953 // unambiguous: it is Running and still owned by THIS worker only
954 // when no terminal frame ever landed.
955 ChildKind::StepTurn {
956 ref run,
957 ref step,
958 reservation,
959 } => {
960 let node_owned = node.0.to_string();
961 let orphaned = self
962 .runs
963 .get(run)
964 .and_then(|st| st.step(step))
965 .is_some_and(|s| {
966 s.status == crate::engine::StepStatus::Running
967 && s.worker.as_deref() == Some(node_owned.as_str())
968 });
969 if orphaned {
970 // `on_turn_failed` would route this, but it re-reads the
971 // child table too and returns early on the reaped node; the
972 // reservation it would have released is released here.
973 if let Some(res) = reservation {
974 self.governor.release(res);
975 }
976 self.log.warn(
977 "turn.failed",
978 json!({"node": node.0, "kind": super::children::kind_label(&child.kind), "err": "worker exited without a result"}),
979 );
980 self.on_step_turn_done(
981 run,
982 step,
983 crate::subagent::protocol::TurnResult {
984 status: "failed".into(),
985 error: Some(format!(
986 "worker exited without a result ({:?})",
987 r.outcome
988 )),
989 ..Default::default()
990 },
991 );
992 }
993 }
994 // A root turn and a think expose no equivalent state to test
995 // here, so they ask `pending_turn_exists`, which answers from the
996 // settled marker `on_turn_done` / `on_turn_failed` leave on the
997 // child record rather than from the child's presence in the table.
998 // Presence cannot answer it: `on_reaped` has already removed the
999 // child by the time this runs, and a normally-settled worker also
1000 // stays in the table until it is reaped, so presence reads the same
1001 // for settled and orphaned workers alike.
1002 ChildKind::RootTurn { .. } | ChildKind::Think { .. } => {
1003 if self.pending_turn_exists(node) {
1004 self.on_turn_failed(
1005 node,
1006 format!("worker exited without a result ({:?})", r.outcome),
1007 );
1008 }
1009 }
1010 ChildKind::Subagent { ref handle } => {
1011 if self
1012 .subagents
1013 .get(handle)
1014 .is_some_and(|s| !is_terminal_status(&s.status))
1015 {
1016 self.on_subagent_result(
1017 node,
1018 Err(format!(
1019 "subagent exited without a result ({:?})",
1020 r.outcome
1021 )),
1022 );
1023 }
1024 }
1025 }
1026 // Answer any tool request that was waiting on this child (a think).
1027 let waiting: Vec<PendingTool> = self
1028 .pending
1029 .iter()
1030 .filter(|p| matches!(&p.kind, PendingKind::Think { child } if *child == node))
1031 .cloned()
1032 .collect();
1033 for p in waiting {
1034 self.pending.retain(|q| q.target != p.target);
1035 self.reply(
1036 &p.target,
1037 Value::String("think worker exited without a result".into()),
1038 true,
1039 );
1040 }
1041 }
1042
1043 fn on_unhealthy_child(&mut self, node: NodeId, health: crate::supervisor::liveness::Health) {
1044 self.log.warn(
1045 "child.unhealthy",
1046 json!({"node": node.0, "health": format!("{health:?}")}),
1047 );
1048 self.children.cancel(node, &format!("{health:?}"));
1049 // Escalate: give it a moment, then kill.
1050 let started = self
1051 .children
1052 .get(node)
1053 .map(|c| c.started)
1054 .unwrap_or_else(Instant::now);
1055 if started.elapsed() > Duration::from_secs(1) {
1056 self.children.kill(node);
1057 }
1058 }
1059
1060 // ---- lifecycle ---------------------------------------------------------
1061
1062 fn check_signals(&mut self) {
1063 if crate::signals::draining() && !self.draining {
1064 self.begin_drain("signal");
1065 }
1066 if crate::signals::reload_requested() {
1067 crate::signals::clear_reload();
1068 self.on_reload_requested();
1069 }
1070 }
1071
1072 pub(crate) fn begin_drain(&mut self, reason: &str) {
1073 if self.draining {
1074 return;
1075 }
1076 self.draining = true;
1077 self.drain_started = Some(Instant::now());
1078 self.drain_reason = reason.to_string();
1079 crate::signals::set_lame_duck(true);
1080 self.log.info("drain.start", json!({"reason": reason, "children": self.children.len(), "runs": self.runs.values().filter(|r| !r.status.is_terminal()).count()}));
1081 crate::obs::metrics::record_drain("started");
1082 // Tell every attached display client, so a client can stop offering
1083 // actions the daemon will now refuse.
1084 #[cfg(feature = "a2a")]
1085 self.feed_push(
1086 "lifecycle",
1087 super::a2a_server::FeedVis::All,
1088 json!({"draining": true, "reason": reason}),
1089 );
1090 self.children.begin_drain(reason);
1091 // Deinitialization workflows: `event {on: lifecycle.shutdown}` starts
1092 // fire NOW — releasing a claimed webhook route, deregistering from a
1093 // service, flushing a summary — and the drain below WAITS for exactly
1094 // those runs (bounded by drain_timeout like everything else). The
1095 // mirror of `once {policy: always}`, which is the init workflow.
1096 self.fire_event_starts("lifecycle.shutdown", &json!({"reason": reason}));
1097 }
1098
1099 /// Non-terminal runs of workflows that declare a `lifecycle.shutdown`
1100 /// start — the runs drain must wait for. (Any of the workflow's runs
1101 /// counts: an in-flight ordinary run of a deinit-capable workflow is not
1102 /// distinguishable from the deinit run by the time both must finish.)
1103 fn shutdown_runs_live(&self) -> usize {
1104 let capable = |name: &str, hash: &str| {
1105 self.definition_for_run_ref(name, hash).is_some_and(|w| {
1106 w.start_steps()
1107 .iter()
1108 .any(|s| s.kind == "event" && s.field_str("on") == Some("lifecycle.shutdown"))
1109 })
1110 };
1111 let live = self
1112 .runs
1113 .values()
1114 .filter(|r| !r.status.is_terminal())
1115 .filter(|r| capable(&r.workflow, &r.workflow_hash))
1116 .count();
1117 // A fired-but-not-yet-created run is still in the inbox for a tick —
1118 // the gate must not slip through that window.
1119 let queued = self
1120 .inbox_queue
1121 .iter()
1122 .filter(|e| e.kind == super::events::kinds::START_FIRED)
1123 .filter(|e| {
1124 e.payload["workflow"]
1125 .as_str()
1126 .and_then(|n| self.workflows.get(n))
1127 .is_some_and(|w| {
1128 w.start_steps().iter().any(|s| {
1129 s.kind == "event" && s.field_str("on") == Some("lifecycle.shutdown")
1130 })
1131 })
1132 })
1133 .count();
1134 live + queued
1135 }
1136
1137 /// Decide whether to exit now. Returns the exit code when done.
1138 fn lifecycle_step(&mut self) -> Option<i32> {
1139 if let Some(code) = self.exit {
1140 // A `finish {exit: true}` or a fatal store failure asked to exit:
1141 // drain first.
1142 if !self.draining {
1143 self.begin_drain("exit");
1144 }
1145 if self.children.is_empty() {
1146 return Some(code);
1147 }
1148 }
1149 if self.draining {
1150 let timeout = self.settings.lifecycle.drain_timeout();
1151 let started = self.drain_started.unwrap_or_else(Instant::now);
1152 let force = crate::signals::force() || started.elapsed() >= timeout;
1153 let done =
1154 self.children.drive_drain(force) && (force || self.shutdown_runs_live() == 0);
1155 if done || started.elapsed() >= timeout + ABANDON_GRACE {
1156 if !done {
1157 self.log
1158 .warn("drain.abandon", json!({"children": self.children.len()}));
1159 self.children.abandon();
1160 }
1161 crate::obs::metrics::record_drain("completed");
1162 self.checkpoint(true);
1163 self.log
1164 .info("drain.done", json!({"reason": self.drain_reason}));
1165 return Some(self.exit.unwrap_or(crate::exit::SUCCESS));
1166 }
1167 return None;
1168 }
1169 // Job shape / idle policy.
1170 let run_until = self.settings.lifecycle.run_until;
1171 // `auto` re-reads the LIVE workflow set, not just the configured one:
1172 // a long-lived workflow the agent defined at runtime (`workflow.create`
1173 // — the self-setup shape, where a `--prompt` tells it to build its own
1174 // loop/schedule/subscribe) turns the one-shot job into a daemon exactly
1175 // as a configured one would have. Without this the instance idle-exits
1176 // out from under the thing it was just asked to set up.
1177 let job_now = self.job_shape && !self.workflows.values().any(|w| w.is_long_lived());
1178 let idle_policy = match run_until {
1179 RunUntil::Idle => true,
1180 RunUntil::Drained => false,
1181 RunUntil::Auto => job_now,
1182 };
1183 if !idle_policy {
1184 return None;
1185 }
1186 let busy = self.paused // a paused instance never idle-exits underneath the operator
1187 || !self.children.is_empty()
1188 || !self.turn_queue.is_empty()
1189 || !self.staged_turns.is_empty()
1190 || !self.inbox_queue.is_empty()
1191 || !self.pending.is_empty()
1192 || !self.executing.is_empty()
1193 || self.runs.values().any(|r| !r.status.is_terminal())
1194 || !self.timers.is_empty();
1195 if busy {
1196 self.idle_since = None;
1197 return None;
1198 }
1199 let since = *self.idle_since.get_or_insert_with(Instant::now);
1200 if since.elapsed() >= self.settings.lifecycle.idle_grace() || job_now {
1201 let code = self.job_exit_code();
1202 self.log.info(
1203 "lifecycle.idle_exit",
1204 json!({"code": code, "job_shape": self.job_shape}),
1205 );
1206 self.checkpoint(true);
1207 return Some(code);
1208 }
1209 None
1210 }
1211
1212 /// The exit code of a job-shaped instance, mapped from the `once`-started
1213 /// workflow's finish status. With several such runs the worst outcome
1214 /// wins, so a partial success is never reported as a clean exit. A daemon
1215 /// is not job-shaped and drains to 0.
1216 fn job_exit_code(&self) -> i32 {
1217 let mut code = crate::exit::SUCCESS;
1218 for id in &self.job_runs {
1219 if let Some(r) = self.runs.get(id) {
1220 let c = run_exit_code(r);
1221 if c != crate::exit::SUCCESS {
1222 code = c;
1223 }
1224 }
1225 }
1226 if self.job_runs.is_empty() && self.job_shape {
1227 // Nothing ever ran (no workflow fired) — a configuration edge; report success.
1228 return crate::exit::SUCCESS;
1229 }
1230 crate::exit::apply_budget_remap(
1231 code,
1232 self.settings
1233 .lifecycle
1234 .exit_code_map
1235 .get(&code.to_string())
1236 .copied(),
1237 )
1238 }
1239
1240 fn shutdown(&mut self, code: i32) {
1241 self.children.abandon();
1242 let _ = self.durable.flush(true);
1243 self.log.info("proc.exit", json!({"code": code, "uptime_ms": self.started.elapsed().as_millis() as u64, "turns": self.counters.turns, "tool_calls": self.counters.tool_calls, "runs": self.counters.runs_finished, "tokens_in": self.counters.tokens_in, "tokens_out": self.counters.tokens_out}));
1244 }
1245
1246 /// The job's result (the once-started run's output), for stdout.
1247 pub fn job_output(&self) -> Option<Value> {
1248 self.job_runs
1249 .iter()
1250 .rev()
1251 .filter_map(|id| self.runs.get(id))
1252 .find_map(|r| r.output.clone())
1253 // A `--prompt` job has no `once` run to carry an output: its answer
1254 // is the root turn's reply.
1255 .or_else(|| self.last_root_reply.clone().map(Value::String))
1256 }
1257
1258 // ---- checkpoints ---------------------------------------------------------
1259
1260 /// Persist dirty runs/contexts/subagents; flush the manifest (debounced,
1261 /// forced at drain). A halting store error triggers an exit.
1262 pub(crate) fn checkpoint(&mut self, force: bool) {
1263 let mut failed: Option<String> = None;
1264 for run in self.runs.values_mut() {
1265 if run.dirty {
1266 // A non-durable run (workflow `durable: false`, or the
1267 // `store.durability.work: ephemeral` default) is memory-only:
1268 // no serialization, no write, gone after a restart.
1269 if !run.durable {
1270 run.dirty = false;
1271 continue;
1272 }
1273 crate::state::kill_point("step.before_done");
1274 match self.durable.put(
1275 Kind::Run,
1276 &run.id,
1277 serde_json::to_value(&*run).unwrap_or(Value::Null),
1278 Some(run.workflow_hash.clone()),
1279 ) {
1280 Ok(_) => run.dirty = false,
1281 Err(e) => failed = Some(format!("run {}: {e}", run.id)),
1282 }
1283 }
1284 }
1285 if let Err(e) = self.contexts.checkpoint(&self.durable) {
1286 failed = Some(format!("context: {e}"));
1287 }
1288 for s in self.subagents.values_mut() {
1289 if s.dirty {
1290 if !s.durable {
1291 s.dirty = false;
1292 continue;
1293 }
1294 match self.durable.put(
1295 Kind::Subagent,
1296 &s.handle,
1297 serde_json::to_value(&*s).unwrap_or(Value::Null),
1298 None,
1299 ) {
1300 Ok(_) => s.dirty = false,
1301 Err(e) => failed = Some(format!("subagent {}: {e}", s.handle)),
1302 }
1303 }
1304 }
1305 // Manifest: budget counters + lifecycle, debounced.
1306 let budget = self.governor.to_value();
1307 self.durable.manifest_update(|m| {
1308 m.budget = budget;
1309 });
1310 match self.durable.flush(force) {
1311 Ok(_) => {}
1312 Err(e) => failed = Some(format!("manifest: {e}")),
1313 }
1314 if let Some(e) = failed {
1315 self.log.error("store.checkpoint.fail", json!({"err": e}));
1316 if !self.durable.is_degraded() {
1317 // Halt policy: refuse new intake, drain.
1318 self.exit = Some(crate::exit::GENERIC);
1319 }
1320 }
1321 }
1322
1323 // ---- status ------------------------------------------------------------
1324
1325 /// `status` tool / `agent://status`.
1326 pub(crate) fn status_value(&self) -> Value {
1327 json!({
1328 "instance": self.instance,
1329 "run_id": self.run_id,
1330 "uptime_ms": self.started.elapsed().as_millis() as u64,
1331 "job_shape": self.job_shape,
1332 "draining": self.draining,
1333 "paused": self.paused,
1334 "store": {"kind": self.durable.store_kind(), "degraded": self.durable.is_degraded(), "generation": self.durable.manifest().generation},
1335 "workflows": self.workflows.values().map(|w| json!({"name": w.name, "hash": w.hash, "armed": w.armed, "starts": w.start_steps().iter().map(|s| s.kind.clone()).collect::<Vec<_>>()})).collect::<Vec<_>>(),
1336 "runs": self.runs.values().map(RunState::summary).collect::<Vec<_>>(),
1337 "conversations": self.contexts.status(),
1338 "subagents": self.subagents.values().map(|s| json!({"handle": s.handle, "mode": s.mode, "status": s.status, "tokens": s.tokens, "template": s.template, "tier": s.tier, "pid": s.pid, "retire_at": s.retire_at})).collect::<Vec<_>>(),
1339 "children": self.children.status(),
1340 "timers": self.timers.status(),
1341 "inbox_pending": self.inbox_queue.len(),
1342 "budget": self.governor.status(now_ms()),
1343 "tools": self.registry.len(),
1344 "skills": self.skills.names(),
1345 "counters": {"turns": self.counters.turns, "tool_calls": self.counters.tool_calls, "runs_started": self.counters.runs_started, "runs_finished": self.counters.runs_finished, "tokens_in": self.counters.tokens_in, "tokens_out": self.counters.tokens_out},
1346 "instruction": {"source": self.instruction.source, "uri": self.instruction.uri, "version": self.instruction.version, "bytes": self.instruction.text.len()},
1347 "model": self.model,
1348 "activity": self.activity_value(),
1349 })
1350 }
1351
1352 /// The shortest time until the next time-based wake (a timer, an armed
1353 /// schedule/loop start, a suspended wait deadline, a budget wait). Bounded
1354 /// below at 5 ms so a due deadline is serviced on the next pass without a
1355 /// busy spin.
1356 fn next_wake(&self) -> Duration {
1357 let now = now_ms();
1358 let mut soonest = now + 200;
1359 if let Some(t) = self.timers.next_deadline() {
1360 soonest = soonest.min(t);
1361 }
1362 for st in self.durable.manifest().starts.values() {
1363 for k in ["next_ms", "debounce_until"] {
1364 if let Some(n) = st[k].as_u64() {
1365 soonest = soonest.min(n);
1366 }
1367 }
1368 }
1369 for run in self.runs.values() {
1370 if run.status.is_terminal() {
1371 continue;
1372 }
1373 for step in run.steps.values() {
1374 if let Some(w) = &step.wait
1375 && let Some(d) = w["deadline_ms"].as_u64()
1376 {
1377 soonest = soonest.min(d);
1378 }
1379 }
1380 }
1381 if !self.pending.is_empty() || !self.turn_queue.is_empty() {
1382 soonest = soonest.min(now + 50);
1383 }
1384 Duration::from_millis(soonest.saturating_sub(now).max(5))
1385 }
1386
1387 /// The model window (compaction threshold base): `context.model_window`
1388 /// when set, else inferred from the model name.
1389 /// The model window (compaction threshold base).
1390 ///
1391 /// `context.model_window` wins, then the active tier's declared `window`,
1392 /// and only then the guess from the model NAME — a substring match that is
1393 /// simply wrong for any provider whose naming does not happen to match.
1394 /// A tier that declares its window replaces the guess with a fact.
1395 pub(crate) fn model_window(&self) -> u64 {
1396 if let Some(w) = self.settings.context.model_window {
1397 return w;
1398 }
1399 if let Some(w) = self
1400 .settings
1401 .intelligence
1402 .default_reference()
1403 .and_then(|r| self.settings.intelligence.tier(&r).and_then(|t| t.window))
1404 {
1405 return w;
1406 }
1407 tokens::window_for_model(&self.model)
1408 }
1409}
1410
1411pub(crate) fn is_terminal_status(s: &str) -> bool {
1412 matches!(
1413 s,
1414 "completed" | "failed" | "cancelled" | "refused" | "killed" | "crashed" | "retired"
1415 )
1416}
1417
1418/// Map a finished run's status onto a process exit code, so a caller can tell
1419/// *how* a job ended without parsing its output: refusal, budget exhaustion,
1420/// a missed deadline and an unreachable model each get their own code, and
1421/// anything still unfinished reports as partial.
1422pub fn run_exit_code(r: &RunState) -> i32 {
1423 match r.status {
1424 RunStatus::Completed => crate::exit::SUCCESS,
1425 RunStatus::Refused => crate::exit::REFUSED,
1426 RunStatus::Stalled => crate::exit::PARTIAL,
1427 RunStatus::Failed => {
1428 let e = r.error.as_deref().unwrap_or("");
1429 if e.contains("exhausted") || e.contains("budget") {
1430 crate::exit::BUDGET
1431 } else if e.contains("deadline") {
1432 crate::exit::DEADLINE
1433 } else if e.contains("intel") {
1434 crate::exit::INTEL_UNAVAILABLE
1435 } else {
1436 crate::exit::GENERIC
1437 }
1438 }
1439 RunStatus::Cancelled => crate::exit::GENERIC,
1440 _ => crate::exit::PARTIAL,
1441 }
1442}